@malloy-publisher/sdk 0.17.0 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +32 -50
  2. package/dist/{RenderedResult-BcEDcw0V.es.js → RenderedResult-CYJ2Y9Fm.es.js} +24 -24
  3. package/dist/{RenderedResult-uT2oc6ke.cjs.js → RenderedResult-hRvgFMAF.cjs.js} +1 -1
  4. package/dist/ServerProvider-DeVejmVr.cjs.js +1 -0
  5. package/dist/{ServerProvider-vmEUjlEu.es.js → ServerProvider-DzzfVDg_.es.js} +1314 -1712
  6. package/dist/builder/index.cjs.js +12 -12
  7. package/dist/builder/index.es.js +4 -9
  8. package/dist/client/api.d.ts +63 -506
  9. package/dist/client/configuration.d.ts +1 -1
  10. package/dist/client/index.cjs.js +1 -1
  11. package/dist/client/index.d.ts +1 -1
  12. package/dist/client/index.es.js +132 -144
  13. package/dist/components/Dashboard/DashboardGrid.d.ts +1 -1
  14. package/dist/components/Model/ExplorerPage.d.ts +1 -3
  15. package/dist/components/Model/Model.d.ts +1 -4
  16. package/dist/components/Model/ModelExplorer.d.ts +1 -2
  17. package/dist/components/Package/reportQueries.d.ts +2 -4
  18. package/dist/components/Report/Report.d.ts +20 -9
  19. package/dist/components/{legacy → Report}/malloynb/CellRunnerView.d.ts +13 -16
  20. package/dist/components/Report/malloynb/MalloynbReport.d.ts +11 -0
  21. package/dist/components/{legacy → Report}/malloynb/cellKind.d.ts +1 -1
  22. package/dist/components/ServerProvider.d.ts +1 -3
  23. package/dist/components/drill/drillClauses.d.ts +8 -9
  24. package/dist/components/drill/rowsTarget.d.ts +7 -9
  25. package/dist/components/legacy/index.d.ts +3 -7
  26. package/dist/components/modelPage.d.ts +2 -5
  27. package/dist/hooks/useModelGivens.d.ts +2 -2
  28. package/dist/hooks/useQueryResult.d.ts +7 -0
  29. package/dist/index.cjs.js +33 -33
  30. package/dist/index.es.js +8799 -8903
  31. package/dist/{useCompiledDocument-h5-Kc1Zh.cjs.js → useCompiledDocument-BCr-xB_i.cjs.js} +4 -4
  32. package/dist/{useCompiledDocument-rOwDSK_s.es.js → useCompiledDocument-E0tU5KzP.es.js} +266 -277
  33. package/package.json +1 -1
  34. package/src/components/Dashboard/DashboardGrid.tsx +1 -1
  35. package/src/components/Dashboard/DashboardTile.spec.tsx +1 -1
  36. package/src/components/Model/ExplorerPage.tsx +1 -3
  37. package/src/components/Model/Model.tsx +1 -4
  38. package/src/components/Model/ModelExplorer.tsx +1 -2
  39. package/src/components/Package/Package.tsx +1 -5
  40. package/src/components/Package/reportQueries.ts +3 -15
  41. package/src/components/Report/Report.malloynb.spec.tsx +230 -0
  42. package/src/components/Report/Report.spec.tsx +429 -38
  43. package/src/components/Report/Report.telemetry.spec.tsx +51 -10
  44. package/src/components/Report/Report.tsx +63 -44
  45. package/src/components/{legacy → Report}/malloynb/CellRunnerView.spec.tsx +11 -44
  46. package/src/components/{legacy → Report}/malloynb/CellRunnerView.tsx +63 -107
  47. package/src/components/Report/malloynb/MalloynbReport.tsx +110 -0
  48. package/src/components/{legacy → Report}/malloynb/cellKind.ts +5 -4
  49. package/src/components/ReportBuilder/EditorSurface.tsx +3 -3
  50. package/src/components/ReportBuilder/ReportBuilder.spec.tsx +2 -2
  51. package/src/components/ReportBuilder/ReportEditor.notebook.spec.tsx +0 -4
  52. package/src/components/ReportBuilder/ReportEditor.queryVersion.spec.tsx +0 -1
  53. package/src/components/ReportBuilder/ReportEditor.resourceUri.spec.tsx +3 -3
  54. package/src/components/ReportBuilder/ReportEditor.tsx +1 -1
  55. package/src/components/ReportBuilder/loadMalloy.ts +1 -4
  56. package/src/components/ReportBuilder/useSaveChannel.ts +1 -6
  57. package/src/components/ServerProvider.tsx +0 -4
  58. package/src/components/drill/drillClauses.ts +8 -9
  59. package/src/components/drill/rowsTarget.ts +7 -9
  60. package/src/components/index.ts +2 -3
  61. package/src/components/legacy/index.ts +3 -7
  62. package/src/components/modelPage.ts +2 -5
  63. package/src/hooks/useGivensState.ts +8 -8
  64. package/src/hooks/useModelGivens.ts +2 -2
  65. package/src/hooks/useQueryResult.ts +30 -18
  66. package/test/README.md +4 -4
  67. package/dist/ServerProvider-DDRwHiPz.cjs.js +0 -1
  68. package/dist/components/legacy/Dashboard.d.ts +0 -68
  69. package/dist/components/legacy/malloynb/MalloynbCells.d.ts +0 -13
  70. package/dist/components/legacy/malloynb/Notebook.d.ts +0 -15
  71. package/dist/components/legacy/queryKeys.d.ts +0 -8
  72. package/src/components/legacy/Dashboard.spec.tsx +0 -242
  73. package/src/components/legacy/Dashboard.tsx +0 -181
  74. package/src/components/legacy/malloynb/MalloynbCells.tsx +0 -88
  75. package/src/components/legacy/malloynb/Notebook.layout.spec.tsx +0 -103
  76. package/src/components/legacy/malloynb/Notebook.served.spec.tsx +0 -84
  77. package/src/components/legacy/malloynb/Notebook.spec.tsx +0 -223
  78. package/src/components/legacy/malloynb/Notebook.tsx +0 -46
  79. package/src/components/legacy/queryKeys.ts +0 -26
  80. /package/dist/components/{legacy → Report}/malloynb/NotebookCell.d.ts +0 -0
  81. /package/dist/components/{legacy → Report}/malloynb/runPlan.d.ts +0 -0
  82. /package/dist/components/{legacy → Report}/malloynb/types.d.ts +0 -0
  83. /package/src/components/{legacy → Report}/malloynb/NotebookCell.tsx +0 -0
  84. /package/src/components/{legacy → Report}/malloynb/cellKind.spec.ts +0 -0
  85. /package/src/components/{legacy → Report}/malloynb/runPlan.spec.ts +0 -0
  86. /package/src/components/{legacy → Report}/malloynb/runPlan.ts +0 -0
  87. /package/src/components/{legacy → Report}/malloynb/types.ts +0 -0
package/dist/index.cjs.js CHANGED
@@ -1,43 +1,43 @@
1
- "use strict";var Gu=Object.create;var Si=Object.defineProperty;var Yu=Object.getOwnPropertyDescriptor;var Ku=Object.getOwnPropertyNames;var Qu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var Xu=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Ku(n))!Zu.call(e,i)&&i!==r&&Si(e,i,{get:()=>n[i],enumerable:!(o=Yu(n,i))||o.enumerable});return e};var ki=(e,n,r)=>(r=e!=null?Gu(Qu(e)):{},Xu(n||!e||!e.__esModule?Si(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),p=require("@mui/material"),j=require("react"),c=require("./useCompiledDocument-h5-Kc1Zh.cjs.js"),q=require("./ServerProvider-DDRwHiPz.cjs.js"),yt=require("@tanstack/react-query"),wr=require("@mui/system"),Pt=require("@mui/icons-material"),Ju=require("@malloydata/malloy-tag"),oo=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-uT2oc6ke.cjs.js"),ed=require("@malloydata/malloy-filter"),Gr=require("react-router-dom");function td(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const Ce=td(j),nd=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function rd({label:e,href:n,onClick:r}){const o=i=>{const l=i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||i.button!==0;n!==void 0&&l||(i.preventDefault(),r(i))};return t.jsxs(p.Link,{...n===void 0?{component:"button",type:"button"}:{href:n},onClick:o,underline:"none","aria-label":`Back to ${e}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[t.jsx(nd,{sx:{fontSize:18}}),"Back to ",e]})}const Aa="(max-width:599.95px)";function Fa(){return p.useMediaQuery(Aa,{noSsr:!0})}function Ra(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Aa).matches}function sd({children:e}){const[n]=j.useState(Ra),[r,o]=j.useState(!1);return!n||r?t.jsx(t.Fragment,{children:e}):t.jsxs(p.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(p.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(p.Button,{variant:"outlined",onClick:()=>o(!0),children:"Edit anyway"})]})}function od(){const e=Gr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const o=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(o,"_blank")}}function Na(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const o=id(r.value,n);return o===void 0?[]:[{field:r.expression.name,label:o,expression:r.expression}]})}function La(e,n){switch(e.kind){case"string_literal":return`'${c.escapeMalloyString(e.string_value)}'`;case"number_literal":return e.string_value!==void 0?/^-?\d+(\.\d+)?$/.test(e.string_value)?e.string_value:void 0:Number.isFinite(e.number_value)?String(e.number_value):void 0;case"boolean_literal":return String(e.boolean_value);case"date_literal":{const r=_a(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=za(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Pa(e.timestamp_value)}`}default:return}}function id(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=_a(e.date_value);return r&&Ci([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=za(e.timestamp_value,n);return r&&Ci(r,e.granularity??"second")+(e.granularity===void 0?Pa(e.timestamp_value):"")}default:return La(e)}}function _a(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Pa(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function za(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:n??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(r)}catch{return}const i=l=>o.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function Ci([e,n,r,o,i,l],a){switch(a){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(n)-1)/3)+1}`;case"month":return`${e}-${n}`;case"week":case"day":return`${e}-${n}-${r}`;case"hour":return`${e}-${n}-${r} ${o}`;case"minute":return`${e}-${n}-${r} ${o}:${i}`;default:return`${e}-${n}-${r} ${o}:${i}:${l}`}}const ad="drill_metadata_corrected",Zr=e=>e,Rn=e=>{try{return e?.()}catch{return}},Wa=e=>Rn(e.isBasic?.bind(e))===!0&&Rn(e.wasDimension?.bind(e))===!0,ld=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>Rn(n?.bind(e))===!0);function Xr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function qa(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function Ba(e){const n=qa(e),o=(n[n.length-1]??e).metadataTag,i=o?.text("source","name");if(!i||!o?.array||o.array("source","parameters")!==void 0||o.has?.(ad)!==!0)return;const l=[];for(const d of[...n].reverse())if(Rn(d.isArray?.bind(d))===!0){if(d.metadataTag?.has?.("drillable")!==!0)return;for(const u of d.metadataTag?.array?.("drill_filters")??[]){const h=u.text("code");if(!h)return;l.push(h)}}const a=o?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of qa(e))for(const o of r.fields??[])Wa(o)&&n.add(o);return[...n]}function Va(e){const n=new Set(Er(e).filter(r=>Rn(r.isTime?.bind(r))===!0).map(r=>Rn(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function ji(e){return!Wa(e)||Xr(e)===void 0||Ba(e)===void 0||Va(e)===null?!1:Er(e).every(n=>Xr(n)!==void 0&&n.drillStableExpression!==void 0&&ld(n))}function cd(e,n){const r=Er(e),o=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const d=JSON.stringify(a.expression),u=r.find(y=>JSON.stringify(y.drillStableExpression)===d),h=u&&Xr(u);if(u===void 0||h===void 0)return;o.push({code:h,value:a.value}),i.add(u)}return r.every(l=>i.has(l))&&o.length>0?o:void 0}const ud=360;function Us(e){return e?e.getLabel?.()??e.tag?.text("label")??Zr(e).metadataTag?.text("label")??e.name:""}function dd(e,n){const r=e.drillClauses?Na(e.drillClauses,e.timezone):[];if(r.length===0)return`${Us(n)}: ${e.label}`;const o=Er(Zr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=o.find(d=>JSON.stringify(d.drillStableExpression)===l);return`${a?Us(a):i.field}: ${i.label}`}).join(", ")}function io({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:o,onRows:i}){const[l,a]=j.useState(null),d=j.useCallback((S,T)=>S.filter(O=>O===c.DRILL_SELF?n!==void 0&&(o?.(T)??!0):e!==void 0),[e,n,o]),u=j.useCallback((S,T,O)=>{if(T===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:T,dashboard:T,givens:{[S.given]:S.value}},O)},[e,n]),h=j.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const T=Zr(S.field);if(!ji(T))return;const O=Ba(T);if(O===void 0)return;const M=S.drillClauses;let E;if(M!==void 0){const P=cd(T,M);if(P===void 0)return;E={dimensions:P}}else{const P=Xr(T);if(P===void 0||Er(T).length!==1||c.drillValueToFilter(S.value)===void 0||typeof S.value=="number"&&Number.isInteger(S.value)&&!Number.isSafeInteger(S.value))return;E={code:P}}const R=Va(T)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:O,...E,...S.context===void 0?{}:{context:S.context},...M===void 0?{}:{drillClauses:M},...R===void 0?{}:{timezone:R}}},[i]),y=j.useCallback(S=>{const T=c.resolveDrill(S),O=h(S),M=T?Array.from(new Set(d(T.to,T.given))).sort((P,A)=>+(A===c.DRILL_SELF)-+(P===c.DRILL_SELF)):[],E=`${Us(S.field)}: ${T?.label??c.drillValueLabel(S.value)}`,R=M.map(P=>({key:`to:${P}`,label:P===c.DRILL_SELF?`Filter to ${E}`:`Open ${r?.(P)??c.humanizeSlug(P.split("/").pop()??P)} (${E})`,run:()=>{T&&u(T,P,S.event)}}));O&&S.field&&R.push({key:"rows",label:`Show rows (${dd(O,S.field)})`,run:()=>i?.(O)}),R.length!==0&&a({items:R,top:S.event?.clientY??0,left:S.event?.clientX??0})},[u,d,i,h,r]),b=j.useCallback(S=>d(c.drillDestinations(S),c.drillGivenName(S)).length>0,[d]),x=j.useCallback(S=>i!==void 0&&ji(Zr(S)),[i]),v=j.useMemo(()=>({onClick:y,canDrill:S=>b(S)||x(S)}),[y,b,x]),k=j.useCallback((S,T)=>({canDrill:O=>b(O)||T&&x(O),onClick:O=>y({...O,...S===void 0?{}:{context:S},...T?{}:{noRows:!0}})}),[y,b,x]),C=j.useCallback(()=>a(null),[]);return{drill:v,bindingFor:k,drillMenu:t.jsx(p.Menu,{open:l!==null,onClose:C,anchorReference:"anchorPosition",anchorPosition:{top:l?.top??0,left:l?.left??0},children:(l?.items??[]).map(S=>t.jsx(p.MenuItem,{title:S.label,"aria-label":S.label,onClick:()=>{C(),S.run()},sx:{maxWidth:ud},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const hd=e=>{const n=Ce.useRef({});return Ce.useEffect(()=>{n.current=e}),n.current};function fd(){const[e]=Gr.useSearchParams(),n=Gr.useNavigate(),r=Gr.useLocation(),o=j.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=j.useRef(new Set),l=j.useRef(null),a=j.useCallback(h=>{const y=l.current,b=new URLSearchParams(y?.key===r.key?y.search:r.search);h(b);const x=b.toString();l.current={key:r.key,search:x},n({search:x,hash:r.hash},{replace:!0})},[n,r]),d=j.useCallback((h,y)=>{const b=new Set([...y,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...y]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,k]of Object.entries(h))x.set(v,k)})},[a]),u=j.useCallback((h,y)=>a(b=>{y===void 0?b.delete(h):b.set(h,y)}),[a]);return{params:o,onGivensChange:d,setParam:u}}const md=c.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function fr(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function mr(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function pd(e){if(e===void 0)return"";switch(e.kind){case"null_cell":return"";case"number_cell":return e.string_value??String(e.number_value);case"boolean_cell":return e.boolean_value?"true":"false";case"date_cell":return e.date_value;case"timestamp_cell":return e.timestamp_value;case"string_cell":return mr(fr(e.string_value));case"json_cell":return mr(fr(e.json_value));case"sql_native_cell":return mr(fr(e.sql_native_value));default:return mr(fr(JSON.stringify(e)))}}function Ha(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function gd(e){const n=e.schema.fields;return`\uFEFF${[n.map(o=>mr(fr(o.name))).join(","),...Ha(e).map(o=>n.map((i,l)=>pd(o[l])).join(","))].join(`\r
1
+ "use strict";var Uu=Object.create;var wi=Object.defineProperty;var Gu=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Ku=Object.getPrototypeOf,Qu=Object.prototype.hasOwnProperty;var Zu=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Yu(n))!Qu.call(e,i)&&i!==r&&wi(e,i,{get:()=>n[i],enumerable:!(o=Gu(n,i))||o.enumerable});return e};var Si=(e,n,r)=>(r=e!=null?Uu(Ku(e)):{},Zu(n||!e||!e.__esModule?wi(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),p=require("@mui/material"),j=require("react"),c=require("./useCompiledDocument-BCr-xB_i.cjs.js"),q=require("./ServerProvider-DeVejmVr.cjs.js"),mt=require("@tanstack/react-query"),wr=require("@mui/system"),Pt=require("@mui/icons-material"),Xu=require("@malloydata/malloy-tag"),so=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-hRvgFMAF.cjs.js"),Ju=require("@malloydata/malloy-filter"),Gr=require("react-router-dom");function ed(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const je=ed(j),td=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function nd({label:e,href:n,onClick:r}){const o=i=>{const l=i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||i.button!==0;n!==void 0&&l||(i.preventDefault(),r(i))};return t.jsxs(p.Link,{...n===void 0?{component:"button",type:"button"}:{href:n},onClick:o,underline:"none","aria-label":`Back to ${e}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[t.jsx(td,{sx:{fontSize:18}}),"Back to ",e]})}const $a="(max-width:599.95px)";function Fa(){return p.useMediaQuery($a,{noSsr:!0})}function Aa(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia($a).matches}function rd({children:e}){const[n]=j.useState(Aa),[r,o]=j.useState(!1);return!n||r?t.jsx(t.Fragment,{children:e}):t.jsxs(p.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(p.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(p.Button,{variant:"outlined",onClick:()=>o(!0),children:"Edit anyway"})]})}function sd(){const e=Gr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const o=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(o,"_blank")}}function Ra(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const o=od(r.value,n);return o===void 0?[]:[{field:r.expression.name,label:o,expression:r.expression}]})}function La(e,n){switch(e.kind){case"string_literal":return`'${c.escapeMalloyString(e.string_value)}'`;case"number_literal":return e.string_value!==void 0?/^-?\d+(\.\d+)?$/.test(e.string_value)?e.string_value:void 0:Number.isFinite(e.number_value)?String(e.number_value):void 0;case"boolean_literal":return String(e.boolean_value);case"date_literal":{const r=_a(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=Pa(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Na(e.timestamp_value)}`}default:return}}function od(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=_a(e.date_value);return r&&ki([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=Pa(e.timestamp_value,n);return r&&ki(r,e.granularity??"second")+(e.granularity===void 0?Na(e.timestamp_value):"")}default:return La(e)}}function _a(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Na(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function Pa(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:n??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(r)}catch{return}const i=l=>o.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function ki([e,n,r,o,i,l],a){switch(a){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(n)-1)/3)+1}`;case"month":return`${e}-${n}`;case"week":case"day":return`${e}-${n}-${r}`;case"hour":return`${e}-${n}-${r} ${o}`;case"minute":return`${e}-${n}-${r} ${o}:${i}`;default:return`${e}-${n}-${r} ${o}:${i}:${l}`}}const id="drill_metadata_corrected",Zr=e=>e,Rn=e=>{try{return e?.()}catch{return}},za=e=>Rn(e.isBasic?.bind(e))===!0&&Rn(e.wasDimension?.bind(e))===!0,ad=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>Rn(n?.bind(e))===!0);function Xr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function Wa(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function qa(e){const n=Wa(e),o=(n[n.length-1]??e).metadataTag,i=o?.text("source","name");if(!i||!o?.array||o.array("source","parameters")!==void 0||o.has?.(id)!==!0)return;const l=[];for(const u of[...n].reverse())if(Rn(u.isArray?.bind(u))===!0){if(u.metadataTag?.has?.("drillable")!==!0)return;for(const d of u.metadataTag?.array?.("drill_filters")??[]){const h=d.text("code");if(!h)return;l.push(h)}}const a=o?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of Wa(e))for(const o of r.fields??[])za(o)&&n.add(o);return[...n]}function Ba(e){const n=new Set(Er(e).filter(r=>Rn(r.isTime?.bind(r))===!0).map(r=>Rn(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function Ci(e){return!za(e)||Xr(e)===void 0||qa(e)===void 0||Ba(e)===null?!1:Er(e).every(n=>Xr(n)!==void 0&&n.drillStableExpression!==void 0&&ad(n))}function ld(e,n){const r=Er(e),o=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const u=JSON.stringify(a.expression),d=r.find(y=>JSON.stringify(y.drillStableExpression)===u),h=d&&Xr(d);if(d===void 0||h===void 0)return;o.push({code:h,value:a.value}),i.add(d)}return r.every(l=>i.has(l))&&o.length>0?o:void 0}const cd=360;function Hs(e){return e?e.getLabel?.()??e.tag?.text("label")??Zr(e).metadataTag?.text("label")??e.name:""}function ud(e,n){const r=e.drillClauses?Ra(e.drillClauses,e.timezone):[];if(r.length===0)return`${Hs(n)}: ${e.label}`;const o=Er(Zr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=o.find(u=>JSON.stringify(u.drillStableExpression)===l);return`${a?Hs(a):i.field}: ${i.label}`}).join(", ")}function oo({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:o,onRows:i}){const[l,a]=j.useState(null),u=j.useCallback((S,T)=>S.filter(O=>O===c.DRILL_SELF?n!==void 0&&(o?.(T)??!0):e!==void 0),[e,n,o]),d=j.useCallback((S,T,O)=>{if(T===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:T,dashboard:T,givens:{[S.given]:S.value}},O)},[e,n]),h=j.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const T=Zr(S.field);if(!Ci(T))return;const O=qa(T);if(O===void 0)return;const M=S.drillClauses;let E;if(M!==void 0){const P=ld(T,M);if(P===void 0)return;E={dimensions:P}}else{const P=Xr(T);if(P===void 0||Er(T).length!==1||c.drillValueToFilter(S.value)===void 0||typeof S.value=="number"&&Number.isInteger(S.value)&&!Number.isSafeInteger(S.value))return;E={code:P}}const R=Ba(T)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:O,...E,...S.context===void 0?{}:{context:S.context},...M===void 0?{}:{drillClauses:M},...R===void 0?{}:{timezone:R}}},[i]),y=j.useCallback(S=>{const T=c.resolveDrill(S),O=h(S),M=T?Array.from(new Set(u(T.to,T.given))).sort((P,F)=>+(F===c.DRILL_SELF)-+(P===c.DRILL_SELF)):[],E=`${Hs(S.field)}: ${T?.label??c.drillValueLabel(S.value)}`,R=M.map(P=>({key:`to:${P}`,label:P===c.DRILL_SELF?`Filter to ${E}`:`Open ${r?.(P)??c.humanizeSlug(P.split("/").pop()??P)} (${E})`,run:()=>{T&&d(T,P,S.event)}}));O&&S.field&&R.push({key:"rows",label:`Show rows (${ud(O,S.field)})`,run:()=>i?.(O)}),R.length!==0&&a({items:R,top:S.event?.clientY??0,left:S.event?.clientX??0})},[d,u,i,h,r]),b=j.useCallback(S=>u(c.drillDestinations(S),c.drillGivenName(S)).length>0,[u]),x=j.useCallback(S=>i!==void 0&&Ci(Zr(S)),[i]),v=j.useMemo(()=>({onClick:y,canDrill:S=>b(S)||x(S)}),[y,b,x]),k=j.useCallback((S,T)=>({canDrill:O=>b(O)||T&&x(O),onClick:O=>y({...O,...S===void 0?{}:{context:S},...T?{}:{noRows:!0}})}),[y,b,x]),C=j.useCallback(()=>a(null),[]);return{drill:v,bindingFor:k,drillMenu:t.jsx(p.Menu,{open:l!==null,onClose:C,anchorReference:"anchorPosition",anchorPosition:{top:l?.top??0,left:l?.left??0},children:(l?.items??[]).map(S=>t.jsx(p.MenuItem,{title:S.label,"aria-label":S.label,onClick:()=>{C(),S.run()},sx:{maxWidth:cd},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const dd=e=>{const n=je.useRef({});return je.useEffect(()=>{n.current=e}),n.current};function hd(){const[e]=Gr.useSearchParams(),n=Gr.useNavigate(),r=Gr.useLocation(),o=j.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=j.useRef(new Set),l=j.useRef(null),a=j.useCallback(h=>{const y=l.current,b=new URLSearchParams(y?.key===r.key?y.search:r.search);h(b);const x=b.toString();l.current={key:r.key,search:x},n({search:x,hash:r.hash},{replace:!0})},[n,r]),u=j.useCallback((h,y)=>{const b=new Set([...y,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...y]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,k]of Object.entries(h))x.set(v,k)})},[a]),d=j.useCallback((h,y)=>a(b=>{y===void 0?b.delete(h):b.set(h,y)}),[a]);return{params:o,onGivensChange:u,setParam:d}}const fd=c.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function fr(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function mr(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function md(e){if(e===void 0)return"";switch(e.kind){case"null_cell":return"";case"number_cell":return e.string_value??String(e.number_value);case"boolean_cell":return e.boolean_value?"true":"false";case"date_cell":return e.date_value;case"timestamp_cell":return e.timestamp_value;case"string_cell":return mr(fr(e.string_value));case"json_cell":return mr(fr(e.json_value));case"sql_native_cell":return mr(fr(e.sql_native_value));default:return mr(fr(JSON.stringify(e)))}}function Va(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function pd(e){const n=e.schema.fields;return`\uFEFF${[n.map(o=>mr(fr(o.name))).join(","),...Va(e).map(o=>n.map((i,l)=>md(o[l])).join(","))].join(`\r
2
2
  `)}\r
3
- `}function yd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function xd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const Ti="Download the rows behind this value as CSV, up to the server's row limit",vd=4e4;function bd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=r,o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),vd)}function wd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ua({query:e,preamble:n,environmentName:r,packageName:o,modelPath:i,versionId:l,givens:a,fileName:d}){const{apiClients:u}=q.useServer(),[h,y]=j.useState(!1),[b,x]=j.useState(Ti),[v,k]=j.useState(void 0),C=j.useRef(void 0);j.useEffect(()=>()=>C.current?.abort(),[]);const S=async()=>{C.current?.abort();const T=new AbortController;C.current=T,y(!0),k(void 0);try{const O=await u.models.executeQueryModel(r,o,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,void 0,{signal:T.signal});if(T.signal.aborted)return;const M=O.data,E=JSON.parse(M.result??"{}"),R=xd(Ha(E).length,M.queryRowLimit,M.queryRowLimitSource);x(R===void 0?Ti:`First ${R} rows: the server's row limit, so there may be more`),bd(gd(E),R===void 0?`${d}.csv`:`${d}_first_${R}_rows_server_limit.csv`)}catch(O){if(T.signal.aborted)return;k(`Download failed: ${wd(O)}`)}finally{C.current===T&&(C.current=void 0,y(!1))}};return t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[v&&t.jsx(p.Typography,{role:"alert",variant:"caption",color:"error",sx:{maxWidth:320},children:v}),t.jsx(p.Tooltip,{title:b,children:t.jsx("span",{children:t.jsx(p.Button,{size:"small",startIcon:t.jsx(md,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ga=200;function Sd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function Oi(e,n=Ga){const r=Cd(e);if(r===void 0)return;const o=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=kd(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${o}; select: *${l} }`}function kd(e){return oo.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function js(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function Cd(e){if(e.dimensions){const r=[];for(const{code:o,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${js(o)} is null`);continue}const l=La(i,e.timezone);if(l===void 0)return;r.push(`${js(o)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${js(e.code)} = ${n}`]:void 0}const jd="This value cannot be written as a filter, so its rows cannot be fetched.";function Mi(e){const n=e.drillClauses?Na(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function Td({request:e,environmentName:n,packageName:r,versionId:o,modelPath:i,preamble:l,givens:a,onClose:d,onDone:u,actions:h}){const{theme:y}=q.usePublisherTheme(),b=e?Oi(e):void 0,x=e?Oi(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},givens:a,fileName:yd(e.target.source,Mi(e).map(k=>k.label))}:void 0;return t.jsxs(p.Dialog,{open:e!==void 0,onClose:d,maxWidth:"lg",fullWidth:!0,children:[t.jsxs(p.DialogTitle,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",pb:.5},children:[t.jsxs(p.Box,{children:[e?t.jsxs(t.Fragment,{children:["Rows where"," ",Mi(e).map((k,C)=>t.jsxs(j.Fragment,{children:[C>0&&" and ",t.jsx(p.Box,{component:"code",sx:{fontSize:"0.9em"},children:k.field})," ","is ",k.label]},C))]}):"Rows",t.jsx(p.Typography,{component:"div",variant:"caption",sx:{color:y.tileTitle,mt:.25},children:e?`The first ${Ga} rows of ${e.target.source} behind this value, with the tile's own filters and the controls applied.`:""})]}),t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1,ml:1},children:[v&&(h?h(v):t.jsx(Ua,{...v})),t.jsx(p.IconButton,{onClick:d,"aria-label":"Close",size:"small",sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]})]}),t.jsxs(p.DialogContent,{dividers:!0,sx:{p:0,minHeight:240},children:[b===void 0&&e&&t.jsx(p.Typography,{variant:"body2",sx:{p:2},children:jd}),b!==void 0&&t.jsx(Od,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:i,givens:a,...u?{onDone:u}:{}})]}),t.jsxs(p.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(p.Typography,{variant:"caption",sx:{mr:"auto",color:y.tileTitle,fontFamily:y.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(p.Button,{onClick:d,children:"Close"})]})]})}function Od({query:e,environmentName:n,packageName:r,versionId:o,modelPath:i,givens:l,onDone:a}){const d=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},query:e,givens:l}),{isSuccess:u,isError:h}=d,y=j.useRef(void 0);return j.useEffect(()=>{y.current=c.now()},[e]),j.useEffect(()=>{y.current===void 0||!u&&!h||(a?.(u,c.now()-y.current),y.current=void 0)},[u,h,a]),t.jsx(p.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:d,context:e})})}function rs({manifest:e,environmentName:n,packageName:r,versionId:o,documentName:i,givens:l,onGivensChange:a,onNavigate:d,height:u,maxResultSize:h,controlsLayout:y="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:k,onLinkNavigate:C,actions:S,rowsActions:T}){const O=j.useMemo(()=>C?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:C}:void 0,[n,r,e.path,i,C]),M=j.useMemo(()=>(e.givens??[]).filter(oe=>!(b!==void 0&&oe.secure===!0)&&!(oe.name!==void 0&&v?.includes(oe.name))),[e,v,b]),E=j.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,oe])=>typeof oe=="string")),[l]),R=c.useDocumentControls({specs:M,loaded:!0,startingValues:e.startingGivens,params:E,onGivensChange:a,documentKey:`${n}/${r}/${o??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:o,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:P,declaredTypes:A,canSelf:H,onSelf:D}=R,L=c.useReportEvents(),U=j.useMemo(()=>{const oe=new Set((e.tiles??[]).flatMap(K=>K.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([K])=>oe.has(K)&&!A.has(K)))},[e,l,A]),[$,W]=j.useState(void 0),Q=j.useCallback(oe=>{const K=Sd(oe);K!==void 0&&W(K)},[]),te=j.useMemo(()=>c.withHostGivens(c.givensToRequest(P,A),U),[P,A,U]),{reports:ee}=c.useReportListing(n,r,o,d!==void 0),G=j.useCallback(oe=>{const K=c.resolveDrillTarget(oe,ee);if(K.kind!=="path")return;const le=K.report.path;return ee.find(be=>be.path===le)?.title||void 0},[ee]),{bindingFor:Z,drillMenu:ae}=io({onNavigate:d,onSelf:D,canSelf:H,onRows:Q,destinationTitle:G}),z=j.useCallback((oe,K)=>Z(oe,K!==!0),[Z]),{columns:re,layout:se,tileMaxHeight:ne,tableMaxHeight:Ie}=c.layoutRules(e.layout,e.dashboardColumns),de=j.useMemo(()=>c.missingRequiredGivens(M,P,l),[M,P,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Ei,{manifest:e,links:O,actions:S}),children:t.jsx(p.Alert,{severity:"error",children:e.error})});const pe=x??e.path,De=e.tiles??[],Le=c.isPlaced(De);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Ei,{manifest:e,links:O,actions:S}),controls:M.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...R.panel,layout:y})}):void 0,children:[de.length>0&&t.jsx(p.Alert,{severity:"info",children:c.requiredPrompt(de)}),pe===void 0?t.jsx(p.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):De.length>0?t.jsx(c.DashboardGrid,{tiles:De,columns:re,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(oe,K)=>`${K}:${oe.kind==="text"?`text:${oe.name}`:oe.query}`,renderTile:(oe,K)=>oe.kind==="text"||oe.query===void 0?t.jsx(p.Box,{sx:oe.rowspan!==void 0||Le?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Md,{markdown:oe.markdown??"",links:O})}):t.jsx(c.DashboardTile,{index:K,environmentName:n,packageName:r,versionId:o,modelPath:pe,tile:oe.query,label:oe.label,subtitle:oe.subtitle,borderless:oe.borderless,givens:P,hostGivens:U,declaredTypes:A,givenNames:oe.givenNames,height:oe.rowspan!==void 0||Le?c.tileHeightPx(oe.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?u??ne:ne,tableMaxHeight:Ie,fixedHeight:oe.rowspan!==void 0||Le,maxResultSize:h,drill:z(oe.query,oe.restricted),ignoredFilters:c.tileIgnoredFilterLabels(oe.givenNames&&(oe.query&&k?.[oe.query]?[...oe.givenNames,...k[oe.query]]:oe.givenNames),M),...b!==void 0?{preamble:b,restricted:oe.restricted}:{},...(()=>{const le=c.waitingOn(de,oe.givenNames);return le.length>0?{waitingFor:c.waitingText(le)}:{}})()})}):t.jsx(p.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),ae,pe!==void 0&&t.jsx(Td,{request:$,environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:pe,...b===void 0?{}:{preamble:b},givens:te,...T===void 0?{}:{actions:T},onClose:()=>W(void 0),onDone:(oe,K)=>{$&&L.emit({type:"report.rows_shown",source:$.target.source,view:$.target.queryName??"",field:$.field,ok:oe,durationMs:K})}})]})}function Md({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Ei({manifest:e,links:n,actions:r}){return t.jsx(c.ReportHeader,{title:e.title??e.name,actions:r,description:e.description?t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e.description})}):void 0})}const Ya=c.createSvgIcon(t.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"})),Ed="publisher:resize";function Id(e){return typeof e=="object"&&e!==null&&e.type===Ed&&typeof e.height=="number"}function Ka(e){return e.replace(/\/api\/v0\/?$/,"")}function Qa({server:e,environmentName:n,packageName:r,path:o,versionId:i}){const l=o.startsWith("public/")?o.slice(7):o,a=`${Ka(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Dd(e){try{const{environmentName:n,packageName:r,modelPath:o,versionId:i}=c.parseResourceUri(e);return!n||!r||!o?null:{environmentName:n,packageName:r,dataAppPath:o,versionId:i}}catch{return null}}function $d({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),o=Dd(e),i=o?.environmentName??"",l=o?.packageName??"",a=o?.dataAppPath??"",d=o?.versionId,u=j.useMemo(()=>Qa({server:n,environmentName:i,packageName:l,path:a,...d!==void 0?{versionId:d}:{}}),[n,i,l,a,d]),y=c.useQueryWithApiError({queryKey:["data-apps",i,l,d],queryFn:()=>r.dataApps.listDataApps(i,l,d),enabled:!!o}).data?.data?.find(S=>S.path===a),b=y?.title??a,x=y?.fit==="viewport",v=j.useRef(null),[k,C]=j.useState(120);return j.useEffect(()=>{if(x)return;function S(T){Id(T.data)&&T.source===v.current?.contentWindow&&T.data.height>0&&C(Math.ceil(T.data.height))}return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[x]),o?t.jsxs(p.Box,{sx:{p:3,...x?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1600,mx:"auto"}},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[t.jsx(p.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium",letterSpacing:"-0.025em"},children:b}),t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a}),t.jsx(p.Box,{sx:{flex:1}}),t.jsx(p.Tooltip,{title:"Open standalone in new tab",children:t.jsx(p.IconButton,{size:"small",href:u,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})]}),t.jsx(p.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...x?{flex:1,minHeight:0}:{}},children:t.jsx("iframe",{ref:v,src:u,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:x?"100%":k,border:0}})})]}):t.jsxs(p.Box,{sx:{p:3,maxWidth:1600,mx:"auto"},children:[t.jsx(p.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium"},children:"Can't open data app"}),t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",t.jsx(p.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,ml:1},children:e})]})]})}function _t({title:e,count:n,description:r,action:o,children:i}){const l=j.useId();return t.jsxs(p.Box,{component:"section","aria-labelledby":l,sx:{mb:4},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:r?0:1,minHeight:40},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[t.jsx(p.Typography,{id:l,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:e}),n!==void 0&&t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",children:["(",n,")"]})]}),o]}),r&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(p.Box,{children:i})]})}function Ad({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[o,i]=j.useState(!1),l=90,{data:a,isSuccess:d,isError:u,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),y=a?.data?.readme||"",b=y.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!d&&!u&&t.jsx(c.Loading,{text:"Fetching About..."}),d&&y&&t.jsxs(_t,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:o||!x?y:v}),x&&t.jsx(p.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:o?"Read less":"Read more",onClick:()=>i(!o)})})]}),u&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Fd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:o,open:i,resumeHideDuration:l}=e,a=c.useTimeout();Ce.useEffect(()=>{if(!i)return;function T(O){O.defaultPrevented||O.key==="Escape"&&o?.(O,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[i,o]);const d=c.useEventCallback((T,O)=>{o?.(T,O)}),u=c.useEventCallback(T=>{!o||T==null||a.start(T,()=>{d(null,"timeout")})});Ce.useEffect(()=>(i&&u(n),a.clear),[i,n,u,a]);const h=T=>{o?.(T,"clickaway")},y=a.clear,b=Ce.useCallback(()=>{n!=null&&u(l??n*.5)},[n,l,u]),x=T=>O=>{const M=T.onBlur;M?.(O),b()},v=T=>O=>{const M=T.onFocus;M?.(O),y()},k=T=>O=>{const M=T.onMouseEnter;M?.(O),y()},C=T=>O=>{const M=T.onMouseLeave;M?.(O),b()};return Ce.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",y),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",y)}},[r,i,b,y]),{getRootProps:(T={})=>{const O={...c.extractEventHandlers(e),...c.extractEventHandlers(T)};return{role:"presentation",...T,...O,onBlur:x(O),onFocus:v(O),onMouseEnter:k(O),onMouseLeave:C(O)}},onClickAway:h}}function Ii(e){return e.substring(2).toLowerCase()}function Rd(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Nd(e){const{children:n,disableReactTree:r=!1,mouseEvent:o="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=Ce.useRef(!1),d=Ce.useRef(null),u=Ce.useRef(!1),h=Ce.useRef(!1);Ce.useEffect(()=>(setTimeout(()=>{u.current=!0},0),()=>{u.current=!1}),[]);const y=c.useForkRef(c.getReactElementRef(n),d),b=c.useEventCallback(k=>{const C=h.current;h.current=!1;const S=c.ownerDocument(d.current);if(!u.current||!d.current||"clientX"in k&&Rd(k,S))return;if(a.current){a.current=!1;return}let T;k.composedPath?T=k.composedPath().includes(d.current):T=!S.documentElement.contains(k.target)||d.current.contains(k.target),!T&&(r||!C)&&i(k)}),x=k=>C=>{h.current=!0;const S=n.props[k];S&&S(C)},v={ref:y};return l!==!1&&(v[l]=x(l)),Ce.useEffect(()=>{if(l!==!1){const k=Ii(l),C=c.ownerDocument(d.current),S=()=>{a.current=!0};return C.addEventListener(k,b),C.addEventListener("touchmove",S),()=>{C.removeEventListener(k,b),C.removeEventListener("touchmove",S)}}},[b,l]),o!==!1&&(v[o]=x(o)),Ce.useEffect(()=>{if(o!==!1){const k=Ii(o),C=c.ownerDocument(d.current);return C.addEventListener(k,b),()=>{C.removeEventListener(k,b)}}},[b,o]),Ce.cloneElement(n,v)}function Ld(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const _d=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,Ld,n)},Pd=c.styled(c.Paper,{name:"MuiSnackbarContent",slot:"Root"})(c.memoTheme(({theme:e})=>{const n=e.palette.mode==="light"?.8:.98;return{...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(c.emphasize(e.palette.background.default,n)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:c.emphasize(e.palette.background.default,n),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),zd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Wd=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),qd=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:d="alert",...u}=o,h=o,y=_d(h);return t.jsxs(Pd,{role:d,elevation:6,className:c.clsx(y.root,l),ownerState:h,ref:r,...u,children:[t.jsx(zd,{className:y.message,ownerState:h,children:a}),i?t.jsx(Wd,{className:y.action,ownerState:h,children:i}):null]})});function Bd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Vd=e=>{const{classes:n,anchorOrigin:r}=e,o={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(o,Bd,n)},Hd=c.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,n[`anchorOrigin${c.capitalize(r.anchorOrigin.vertical)}${c.capitalize(r.anchorOrigin.horizontal)}`]]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:n})=>n.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:n})=>n.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Ud=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:d,horizontal:u}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:y,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:k=!1,message:C,onBlur:S,onClose:T,onFocus:O,onMouseEnter:M,onMouseLeave:E,open:R,resumeHideDuration:P,slots:A={},slotProps:H={},TransitionComponent:D,transitionDuration:L=l,TransitionProps:{onEnter:U,onExited:$,...W}={},...Q}=o,te={...o,anchorOrigin:{vertical:d,horizontal:u},autoHideDuration:h,disableWindowBlurListener:k,TransitionComponent:D,transitionDuration:L},ee=Vd(te),{getRootProps:G,onClickAway:Z}=Fd({...te}),[ae,z]=Ce.useState(!0),re=ge=>{z(!0),$&&$(ge)},se=(ge,ue)=>{z(!1),U&&U(ge,ue)},ne={slots:{transition:D,...A},slotProps:{content:v,clickAwayListener:x,transition:W,...H}},[Ie,de]=c.useSlot("root",{ref:r,className:[ee.root,b],elementType:Hd,getSlotProps:G,externalForwardedProps:{...ne,...Q},ownerState:te}),[pe,{ownerState:De,...Le}]=c.useSlot("clickAwayListener",{elementType:Nd,externalForwardedProps:ne,getSlotProps:ge=>({onClickAway:(...ue)=>{const ye=ue[0];ge.onClickAway?.(...ue),!ye?.defaultMuiPrevented&&Z(...ue)}}),ownerState:te}),[oe,K]=c.useSlot("content",{elementType:qd,shouldForwardComponentProp:!0,externalForwardedProps:ne,additionalProps:{message:C,action:a},ownerState:te}),[le,be]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ne,getSlotProps:ge=>({onEnter:(...ue)=>{ge.onEnter?.(...ue),se(...ue)},onExited:(...ue)=>{ge.onExited?.(...ue),re(...ue)}}),additionalProps:{appear:!0,in:R,timeout:L,direction:d==="top"?"down":"up"},ownerState:te});return!R&&ae?null:t.jsx(pe,{...Le,...A.clickAwayListener&&{ownerState:De},children:t.jsx(Ie,{...de,children:t.jsx(le,{...be,children:y||t.jsx(oe,{...K})})})})});let Gs;function Gd(e){Gs=e}function Di(e){if(Gs)try{Gs(e)}catch{}}function Ht(e,n,r){return(async o=>{const i=Date.now();try{const l=await r(o);return Di({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw Di({type:"console.mutation",resource:e,action:n,ok:!1,durationMs:Date.now()-i,reason:l instanceof Error?l.message:"An unknown error occurred"}),l}})}function _n({mutationFn:e,success:n,invalidates:r,closeDialog:o,resource:i,action:l}){const a=yt.useQueryClient(),[d,u]=j.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){o();for(const y of r)a.invalidateQueries({queryKey:y});u(n)},onError(y){u(y instanceof Error?y.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Ud,{open:d!=="",autoHideDuration:6e3,onClose:()=>u(""),message:d})}}const Za="https://docs.malloydata.dev/documentation",Ts=`${Za}/user_guides/publishing`,In="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${Za}/`,publishing:`${Ts}/publishing`,explorer:`${Ts}/explorer`,mcpAgents:`${Ts}/mcp_agents`,surfaces:`${In}/choosing-a-surface.md`,dashboards:`${In}/dashboards.md`,dataApps:`${In}/html-data-apps.md`,givens:`${In}/givens.md`,materialization:`${In}/materialization.md`,connections:`${In}/connections.md`};function Yd({resourceUri:e}){const[n,r]=j.useState(!1),{apiClients:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=_n({mutationFn(d){return o.packages.createPackage(i,{name:d.name,description:d.description,location:d.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=d=>{d.preventDefault();const u=new FormData(d.currentTarget),h=u.get("name")?.toString(),y=u.get("description")?.toString(),b=u.get("location")?.toString();l.mutate({name:h,description:y,location:b})};return t.jsxs(t.Fragment,{children:[t.jsx(c.AddButton,{label:"Package",onClick:()=>r(!0)}),t.jsx(c.AppDialog,{open:n,onClose:()=>r(!1),title:"New package",description:t.jsxs(t.Fragment,{children:["A package is a directory of Malloy models and their data. Give its location as a GitHub, S3 or GCS URL, or an absolute path the server can read; see the"," ",t.jsx(p.Box,{component:"a",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{disabled:l.isPending,onClick:()=>r(!1),children:"Cancel"}),t.jsx(p.Button,{type:"submit",form:"package-form",variant:"contained",loading:l.isPending,children:"Create package"})]}),children:t.jsx("form",{onSubmit:a,id:"package-form",children:t.jsxs(p.Stack,{sx:{gap:2},children:[t.jsx(p.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(p.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(p.TextField,{id:"location",name:"location",label:"Location",type:"text",placeholder:"e.g. s3://my-bucket/my-package.zip",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),l.notice]})}const Kd=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function ss({icon:e,tint:n,label:r,mono:o,description:i,rightLabel:l,trailingAction:a,onClick:d,ariaLabel:u}){const h=!!d,y=b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d(b))};return t.jsxs(p.Box,{onClick:d,onKeyDown:h?y:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":u,sx:b=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:h?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":h?{backgroundColor:b.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":h?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[t.jsx(p.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:n,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e}),t.jsxs(p.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[t.jsx(p.Typography,{variant:"body2",sx:{...o?{fontFamily:q.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),i&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),l&&t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:l}),a&&t.jsx(p.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:a})]})}const Xa=c.createSvgIcon(t.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"})),Qd=c.generateUtilityClasses("MuiBox",["root"]),Zd=c.createTheme(),Ye=wr.createBox({themeId:c.THEME_ID,defaultTheme:Zd,defaultClassName:Qd.root,generateClassName:c.ClassNameGenerator.generate}),os=wr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),$i=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Xd(e){return c.generateUtilityClass("MuiListItemIcon",e)}const Ai=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Jd=e=>{const{alignItems:n,classes:r}=e,o={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(o,Xd,r)},eh=c.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.alignItems==="flex-start"&&n.alignItemsFlexStart]}})(c.memoTheme(({theme:e})=>({minWidth:56,color:(e.vars||e).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),ao=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=o,a=Ce.useContext(c.ListContext),d={...o,alignItems:a.alignItems},u=Jd(d);return t.jsx(eh,{className:c.clsx(u.root,i),ownerState:d,ref:r,...l})});function th(e){return c.generateUtilityClass("MuiListItemText",e)}const $n=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),nh=e=>{const{classes:n,inset:r,primary:o,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",o&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,th,n)},rh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${$n.primary}`]:n.primary},{[`& .${$n.secondary}`]:n.secondary},n.root,r.inset&&n.inset,r.primary&&r.secondary&&n.multiline,r.dense&&n.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${c.typographyClasses.root}:where(& .${$n.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${$n.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),lo=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:d=!1,primary:u,primaryTypographyProps:h,secondary:y,secondaryTypographyProps:b,slots:x={},slotProps:v={},...k}=o,{dense:C}=Ce.useContext(c.ListContext);let S=u??i,T=y;const O={...o,disableTypography:a,inset:d,primary:!!S,secondary:!!T,dense:C},M=nh(O),E={slots:x,slotProps:{primary:h,secondary:b,...v}},[R,P]=c.useSlot("root",{className:c.clsx(M.root,l),elementType:rh,externalForwardedProps:{...E,...k},ownerState:O,ref:r}),[A,H]=c.useSlot("primary",{className:M.primary,elementType:c.Typography,externalForwardedProps:E,ownerState:O}),[D,L]=c.useSlot("secondary",{className:M.secondary,elementType:c.Typography,externalForwardedProps:E,ownerState:O});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx(A,{variant:C?"body2":"body1",component:H?.variant?void 0:"span",...H,children:S})),T!=null&&T.type!==c.Typography&&!a&&(T=t.jsx(D,{variant:"body2",color:"textSecondary",...L,children:T})),t.jsxs(R,{...P,children:[S,T]})});function sh(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),oh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},ih=e=>{const{disabled:n,dense:r,divider:o,disableGutters:i,selected:l,classes:a}=e,d={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",o&&"divider",l&&"selected"]},u=c.composeClasses(d,sh,a);return{...a,...u}},ah=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:oh})(c.memoTheme(({theme:e})=>({...e.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${er.selected}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${er.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}},[`&.${er.selected}:hover`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity)}},[`&.${er.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${er.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${$i.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${$i.inset}`]:{marginLeft:52},[`& .${$n.root}`]:{marginTop:0,marginBottom:0},[`& .${$n.inset}`]:{paddingLeft:36},[`& .${Ai.root}`]:{minWidth:36},variants:[{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.divider,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:n})=>!n.dense,style:{[e.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:n})=>n.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...e.typography.body2,[`& .${Ai.root} svg`]:{fontSize:"1.25rem"}}}]}))),tt=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:d=!1,disableGutters:u=!1,focusVisibleClassName:h,role:y="menuitem",tabIndex:b,className:x,...v}=o,k=Ce.useContext(c.ListContext),C=Ce.useMemo(()=>({dense:a||k.dense||!1,disableGutters:u}),[k.dense,a,u]),S=Ce.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const T={...o,dense:C.dense,divider:d,disableGutters:u},O=ih(o),M=c.useForkRef(S,r);let E;return o.disabled||(E=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:C,children:t.jsx(ah,{ref:M,role:y,tabIndex:E,component:l,focusVisibleClassName:c.clsx(O.focusVisible,h),className:c.clsx(O.root,x),...v,ownerState:T,classes:O})})}),Gt={postgres:[{label:"Host",name:"host",type:"text",required:!1},{label:"Port",name:"port",type:"number",required:!1},{label:"Database Name",name:"databaseName",type:"text",required:!1},{label:"User Name",name:"userName",type:"text",required:!1},{label:"Password",name:"password",type:"password",required:!1},{label:"Connection String",name:"connectionString",type:"text",required:!1}],bigquery:[{label:"Project ID",name:"defaultProjectId",type:"text",required:!1},{label:"Billing Project ID",name:"billingProjectId",type:"text",required:!1},{label:"Location",name:"location",type:"text",required:!1},{label:"Service Account Key JSON",name:"serviceAccountKeyJson",type:"text",required:!0},{label:"Maximum Bytes Billed",name:"maximumBytesBilled",type:"text",required:!1},{label:"Query Timeout Milliseconds",name:"queryTimeoutMilliseconds",type:"text",required:!1},{label:"Database Metadata",name:"dbmeta",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]}],snowflake:[{label:"Account",name:"account",type:"text",required:!0},{label:"Username",name:"username",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Role",name:"role",type:"text",required:!1},{label:"Warehouse",name:"warehouse",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"Response Timeout Milliseconds",name:"responseTimeoutMilliseconds",type:"text",required:!1},{label:"Private Key",name:"privateKey",type:"password",required:!1},{label:"Private Key Passphrase",name:"privateKeyPass",type:"password",required:!1}],trino:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Catalog",name:"catalog",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Peaka Key",name:"peakaKey",type:"password",required:!1}],databricks:[{label:"Host",name:"host",type:"text",required:!0},{label:"HTTP Path",name:"path",type:"text",required:!0},{label:"Access Token",name:"token",type:"password",required:!1},{label:"OAuth Client ID",name:"oauthClientId",type:"text",required:!1},{label:"OAuth Client Secret",name:"oauthClientSecret",type:"password",required:!1},{label:"Default Catalog",name:"defaultCatalog",type:"text",required:!1},{label:"Default Schema",name:"defaultSchema",type:"text",required:!1}],mysql:[{label:"Host",name:"host",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Database",name:"database",type:"text",required:!0}],sqlserver:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Database",name:"database",type:"text",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Encrypt",name:"encrypt",type:"text",required:!1,selectOptions:[{label:"Yes",value:"true"},{label:"No",value:"false"}]},{label:"Trust server certificate",name:"trustServerCertificate",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]},{label:"Host name in certificate",name:"hostNameInCertificate",type:"text",required:!1},{label:"Instance name",name:"instanceName",type:"text",required:!1}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},pr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",sqlserver:"sqlserverConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},lh={bigquery:{dbmeta:"boolean"},sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},ch={sqlserver:["hostNameInCertificate","instanceName"]};function Ja(e,n){const r=lh[e],o=ch[e];if(!r&&!o)return n;const i={...n};for(const l of o??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const d=n[l];if(d!==void 0){if(d===""){delete i[l];continue}if(a==="integer"){const u=Number(d);Number.isInteger(u)&&(i[l]=u)}else(d==="true"||d==="false")&&(i[l]=d==="true")}}return i}const el=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Ys={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},Sr=[{label:"Credential Provider",name:"provider",type:"text",required:!1,selectOptions:[{label:"Access key pair",value:"config"},{label:"Host credential chain",value:"credential_chain"}]},{label:"Access Key ID",name:"accessKeyId",type:"text",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Secret Access Key",name:"secretAccessKey",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Credential Chain",name:"chain",type:"text",required:!1,visibleWhen:{field:"provider",value:"credential_chain"}},{label:"Region",name:"region",type:"text",required:!1},{label:"Endpoint",name:"endpoint",type:"text",required:!1},{label:"Session Token",name:"sessionToken",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}}],kr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],uh=[{label:"Auth Type",name:"authType",type:"text",required:!0,selectOptions:[{label:"SAS Token",value:"sas_token"},{label:"Service Principal (SPN)",value:"service_principal"}]},{label:"SAS URL (e.g. https://account.blob.core.windows.net/container/file.parquet?sp=r&st=...)",name:"sasUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"sas_token"}},{label:"Tenant ID",name:"tenantId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client ID",name:"clientId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client Secret",name:"clientSecret",type:"password",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Account Name",name:"accountName",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"File URL (e.g. abfss://container/path/file.parquet)",name:"fileUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}}];function Jr(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?Sr:e==="gcs"?kr:e==="azure"?uh:[]}function dh({onSubmit:e,isSubmitting:n}){const[r,o]=j.useState(!1),[i,l]=j.useState("postgres"),[a,d]=j.useState([]),[u,h]=j.useState("postgres"),[y,b]=j.useState("s3"),[x,v]=j.useState("config"),k=()=>{o(!0)},C=()=>{o(!1),d([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async E=>{E.preventDefault();const R=new FormData(E.currentTarget),P=R.get("name")?.toString(),A=R.get("type")?.toString(),H=Gt[A];if(!P)throw new Error("Name is required");if(!A)throw new Error("Type is required");let D;if(A==="ducklake"){const L={};if(u==="postgres"){const W=Gt.postgres,Q={};if(W.forEach(te=>{const ee=R.get(`ducklake_pg_${te.name}`)?.toString();ee&&(Q[te.name]=ee)}),Object.keys(Q).length===0)throw new Error("DuckLake requires catalog connection");L.postgresConnection=Q}const U=R.get("ducklake_bucketUrl")?.toString();if(!U)throw new Error("DuckLake requires a bucket URL");const $={bucketUrl:U};if(y==="s3"){const W={};if(Sr.forEach(Q=>{const te=R.get(`ducklake_s3_${Q.name}`)?.toString();te&&(W[Q.name]=te)}),W.provider==="credential_chain")delete W.accessKeyId,delete W.secretAccessKey,delete W.sessionToken;else{if(delete W.chain,!W.accessKeyId)throw new Error("S3 Access Key ID is required");if(!W.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(W).length>0&&($.s3Connection=W)}else if(y==="gcs"){const W={};if(kr.forEach(Q=>{const te=R.get(`ducklake_gcs_${Q.name}`)?.toString();te&&(W[Q.name]=te)}),!W.keyId)throw new Error("GCS Key ID is required");if(!W.secret)throw new Error("GCS Secret is required");Object.keys(W).length>0&&($.gcsConnection=W)}D={name:P,type:A,ducklakeConnection:{catalog:L,storage:$}}}else if(A==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const L=a.map((U,$)=>{const W=U.dbType,Q=R.get(`attachedDb_${$}_name`)?.toString();if(!Q)throw new Error(`Attached database at index ${$} must have a name`);const te={name:Q,type:W},ee=Jr(W);if(ee&&ee.length>0){const G={};if(ee.forEach(ae=>{const z=R.get(`attachedDb_${$}_${ae.name}`)?.toString();z&&(G[ae.name]=z)}),W==="s3"){if(G.provider==="credential_chain")delete G.accessKeyId,delete G.secretAccessKey,delete G.sessionToken;else if(delete G.chain,!G.accessKeyId||!G.secretAccessKey)throw new Error(`Attached database "${Q}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Z=Ys[W];Z&&(te[Z]=G)}return te});D={name:P,type:A,duckdbConnection:{attachedDatabases:L}}}else{const L={};if(H.forEach(U=>{const $=R.get(U.name)?.toString();$&&(L[U.name]=$)}),A==="postgres"){if(!!!L.connectionString?.trim()){const $=["host","port","databaseName","userName","password"];for(const W of $)if(!L[W])throw new Error(`${H.find(Q=>Q.name===W)?.label||W} is required`)}}else if(A==="bigquery"){if(!L.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(A==="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(A==="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(A==="mysql"){const U=["host","port","database","user","password"];for(const $ of U)if(!L[$])throw new Error(`${H.find(W=>W.name===$)?.label||$} is required`)}else if(A==="sqlserver"){const U=["server","database","user","password"];if(!L.instanceName&&!L.port)throw new Error("Port is required unless an instance name is given");for(const $ of U)if(!L[$])throw new Error(`${H.find(W=>W.name===$)?.label||$} is required`)}else if(A==="motherduck"){if(!L.accessToken)throw new Error("Access Token is required")}else if(A==="databricks"){if(!L.host)throw new Error("Host is required");if(!L.path)throw new Error("HTTP Path is required");const U=L.oauthClientId&&L.oauthClientSecret;if(!L.token&&!U)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}D={name:P,type:A,[pr[A]]:Ja(A,L)}}await e(D),C()},T=()=>{d([...a,{name:"",dbType:"postgres"}])},O=E=>{d(a.filter((R,P)=>P!==E))},M=(E,R)=>{const P=[...a];P[E]={...P[E],dbType:R},d(P)};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:k}),t.jsx(c.AppDialog,{open:r,onClose:C,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:n,onClick:C,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:n,children:"Create connection"})]}),children:t.jsx("form",{onSubmit:S,id:"connection-form",children:t.jsxs(os,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:i,select:!0,onChange:E=>l(E.target.value),children:el.map(E=>t.jsx(tt,{value:E,children:E},E))}),i==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:u,select:!0,onChange:E=>h(E.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),u==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(E=>t.jsx(c.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:y,select:!0,onChange:E=>b(E.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:y==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),y==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(E=>E.visibleWhen?x===E.visibleWhen.value:!0).map(E=>t.jsx(c.TextField,{id:`ducklake_s3_${E.name}`,name:`ducklake_s3_${E.name}`,label:E.label,type:E.selectOptions?void 0:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?x:void 0,onChange:E.name==="provider"?R=>v(R.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},`s3_${E.name}`))]}),y==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(E=>t.jsx(c.TextField,{id:`ducklake_gcs_${E.name}`,name:`ducklake_gcs_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},`gcs_${E.name}`))]})]})]}):i==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:T,ariaLabel:"Add database"})]}),a.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),a.map((E,R)=>{const P=Jr(E.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",R+1]}),t.jsx(c.IconButton,{onClick:()=>O(R),size:"small",color:"error",children:t.jsx(Xa,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${R}_name`,name:`attachedDb_${R}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),t.jsx(c.TextField,{id:`attachedDb_${R}_type`,name:`attachedDb_${R}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:A=>M(R,A.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(A=>t.jsx(tt,{value:A,children:A},A))}),P.filter(A=>A.visibleWhen?(E[A.visibleWhen.field]||P.find(D=>D.name===A.visibleWhen?.field)?.selectOptions?.[0]?.value)===A.visibleWhen.value:!0).map(A=>t.jsx(c.TextField,{id:`attachedDb_${R}_${A.name}`,name:`attachedDb_${R}_${A.name}`,label:A.label,type:A.selectOptions?void 0:A.type,fullWidth:!0,size:"small",required:A.required,select:!!A.selectOptions,defaultValue:A.selectOptions?.[0]?.value,onChange:A.selectOptions?H=>{const D=[...a];D[R]={...D[R],[A.name]:H.target.value},d(D)}:void 0,children:A.selectOptions?.map(H=>t.jsx(tt,{value:H.value,children:H.label},H.value))},A.name))]},R)})]}):Gt[i].map(E=>t.jsx(c.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?E.selectOptions[0]?.value:void 0,children:E.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},E.name))]})})})]})}function hh({connection:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=j.useState(!1),a=()=>{l(!0)},d=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:u=>{u.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(ao,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(lo,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:d,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:d,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete connection"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Fi=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ri(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Ni(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function fh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:o}){const[i,l]=j.useState(!1),[a,d]=j.useState(e.type),u=j.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,y]=j.useState(()=>Ri(e)),[b,x]=j.useState("postgres"),[v,k]=j.useState(()=>Ni(e)),[C,S]=j.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{y(Ri(e)),d(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),k(Ni(e)),l(!0)},O=()=>{l(!1),o?.()},M=async D=>{D.preventDefault();const L=new FormData(D.currentTarget),U=L.get("name")?.toString(),$=L.get("type")?.toString(),W=Gt[$];if(!U)throw new Error("Name is required");if(!$)throw new Error("Type is required");let Q;if($==="ducklake"){const te={};if(b==="postgres"){const Z=Gt.postgres,ae={};if(Z.forEach(z=>{const re=L.get(`ducklake_pg_${z.name}`)?.toString();re&&(ae[z.name]=re)}),Object.keys(ae).length===0)throw new Error("DuckLake requires catalog connection");te.postgresConnection=ae}const ee=L.get("ducklake_bucketUrl")?.toString();if(!ee)throw new Error("DuckLake requires a bucket URL");const G={bucketUrl:ee};if(v==="s3"){const Z={};Sr.forEach(z=>{const re=L.get(`ducklake_s3_${z.name}`)?.toString();re&&(Z[z.name]=re)});const ae=e.ducklakeConnection?.storage?.s3Connection;if(ae&&(!Z.provider&&ae.provider&&(Z.provider=ae.provider),!Z.chain&&ae.chain&&(Z.chain=ae.chain),!Z.accessKeyId&&ae.accessKeyId&&(Z.accessKeyId=ae.accessKeyId)),Z.provider==="credential_chain")delete Z.accessKeyId,delete Z.secretAccessKey,delete Z.sessionToken;else if(delete Z.chain,!Z.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(Z).length>0&&(G.s3Connection=Z)}else if(v==="gcs"){const Z={};kr.forEach(z=>{const re=L.get(`ducklake_gcs_${z.name}`)?.toString();re&&(Z[z.name]=re)});const ae=e.ducklakeConnection?.storage?.gcsConnection;if(ae&&!Z.keyId&&ae.keyId&&(Z.keyId=ae.keyId),!Z.keyId)throw new Error("GCS Key ID is required");Object.keys(Z).length>0&&(G.gcsConnection=Z)}Q={name:U,type:$,ducklakeConnection:{catalog:te,storage:G}}}else if($==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const te=h.map((ee,G)=>{const Z=ee.dbType,ae=L.get(`attachedDb_${G}_name`)?.toString();if(!ae)throw new Error(`Attached database at index ${G} must have a name`);const z={name:ae,type:Z},re=Jr(Z);if(re&&re.length>0){const se={};if(re.forEach(Ie=>{const de=L.get(`attachedDb_${G}_${Ie.name}`)?.toString();de&&(se[Ie.name]=de)}),Z==="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 "${ae}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ne=Ys[Z];ne&&(z[ne]=se)}return z});Q={name:U,type:$,duckdbConnection:{attachedDatabases:te}}}else{const te=e[pr[$]]||{},ee={};if(W.forEach(G=>{const Z=L.get(G.name)?.toString(),ae=te[G.name];Z?ee[G.name]=Z:Fi.has(G.name)||(Z!==void 0?ee[G.name]=Z:ae&&(ee[G.name]=ae))}),$==="postgres"){const G=["host","port","databaseName","userName"],Z=u.has("postgresConnection.connectionString");if(!(!!ee.connectionString?.trim()||Z)){const z=G;for(const re of z)if(!ee[re])throw new Error(`${W.find(se=>se.name===re)?.label||re} is required`)}}else if($==="snowflake"){if(!ee.account)throw new Error("Account is required");if(!ee.username)throw new Error("Username is required");if(!ee.warehouse)throw new Error("Warehouse is required")}else if($==="trino"){if(!ee.server)throw new Error("Server is required");if(!ee.user)throw new Error("User is required")}else if($==="mysql"){const G=["host","port","database","user"];for(const Z of G)if(!ee[Z])throw new Error(`${W.find(ae=>ae.name===Z)?.label||Z} is required`)}else if($==="sqlserver"){const G=["server","database","user"];if(!ee.instanceName&&!ee.port)throw new Error("Port is required unless an instance name is given");for(const Z of G)if(!ee[Z])throw new Error(`${W.find(ae=>ae.name===Z)?.label||Z} is required`)}else if($==="databricks"){if(!ee.host)throw new Error("Host is required");if(!ee.path)throw new Error("HTTP Path is required")}Q={name:U,type:$,[pr[$]]:Ja($,ee)}}await n(Q),O()},E=()=>{y([...h,{name:"",dbType:"postgres"}])},R=D=>{y(h.filter((L,U)=>U!==D))},P=(D,L)=>{const U=[...h];U[D]={...U[D],dbType:L},y(U)},A=(D,L)=>{const U=e.duckdbConnection?.attachedDatabases;if(!U||!U[D])return"";const $=U[D],W=Ys[$.type||""];return W&&$[W]?$[W][L]??"":""},H=D=>{const L=e.ducklakeConnection;if(!L)return"";if(D.startsWith("pg_")){const U=D.replace("pg_","");return L.catalog?.postgresConnection?.[U]??""}if(D==="bucketUrl")return L.storage?.bucketUrl??"";if(D.startsWith("s3_")){const U=D.replace("s3_","");return L.storage?.s3Connection?.[U]??""}if(D.startsWith("gcs_")){const U=D.replace("gcs_","");return L.storage?.gcsConnection?.[U]??""}return""};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:D=>{D.preventDefault(),D.stopPropagation(),T()},children:[t.jsx(ao,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(lo,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:i,onClose:O,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:r,onClick:O,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:r,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:M,id:"connection-form",children:t.jsxs(os,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:e.name}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:a,select:!0,onChange:D=>d(D.target.value),children:el.map(D=>t.jsx(tt,{value:D,children:D},D))}),a==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:b,select:!0,onChange:D=>x(D.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(D=>t.jsx(c.TextField,{id:`ducklake_pg_${D.name}`,name:`ducklake_pg_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",defaultValue:H(`pg_${D.name}`)},`pg_${D.name}`))})]}),t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:D=>k(D.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:v==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:H("bucketUrl")}),v==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(D=>D.visibleWhen?C===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`ducklake_s3_${D.name}`,name:`ducklake_s3_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secretAccessKey",select:!!D.selectOptions,defaultValue:D.selectOptions?C:H(`s3_${D.name}`),onChange:D.name==="provider"?L=>S(L.target.value):void 0,placeholder:D.name==="region"?"us-east-1":D.name==="secretAccessKey"&&u.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:D.selectOptions?.map(L=>t.jsx(tt,{value:L.value,children:L.label},L.value))},`s3_${D.name}`))]}),v==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(D=>t.jsx(c.TextField,{id:`ducklake_gcs_${D.name}`,name:`ducklake_gcs_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secret",defaultValue:H(`gcs_${D.name}`),placeholder:D.name==="secret"&&u.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${D.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),h.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),h.map((D,L)=>{const U=Jr(D.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",L+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${L+1}`,onClick:()=>R(L),size:"small",color:"error",children:t.jsx(Xa,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${L}_name`,name:`attachedDb_${L}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:D.name}),t.jsx(c.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:D.dbType,select:!0,onChange:$=>P(L,$.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map($=>t.jsx(tt,{value:$,children:$},$))}),U.filter($=>$.visibleWhen?(D[$.visibleWhen.field]||A(L,$.visibleWhen.field)||U.find(Q=>Q.name===$.visibleWhen?.field)?.selectOptions?.[0]?.value)===$.visibleWhen.value:!0).map($=>t.jsx(c.TextField,{id:`attachedDb_${L}_${$.name}`,name:`attachedDb_${L}_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required,select:!!$.selectOptions,defaultValue:A(L,$.name)||$.selectOptions?.[0]?.value,onChange:$.selectOptions?W=>{const Q=[...h];Q[L]={...Q[L],[$.name]:W.target.value},y(Q)}:void 0,children:$.selectOptions?.map(W=>t.jsx(tt,{value:W.value,children:W.label},W.value))},$.name))]},L)})]}):Gt[a].map(D=>{const L=e?.[pr[a]??""]?.[D.name??""]??"",U=D.type==="password"||Fi.has(D.name),$=u.has(`${pr[a]??""}.${D.name}`),W=D.selectOptions?L===""||L===void 0?D.selectOptions[0]?.value:String(L):void 0;return t.jsx(c.TextField,{id:D.name,name:D.name,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&!U&&!L,select:!!D.selectOptions,defaultValue:D.selectOptions?W:L,placeholder:$?"Leave empty to keep existing":void 0,helperText:U?$?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:D.selectOptions?.map(Q=>t.jsx(tt,{value:Q.value,children:Q.label},Q.value))},D.name)})]})})})]})}function Li(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(o=>o.type==="azure"&&o.name===n)}function mh(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function tl({connectionName:e,resourceUri:n,schema:r,connection:o}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,d]=j.useState(null),[u,h]=j.useState(r||null),[y,b]=j.useState(!1),{data:x,isError:v,isLoading:k,error:C}=c.useQueryWithApiError({queryKey:["schemas",l,e],queryFn:()=>i.connections.listSchemas(l,e)}),S=x?.data||[];return t.jsxs(p.Grid,{container:!0,spacing:1,children:[!r&&t.jsx(p.Grid,{size:{xs:12,md:4},children:t.jsxs(p.Paper,{sx:{p:1,m:0},children:[t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[t.jsx(p.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),t.jsx(p.FormControlLabel,{control:t.jsx(p.Switch,{checked:y,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(p.Divider,{sx:{mt:"2px"}}),t.jsxs(p.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:C,context:`${l} > ${e} > Schemas`}),!k&&!v&&S.length===0&&t.jsx(p.Typography,{variant:"body2",children:"No Schemas"}),!k&&!v&&S.length>0&&t.jsx(p.List,{dense:!0,disablePadding:!0,children:S.map(T=>{const O=T.name;if(T.isHidden&&!y)return null;const E=u===O;return t.jsx(p.ListItemButton,{selected:E,onClick:()=>{h(O),d(null)},children:t.jsx(p.ListItemText,{primary:O})},O)})})]})]})}),t.jsx(p.Grid,{size:{xs:12,md:r?6:4},children:u&&t.jsx(p.Paper,{sx:{p:1,m:0},children:t.jsx(yh,{connectionName:e,schemaName:u,onTableSelect:T=>{d(T)},resourceUri:n,connection:o})})}),t.jsx(p.Grid,{size:{xs:12,md:r?6:4},children:u&&a&&t.jsx(ph,{environmentName:l,connectionName:e,schemaName:u,tableResource:a})})]})}function ph({environmentName:e,connectionName:n,schemaName:r,tableResource:o}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:d,error:u}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,o],queryFn:()=>i.connections.getTable(e,n,r,o),enabled:!!r&&!!o}),h={resource:l?.data?.resource??o,columns:l?.data?.columns??[]};return t.jsxs(p.Paper,{sx:{p:1,m:0},children:[d&&t.jsx(c.ApiErrorDisplay,{error:u,context:`${e} > ${n} > ${r} > ${o}`}),!d&&t.jsx(gh,{table:h,loading:a})]})}function gh({table:e,loading:n}){return n?t.jsx(c.Loading,{text:"Loading columns..."}):t.jsxs(t.Fragment,{children:[t.jsxs(p.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[e.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(e.resource)?"File":"Table",": ",e.resource]}),t.jsx(p.Divider,{}),t.jsx(p.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:t.jsx(p.TableContainer,{children:t.jsxs(p.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"NAME"}),t.jsx(p.TableCell,{children:"TYPE"})]})}),t.jsx(p.TableBody,{children:e.columns?.sort((r,o)=>r.name.localeCompare(o.name))?.map(r=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:r.name}),t.jsx(p.TableCell,{children:r.type})]},r.name))})]})})})]})}function yh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:o,connection:i}){const{environmentName:l}=c.parseResourceUri(o),{apiClients:a}=q.useServer(),[d,u]=j.useState(""),{data:h,isSuccess:y,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),k=Li(i,n),C=T=>k?T:T.split(".").pop()||T,S=y&&h?.data?h.data.filter(T=>C(T.resource).toLowerCase().includes(d.toLowerCase())).sort((T,O)=>C(T.resource).localeCompare(C(O.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(p.Typography,{variant:"overline",fontWeight:"bold",children:mh(n)||Li(i,n)?`Files in ${n}`:`Tables in ${n}`}),t.jsx(p.Divider,{}),t.jsx(p.Box,{sx:{mt:1,mb:1},children:t.jsx(p.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:d,onChange:T=>u(T.target.value),variant:"outlined"})}),t.jsx(p.Divider,{}),t.jsxs(p.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[v&&t.jsx(c.Loading,{text:"Fetching Tables..."}),b&&t.jsx(c.ApiErrorDisplay,{error:x,context:`${l} > ${e} > ${n}`}),y&&S.length===0&&t.jsx(p.Typography,{variant:"body2",children:"No Tables"}),y&&h?.data&&h.data.length>0&&t.jsx(p.List,{dense:!0,disablePadding:!0,children:S.map(T=>{let O=C(T.resource);return!k&&T.resource.includes("://")&&(O=T.resource.split("/").pop()||T.resource),t.jsx(p.ListItemButton,{onClick:()=>r(T.resource),children:t.jsx(p.ListItemText,{primary:O,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const xh={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",sqlserver:"SQL Server",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function vh(e){return e?xh[e]??e:""}function bh({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),o=yt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=j.useState(""),[d,u]=j.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:d}),{data:y,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),k=c.useMutationWithApiError({mutationFn:Ht("connection","create",M=>n.environments.updateEnvironment(i,{name:i,connections:[...y.data,M]})),onSuccess(){a("Connection added successfully"),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),C=c.useMutationWithApiError({mutationFn:Ht("connection","update",M=>n.environments.updateEnvironment(i,{name:i,connections:y.data.map(E=>E.name===M.name?M:E)})),onSuccess(M,E){a(`Connection ${E.name} updated successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),S=c.useMutationWithApiError({mutationFn:Ht("connection","delete",M=>{if(!M.name)throw new Error("Cannot delete a connection with no name");return n.connections.deleteConnection(i,M.name)}),onSuccess(M,E){a(`Connection ${E.name} deleted successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),T=b?[...y.data].sort((M,E)=>(M.name??"").localeCompare(E.name??"")):[],O=k.isPending||C.isPending||S.isPending;return t.jsxs(_t,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(dh,{onSubmit:M=>k.mutateAsync(M),isSubmitting:k.isPending})}:{},children:[!b&&!x&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),x&&t.jsx(c.ApiErrorDisplay,{error:v,context:`${i} > Connections`}),b&&T.length===0&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(p.Stack,{children:T.map(M=>t.jsx(wh,{connection:M,mutable:r,isMutating:O,onOpenExplorer:()=>u(M.name??null),onEdit:E=>C.mutateAsync(E),onDelete:E=>S.mutateAsync(E)},M.name))}),t.jsx(p.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:d!==null,onClose:()=>u(null),maxWidth:"lg",title:`Connection explorer: ${d??""}`,showClose:!0,children:d&&t.jsx(tl,{resourceUri:h,connectionName:d,connection:y?.data?.find(M=>M.name===d)})})]})}function wh({connection:e,mutable:n,isMutating:r,onOpenExplorer:o,onEdit:i,onDelete:l}){const[a,d]=j.useState(null),u=!!a,h=b=>{b.stopPropagation(),d(b.currentTarget)},y=()=>d(null);return t.jsx(ss,{icon:t.jsx(Kd,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:vh(e.type),onClick:o,...n?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${e.name??""}`.trim(),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:a,open:u,onClose:y,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(fh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:y}),t.jsx(hh,{connection:e,onCloseDialog:y,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const Sh=c.createSvgIcon([t.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-1 18H5V9h14zm1-13H4V4h16z"},"0"),t.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function kh({resourceUri:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},{environmentName:d,packageName:u}=c.parseResourceUri(e),h=_n({mutationFn:()=>i.packages.deletePackage(d,u),success:"Package deleted",invalidates:[["packages",d]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete package",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:u}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function Ch({package:e,resourceUri:n,onCloseDialog:r}){const[o,i]=j.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},d=()=>{i(!1),r()},{packageName:u,environmentName:h}=c.parseResourceUri(n),y=_n({mutationFn(x){return l.packages.updatePackage(h,u,{name:u,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:d,resource:"package",action:"update"}),b=x=>{x.preventDefault();const k=new FormData(x.currentTarget).get("description")?.toString();y.mutate({description:k})};return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:a,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:o,onClose:d,title:"Edit package",description:`What ${e.name} is, for the people who open it.`,actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:y.isPending,onClick:d,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:y.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:b,id:"package-form",children:t.jsxs(p.Stack,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:e.description,InputLabelProps:{shrink:!0}})]})})}),y.notice]})}function nl({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:o}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:d}=c.useQueryWithApiError({queryKey:["packages",o],queryFn:()=>r.packages.listPackages(o)});if(a)return t.jsx(c.ApiErrorDisplay,{error:d,context:`${o} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const u=[...i.data].sort((h,y)=>h.name.localeCompare(y.name));return t.jsx(p.Stack,{children:u.map(h=>{const y=c.encodeResourceUri({environmentName:o,packageName:h.name});return t.jsx(jh,{pkg:h,packageResourceUri:y,onSelectPackage:e},h.name)})})}function jh({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:o}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=j.useState(null),d=!!l,u=y=>{y.stopPropagation(),a(y.currentTarget)},h=()=>a(null);return t.jsx(ss,{icon:t.jsx(Sh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:y=>r(e.name,y),...o?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:u,"aria-label":`Package actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:l,open:d,onClose:h,onClick:y=>y.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(Ch,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(kh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function Th({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(n),l=c.useQueryWithApiError({queryKey:["packages",i],queryFn:()=>r.packages.listPackages(i)});return j.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(p.Box,{sx:{mb:4},children:[t.jsx(p.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:i}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),t.jsx(_t,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...o?{action:t.jsx(Yd,{resourceUri:n})}:{},children:t.jsx(nl,{onSelectPackage:e,resourceUri:n})}),t.jsx(bh,{resourceUri:n}),t.jsx(Ad,{resourceUri:n})]})}function _i({array1:e,array2:n,parser:r=o=>o}){return e&&n&&e.length===n.length&&e.every((o,i)=>r(o)===r(n[i]))}function Pi(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Oh(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:o,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(d,{inputValue:u,getOptionLabel:h})=>{let y=a?u.trim():u;r&&(y=y.toLowerCase()),n&&(y=Pi(y));const b=y?d.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Pi(v)),i==="start"?v.startsWith(y):v.includes(y)}):d;return typeof o=="number"?b.slice(0,o):b}}const Mh=Oh(),zi=5,Eh=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Ih=[];function Wi(e,n,r,o){if(n||e==null||o)return"";const i=r(e);return typeof i=="string"?i:""}function Dh(e){const{unstable_isActiveElementInListbox:n=Eh,unstable_classNamePrefix:r="Mui",autoComplete:o=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:d=!e.freeSolo,clearOnEscape:u=!1,componentName:h="useAutocomplete",defaultValue:y=e.multiple?Ih:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:k=!1,disableListWrap:C=!1,filterOptions:S=Mh,filterSelectedOptions:T=!1,freeSolo:O=!1,getOptionDisabled:M,getOptionKey:E,getOptionLabel:R=V=>V.label??V,groupBy:P,handleHomeEndKeys:A=!e.freeSolo,id:H,includeInputInList:D=!1,inputValue:L,isOptionEqualToValue:U=(V,B)=>V===B,multiple:$=!1,onChange:W,onClose:Q,onHighlightChange:te,onInputChange:ee,onOpen:G,open:Z,openOnFocus:ae=!1,options:z,readOnly:re=!1,renderValue:se,selectOnFocus:ne=!e.freeSolo,value:Ie}=e,de=c.useId(H);let pe=R;pe=V=>{const B=R(V);return typeof B!="string"?String(B):B};const De=Ce.useRef(!1),Le=Ce.useRef(!0),oe=Ce.useRef(null),K=Ce.useRef(null),[le,be]=Ce.useState(null),[ge,ue]=Ce.useState(-1),ye=i?0:-1,$e=Ce.useRef(ye),ze=Ce.useRef(Wi(y??Ie,$,pe)).current,[me,Y]=c.useControlled({controlled:Ie,default:y,name:h}),[ie,Oe]=c.useControlled({controlled:L,default:ze,name:h,state:"inputValue"}),[Fe,at]=Ce.useState(!1),Me=Ce.useCallback((V,B,ce)=>{if(!($?me.length<B.length:B!==null)&&!d)return;const J=Wi(B,$,pe,se);ie!==J&&(Oe(J),ee&&ee(V,J,ce))},[pe,ie,$,ee,Oe,d,me,se]),[lt,xt]=c.useControlled({controlled:Z,default:!1,name:h,state:"open"}),[vt,Ot]=Ce.useState(!0),pt=!$&&me!=null&&ie===pe(me),Ke=lt&&!re,he=Ke?S(z.filter(V=>!(T&&($?me:[me]).some(B=>B!==null&&U(V,B)))),{inputValue:pt&&vt?"":ie,getOptionLabel:pe}):[],Qe=hd({filteredOptions:he,value:me,inputValue:ie});Ce.useEffect(()=>{const V=me!==Qe.value;Fe&&!V||O&&!V||Me(null,me,"reset")},[me,Me,Fe,Qe.value,O]);const qe=lt&&he.length>0&&!re,ct=c.useEventCallback(V=>{if(V===-1)oe.current.focus();else{const B=se?"data-item-index":"data-tag-index";le.querySelector(`[${B}="${V}"]`).focus()}});Ce.useEffect(()=>{$&&ge>me.length-1&&(ue(-1),ct(-1))},[me,$,ge,ct]);function ut(V,B){if(!K.current||V<0||V>=he.length)return-1;let ce=V;for(;;){const ve=K.current.querySelector(`[data-option-index="${ce}"]`),J=k?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!J)return ce;if(B==="next"?ce=(ce+1)%he.length:ce=(ce-1+he.length)%he.length,ce===V)return-1}}const Ze=c.useEventCallback(({event:V,index:B,reason:ce})=>{if($e.current=B,B===-1?oe.current.removeAttribute("aria-activedescendant"):oe.current.setAttribute("aria-activedescendant",`${de}-option-${B}`),te&&["mouse","keyboard","touch"].includes(ce)&&te(V,B===-1?null:he[B],ce),!K.current)return;const ve=K.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let J=K.current;if(K.current.getAttribute("role")!=="listbox"&&(J=K.current.parentElement.querySelector('[role="listbox"]')),!J)return;if(B===-1){J.scrollTop=0;return}const Ve=K.current.querySelector(`[data-option-index="${B}"]`);if(Ve&&(Ve.classList.add(`${r}-focused`),ce==="keyboard"&&Ve.classList.add(`${r}-focusVisible`),J.scrollHeight>J.clientHeight&&ce!=="mouse"&&ce!=="touch")){const Ge=Ve,Ct=J.clientHeight+J.scrollTop,vn=Ge.offsetTop+Ge.offsetHeight;vn>Ct?J.scrollTop=vn-J.clientHeight:Ge.offsetTop-Ge.offsetHeight*(P?1.3:0)<J.scrollTop&&(J.scrollTop=Ge.offsetTop-Ge.offsetHeight*(P?1.3:0))}}),fe=c.useEventCallback(({event:V,diff:B,direction:ce="next",reason:ve})=>{if(!Ke)return;const Ve=ut((()=>{const Ge=he.length-1;if(B==="reset")return ye;if(B==="start")return 0;if(B==="end")return Ge;const Ct=$e.current+B;return Ct<0?Ct===-1&&D?-1:C&&$e.current!==-1||Math.abs(B)>1?0:Ge:Ct>Ge?Ct===Ge+1&&D?-1:C||Math.abs(B)>1?Ge:0:Ct})(),ce);if(Ze({index:Ve,reason:ve,event:V}),o&&B!=="reset")if(Ve===-1)oe.current.value=ie;else{const Ge=pe(he[Ve]);oe.current.value=Ge,Ge.toLowerCase().indexOf(ie.toLowerCase())===0&&ie.length>0&&oe.current.setSelectionRange(ie.length,Ge.length)}}),Ue=!_i({array1:Qe.filteredOptions,array2:he,parser:pe}),bt=()=>{const V=(B,ce)=>{const ve=B?pe(B):"",J=ce?pe(ce):"";return ve===J};if($e.current!==-1&&!_i({array1:Qe.filteredOptions,array2:he,parser:pe})&&Qe.inputValue===ie&&($?me.length===Qe.value.length&&Qe.value.every((B,ce)=>pe(me[ce])===pe(B)):V(Qe.value,me))){const B=Qe.filteredOptions[$e.current];if(B)return he.findIndex(ce=>pe(ce)===pe(B))}return-1},ke=Ce.useCallback(()=>{if(!Ke)return;const V=bt();if(V!==-1){$e.current=V;return}const B=$?me[0]:me;if(he.length===0||B==null){fe({diff:"reset"});return}if(K.current){if(B!=null){const ce=he[$e.current];if($&&ce&&me.findIndex(J=>U(ce,J))!==-1)return;const ve=he.findIndex(J=>U(J,B));ve===-1?fe({diff:"reset"}):Ze({index:ve});return}if($e.current>=he.length-1){Ze({index:he.length-1});return}Ze({index:$e.current})}},[he.length,$?!1:me,T,fe,Ze,Ke,ie,$]),Ne=c.useEventCallback(V=>{c.setRef(K,V),V&&ke()});Ce.useEffect(()=>{Ue&&ke()},[ke,Ue]);const Ee=V=>{lt||(xt(!0),Ot(!0),G&&G(V))},Be=(V,B)=>{lt&&(xt(!1),Q&&Q(V,B))},ht=(V,B,ce,ve)=>{if($){if(me.length===B.length&&me.every((J,Ve)=>J===B[Ve]))return}else if(me===B)return;W&&W(V,B,ce,ve),Y(B)},We=Ce.useRef(!1),nt=(V,B,ce="selectOption",ve="options")=>{let J=ce,Ve=B;if($){Ve=Array.isArray(me)?me.slice():[];const Ge=Ve.findIndex(Ct=>U(B,Ct));Ge===-1?Ve.push(B):ve!=="freeSolo"&&(Ve.splice(Ge,1),J="removeOption")}Me(V,Ve,J),ht(V,Ve,J,{option:B}),!x&&(!V||!V.ctrlKey&&!V.metaKey)&&Be(V,J),(a===!0||a==="touch"&&We.current||a==="mouse"&&!We.current)&&oe.current.blur()};function Mt(V,B){if(V===-1)return-1;let ce=V;for(;;){if(B==="next"&&ce===me.length||B==="previous"&&ce===-1)return-1;const ve=se?"data-item-index":"data-tag-index",J=le.querySelector(`[${ve}="${ce}"]`);if(!J||!J.hasAttribute("tabindex")||J.disabled||J.getAttribute("aria-disabled")==="true")ce+=B==="next"?1:-1;else return ce}}const kt=(V,B)=>{if(!$)return;ie===""&&Be(V,"toggleInput");let ce=ge;ge===-1?ie===""&&B==="previous"&&(ce=me.length-1):(ce+=B==="next"?1:-1,ce<0&&(ce=0),ce===me.length&&(ce=-1)),ce=Mt(ce,B),ue(ce),ct(ce)},At=V=>{De.current=!0,Oe(""),ee&&ee(V,"","clear"),ht(V,$?[]:null,"clear")},gn=V=>B=>{if(V.onKeyDown&&V.onKeyDown(B),!B.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(B.key)&&(ue(-1),ct(-1)),B.which!==229))switch(B.key){case"Home":Ke&&A&&(B.preventDefault(),fe({diff:"start",direction:"next",reason:"keyboard",event:B}));break;case"End":Ke&&A&&(B.preventDefault(),fe({diff:"end",direction:"previous",reason:"keyboard",event:B}));break;case"PageUp":B.preventDefault(),fe({diff:-zi,direction:"previous",reason:"keyboard",event:B}),Ee(B);break;case"PageDown":B.preventDefault(),fe({diff:zi,direction:"next",reason:"keyboard",event:B}),Ee(B);break;case"ArrowDown":B.preventDefault(),fe({diff:1,direction:"next",reason:"keyboard",event:B}),Ee(B);break;case"ArrowUp":B.preventDefault(),fe({diff:-1,direction:"previous",reason:"keyboard",event:B}),Ee(B);break;case"ArrowLeft":!$&&se?ct(0):kt(B,"previous");break;case"ArrowRight":!$&&se?ct(-1):kt(B,"next");break;case"Enter":if($e.current!==-1&&Ke){const ce=he[$e.current],ve=M?M(ce):!1;if(B.preventDefault(),ve)return;nt(B,ce,"selectOption"),o&&oe.current.setSelectionRange(oe.current.value.length,oe.current.value.length)}else O&&ie!==""&&pt===!1&&($&&B.preventDefault(),nt(B,ie,"createOption","freeSolo"));break;case"Escape":Ke?(B.preventDefault(),B.stopPropagation(),Be(B,"escape")):u&&(ie!==""||$&&me.length>0||se)&&(B.preventDefault(),B.stopPropagation(),At(B));break;case"Backspace":if($&&!re&&ie===""&&me.length>0){const ce=ge===-1?me.length-1:ge,ve=me.slice();ve.splice(ce,1),ht(B,ve,"removeOption",{option:me[ce]})}!$&&se&&!re&&(Y(null),ct(-1));break;case"Delete":if($&&!re&&ie===""&&me.length>0&&ge!==-1){const ce=ge,ve=me.slice();ve.splice(ce,1),ht(B,ve,"removeOption",{option:me[ce]})}!$&&se&&!re&&(Y(null),ct(-1));break}},Pe=V=>{at(!0),ae&&!De.current&&Ee(V)},dt=V=>{if(n(K)){oe.current.focus();return}at(!1),Le.current=!0,De.current=!1,l&&$e.current!==-1&&Ke?nt(V,he[$e.current],"blur"):l&&O&&ie!==""?nt(V,ie,"blur","freeSolo"):d&&Me(V,me,"blur"),Be(V,"blur")},Kt=V=>{const B=V.target.value;ie!==B&&(Oe(B),Ot(!1),ee&&ee(V,B,"input")),B===""?!b&&!$&&ht(V,null,"clear"):Ee(V)},yn=V=>{const B=Number(V.currentTarget.getAttribute("data-option-index"));$e.current!==B&&Ze({event:V,index:B,reason:"mouse"})},ft=V=>{Ze({event:V,index:Number(V.currentTarget.getAttribute("data-option-index")),reason:"touch"}),We.current=!0},en=V=>{const B=Number(V.currentTarget.getAttribute("data-option-index"));nt(V,he[B],"selectOption"),We.current=!1},xn=V=>B=>{const ce=me.slice();ce.splice(V,1),ht(B,ce,"removeOption",{option:me[V]})},Qt=V=>{ht(V,null,"removeOption",{option:me})},Xe=V=>{lt?Be(V,"toggleInput"):Ee(V)},Je=V=>{V.currentTarget.contains(V.target)&&V.target.getAttribute("id")!==de&&V.preventDefault()},Ft=V=>{V.currentTarget.contains(V.target)&&(oe.current.focus(),ne&&Le.current&&oe.current.selectionEnd-oe.current.selectionStart===0&&oe.current.select(),Le.current=!1)},tn=V=>{!v&&(ie===""||!lt)&&Xe(V)};let Zt=O&&ie.length>0;Zt=Zt||($?me.length>0:me!==null);let nn=he;return P&&(nn=he.reduce((V,B,ce)=>{const ve=P(B);return V.length>0&&V[V.length-1].group===ve?V[V.length-1].options.push(B):V.push({key:ce,index:ce,group:ve,options:[B]}),V},[])),v&&Fe&&dt(),{getRootProps:(V={})=>({...V,onKeyDown:gn(V),onMouseDown:Je,onClick:Ft}),getInputLabelProps:()=>({id:`${de}-label`,htmlFor:de}),getInputProps:()=>({id:de,value:ie,onBlur:dt,onFocus:Pe,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ke?"":null,"aria-autocomplete":o?"both":"list","aria-controls":qe?`${de}-listbox`:void 0,"aria-expanded":qe,autoComplete:"off",ref:oe,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:At}),getItemProps:({index:V=0}={})=>({...$&&{key:V},...se?{"data-item-index":V}:{"data-tag-index":V},tabIndex:-1,...!re&&{onDelete:$?xn(V):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Xe}),getTagProps:({index:V})=>({key:V,"data-tag-index":V,tabIndex:-1,...!re&&{onDelete:xn(V)}}),getListboxProps:()=>({role:"listbox",id:`${de}-listbox`,"aria-labelledby":`${de}-label`,ref:Ne,onMouseDown:V=>{V.preventDefault()}}),getOptionProps:({index:V,option:B})=>{const ce=($?me:[me]).some(J=>J!=null&&U(B,J)),ve=M?M(B):!1;return{key:E?.(B)??pe(B),tabIndex:-1,role:"option",id:`${de}-option-${V}`,onMouseMove:yn,onClick:en,onTouchStart:ft,"data-option-index":V,"aria-disabled":ve,"aria-selected":ce}},id:de,inputValue:ie,value:me,dirty:Zt,expanded:Ke&&le,popupOpen:Ke,focused:Fe||ge!==-1,anchorEl:le,setAnchorEl:be,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function $h(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const Ah=e=>{const{classes:n,color:r,disableGutters:o,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!o&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,$h,n)},Fh=c.styled("li",{name:"MuiListSubheader",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.color!=="default"&&n[`color${c.capitalize(r.color)}`],!r.disableGutters&&n.gutters,r.inset&&n.inset,!r.disableSticky&&n.sticky]}})(c.memoTheme(({theme:e})=>({boxSizing:"border-box",lineHeight:"48px",listStyle:"none",color:(e.vars||e).palette.text.secondary,fontFamily:e.typography.fontFamily,fontWeight:e.typography.fontWeightMedium,fontSize:e.typography.pxToRem(14),variants:[{props:{color:"primary"},style:{color:(e.vars||e).palette.primary.main}},{props:{color:"inherit"},style:{color:"inherit"}},{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.inset,style:{paddingLeft:72}},{props:({ownerState:n})=>!n.disableSticky,style:{position:"sticky",top:0,zIndex:1,backgroundColor:(e.vars||e).palette.background.paper}}]}))),Ks=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:d=!1,disableSticky:u=!1,inset:h=!1,...y}=o,b={...o,color:l,component:a,disableGutters:d,disableSticky:u,inset:h},x=Ah(b);return t.jsx(Fh,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...y})});Ks&&(Ks.muiSkipListHighlight=!0);const Rh=c.createSvgIcon(t.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}));function Nh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Te=c.generateUtilityClasses("MuiAutocomplete",["root","expanded","fullWidth","focused","focusVisible","tag","tagSizeSmall","tagSizeMedium","hasPopupIcon","hasClearIcon","inputRoot","input","inputFocused","endAdornment","clearIndicator","popupIndicator","popupIndicatorOpen","popper","popperDisablePortal","paper","listbox","loading","noOptions","option","groupLabel","groupUl"]);var qi,Bi;const Lh=e=>{const{classes:n,disablePortal:r,expanded:o,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:d,inputFocused:u,popupOpen:h,size:y}=e,b={root:["root",o&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",d&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",u&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(y)}`],endAdornment:["endAdornment"],clearIndicator:["clearIndicator"],popupIndicator:["popupIndicator",h&&"popupIndicatorOpen"],popper:["popper",r&&"popperDisablePortal"],paper:["paper"],listbox:["listbox"],loading:["loading"],noOptions:["noOptions"],option:["option"],groupLabel:["groupLabel"],groupUl:["groupUl"]};return c.composeClasses(b,Nh,n)},_h=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:o,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:d}=r;return[{[`& .${Te.tag}`]:n.tag},{[`& .${Te.tag}`]:n[`tagSize${c.capitalize(d)}`]},{[`& .${Te.inputRoot}`]:n.inputRoot},{[`& .${Te.input}`]:n.input},{[`& .${Te.input}`]:a&&n.inputFocused},n.root,o&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Te.focused} .${Te.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Te.clearIndicator}`]:{visibility:"visible"}},[`& .${Te.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Te.inputRoot}`]:{[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:30},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:56},[`& .${Te.input}`]:{width:0,minWidth:30}},[`& .${c.inputClasses.root}`]:{paddingBottom:1,"& .MuiInput-input":{padding:"4px 4px 4px 0px"}},[`& .${c.inputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${c.inputClasses.input}`]:{padding:"2px 4px 3px 0"}},[`& .${c.outlinedInputClasses.root}`]:{padding:9,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${Te.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Te.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingBottom:1,[`& .${c.filledInputClasses.input}`]:{padding:"2.5px 4px"}},[`& .${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:8},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:0,paddingBottom:0,[`& .${Te.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Te.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Te.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Te.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Te.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Te.inputRoot}`]:{flexWrap:"wrap"}}}]}),Ph=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),zh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),Wh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"PopupIndicator",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.popupIndicator,r.popupOpen&&n.popupIndicatorOpen]}})({padding:2,marginRight:-2,variants:[{props:{popupOpen:!0},style:{transform:"rotate(180deg)"}}]}),qh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Te.option}`]:n.option},n.popper,r.disablePortal&&n.popperDisablePortal]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.modal,variants:[{props:{disablePortal:!0},style:{position:"absolute"}}]}))),Bh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Hh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Uh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Te.option}`]:{minHeight:48,display:"flex",overflow:"hidden",justifyContent:"flex-start",alignItems:"center",cursor:"pointer",paddingTop:6,boxSizing:"border-box",outline:"0",WebkitTapHighlightColor:"transparent",paddingBottom:6,paddingLeft:16,paddingRight:16,[e.breakpoints.up("sm")]:{minHeight:"auto"},[`&.${Te.focused}`]:{backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},'&[aria-disabled="true"]':{opacity:(e.vars||e).palette.action.disabledOpacity,pointerEvents:"none"},[`&.${Te.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},'&[aria-selected="true"]':{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${Te.focused}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:(e.vars||e).palette.action.selected}},[`&.${Te.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Gh=c.styled(Ks,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Yh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Te.option}`]:{paddingLeft:24}}),Qs=Ce.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:d=!1,ChipProps:u,className:h,clearIcon:y=qi||(qi=t.jsx(Rh,{fontSize:"small"})),clearOnBlur:b=!o.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:k="Close",componentsProps:C,defaultValue:S=o.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:O=!1,disabled:M=!1,disabledItemsFocusable:E=!1,disableListWrap:R=!1,disablePortal:P=!1,filterOptions:A,filterSelectedOptions:H=!1,forcePopupIcon:D="auto",freeSolo:L=!1,fullWidth:U=!1,getLimitTagsText:$=Ae=>`+${Ae}`,getOptionDisabled:W,getOptionKey:Q,getOptionLabel:te,isOptionEqualToValue:ee,groupBy:G,handleHomeEndKeys:Z=!o.freeSolo,id:ae,includeInputInList:z=!1,inputValue:re,limitTags:se=-1,ListboxComponent:ne,ListboxProps:Ie,loading:de=!1,loadingText:pe="Loading…",multiple:De=!1,noOptionsText:Le="No options",onChange:oe,onClose:K,onHighlightChange:le,onInputChange:be,onOpen:ge,open:ue,openOnFocus:ye=!1,openText:$e="Open",options:ze,PaperComponent:me,PopperComponent:Y,popupIcon:ie=Bi||(Bi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Oe=!1,renderGroup:Fe,renderInput:at,renderOption:Me,renderTags:lt,renderValue:xt,selectOnFocus:vt=!o.freeSolo,size:Ot="medium",slots:pt={},slotProps:Ke={},value:he,...Qe}=o,{getRootProps:qe,getInputProps:ct,getInputLabelProps:ut,getPopupIndicatorProps:Ze,getClearProps:fe,getItemProps:Ue,getListboxProps:bt,getOptionProps:ke,value:Ne,dirty:Ee,expanded:Be,id:ht,popupOpen:We,focused:nt,focusedItem:Mt,anchorEl:kt,setAnchorEl:At,inputValue:gn,groupedOptions:Pe}=Dh({...o,componentName:"Autocomplete"}),dt=!T&&!M&&Ee&&!Oe,Kt=(!L||D===!0)&&D!==!1,{onMouseDown:yn}=ct(),{ref:ft,...en}=bt(),Qt=te||(Ae=>Ae.label??Ae),Xe={...o,disablePortal:P,expanded:Be,focused:nt,fullWidth:U,getOptionLabel:Qt,hasClearIcon:dt,hasPopupIcon:Kt,inputFocused:Mt===-1,popupOpen:We,size:Ot},Je=Lh(Xe),Ft={slots:{paper:me,popper:Y,...pt},slotProps:{chip:u,listbox:Ie,...C,...Ke}},[tn,Zt]=c.useSlot("listbox",{elementType:Uh,externalForwardedProps:Ft,ownerState:Xe,className:Je.listbox,additionalProps:en,ref:ft}),[nn,V]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:Ft,ownerState:Xe,className:Je.paper}),[B,ce]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:Ft,ownerState:Xe,className:Je.popper,additionalProps:{disablePortal:P,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:We}});let ve;const J=Ae=>({className:Je.tag,disabled:M,...Ue(Ae)});if(De?Ne.length>0&&(lt?ve=lt(Ne,J,Xe):xt?ve=xt(Ne,J,Xe):ve=Ne.map((Ae,zt)=>{const{key:gt,...qt}=J({index:zt});return t.jsx(c.Chip,{label:Qt(Ae),size:Ot,...qt,...Ft.slotProps.chip},gt)})):xt&&Ne!=null&&(ve=xt(Ne,J,Xe)),se>-1&&Array.isArray(ve)){const Ae=ve.length-se;!nt&&Ae>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Je.tag,children:$(Ae)},ve.length)))}const Ge=Fe||(Ae=>t.jsxs("li",{children:[t.jsx(Gh,{className:Je.groupLabel,ownerState:Xe,component:"div",children:Ae.group}),t.jsx(Yh,{className:Je.groupUl,ownerState:Xe,children:Ae.children})]},Ae.key)),vn=Me||((Ae,zt)=>{const{key:gt,...qt}=Ae;return t.jsx("li",{...qt,children:Qt(zt)},gt)}),zn=(Ae,zt)=>{const gt=ke({option:Ae,index:zt});return vn({...gt,className:Je.option},Ae,{selected:gt["aria-selected"],index:zt,inputValue:gn},Xe)},Wn=Ft.slotProps.clearIndicator,Dr=Ft.slotProps.popupIndicator;return t.jsxs(Ce.Fragment,{children:[t.jsx(_h,{ref:r,className:c.clsx(Je.root,h),ownerState:Xe,...qe(Qe),children:at({id:ht,disabled:M,fullWidth:!0,size:Ot==="small"?"small":void 0,InputLabelProps:ut(),InputProps:{ref:At,className:Je.inputRoot,startAdornment:ve,onMouseDown:Ae=>{Ae.target===Ae.currentTarget&&yn(Ae)},...(dt||Kt)&&{endAdornment:t.jsxs(Ph,{className:Je.endAdornment,ownerState:Xe,children:[dt?t.jsx(zh,{...fe(),"aria-label":v,title:v,ownerState:Xe,...Wn,className:c.clsx(Je.clearIndicator,Wn?.className),children:y}):null,Kt?t.jsx(Wh,{...Ze(),disabled:M,"aria-label":We?k:$e,title:We?k:$e,ownerState:Xe,...Dr,className:c.clsx(Je.popupIndicator,Dr?.className),children:ie}):null]})}},inputProps:{className:Je.input,disabled:M,readOnly:Oe,...ct()}})}),kt?t.jsx(qh,{as:B,...ce,children:t.jsxs(Bh,{as:nn,...V,children:[de&&Pe.length===0?t.jsx(Vh,{className:Je.loading,ownerState:Xe,children:pe}):null,Pe.length===0&&!L&&!de?t.jsx(Hh,{className:Je.noOptions,ownerState:Xe,role:"presentation",onMouseDown:Ae=>{Ae.preventDefault()},children:Le}):null,Pe.length>0?t.jsx(tn,{as:ne,...Zt,children:Pe.map((Ae,zt)=>G?Ge({key:Ae.key,group:Ae.group,children:Ae.options.map((gt,qt)=>zn(gt,Ae.index+qt))}):zn(Ae,zt))}):null]})}):null]})});c.dayjs.extend(c.utc);function Os(e){switch(e){case"Star":return["Equals","Contains"];case"MinMax":return["Equals","Less Than","Greater Than","Between"];case"DateMinMax":return["Equals","Before","After","Between"];case"Retrieval":return["Semantic Search"];case"Boolean":return["Equals"];case"NONE":default:return[]}}function Kh(e){return e==="DateMinMax"}function Ms(e){return e==="Between"}function Qh({spec:e,values:n,selection:r,onChange:o,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Os(e.filterType)[0]||"Equals",[a,d]=j.useState(l()),[u,h]=j.useState(r?.value??""),[y,b]=j.useState(r?.value2??""),[x,v]=j.useState([]),[k,C]=j.useState(!1),[S,T]=j.useState(""),[O,M]=j.useState(!1),[E,R]=j.useState(!1),P=j.useRef(null),A=j.useRef(0),[H,D]=j.useState(!1);j.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),M(!1);return}return P.current&&clearTimeout(P.current),P.current=setTimeout(async()=>{A.current+=1;const re=A.current;C(!0);try{const se=await i(z,e);re===A.current&&v(se)}catch(se){re===A.current&&(console.error("Retrieval failed",se),v([]))}finally{re===A.current&&(C(!1),M(!0))}},500),()=>{P.current&&clearTimeout(P.current)}},[S,e,i]),j.useEffect(()=>{r===null?(h(""),b(""),d(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Os(e.filterType)[0]||"Equals"))):r&&(d(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const L=Os(e.filterType),U=Kh(e.filterType),$=Ms(a),W=U&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,Q=U&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,te=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,ee=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(L.length===0)return null;const G=z=>{const re=z.target.value;d(re),Ms(re)||b(""),u&&o({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:re,value:u,...Ms(re)&&y&&{value2:y}})},Z=(z,re)=>{h(z??""),re!==void 0&&b(re??"");const se=Array.isArray(z)&&z.length===0;o(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...$&&re&&{value2:re}}:null)},ae=()=>{h(""),b(""),o(null)};return t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1.5,fontSize:"0.75rem","& .MuiInputBase-root":{fontSize:"0.75rem"},"& .MuiInputBase-input":{padding:"6px 10px"},"& .MuiSelect-select":{padding:"6px 10px !important"},"& .MuiAutocomplete-input":{padding:"0 !important"},"& .MuiAutocomplete-root .MuiInputBase-root":{padding:"5px 10px",minHeight:"29.5px",boxSizing:"border-box",flexWrap:"wrap"},"& .MuiChip-root":{height:"16px",margin:"0 2px 0 0"},"& .MuiChip-label":{fontSize:"0.7rem",padding:"0 6px"},"& .MuiChip-deleteIcon":{fontSize:"14px",margin:"0 2px 0 -4px"},"& .MuiInputLabel-root":{fontSize:"0.75rem",transform:"translate(10px, 6px) scale(1)"},"& .MuiInputLabel-shrink":{fontSize:"0.85rem",transform:"translate(14px, -9px) scale(0.75)"},"& .MuiOutlinedInput-notchedOutline legend":{fontSize:"0.65rem"},"& .MuiFormHelperText-root":{fontSize:"0.65rem",marginTop:"2px"},"& .MuiSvgIcon-root":{fontSize:"1.25rem"}},children:[t.jsxs(Ye,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ye,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&L.length>1&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Match Type"}),t.jsx(c.Select,{value:a,label:"Match Type",onChange:G,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:L.map(z=>t.jsx(tt,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Qs,{multiple:!0,size:"small",options:n,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(u)?u.map(z=>n.find(re=>re.value===z)||z):u?[n.find(z=>z.value===u)||u]:[],onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);Z(se)},noOptionsText:"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!e.values||e.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="Star"&&a==="Contains"&&t.jsx(c.TextField,{size:"small",label:"Search Text",value:u,onChange:z=>h(z.target.value),onBlur:()=>Z(u),onKeyDown:z=>{z.key==="Enter"&&Z(u)},placeholder:"Enter text to search...",fullWidth:!0}),e.filterType==="Boolean"&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Value"}),t.jsxs(c.Select,{value:u===!0?"true":u===!1?"false":"",label:"Value",onChange:z=>{const re=z.target.value;re==="true"?Z(!0):re==="false"?Z(!1):ae()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(tt,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(tt,{value:"true",children:"True"}),t.jsx(tt,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Qs,{multiple:!0,size:"small",options:x,loading:k,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(u)?u.map(z=>x.find(se=>se.value===z)||{value:z}):u?[{value:u}]:[],onInputChange:(z,re)=>{T(re)},onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);Z(se)},noOptionsText:S.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>R(!0),onBlur:()=>R(!1),helperText:E&&!k&&O&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[k?t.jsx(c.CircularProgress,{color:"inherit",size:20}):null,z.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:z=>z,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="MinMax"&&!$&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:u,onChange:z=>Z(parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:te,max:ee},helperText:H&&te!==void 0&&ee!==void 0?`Valid range: [${te} - ${ee}]`:void 0}),e.filterType==="MinMax"&&$&&t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:u,onChange:z=>Z(parseFloat(z.target.value)||"",y),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:te,max:y||ee}}),t.jsx(Ye,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:y,onChange:z=>Z(u,parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:u||te,max:ee}})]}),H&&te!==void 0&&ee!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",te," - ",ee,"]"]})]}),U&&!$&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Z(null):z.isValid()&&Z(z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:u instanceof Date?void 0:Q,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>D(!0),onBlur:()=>D(!1),helperText:H&&W&&Q?`Valid range: [${W.format("YYYY-MM-DD")} - ${Q.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),U&&$&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Z(null,y):z.isValid()&&Z(z.utc().toDate(),y)},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:y instanceof Date?c.dayjs.utc(y):u instanceof Date?void 0:Q,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ye,{children:"to"}),t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:y instanceof Date?c.dayjs.utc(y):null,onChange:z=>{z===null?Z(u,null):z.isValid()&&Z(u,z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?c.dayjs.utc(u):y instanceof Date?void 0:W,maxDate:y instanceof Date?void 0:Q,referenceDate:u instanceof Date?c.dayjs.utc(u):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),H&&W&&Q&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",Q.format("YYYY-MM-DD"),"]"]})]})})]})}function is(e,n){const{matchType:r,value:o,value2:i}=n;if(Array.isArray(o))return r!=="Equals"&&r!=="Semantic Search"||o.length===0?"":`(${o.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(o)}`;case"Contains":if(typeof o=="string"){const l=ed.StringFilterExpression.unparse({operator:"contains",values:[o]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(o)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(o)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(o)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(o)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(o)}`;default:return""}}function Zh(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const o of r)"kind"in o&&o.kind==="join"&&o.name&&n.add(o.name);return n}function Xh(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const o=JSON.parse(r);if(Array.isArray(o)){const i=[];for(const l of o)if(typeof l=="string"){const a=l.indexOf(".");a>0&&a<l.length-1&&i.push({source:l.substring(0,a),dimension:l.substring(a+1)})}if(i.length>0)return{filters:i}}}catch(o){console.error(`Failed to parse "${n}" annotation:`,o)}}return null}function rl(e){if(e.startsWith("#(filter)")){const n=e.slice(9).trim();try{const r=JSON.parse(n);if(r.type)return r}catch(r){console.error(`Failed to parse "${e}" annotation:`,r)}}return null}function Jh(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function ef(e){const n=new Map;let r="";for(const o of e)if(o.type==="code"){if(!r&&o.text){const l=o.text.split(`
4
- `).map(a=>a.trim()).find(a=>a.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);l&&(r=l[1])}if(o.newSources&&o.newSources.length>0)for(const i of o.newSources)try{const l=JSON.parse(i);l.name&&n.set(l.name,l)}catch(l){console.error("Failed to parse SourceInfo:",l)}}return{sourceInfoMap:n,modelPath:r}}function tf(e,n,r){const o=[];for(const{source:i,dimension:l}of n){const a=e.get(i);if(!a){console.warn(`Source "${i}" not found in notebook sources`),o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const d=a.schema?.fields;if(!d){o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const u=d.find(b=>b.name===l);if(!u){console.warn(`Dimension "${l}" not found in source "${i}"`),o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}let h="Star",y;if("annotations"in u&&u.annotations){for(const b of u.annotations)if(b.value){const x=rl(b.value);x&&(h=x.type);const v=Jh(b.value);v&&(y=v)}}o.push({source:i,model:r,dimensionName:l,filterType:h,label:y})}return o}function nf(e,n,r){return e.length===0?"":e.map(i=>{const{dimensionName:l,source:a}=i,u=a&&a!==r?`\`${a}\`.\`${l}\``:`\`${l}\``;return is(u,i)}).filter(i=>i.length>0).join(" and ")}function rf(e){const n=e.match(/run\s*:\s*(\w+)\s*->/);if(n)return n[1];const r=e.match(/^\s*(\w+)\s*->/m);return r?r[1]:null}function sf(e,n){return`${e.trimEnd()} + {where: ${n}}`}const of=c.createSvgIcon(t.jsx("path",{d:"m9.17 6 2 2H20v10H4V6zM10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"})),sl=e=>{if(!e)return"Explore semantic models, run queries, and build reports";const n=e.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),o=n.split(/\n\s*\n/)[1]||n;if(o.length<=120)return o;const i=o.substring(0,120).split(" ");return i.pop(),i.join(" ")+"..."},ol=(e,n)=>{const r=(e.readme||void 0)?.split(`
3
+ `}function gd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function yd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const ji="Download the rows behind this value as CSV, up to the server's row limit",xd=4e4;function vd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=r,o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),xd)}function bd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ha({query:e,preamble:n,environmentName:r,packageName:o,modelPath:i,versionId:l,givens:a,fileName:u}){const{apiClients:d}=q.useServer(),[h,y]=j.useState(!1),[b,x]=j.useState(ji),[v,k]=j.useState(void 0),C=j.useRef(void 0);j.useEffect(()=>()=>C.current?.abort(),[]);const S=async()=>{C.current?.abort();const T=new AbortController;C.current=T,y(!0),k(void 0);try{const O=await d.models.executeQueryModel(r,o,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,void 0,{signal:T.signal});if(T.signal.aborted)return;const M=O.data,E=JSON.parse(M.result??"{}"),R=yd(Va(E).length,M.queryRowLimit,M.queryRowLimitSource);x(R===void 0?ji:`First ${R} rows: the server's row limit, so there may be more`),vd(pd(E),R===void 0?`${u}.csv`:`${u}_first_${R}_rows_server_limit.csv`)}catch(O){if(T.signal.aborted)return;k(`Download failed: ${bd(O)}`)}finally{C.current===T&&(C.current=void 0,y(!1))}};return t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[v&&t.jsx(p.Typography,{role:"alert",variant:"caption",color:"error",sx:{maxWidth:320},children:v}),t.jsx(p.Tooltip,{title:b,children:t.jsx("span",{children:t.jsx(p.Button,{size:"small",startIcon:t.jsx(fd,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ua=200;function wd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function Ti(e,n=Ua){const r=kd(e);if(r===void 0)return;const o=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=Sd(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${o}; select: *${l} }`}function Sd(e){return so.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function Cs(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function kd(e){if(e.dimensions){const r=[];for(const{code:o,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${Cs(o)} is null`);continue}const l=La(i,e.timezone);if(l===void 0)return;r.push(`${Cs(o)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${Cs(e.code)} = ${n}`]:void 0}const Cd="This value cannot be written as a filter, so its rows cannot be fetched.";function Oi(e){const n=e.drillClauses?Ra(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function jd({request:e,environmentName:n,packageName:r,versionId:o,modelPath:i,preamble:l,givens:a,onClose:u,onDone:d,actions:h}){const{theme:y}=q.usePublisherTheme(),b=e?Ti(e):void 0,x=e?Ti(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},givens:a,fileName:gd(e.target.source,Oi(e).map(k=>k.label))}:void 0;return t.jsxs(p.Dialog,{open:e!==void 0,onClose:u,maxWidth:"lg",fullWidth:!0,children:[t.jsxs(p.DialogTitle,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",pb:.5},children:[t.jsxs(p.Box,{children:[e?t.jsxs(t.Fragment,{children:["Rows where"," ",Oi(e).map((k,C)=>t.jsxs(j.Fragment,{children:[C>0&&" and ",t.jsx(p.Box,{component:"code",sx:{fontSize:"0.9em"},children:k.field})," ","is ",k.label]},C))]}):"Rows",t.jsx(p.Typography,{component:"div",variant:"caption",sx:{color:y.tileTitle,mt:.25},children:e?`The first ${Ua} rows of ${e.target.source} behind this value, with the tile's own filters and the controls applied.`:""})]}),t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1,ml:1},children:[v&&(h?h(v):t.jsx(Ha,{...v})),t.jsx(p.IconButton,{onClick:u,"aria-label":"Close",size:"small",sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]})]}),t.jsxs(p.DialogContent,{dividers:!0,sx:{p:0,minHeight:240},children:[b===void 0&&e&&t.jsx(p.Typography,{variant:"body2",sx:{p:2},children:Cd}),b!==void 0&&t.jsx(Td,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:i,givens:a,...d?{onDone:d}:{}})]}),t.jsxs(p.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(p.Typography,{variant:"caption",sx:{mr:"auto",color:y.tileTitle,fontFamily:y.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(p.Button,{onClick:u,children:"Close"})]})]})}function Td({query:e,environmentName:n,packageName:r,versionId:o,modelPath:i,givens:l,onDone:a}){const u=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},query:e,givens:l}),{isSuccess:d,isError:h}=u,y=j.useRef(void 0);return j.useEffect(()=>{y.current=c.now()},[e]),j.useEffect(()=>{y.current===void 0||!d&&!h||(a?.(d,c.now()-y.current),y.current=void 0)},[d,h,a]),t.jsx(p.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:u,context:e})})}function Ga({manifest:e,environmentName:n,packageName:r,versionId:o,documentName:i,givens:l,onGivensChange:a,onNavigate:u,height:d,maxResultSize:h,controlsLayout:y="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:k,onLinkNavigate:C,actions:S,rowsActions:T}){const O=j.useMemo(()=>C?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:C}:void 0,[n,r,e.path,i,C]),M=j.useMemo(()=>(e.givens??[]).filter(te=>!(b!==void 0&&te.secure===!0)&&!(te.name!==void 0&&v?.includes(te.name))),[e,v,b]),E=j.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,te])=>typeof te=="string")),[l]),R=c.useDocumentControls({specs:M,loaded:!0,startingValues:e.startingGivens,params:E,onGivensChange:a,documentKey:`${n}/${r}/${o??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:o,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:P,declaredTypes:F,canSelf:B,onSelf:D}=R,_=c.useReportEvents(),V=j.useMemo(()=>{const te=new Set((e.tiles??[]).flatMap(K=>K.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([K])=>te.has(K)&&!F.has(K)))},[e,l,F]),[$,W]=j.useState(void 0),Z=j.useCallback(te=>{const K=wd(te);K!==void 0&&W(K)},[]),ne=j.useMemo(()=>c.withHostGivens(c.givensToRequest(P,F),V),[P,F,V]),{reports:J}=c.useReportListing(n,r,o,u!==void 0),H=j.useCallback(te=>{const K=c.resolveDrillTarget(te,J);if(K.kind!=="path")return;const he=K.report.path;return J.find(we=>we.path===he)?.title||void 0},[J]),{bindingFor:Q,drillMenu:re}=oo({onNavigate:u,onSelf:D,canSelf:B,onRows:Z,destinationTitle:H}),z=j.useCallback((te,K)=>Q(te,K!==!0),[Q]),{columns:oe,layout:se,tileMaxHeight:ie,tableMaxHeight:De}=c.layoutRules(e.layout,e.dashboardColumns),de=j.useMemo(()=>c.missingRequiredGivens(M,P,l),[M,P,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Mi,{manifest:e,links:O,actions:S}),children:t.jsx(p.Alert,{severity:"error",children:e.error})});const ue=x??e.path,be=e.tiles??[],Me=c.isPlaced(be);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Mi,{manifest:e,links:O,actions:S}),controls:M.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...R.panel,layout:y})}):void 0,children:[de.length>0&&t.jsx(p.Alert,{severity:"info",children:c.requiredPrompt(de)}),ue===void 0?t.jsx(p.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):be.length>0?t.jsx(c.DashboardGrid,{tiles:be,columns:oe,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(te,K)=>`${K}:${te.kind==="text"?`text:${te.name}`:te.query}`,renderTile:(te,K)=>te.kind==="text"||te.query===void 0?t.jsx(p.Box,{sx:te.rowspan!==void 0||Me?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Od,{markdown:te.markdown??"",links:O})}):t.jsx(c.DashboardTile,{index:K,environmentName:n,packageName:r,versionId:o,modelPath:ue,tile:te.query,label:te.label,subtitle:te.subtitle,borderless:te.borderless,givens:P,hostGivens:V,declaredTypes:F,givenNames:te.givenNames,height:te.rowspan!==void 0||Me?c.tileHeightPx(te.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?d??ie:ie,tableMaxHeight:De,fixedHeight:te.rowspan!==void 0||Me,maxResultSize:h,drill:z(te.query,te.restricted),ignoredFilters:c.tileIgnoredFilterLabels(te.givenNames&&(te.query&&k?.[te.query]?[...te.givenNames,...k[te.query]]:te.givenNames),M),...b!==void 0?{preamble:b,restricted:te.restricted}:{},...(()=>{const he=c.waitingOn(de,te.givenNames);return he.length>0?{waitingFor:c.waitingText(he)}:{}})()})}):t.jsx(p.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),re,ue!==void 0&&t.jsx(jd,{request:$,environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:ue,...b===void 0?{}:{preamble:b},givens:ne,...T===void 0?{}:{actions:T},onClose:()=>W(void 0),onDone:(te,K)=>{$&&_.emit({type:"report.rows_shown",source:$.target.source,view:$.target.queryName??"",field:$.field,ok:te,durationMs:K})}})]})}function Od({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Mi({manifest:e,links:n,actions:r}){return t.jsx(c.ReportHeader,{title:e.title??e.name,actions:r,description:e.description?t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e.description})}):void 0})}const Ya=c.createSvgIcon(t.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"})),Md="publisher:resize";function Ed(e){return typeof e=="object"&&e!==null&&e.type===Md&&typeof e.height=="number"}function Ka(e){return e.replace(/\/api\/v0\/?$/,"")}function Qa({server:e,environmentName:n,packageName:r,path:o,versionId:i}){const l=o.startsWith("public/")?o.slice(7):o,a=`${Ka(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Id(e){try{const{environmentName:n,packageName:r,modelPath:o,versionId:i}=c.parseResourceUri(e);return!n||!r||!o?null:{environmentName:n,packageName:r,dataAppPath:o,versionId:i}}catch{return null}}function Dd({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),o=Id(e),i=o?.environmentName??"",l=o?.packageName??"",a=o?.dataAppPath??"",u=o?.versionId,d=j.useMemo(()=>Qa({server:n,environmentName:i,packageName:l,path:a,...u!==void 0?{versionId:u}:{}}),[n,i,l,a,u]),y=c.useQueryWithApiError({queryKey:["data-apps",i,l,u],queryFn:()=>r.dataApps.listDataApps(i,l,u),enabled:!!o}).data?.data?.find(S=>S.path===a),b=y?.title??a,x=y?.fit==="viewport",v=j.useRef(null),[k,C]=j.useState(120);return j.useEffect(()=>{if(x)return;function S(T){Ed(T.data)&&T.source===v.current?.contentWindow&&T.data.height>0&&C(Math.ceil(T.data.height))}return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[x]),o?t.jsxs(p.Box,{sx:{p:3,...x?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1600,mx:"auto"}},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[t.jsx(p.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium",letterSpacing:"-0.025em"},children:b}),t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a}),t.jsx(p.Box,{sx:{flex:1}}),t.jsx(p.Tooltip,{title:"Open standalone in new tab",children:t.jsx(p.IconButton,{size:"small",href:d,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})]}),t.jsx(p.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...x?{flex:1,minHeight:0}:{}},children:t.jsx("iframe",{ref:v,src:d,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:x?"100%":k,border:0}})})]}):t.jsxs(p.Box,{sx:{p:3,maxWidth:1600,mx:"auto"},children:[t.jsx(p.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium"},children:"Can't open data app"}),t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",t.jsx(p.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,ml:1},children:e})]})]})}function Nt({title:e,count:n,description:r,action:o,children:i}){const l=j.useId();return t.jsxs(p.Box,{component:"section","aria-labelledby":l,sx:{mb:4},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:r?0:1,minHeight:40},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[t.jsx(p.Typography,{id:l,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:e}),n!==void 0&&t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",children:["(",n,")"]})]}),o]}),r&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(p.Box,{children:i})]})}function $d({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[o,i]=j.useState(!1),l=90,{data:a,isSuccess:u,isError:d,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),y=a?.data?.readme||"",b=y.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!u&&!d&&t.jsx(c.Loading,{text:"Fetching About..."}),u&&y&&t.jsxs(Nt,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:o||!x?y:v}),x&&t.jsx(p.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:o?"Read less":"Read more",onClick:()=>i(!o)})})]}),d&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Fd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:o,open:i,resumeHideDuration:l}=e,a=c.useTimeout();je.useEffect(()=>{if(!i)return;function T(O){O.defaultPrevented||O.key==="Escape"&&o?.(O,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[i,o]);const u=c.useEventCallback((T,O)=>{o?.(T,O)}),d=c.useEventCallback(T=>{!o||T==null||a.start(T,()=>{u(null,"timeout")})});je.useEffect(()=>(i&&d(n),a.clear),[i,n,d,a]);const h=T=>{o?.(T,"clickaway")},y=a.clear,b=je.useCallback(()=>{n!=null&&d(l??n*.5)},[n,l,d]),x=T=>O=>{const M=T.onBlur;M?.(O),b()},v=T=>O=>{const M=T.onFocus;M?.(O),y()},k=T=>O=>{const M=T.onMouseEnter;M?.(O),y()},C=T=>O=>{const M=T.onMouseLeave;M?.(O),b()};return je.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",y),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",y)}},[r,i,b,y]),{getRootProps:(T={})=>{const O={...c.extractEventHandlers(e),...c.extractEventHandlers(T)};return{role:"presentation",...T,...O,onBlur:x(O),onFocus:v(O),onMouseEnter:k(O),onMouseLeave:C(O)}},onClickAway:h}}function Ei(e){return e.substring(2).toLowerCase()}function Ad(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Rd(e){const{children:n,disableReactTree:r=!1,mouseEvent:o="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=je.useRef(!1),u=je.useRef(null),d=je.useRef(!1),h=je.useRef(!1);je.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const y=c.useForkRef(c.getReactElementRef(n),u),b=c.useEventCallback(k=>{const C=h.current;h.current=!1;const S=c.ownerDocument(u.current);if(!d.current||!u.current||"clientX"in k&&Ad(k,S))return;if(a.current){a.current=!1;return}let T;k.composedPath?T=k.composedPath().includes(u.current):T=!S.documentElement.contains(k.target)||u.current.contains(k.target),!T&&(r||!C)&&i(k)}),x=k=>C=>{h.current=!0;const S=n.props[k];S&&S(C)},v={ref:y};return l!==!1&&(v[l]=x(l)),je.useEffect(()=>{if(l!==!1){const k=Ei(l),C=c.ownerDocument(u.current),S=()=>{a.current=!0};return C.addEventListener(k,b),C.addEventListener("touchmove",S),()=>{C.removeEventListener(k,b),C.removeEventListener("touchmove",S)}}},[b,l]),o!==!1&&(v[o]=x(o)),je.useEffect(()=>{if(o!==!1){const k=Ei(o),C=c.ownerDocument(u.current);return C.addEventListener(k,b),()=>{C.removeEventListener(k,b)}}},[b,o]),je.cloneElement(n,v)}function Ld(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const _d=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,Ld,n)},Nd=c.styled(c.Paper,{name:"MuiSnackbarContent",slot:"Root"})(c.memoTheme(({theme:e})=>{const n=e.palette.mode==="light"?.8:.98;return{...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(c.emphasize(e.palette.background.default,n)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:c.emphasize(e.palette.background.default,n),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),Pd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),zd=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Wd=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:u="alert",...d}=o,h=o,y=_d(h);return t.jsxs(Nd,{role:u,elevation:6,className:c.clsx(y.root,l),ownerState:h,ref:r,...d,children:[t.jsx(Pd,{className:y.message,ownerState:h,children:a}),i?t.jsx(zd,{className:y.action,ownerState:h,children:i}):null]})});function qd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Bd=e=>{const{classes:n,anchorOrigin:r}=e,o={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(o,qd,n)},Vd=c.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,n[`anchorOrigin${c.capitalize(r.anchorOrigin.vertical)}${c.capitalize(r.anchorOrigin.horizontal)}`]]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:n})=>n.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:n})=>n.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Hd=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:u,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:y,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:k=!1,message:C,onBlur:S,onClose:T,onFocus:O,onMouseEnter:M,onMouseLeave:E,open:R,resumeHideDuration:P,slots:F={},slotProps:B={},TransitionComponent:D,transitionDuration:_=l,TransitionProps:{onEnter:V,onExited:$,...W}={},...Z}=o,ne={...o,anchorOrigin:{vertical:u,horizontal:d},autoHideDuration:h,disableWindowBlurListener:k,TransitionComponent:D,transitionDuration:_},J=Bd(ne),{getRootProps:H,onClickAway:Q}=Fd({...ne}),[re,z]=je.useState(!0),oe=ge=>{z(!0),$&&$(ge)},se=(ge,pe)=>{z(!1),V&&V(ge,pe)},ie={slots:{transition:D,...F},slotProps:{content:v,clickAwayListener:x,transition:W,...B}},[De,de]=c.useSlot("root",{ref:r,className:[J.root,b],elementType:Vd,getSlotProps:H,externalForwardedProps:{...ie,...Z},ownerState:ne}),[ue,{ownerState:be,...Me}]=c.useSlot("clickAwayListener",{elementType:Rd,externalForwardedProps:ie,getSlotProps:ge=>({onClickAway:(...pe)=>{const ye=pe[0];ge.onClickAway?.(...pe),!ye?.defaultMuiPrevented&&Q(...pe)}}),ownerState:ne}),[te,K]=c.useSlot("content",{elementType:Wd,shouldForwardComponentProp:!0,externalForwardedProps:ie,additionalProps:{message:C,action:a},ownerState:ne}),[he,we]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ie,getSlotProps:ge=>({onEnter:(...pe)=>{ge.onEnter?.(...pe),se(...pe)},onExited:(...pe)=>{ge.onExited?.(...pe),oe(...pe)}}),additionalProps:{appear:!0,in:R,timeout:_,direction:u==="top"?"down":"up"},ownerState:ne});return!R&&re?null:t.jsx(ue,{...Me,...F.clickAwayListener&&{ownerState:be},children:t.jsx(De,{...de,children:t.jsx(he,{...we,children:y||t.jsx(te,{...K})})})})});let Us;function Ud(e){Us=e}function Ii(e){if(Us)try{Us(e)}catch{}}function Ht(e,n,r){return(async o=>{const i=Date.now();try{const l=await r(o);return Ii({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw Ii({type:"console.mutation",resource:e,action:n,ok:!1,durationMs:Date.now()-i,reason:l instanceof Error?l.message:"An unknown error occurred"}),l}})}function Nn({mutationFn:e,success:n,invalidates:r,closeDialog:o,resource:i,action:l}){const a=mt.useQueryClient(),[u,d]=j.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){o();for(const y of r)a.invalidateQueries({queryKey:y});d(n)},onError(y){d(y instanceof Error?y.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Hd,{open:u!=="",autoHideDuration:6e3,onClose:()=>d(""),message:u})}}const Za="https://docs.malloydata.dev/documentation",js=`${Za}/user_guides/publishing`,In="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${Za}/`,publishing:`${js}/publishing`,explorer:`${js}/explorer`,mcpAgents:`${js}/mcp_agents`,surfaces:`${In}/choosing-a-surface.md`,dashboards:`${In}/dashboards.md`,dataApps:`${In}/html-data-apps.md`,givens:`${In}/givens.md`,materialization:`${In}/materialization.md`,connections:`${In}/connections.md`};function Gd({resourceUri:e}){const[n,r]=j.useState(!1),{apiClients:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=Nn({mutationFn(u){return o.packages.createPackage(i,{name:u.name,description:u.description,location:u.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=u=>{u.preventDefault();const d=new FormData(u.currentTarget),h=d.get("name")?.toString(),y=d.get("description")?.toString(),b=d.get("location")?.toString();l.mutate({name:h,description:y,location:b})};return t.jsxs(t.Fragment,{children:[t.jsx(c.AddButton,{label:"Package",onClick:()=>r(!0)}),t.jsx(c.AppDialog,{open:n,onClose:()=>r(!1),title:"New package",description:t.jsxs(t.Fragment,{children:["A package is a directory of Malloy models and their data. Give its location as a GitHub, S3 or GCS URL, or an absolute path the server can read; see the"," ",t.jsx(p.Box,{component:"a",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{disabled:l.isPending,onClick:()=>r(!1),children:"Cancel"}),t.jsx(p.Button,{type:"submit",form:"package-form",variant:"contained",loading:l.isPending,children:"Create package"})]}),children:t.jsx("form",{onSubmit:a,id:"package-form",children:t.jsxs(p.Stack,{sx:{gap:2},children:[t.jsx(p.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(p.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(p.TextField,{id:"location",name:"location",label:"Location",type:"text",placeholder:"e.g. s3://my-bucket/my-package.zip",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),l.notice]})}const Yd=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function rs({icon:e,tint:n,label:r,mono:o,description:i,rightLabel:l,trailingAction:a,onClick:u,ariaLabel:d}){const h=!!u,y=b=>{u&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u(b))};return t.jsxs(p.Box,{onClick:u,onKeyDown:h?y:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":d,sx:b=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:h?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":h?{backgroundColor:b.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":h?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[t.jsx(p.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:n,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e}),t.jsxs(p.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[t.jsx(p.Typography,{variant:"body2",sx:{...o?{fontFamily:q.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),i&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),l&&t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:l}),a&&t.jsx(p.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:a})]})}const Xa=c.createSvgIcon(t.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"})),Kd=c.generateUtilityClasses("MuiBox",["root"]),Qd=c.createTheme(),Ge=wr.createBox({themeId:c.THEME_ID,defaultTheme:Qd,defaultClassName:Kd.root,generateClassName:c.ClassNameGenerator.generate}),ss=wr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),Di=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Zd(e){return c.generateUtilityClass("MuiListItemIcon",e)}const $i=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Xd=e=>{const{alignItems:n,classes:r}=e,o={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(o,Zd,r)},Jd=c.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.alignItems==="flex-start"&&n.alignItemsFlexStart]}})(c.memoTheme(({theme:e})=>({minWidth:56,color:(e.vars||e).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),io=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=o,a=je.useContext(c.ListContext),u={...o,alignItems:a.alignItems},d=Xd(u);return t.jsx(Jd,{className:c.clsx(d.root,i),ownerState:u,ref:r,...l})});function eh(e){return c.generateUtilityClass("MuiListItemText",e)}const $n=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),th=e=>{const{classes:n,inset:r,primary:o,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",o&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,eh,n)},nh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${$n.primary}`]:n.primary},{[`& .${$n.secondary}`]:n.secondary},n.root,r.inset&&n.inset,r.primary&&r.secondary&&n.multiline,r.dense&&n.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${c.typographyClasses.root}:where(& .${$n.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${$n.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),ao=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:u=!1,primary:d,primaryTypographyProps:h,secondary:y,secondaryTypographyProps:b,slots:x={},slotProps:v={},...k}=o,{dense:C}=je.useContext(c.ListContext);let S=d??i,T=y;const O={...o,disableTypography:a,inset:u,primary:!!S,secondary:!!T,dense:C},M=th(O),E={slots:x,slotProps:{primary:h,secondary:b,...v}},[R,P]=c.useSlot("root",{className:c.clsx(M.root,l),elementType:nh,externalForwardedProps:{...E,...k},ownerState:O,ref:r}),[F,B]=c.useSlot("primary",{className:M.primary,elementType:c.Typography,externalForwardedProps:E,ownerState:O}),[D,_]=c.useSlot("secondary",{className:M.secondary,elementType:c.Typography,externalForwardedProps:E,ownerState:O});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx(F,{variant:C?"body2":"body1",component:B?.variant?void 0:"span",...B,children:S})),T!=null&&T.type!==c.Typography&&!a&&(T=t.jsx(D,{variant:"body2",color:"textSecondary",..._,children:T})),t.jsxs(R,{...P,children:[S,T]})});function rh(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),sh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},oh=e=>{const{disabled:n,dense:r,divider:o,disableGutters:i,selected:l,classes:a}=e,u={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",o&&"divider",l&&"selected"]},d=c.composeClasses(u,rh,a);return{...a,...d}},ih=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:sh})(c.memoTheme(({theme:e})=>({...e.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${er.selected}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${er.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}},[`&.${er.selected}:hover`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity)}},[`&.${er.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${er.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${Di.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Di.inset}`]:{marginLeft:52},[`& .${$n.root}`]:{marginTop:0,marginBottom:0},[`& .${$n.inset}`]:{paddingLeft:36},[`& .${$i.root}`]:{minWidth:36},variants:[{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.divider,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:n})=>!n.dense,style:{[e.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:n})=>n.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...e.typography.body2,[`& .${$i.root} svg`]:{fontSize:"1.25rem"}}}]}))),et=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:u=!1,disableGutters:d=!1,focusVisibleClassName:h,role:y="menuitem",tabIndex:b,className:x,...v}=o,k=je.useContext(c.ListContext),C=je.useMemo(()=>({dense:a||k.dense||!1,disableGutters:d}),[k.dense,a,d]),S=je.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const T={...o,dense:C.dense,divider:u,disableGutters:d},O=oh(o),M=c.useForkRef(S,r);let E;return o.disabled||(E=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:C,children:t.jsx(ih,{ref:M,role:y,tabIndex:E,component:l,focusVisibleClassName:c.clsx(O.focusVisible,h),className:c.clsx(O.root,x),...v,ownerState:T,classes:O})})}),Gt={postgres:[{label:"Host",name:"host",type:"text",required:!1},{label:"Port",name:"port",type:"number",required:!1},{label:"Database Name",name:"databaseName",type:"text",required:!1},{label:"User Name",name:"userName",type:"text",required:!1},{label:"Password",name:"password",type:"password",required:!1},{label:"Connection String",name:"connectionString",type:"text",required:!1}],bigquery:[{label:"Project ID",name:"defaultProjectId",type:"text",required:!1},{label:"Billing Project ID",name:"billingProjectId",type:"text",required:!1},{label:"Location",name:"location",type:"text",required:!1},{label:"Service Account Key JSON",name:"serviceAccountKeyJson",type:"text",required:!0},{label:"Maximum Bytes Billed",name:"maximumBytesBilled",type:"text",required:!1},{label:"Query Timeout Milliseconds",name:"queryTimeoutMilliseconds",type:"text",required:!1},{label:"Database Metadata",name:"dbmeta",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]}],snowflake:[{label:"Account",name:"account",type:"text",required:!0},{label:"Username",name:"username",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Role",name:"role",type:"text",required:!1},{label:"Warehouse",name:"warehouse",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"Response Timeout Milliseconds",name:"responseTimeoutMilliseconds",type:"text",required:!1},{label:"Private Key",name:"privateKey",type:"password",required:!1},{label:"Private Key Passphrase",name:"privateKeyPass",type:"password",required:!1}],trino:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Catalog",name:"catalog",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Peaka Key",name:"peakaKey",type:"password",required:!1}],databricks:[{label:"Host",name:"host",type:"text",required:!0},{label:"HTTP Path",name:"path",type:"text",required:!0},{label:"Access Token",name:"token",type:"password",required:!1},{label:"OAuth Client ID",name:"oauthClientId",type:"text",required:!1},{label:"OAuth Client Secret",name:"oauthClientSecret",type:"password",required:!1},{label:"Default Catalog",name:"defaultCatalog",type:"text",required:!1},{label:"Default Schema",name:"defaultSchema",type:"text",required:!1}],mysql:[{label:"Host",name:"host",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Database",name:"database",type:"text",required:!0}],sqlserver:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Database",name:"database",type:"text",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Encrypt",name:"encrypt",type:"text",required:!1,selectOptions:[{label:"Yes",value:"true"},{label:"No",value:"false"}]},{label:"Trust server certificate",name:"trustServerCertificate",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]},{label:"Host name in certificate",name:"hostNameInCertificate",type:"text",required:!1},{label:"Instance name",name:"instanceName",type:"text",required:!1}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},pr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",sqlserver:"sqlserverConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ah={bigquery:{dbmeta:"boolean"},sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},lh={sqlserver:["hostNameInCertificate","instanceName"]};function Ja(e,n){const r=ah[e],o=lh[e];if(!r&&!o)return n;const i={...n};for(const l of o??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const u=n[l];if(u!==void 0){if(u===""){delete i[l];continue}if(a==="integer"){const d=Number(u);Number.isInteger(d)&&(i[l]=d)}else(u==="true"||u==="false")&&(i[l]=u==="true")}}return i}const el=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Gs={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},Sr=[{label:"Credential Provider",name:"provider",type:"text",required:!1,selectOptions:[{label:"Access key pair",value:"config"},{label:"Host credential chain",value:"credential_chain"}]},{label:"Access Key ID",name:"accessKeyId",type:"text",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Secret Access Key",name:"secretAccessKey",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Credential Chain",name:"chain",type:"text",required:!1,visibleWhen:{field:"provider",value:"credential_chain"}},{label:"Region",name:"region",type:"text",required:!1},{label:"Endpoint",name:"endpoint",type:"text",required:!1},{label:"Session Token",name:"sessionToken",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}}],kr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],ch=[{label:"Auth Type",name:"authType",type:"text",required:!0,selectOptions:[{label:"SAS Token",value:"sas_token"},{label:"Service Principal (SPN)",value:"service_principal"}]},{label:"SAS URL (e.g. https://account.blob.core.windows.net/container/file.parquet?sp=r&st=...)",name:"sasUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"sas_token"}},{label:"Tenant ID",name:"tenantId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client ID",name:"clientId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client Secret",name:"clientSecret",type:"password",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Account Name",name:"accountName",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"File URL (e.g. abfss://container/path/file.parquet)",name:"fileUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}}];function Jr(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?Sr:e==="gcs"?kr:e==="azure"?ch:[]}function uh({onSubmit:e,isSubmitting:n}){const[r,o]=j.useState(!1),[i,l]=j.useState("postgres"),[a,u]=j.useState([]),[d,h]=j.useState("postgres"),[y,b]=j.useState("s3"),[x,v]=j.useState("config"),k=()=>{o(!0)},C=()=>{o(!1),u([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async E=>{E.preventDefault();const R=new FormData(E.currentTarget),P=R.get("name")?.toString(),F=R.get("type")?.toString(),B=Gt[F];if(!P)throw new Error("Name is required");if(!F)throw new Error("Type is required");let D;if(F==="ducklake"){const _={};if(d==="postgres"){const W=Gt.postgres,Z={};if(W.forEach(ne=>{const J=R.get(`ducklake_pg_${ne.name}`)?.toString();J&&(Z[ne.name]=J)}),Object.keys(Z).length===0)throw new Error("DuckLake requires catalog connection");_.postgresConnection=Z}const V=R.get("ducklake_bucketUrl")?.toString();if(!V)throw new Error("DuckLake requires a bucket URL");const $={bucketUrl:V};if(y==="s3"){const W={};if(Sr.forEach(Z=>{const ne=R.get(`ducklake_s3_${Z.name}`)?.toString();ne&&(W[Z.name]=ne)}),W.provider==="credential_chain")delete W.accessKeyId,delete W.secretAccessKey,delete W.sessionToken;else{if(delete W.chain,!W.accessKeyId)throw new Error("S3 Access Key ID is required");if(!W.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(W).length>0&&($.s3Connection=W)}else if(y==="gcs"){const W={};if(kr.forEach(Z=>{const ne=R.get(`ducklake_gcs_${Z.name}`)?.toString();ne&&(W[Z.name]=ne)}),!W.keyId)throw new Error("GCS Key ID is required");if(!W.secret)throw new Error("GCS Secret is required");Object.keys(W).length>0&&($.gcsConnection=W)}D={name:P,type:F,ducklakeConnection:{catalog:_,storage:$}}}else if(F==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const _=a.map((V,$)=>{const W=V.dbType,Z=R.get(`attachedDb_${$}_name`)?.toString();if(!Z)throw new Error(`Attached database at index ${$} must have a name`);const ne={name:Z,type:W},J=Jr(W);if(J&&J.length>0){const H={};if(J.forEach(re=>{const z=R.get(`attachedDb_${$}_${re.name}`)?.toString();z&&(H[re.name]=z)}),W==="s3"){if(H.provider==="credential_chain")delete H.accessKeyId,delete H.secretAccessKey,delete H.sessionToken;else if(delete H.chain,!H.accessKeyId||!H.secretAccessKey)throw new Error(`Attached database "${Z}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Q=Gs[W];Q&&(ne[Q]=H)}return ne});D={name:P,type:F,duckdbConnection:{attachedDatabases:_}}}else{const _={};if(B.forEach(V=>{const $=R.get(V.name)?.toString();$&&(_[V.name]=$)}),F==="postgres"){if(!!!_.connectionString?.trim()){const $=["host","port","databaseName","userName","password"];for(const W of $)if(!_[W])throw new Error(`${B.find(Z=>Z.name===W)?.label||W} is required`)}}else if(F==="bigquery"){if(!_.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(F==="snowflake"){if(!_.account)throw new Error("Account is required");if(!_.username)throw new Error("Username is required");if(!_.warehouse)throw new Error("Warehouse is required");if(!_.password&&!_.privateKey)throw new Error("Either password or private key is required")}else if(F==="trino"){if(!_.server)throw new Error("Server is required");if(!_.user)throw new Error("User is required");if(_.server.trim().startsWith("https://")&&!_.password&&!_.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(F==="mysql"){const V=["host","port","database","user","password"];for(const $ of V)if(!_[$])throw new Error(`${B.find(W=>W.name===$)?.label||$} is required`)}else if(F==="sqlserver"){const V=["server","database","user","password"];if(!_.instanceName&&!_.port)throw new Error("Port is required unless an instance name is given");for(const $ of V)if(!_[$])throw new Error(`${B.find(W=>W.name===$)?.label||$} is required`)}else if(F==="motherduck"){if(!_.accessToken)throw new Error("Access Token is required")}else if(F==="databricks"){if(!_.host)throw new Error("Host is required");if(!_.path)throw new Error("HTTP Path is required");const V=_.oauthClientId&&_.oauthClientSecret;if(!_.token&&!V)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}D={name:P,type:F,[pr[F]]:Ja(F,_)}}await e(D),C()},T=()=>{u([...a,{name:"",dbType:"postgres"}])},O=E=>{u(a.filter((R,P)=>P!==E))},M=(E,R)=>{const P=[...a];P[E]={...P[E],dbType:R},u(P)};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:k}),t.jsx(c.AppDialog,{open:r,onClose:C,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:n,onClick:C,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:n,children:"Create connection"})]}),children:t.jsx("form",{onSubmit:S,id:"connection-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:i,select:!0,onChange:E=>l(E.target.value),children:el.map(E=>t.jsx(et,{value:E,children:E},E))}),i==="ducklake"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>h(E.target.value),children:t.jsx(et,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(E=>t.jsx(c.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:y,select:!0,onChange:E=>b(E.target.value),children:[t.jsx(et,{value:"s3",children:"S3"}),t.jsx(et,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:y==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),y==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(E=>E.visibleWhen?x===E.visibleWhen.value:!0).map(E=>t.jsx(c.TextField,{id:`ducklake_s3_${E.name}`,name:`ducklake_s3_${E.name}`,label:E.label,type:E.selectOptions?void 0:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?x:void 0,onChange:E.name==="provider"?R=>v(R.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(R=>t.jsx(et,{value:R.value,children:R.label},R.value))},`s3_${E.name}`))]}),y==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(E=>t.jsx(c.TextField,{id:`ducklake_gcs_${E.name}`,name:`ducklake_gcs_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},`gcs_${E.name}`))]})]})]}):i==="duckdb"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:T,ariaLabel:"Add database"})]}),a.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),a.map((E,R)=>{const P=Jr(E.dbType);return t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",R+1]}),t.jsx(c.IconButton,{onClick:()=>O(R),size:"small",color:"error",children:t.jsx(Xa,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${R}_name`,name:`attachedDb_${R}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),t.jsx(c.TextField,{id:`attachedDb_${R}_type`,name:`attachedDb_${R}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:F=>M(R,F.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(F=>t.jsx(et,{value:F,children:F},F))}),P.filter(F=>F.visibleWhen?(E[F.visibleWhen.field]||P.find(D=>D.name===F.visibleWhen?.field)?.selectOptions?.[0]?.value)===F.visibleWhen.value:!0).map(F=>t.jsx(c.TextField,{id:`attachedDb_${R}_${F.name}`,name:`attachedDb_${R}_${F.name}`,label:F.label,type:F.selectOptions?void 0:F.type,fullWidth:!0,size:"small",required:F.required,select:!!F.selectOptions,defaultValue:F.selectOptions?.[0]?.value,onChange:F.selectOptions?B=>{const D=[...a];D[R]={...D[R],[F.name]:B.target.value},u(D)}:void 0,children:F.selectOptions?.map(B=>t.jsx(et,{value:B.value,children:B.label},B.value))},F.name))]},R)})]}):Gt[i].map(E=>t.jsx(c.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?E.selectOptions[0]?.value:void 0,children:E.selectOptions?.map(R=>t.jsx(et,{value:R.value,children:R.label},R.value))},E.name))]})})})]})}function dh({connection:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=j.useState(!1),a=()=>{l(!0)},u=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(et,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(io,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(ao,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:u,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:u,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete connection"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Fi=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ai(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Ri(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function hh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:o}){const[i,l]=j.useState(!1),[a,u]=j.useState(e.type),d=j.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,y]=j.useState(()=>Ai(e)),[b,x]=j.useState("postgres"),[v,k]=j.useState(()=>Ri(e)),[C,S]=j.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{y(Ai(e)),u(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),k(Ri(e)),l(!0)},O=()=>{l(!1),o?.()},M=async D=>{D.preventDefault();const _=new FormData(D.currentTarget),V=_.get("name")?.toString(),$=_.get("type")?.toString(),W=Gt[$];if(!V)throw new Error("Name is required");if(!$)throw new Error("Type is required");let Z;if($==="ducklake"){const ne={};if(b==="postgres"){const Q=Gt.postgres,re={};if(Q.forEach(z=>{const oe=_.get(`ducklake_pg_${z.name}`)?.toString();oe&&(re[z.name]=oe)}),Object.keys(re).length===0)throw new Error("DuckLake requires catalog connection");ne.postgresConnection=re}const J=_.get("ducklake_bucketUrl")?.toString();if(!J)throw new Error("DuckLake requires a bucket URL");const H={bucketUrl:J};if(v==="s3"){const Q={};Sr.forEach(z=>{const oe=_.get(`ducklake_s3_${z.name}`)?.toString();oe&&(Q[z.name]=oe)});const re=e.ducklakeConnection?.storage?.s3Connection;if(re&&(!Q.provider&&re.provider&&(Q.provider=re.provider),!Q.chain&&re.chain&&(Q.chain=re.chain),!Q.accessKeyId&&re.accessKeyId&&(Q.accessKeyId=re.accessKeyId)),Q.provider==="credential_chain")delete Q.accessKeyId,delete Q.secretAccessKey,delete Q.sessionToken;else if(delete Q.chain,!Q.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(Q).length>0&&(H.s3Connection=Q)}else if(v==="gcs"){const Q={};kr.forEach(z=>{const oe=_.get(`ducklake_gcs_${z.name}`)?.toString();oe&&(Q[z.name]=oe)});const re=e.ducklakeConnection?.storage?.gcsConnection;if(re&&!Q.keyId&&re.keyId&&(Q.keyId=re.keyId),!Q.keyId)throw new Error("GCS Key ID is required");Object.keys(Q).length>0&&(H.gcsConnection=Q)}Z={name:V,type:$,ducklakeConnection:{catalog:ne,storage:H}}}else if($==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const ne=h.map((J,H)=>{const Q=J.dbType,re=_.get(`attachedDb_${H}_name`)?.toString();if(!re)throw new Error(`Attached database at index ${H} must have a name`);const z={name:re,type:Q},oe=Jr(Q);if(oe&&oe.length>0){const se={};if(oe.forEach(De=>{const de=_.get(`attachedDb_${H}_${De.name}`)?.toString();de&&(se[De.name]=de)}),Q==="s3"){if(se.provider==="credential_chain")delete se.accessKeyId,delete se.secretAccessKey,delete se.sessionToken;else if(delete se.chain,!se.accessKeyId||!se.secretAccessKey)throw new Error(`Attached database "${re}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ie=Gs[Q];ie&&(z[ie]=se)}return z});Z={name:V,type:$,duckdbConnection:{attachedDatabases:ne}}}else{const ne=e[pr[$]]||{},J={};if(W.forEach(H=>{const Q=_.get(H.name)?.toString(),re=ne[H.name];Q?J[H.name]=Q:Fi.has(H.name)||(Q!==void 0?J[H.name]=Q:re&&(J[H.name]=re))}),$==="postgres"){const H=["host","port","databaseName","userName"],Q=d.has("postgresConnection.connectionString");if(!(!!J.connectionString?.trim()||Q)){const z=H;for(const oe of z)if(!J[oe])throw new Error(`${W.find(se=>se.name===oe)?.label||oe} is required`)}}else if($==="snowflake"){if(!J.account)throw new Error("Account is required");if(!J.username)throw new Error("Username is required");if(!J.warehouse)throw new Error("Warehouse is required")}else if($==="trino"){if(!J.server)throw new Error("Server is required");if(!J.user)throw new Error("User is required")}else if($==="mysql"){const H=["host","port","database","user"];for(const Q of H)if(!J[Q])throw new Error(`${W.find(re=>re.name===Q)?.label||Q} is required`)}else if($==="sqlserver"){const H=["server","database","user"];if(!J.instanceName&&!J.port)throw new Error("Port is required unless an instance name is given");for(const Q of H)if(!J[Q])throw new Error(`${W.find(re=>re.name===Q)?.label||Q} is required`)}else if($==="databricks"){if(!J.host)throw new Error("Host is required");if(!J.path)throw new Error("HTTP Path is required")}Z={name:V,type:$,[pr[$]]:Ja($,J)}}await n(Z),O()},E=()=>{y([...h,{name:"",dbType:"postgres"}])},R=D=>{y(h.filter((_,V)=>V!==D))},P=(D,_)=>{const V=[...h];V[D]={...V[D],dbType:_},y(V)},F=(D,_)=>{const V=e.duckdbConnection?.attachedDatabases;if(!V||!V[D])return"";const $=V[D],W=Gs[$.type||""];return W&&$[W]?$[W][_]??"":""},B=D=>{const _=e.ducklakeConnection;if(!_)return"";if(D.startsWith("pg_")){const V=D.replace("pg_","");return _.catalog?.postgresConnection?.[V]??""}if(D==="bucketUrl")return _.storage?.bucketUrl??"";if(D.startsWith("s3_")){const V=D.replace("s3_","");return _.storage?.s3Connection?.[V]??""}if(D.startsWith("gcs_")){const V=D.replace("gcs_","");return _.storage?.gcsConnection?.[V]??""}return""};return t.jsxs(j.Fragment,{children:[t.jsxs(et,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:D=>{D.preventDefault(),D.stopPropagation(),T()},children:[t.jsx(io,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(ao,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:i,onClose:O,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:r,onClick:O,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:r,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:M,id:"connection-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:e.name}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:a,select:!0,onChange:D=>u(D.target.value),children:el.map(D=>t.jsx(et,{value:D,children:D},D))}),a==="ducklake"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:b,select:!0,onChange:D=>x(D.target.value),children:t.jsx(et,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(D=>t.jsx(c.TextField,{id:`ducklake_pg_${D.name}`,name:`ducklake_pg_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",defaultValue:B(`pg_${D.name}`)},`pg_${D.name}`))})]}),t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:D=>k(D.target.value),children:[t.jsx(et,{value:"s3",children:"S3"}),t.jsx(et,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:v==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:B("bucketUrl")}),v==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(D=>D.visibleWhen?C===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`ducklake_s3_${D.name}`,name:`ducklake_s3_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secretAccessKey",select:!!D.selectOptions,defaultValue:D.selectOptions?C:B(`s3_${D.name}`),onChange:D.name==="provider"?_=>S(_.target.value):void 0,placeholder:D.name==="region"?"us-east-1":D.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:D.selectOptions?.map(_=>t.jsx(et,{value:_.value,children:_.label},_.value))},`s3_${D.name}`))]}),v==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(D=>t.jsx(c.TextField,{id:`ducklake_gcs_${D.name}`,name:`ducklake_gcs_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secret",defaultValue:B(`gcs_${D.name}`),placeholder:D.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${D.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),h.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),h.map((D,_)=>{const V=Jr(D.dbType);return t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",_+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${_+1}`,onClick:()=>R(_),size:"small",color:"error",children:t.jsx(Xa,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${_}_name`,name:`attachedDb_${_}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:D.name}),t.jsx(c.TextField,{id:`attachedDb_${_}_type`,name:`attachedDb_${_}_type`,label:"Database Type",fullWidth:!0,size:"small",value:D.dbType,select:!0,onChange:$=>P(_,$.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map($=>t.jsx(et,{value:$,children:$},$))}),V.filter($=>$.visibleWhen?(D[$.visibleWhen.field]||F(_,$.visibleWhen.field)||V.find(Z=>Z.name===$.visibleWhen?.field)?.selectOptions?.[0]?.value)===$.visibleWhen.value:!0).map($=>t.jsx(c.TextField,{id:`attachedDb_${_}_${$.name}`,name:`attachedDb_${_}_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required,select:!!$.selectOptions,defaultValue:F(_,$.name)||$.selectOptions?.[0]?.value,onChange:$.selectOptions?W=>{const Z=[...h];Z[_]={...Z[_],[$.name]:W.target.value},y(Z)}:void 0,children:$.selectOptions?.map(W=>t.jsx(et,{value:W.value,children:W.label},W.value))},$.name))]},_)})]}):Gt[a].map(D=>{const _=e?.[pr[a]??""]?.[D.name??""]??"",V=D.type==="password"||Fi.has(D.name),$=d.has(`${pr[a]??""}.${D.name}`),W=D.selectOptions?_===""||_===void 0?D.selectOptions[0]?.value:String(_):void 0;return t.jsx(c.TextField,{id:D.name,name:D.name,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&!V&&!_,select:!!D.selectOptions,defaultValue:D.selectOptions?W:_,placeholder:$?"Leave empty to keep existing":void 0,helperText:V?$?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:D.selectOptions?.map(Z=>t.jsx(et,{value:Z.value,children:Z.label},Z.value))},D.name)})]})})})]})}function Li(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(o=>o.type==="azure"&&o.name===n)}function fh(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function tl({connectionName:e,resourceUri:n,schema:r,connection:o}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,u]=j.useState(null),[d,h]=j.useState(r||null),[y,b]=j.useState(!1),{data:x,isError:v,isLoading:k,error:C}=c.useQueryWithApiError({queryKey:["schemas",l,e],queryFn:()=>i.connections.listSchemas(l,e)}),S=x?.data||[];return t.jsxs(p.Grid,{container:!0,spacing:1,children:[!r&&t.jsx(p.Grid,{size:{xs:12,md:4},children:t.jsxs(p.Paper,{sx:{p:1,m:0},children:[t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[t.jsx(p.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),t.jsx(p.FormControlLabel,{control:t.jsx(p.Switch,{checked:y,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(p.Divider,{sx:{mt:"2px"}}),t.jsxs(p.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:C,context:`${l} > ${e} > Schemas`}),!k&&!v&&S.length===0&&t.jsx(p.Typography,{variant:"body2",children:"No Schemas"}),!k&&!v&&S.length>0&&t.jsx(p.List,{dense:!0,disablePadding:!0,children:S.map(T=>{const O=T.name;if(T.isHidden&&!y)return null;const E=d===O;return t.jsx(p.ListItemButton,{selected:E,onClick:()=>{h(O),u(null)},children:t.jsx(p.ListItemText,{primary:O})},O)})})]})]})}),t.jsx(p.Grid,{size:{xs:12,md:r?6:4},children:d&&t.jsx(p.Paper,{sx:{p:1,m:0},children:t.jsx(gh,{connectionName:e,schemaName:d,onTableSelect:T=>{u(T)},resourceUri:n,connection:o})})}),t.jsx(p.Grid,{size:{xs:12,md:r?6:4},children:d&&a&&t.jsx(mh,{environmentName:l,connectionName:e,schemaName:d,tableResource:a})})]})}function mh({environmentName:e,connectionName:n,schemaName:r,tableResource:o}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:u,error:d}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,o],queryFn:()=>i.connections.getTable(e,n,r,o),enabled:!!r&&!!o}),h={resource:l?.data?.resource??o,columns:l?.data?.columns??[]};return t.jsxs(p.Paper,{sx:{p:1,m:0},children:[u&&t.jsx(c.ApiErrorDisplay,{error:d,context:`${e} > ${n} > ${r} > ${o}`}),!u&&t.jsx(ph,{table:h,loading:a})]})}function ph({table:e,loading:n}){return n?t.jsx(c.Loading,{text:"Loading columns..."}):t.jsxs(t.Fragment,{children:[t.jsxs(p.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[e.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(e.resource)?"File":"Table",": ",e.resource]}),t.jsx(p.Divider,{}),t.jsx(p.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:t.jsx(p.TableContainer,{children:t.jsxs(p.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"NAME"}),t.jsx(p.TableCell,{children:"TYPE"})]})}),t.jsx(p.TableBody,{children:e.columns?.sort((r,o)=>r.name.localeCompare(o.name))?.map(r=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:r.name}),t.jsx(p.TableCell,{children:r.type})]},r.name))})]})})})]})}function gh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:o,connection:i}){const{environmentName:l}=c.parseResourceUri(o),{apiClients:a}=q.useServer(),[u,d]=j.useState(""),{data:h,isSuccess:y,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),k=Li(i,n),C=T=>k?T:T.split(".").pop()||T,S=y&&h?.data?h.data.filter(T=>C(T.resource).toLowerCase().includes(u.toLowerCase())).sort((T,O)=>C(T.resource).localeCompare(C(O.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(p.Typography,{variant:"overline",fontWeight:"bold",children:fh(n)||Li(i,n)?`Files in ${n}`:`Tables in ${n}`}),t.jsx(p.Divider,{}),t.jsx(p.Box,{sx:{mt:1,mb:1},children:t.jsx(p.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:u,onChange:T=>d(T.target.value),variant:"outlined"})}),t.jsx(p.Divider,{}),t.jsxs(p.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[v&&t.jsx(c.Loading,{text:"Fetching Tables..."}),b&&t.jsx(c.ApiErrorDisplay,{error:x,context:`${l} > ${e} > ${n}`}),y&&S.length===0&&t.jsx(p.Typography,{variant:"body2",children:"No Tables"}),y&&h?.data&&h.data.length>0&&t.jsx(p.List,{dense:!0,disablePadding:!0,children:S.map(T=>{let O=C(T.resource);return!k&&T.resource.includes("://")&&(O=T.resource.split("/").pop()||T.resource),t.jsx(p.ListItemButton,{onClick:()=>r(T.resource),children:t.jsx(p.ListItemText,{primary:O,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const yh={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",sqlserver:"SQL Server",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function xh(e){return e?yh[e]??e:""}function vh({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),o=mt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=j.useState(""),[u,d]=j.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:u}),{data:y,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),k=c.useMutationWithApiError({mutationFn:Ht("connection","create",M=>n.environments.updateEnvironment(i,{name:i,connections:[...y.data,M]})),onSuccess(){a("Connection added successfully"),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),C=c.useMutationWithApiError({mutationFn:Ht("connection","update",M=>n.environments.updateEnvironment(i,{name:i,connections:y.data.map(E=>E.name===M.name?M:E)})),onSuccess(M,E){a(`Connection ${E.name} updated successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),S=c.useMutationWithApiError({mutationFn:Ht("connection","delete",M=>{if(!M.name)throw new Error("Cannot delete a connection with no name");return n.connections.deleteConnection(i,M.name)}),onSuccess(M,E){a(`Connection ${E.name} deleted successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),T=b?[...y.data].sort((M,E)=>(M.name??"").localeCompare(E.name??"")):[],O=k.isPending||C.isPending||S.isPending;return t.jsxs(Nt,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(uh,{onSubmit:M=>k.mutateAsync(M),isSubmitting:k.isPending})}:{},children:[!b&&!x&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),x&&t.jsx(c.ApiErrorDisplay,{error:v,context:`${i} > Connections`}),b&&T.length===0&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(p.Stack,{children:T.map(M=>t.jsx(bh,{connection:M,mutable:r,isMutating:O,onOpenExplorer:()=>d(M.name??null),onEdit:E=>C.mutateAsync(E),onDelete:E=>S.mutateAsync(E)},M.name))}),t.jsx(p.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:u!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${u??""}`,showClose:!0,children:u&&t.jsx(tl,{resourceUri:h,connectionName:u,connection:y?.data?.find(M=>M.name===u)})})]})}function bh({connection:e,mutable:n,isMutating:r,onOpenExplorer:o,onEdit:i,onDelete:l}){const[a,u]=j.useState(null),d=!!a,h=b=>{b.stopPropagation(),u(b.currentTarget)},y=()=>u(null);return t.jsx(rs,{icon:t.jsx(Yd,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:xh(e.type),onClick:o,...n?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${e.name??""}`.trim(),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:a,open:d,onClose:y,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(hh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:y}),t.jsx(dh,{connection:e,onCloseDialog:y,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const wh=c.createSvgIcon([t.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-1 18H5V9h14zm1-13H4V4h16z"},"0"),t.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function Sh({resourceUri:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},{environmentName:u,packageName:d}=c.parseResourceUri(e),h=Nn({mutationFn:()=>i.packages.deletePackage(u,d),success:"Package deleted",invalidates:[["packages",u]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete package",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function kh({package:e,resourceUri:n,onCloseDialog:r}){const[o,i]=j.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},u=()=>{i(!1),r()},{packageName:d,environmentName:h}=c.parseResourceUri(n),y=Nn({mutationFn(x){return l.packages.updatePackage(h,d,{name:d,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:u,resource:"package",action:"update"}),b=x=>{x.preventDefault();const k=new FormData(x.currentTarget).get("description")?.toString();y.mutate({description:k})};return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:a,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:o,onClose:u,title:"Edit package",description:`What ${e.name} is, for the people who open it.`,actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:y.isPending,onClick:u,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:y.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:b,id:"package-form",children:t.jsxs(p.Stack,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:e.description,InputLabelProps:{shrink:!0}})]})})}),y.notice]})}function nl({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:o}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:u}=c.useQueryWithApiError({queryKey:["packages",o],queryFn:()=>r.packages.listPackages(o)});if(a)return t.jsx(c.ApiErrorDisplay,{error:u,context:`${o} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const d=[...i.data].sort((h,y)=>h.name.localeCompare(y.name));return t.jsx(p.Stack,{children:d.map(h=>{const y=c.encodeResourceUri({environmentName:o,packageName:h.name});return t.jsx(Ch,{pkg:h,packageResourceUri:y,onSelectPackage:e},h.name)})})}function Ch({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:o}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=j.useState(null),u=!!l,d=y=>{y.stopPropagation(),a(y.currentTarget)},h=()=>a(null);return t.jsx(rs,{icon:t.jsx(wh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:y=>r(e.name,y),...o?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:d,"aria-label":`Package actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:l,open:u,onClose:h,onClick:y=>y.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(kh,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(Sh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function jh({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(n),l=c.useQueryWithApiError({queryKey:["packages",i],queryFn:()=>r.packages.listPackages(i)});return j.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(p.Box,{sx:{mb:4},children:[t.jsx(p.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:i}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),t.jsx(Nt,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...o?{action:t.jsx(Gd,{resourceUri:n})}:{},children:t.jsx(nl,{onSelectPackage:e,resourceUri:n})}),t.jsx(vh,{resourceUri:n}),t.jsx($d,{resourceUri:n})]})}function _i({array1:e,array2:n,parser:r=o=>o}){return e&&n&&e.length===n.length&&e.every((o,i)=>r(o)===r(n[i]))}function Ni(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Th(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:o,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(u,{inputValue:d,getOptionLabel:h})=>{let y=a?d.trim():d;r&&(y=y.toLowerCase()),n&&(y=Ni(y));const b=y?u.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Ni(v)),i==="start"?v.startsWith(y):v.includes(y)}):u;return typeof o=="number"?b.slice(0,o):b}}const Oh=Th(),Pi=5,Mh=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Eh=[];function zi(e,n,r,o){if(n||e==null||o)return"";const i=r(e);return typeof i=="string"?i:""}function Ih(e){const{unstable_isActiveElementInListbox:n=Mh,unstable_classNamePrefix:r="Mui",autoComplete:o=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:u=!e.freeSolo,clearOnEscape:d=!1,componentName:h="useAutocomplete",defaultValue:y=e.multiple?Eh:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:k=!1,disableListWrap:C=!1,filterOptions:S=Oh,filterSelectedOptions:T=!1,freeSolo:O=!1,getOptionDisabled:M,getOptionKey:E,getOptionLabel:R=G=>G.label??G,groupBy:P,handleHomeEndKeys:F=!e.freeSolo,id:B,includeInputInList:D=!1,inputValue:_,isOptionEqualToValue:V=(G,U)=>G===U,multiple:$=!1,onChange:W,onClose:Z,onHighlightChange:ne,onInputChange:J,onOpen:H,open:Q,openOnFocus:re=!1,options:z,readOnly:oe=!1,renderValue:se,selectOnFocus:ie=!e.freeSolo,value:De}=e,de=c.useId(B);let ue=R;ue=G=>{const U=R(G);return typeof U!="string"?String(U):U};const be=je.useRef(!1),Me=je.useRef(!0),te=je.useRef(null),K=je.useRef(null),[he,we]=je.useState(null),[ge,pe]=je.useState(-1),ye=i?0:-1,Le=je.useRef(ye),st=je.useRef(zi(y??De,$,ue)).current,[ce,Y]=c.useControlled({controlled:De,default:y,name:h}),[ae,Fe]=c.useControlled({controlled:_,default:st,name:h,state:"inputValue"}),[Ve,St]=je.useState(!1),Ee=je.useCallback((G,U,le)=>{if(!($?ce.length<U.length:U!==null)&&!u)return;const ee=zi(U,$,ue,se);ae!==ee&&(Fe(ee),J&&J(G,ee,le))},[ue,ae,$,J,Fe,u,ce,se]),[at,yt]=c.useControlled({controlled:Q,default:!1,name:h,state:"open"}),[xt,Ot]=je.useState(!0),pt=!$&&ce!=null&&ae===ue(ce),Ye=at&&!oe,fe=Ye?S(z.filter(G=>!(T&&($?ce:[ce]).some(U=>U!==null&&V(G,U)))),{inputValue:pt&&xt?"":ae,getOptionLabel:ue}):[],Ke=dd({filteredOptions:fe,value:ce,inputValue:ae});je.useEffect(()=>{const G=ce!==Ke.value;Ve&&!G||O&&!G||Ee(null,ce,"reset")},[ce,Ee,Ve,Ke.value,O]);const ze=at&&fe.length>0&&!oe,lt=c.useEventCallback(G=>{if(G===-1)te.current.focus();else{const U=se?"data-item-index":"data-tag-index";he.querySelector(`[${U}="${G}"]`).focus()}});je.useEffect(()=>{$&&ge>ce.length-1&&(pe(-1),lt(-1))},[ce,$,ge,lt]);function ct(G,U){if(!K.current||G<0||G>=fe.length)return-1;let le=G;for(;;){const ve=K.current.querySelector(`[data-option-index="${le}"]`),ee=k?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!ee)return le;if(U==="next"?le=(le+1)%fe.length:le=(le-1+fe.length)%fe.length,le===G)return-1}}const Qe=c.useEventCallback(({event:G,index:U,reason:le})=>{if(Le.current=U,U===-1?te.current.removeAttribute("aria-activedescendant"):te.current.setAttribute("aria-activedescendant",`${de}-option-${U}`),ne&&["mouse","keyboard","touch"].includes(le)&&ne(G,U===-1?null:fe[U],le),!K.current)return;const ve=K.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let ee=K.current;if(K.current.getAttribute("role")!=="listbox"&&(ee=K.current.parentElement.querySelector('[role="listbox"]')),!ee)return;if(U===-1){ee.scrollTop=0;return}const qe=K.current.querySelector(`[data-option-index="${U}"]`);if(qe&&(qe.classList.add(`${r}-focused`),le==="keyboard"&&qe.classList.add(`${r}-focusVisible`),ee.scrollHeight>ee.clientHeight&&le!=="mouse"&&le!=="touch")){const Ue=qe,Ct=ee.clientHeight+ee.scrollTop,vn=Ue.offsetTop+Ue.offsetHeight;vn>Ct?ee.scrollTop=vn-ee.clientHeight:Ue.offsetTop-Ue.offsetHeight*(P?1.3:0)<ee.scrollTop&&(ee.scrollTop=Ue.offsetTop-Ue.offsetHeight*(P?1.3:0))}}),me=c.useEventCallback(({event:G,diff:U,direction:le="next",reason:ve})=>{if(!Ye)return;const qe=ct((()=>{const Ue=fe.length-1;if(U==="reset")return ye;if(U==="start")return 0;if(U==="end")return Ue;const Ct=Le.current+U;return Ct<0?Ct===-1&&D?-1:C&&Le.current!==-1||Math.abs(U)>1?0:Ue:Ct>Ue?Ct===Ue+1&&D?-1:C||Math.abs(U)>1?Ue:0:Ct})(),le);if(Qe({index:qe,reason:ve,event:G}),o&&U!=="reset")if(qe===-1)te.current.value=ae;else{const Ue=ue(fe[qe]);te.current.value=Ue,Ue.toLowerCase().indexOf(ae.toLowerCase())===0&&ae.length>0&&te.current.setSelectionRange(ae.length,Ue.length)}}),He=!_i({array1:Ke.filteredOptions,array2:fe,parser:ue}),vt=()=>{const G=(U,le)=>{const ve=U?ue(U):"",ee=le?ue(le):"";return ve===ee};if(Le.current!==-1&&!_i({array1:Ke.filteredOptions,array2:fe,parser:ue})&&Ke.inputValue===ae&&($?ce.length===Ke.value.length&&Ke.value.every((U,le)=>ue(ce[le])===ue(U)):G(Ke.value,ce))){const U=Ke.filteredOptions[Le.current];if(U)return fe.findIndex(le=>ue(le)===ue(U))}return-1},Ce=je.useCallback(()=>{if(!Ye)return;const G=vt();if(G!==-1){Le.current=G;return}const U=$?ce[0]:ce;if(fe.length===0||U==null){me({diff:"reset"});return}if(K.current){if(U!=null){const le=fe[Le.current];if($&&le&&ce.findIndex(ee=>V(le,ee))!==-1)return;const ve=fe.findIndex(ee=>V(ee,U));ve===-1?me({diff:"reset"}):Qe({index:ve});return}if(Le.current>=fe.length-1){Qe({index:fe.length-1});return}Qe({index:Le.current})}},[fe.length,$?!1:ce,T,me,Qe,Ye,ae,$]),Re=c.useEventCallback(G=>{c.setRef(K,G),G&&Ce()});je.useEffect(()=>{He&&Ce()},[Ce,He]);const Ie=G=>{at||(yt(!0),Ot(!0),H&&H(G))},We=(G,U)=>{at&&(yt(!1),Z&&Z(G,U))},dt=(G,U,le,ve)=>{if($){if(ce.length===U.length&&ce.every((ee,qe)=>ee===U[qe]))return}else if(ce===U)return;W&&W(G,U,le,ve),Y(U)},Pe=je.useRef(!1),tt=(G,U,le="selectOption",ve="options")=>{let ee=le,qe=U;if($){qe=Array.isArray(ce)?ce.slice():[];const Ue=qe.findIndex(Ct=>V(U,Ct));Ue===-1?qe.push(U):ve!=="freeSolo"&&(qe.splice(Ue,1),ee="removeOption")}Ee(G,qe,ee),dt(G,qe,ee,{option:U}),!x&&(!G||!G.ctrlKey&&!G.metaKey)&&We(G,ee),(a===!0||a==="touch"&&Pe.current||a==="mouse"&&!Pe.current)&&te.current.blur()};function Mt(G,U){if(G===-1)return-1;let le=G;for(;;){if(U==="next"&&le===ce.length||U==="previous"&&le===-1)return-1;const ve=se?"data-item-index":"data-tag-index",ee=he.querySelector(`[${ve}="${le}"]`);if(!ee||!ee.hasAttribute("tabindex")||ee.disabled||ee.getAttribute("aria-disabled")==="true")le+=U==="next"?1:-1;else return le}}const kt=(G,U)=>{if(!$)return;ae===""&&We(G,"toggleInput");let le=ge;ge===-1?ae===""&&U==="previous"&&(le=ce.length-1):(le+=U==="next"?1:-1,le<0&&(le=0),le===ce.length&&(le=-1)),le=Mt(le,U),pe(le),lt(le)},Ft=G=>{be.current=!0,Fe(""),J&&J(G,"","clear"),dt(G,$?[]:null,"clear")},gn=G=>U=>{if(G.onKeyDown&&G.onKeyDown(U),!U.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(U.key)&&(pe(-1),lt(-1)),U.which!==229))switch(U.key){case"Home":Ye&&F&&(U.preventDefault(),me({diff:"start",direction:"next",reason:"keyboard",event:U}));break;case"End":Ye&&F&&(U.preventDefault(),me({diff:"end",direction:"previous",reason:"keyboard",event:U}));break;case"PageUp":U.preventDefault(),me({diff:-Pi,direction:"previous",reason:"keyboard",event:U}),Ie(U);break;case"PageDown":U.preventDefault(),me({diff:Pi,direction:"next",reason:"keyboard",event:U}),Ie(U);break;case"ArrowDown":U.preventDefault(),me({diff:1,direction:"next",reason:"keyboard",event:U}),Ie(U);break;case"ArrowUp":U.preventDefault(),me({diff:-1,direction:"previous",reason:"keyboard",event:U}),Ie(U);break;case"ArrowLeft":!$&&se?lt(0):kt(U,"previous");break;case"ArrowRight":!$&&se?lt(-1):kt(U,"next");break;case"Enter":if(Le.current!==-1&&Ye){const le=fe[Le.current],ve=M?M(le):!1;if(U.preventDefault(),ve)return;tt(U,le,"selectOption"),o&&te.current.setSelectionRange(te.current.value.length,te.current.value.length)}else O&&ae!==""&&pt===!1&&($&&U.preventDefault(),tt(U,ae,"createOption","freeSolo"));break;case"Escape":Ye?(U.preventDefault(),U.stopPropagation(),We(U,"escape")):d&&(ae!==""||$&&ce.length>0||se)&&(U.preventDefault(),U.stopPropagation(),Ft(U));break;case"Backspace":if($&&!oe&&ae===""&&ce.length>0){const le=ge===-1?ce.length-1:ge,ve=ce.slice();ve.splice(le,1),dt(U,ve,"removeOption",{option:ce[le]})}!$&&se&&!oe&&(Y(null),lt(-1));break;case"Delete":if($&&!oe&&ae===""&&ce.length>0&&ge!==-1){const le=ge,ve=ce.slice();ve.splice(le,1),dt(U,ve,"removeOption",{option:ce[le]})}!$&&se&&!oe&&(Y(null),lt(-1));break}},Ne=G=>{St(!0),re&&!be.current&&Ie(G)},ut=G=>{if(n(K)){te.current.focus();return}St(!1),Me.current=!0,be.current=!1,l&&Le.current!==-1&&Ye?tt(G,fe[Le.current],"blur"):l&&O&&ae!==""?tt(G,ae,"blur","freeSolo"):u&&Ee(G,ce,"blur"),We(G,"blur")},Kt=G=>{const U=G.target.value;ae!==U&&(Fe(U),Ot(!1),J&&J(G,U,"input")),U===""?!b&&!$&&dt(G,null,"clear"):Ie(G)},yn=G=>{const U=Number(G.currentTarget.getAttribute("data-option-index"));Le.current!==U&&Qe({event:G,index:U,reason:"mouse"})},ht=G=>{Qe({event:G,index:Number(G.currentTarget.getAttribute("data-option-index")),reason:"touch"}),Pe.current=!0},en=G=>{const U=Number(G.currentTarget.getAttribute("data-option-index"));tt(G,fe[U],"selectOption"),Pe.current=!1},xn=G=>U=>{const le=ce.slice();le.splice(G,1),dt(U,le,"removeOption",{option:ce[G]})},Qt=G=>{dt(G,null,"removeOption",{option:ce})},Ze=G=>{at?We(G,"toggleInput"):Ie(G)},Xe=G=>{G.currentTarget.contains(G.target)&&G.target.getAttribute("id")!==de&&G.preventDefault()},At=G=>{G.currentTarget.contains(G.target)&&(te.current.focus(),ie&&Me.current&&te.current.selectionEnd-te.current.selectionStart===0&&te.current.select(),Me.current=!1)},tn=G=>{!v&&(ae===""||!at)&&Ze(G)};let Zt=O&&ae.length>0;Zt=Zt||($?ce.length>0:ce!==null);let nn=fe;return P&&(nn=fe.reduce((G,U,le)=>{const ve=P(U);return G.length>0&&G[G.length-1].group===ve?G[G.length-1].options.push(U):G.push({key:le,index:le,group:ve,options:[U]}),G},[])),v&&Ve&&ut(),{getRootProps:(G={})=>({...G,onKeyDown:gn(G),onMouseDown:Xe,onClick:At}),getInputLabelProps:()=>({id:`${de}-label`,htmlFor:de}),getInputProps:()=>({id:de,value:ae,onBlur:ut,onFocus:Ne,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ye?"":null,"aria-autocomplete":o?"both":"list","aria-controls":ze?`${de}-listbox`:void 0,"aria-expanded":ze,autoComplete:"off",ref:te,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:Ft}),getItemProps:({index:G=0}={})=>({...$&&{key:G},...se?{"data-item-index":G}:{"data-tag-index":G},tabIndex:-1,...!oe&&{onDelete:$?xn(G):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Ze}),getTagProps:({index:G})=>({key:G,"data-tag-index":G,tabIndex:-1,...!oe&&{onDelete:xn(G)}}),getListboxProps:()=>({role:"listbox",id:`${de}-listbox`,"aria-labelledby":`${de}-label`,ref:Re,onMouseDown:G=>{G.preventDefault()}}),getOptionProps:({index:G,option:U})=>{const le=($?ce:[ce]).some(ee=>ee!=null&&V(U,ee)),ve=M?M(U):!1;return{key:E?.(U)??ue(U),tabIndex:-1,role:"option",id:`${de}-option-${G}`,onMouseMove:yn,onClick:en,onTouchStart:ht,"data-option-index":G,"aria-disabled":ve,"aria-selected":le}},id:de,inputValue:ae,value:ce,dirty:Zt,expanded:Ye&&he,popupOpen:Ye,focused:Ve||ge!==-1,anchorEl:he,setAnchorEl:we,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function Dh(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const $h=e=>{const{classes:n,color:r,disableGutters:o,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!o&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,Dh,n)},Fh=c.styled("li",{name:"MuiListSubheader",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.color!=="default"&&n[`color${c.capitalize(r.color)}`],!r.disableGutters&&n.gutters,r.inset&&n.inset,!r.disableSticky&&n.sticky]}})(c.memoTheme(({theme:e})=>({boxSizing:"border-box",lineHeight:"48px",listStyle:"none",color:(e.vars||e).palette.text.secondary,fontFamily:e.typography.fontFamily,fontWeight:e.typography.fontWeightMedium,fontSize:e.typography.pxToRem(14),variants:[{props:{color:"primary"},style:{color:(e.vars||e).palette.primary.main}},{props:{color:"inherit"},style:{color:"inherit"}},{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.inset,style:{paddingLeft:72}},{props:({ownerState:n})=>!n.disableSticky,style:{position:"sticky",top:0,zIndex:1,backgroundColor:(e.vars||e).palette.background.paper}}]}))),Ys=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:u=!1,disableSticky:d=!1,inset:h=!1,...y}=o,b={...o,color:l,component:a,disableGutters:u,disableSticky:d,inset:h},x=$h(b);return t.jsx(Fh,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...y})});Ys&&(Ys.muiSkipListHighlight=!0);const Ah=c.createSvgIcon(t.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}));function Rh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Oe=c.generateUtilityClasses("MuiAutocomplete",["root","expanded","fullWidth","focused","focusVisible","tag","tagSizeSmall","tagSizeMedium","hasPopupIcon","hasClearIcon","inputRoot","input","inputFocused","endAdornment","clearIndicator","popupIndicator","popupIndicatorOpen","popper","popperDisablePortal","paper","listbox","loading","noOptions","option","groupLabel","groupUl"]);var Wi,qi;const Lh=e=>{const{classes:n,disablePortal:r,expanded:o,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:u,inputFocused:d,popupOpen:h,size:y}=e,b={root:["root",o&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",u&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",d&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(y)}`],endAdornment:["endAdornment"],clearIndicator:["clearIndicator"],popupIndicator:["popupIndicator",h&&"popupIndicatorOpen"],popper:["popper",r&&"popperDisablePortal"],paper:["paper"],listbox:["listbox"],loading:["loading"],noOptions:["noOptions"],option:["option"],groupLabel:["groupLabel"],groupUl:["groupUl"]};return c.composeClasses(b,Rh,n)},_h=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:o,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:u}=r;return[{[`& .${Oe.tag}`]:n.tag},{[`& .${Oe.tag}`]:n[`tagSize${c.capitalize(u)}`]},{[`& .${Oe.inputRoot}`]:n.inputRoot},{[`& .${Oe.input}`]:n.input},{[`& .${Oe.input}`]:a&&n.inputFocused},n.root,o&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Oe.focused} .${Oe.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Oe.clearIndicator}`]:{visibility:"visible"}},[`& .${Oe.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Oe.inputRoot}`]:{[`.${Oe.hasPopupIcon}&, .${Oe.hasClearIcon}&`]:{paddingRight:30},[`.${Oe.hasPopupIcon}.${Oe.hasClearIcon}&`]:{paddingRight:56},[`& .${Oe.input}`]:{width:0,minWidth:30}},[`& .${c.inputClasses.root}`]:{paddingBottom:1,"& .MuiInput-input":{padding:"4px 4px 4px 0px"}},[`& .${c.inputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${c.inputClasses.input}`]:{padding:"2px 4px 3px 0"}},[`& .${c.outlinedInputClasses.root}`]:{padding:9,[`.${Oe.hasPopupIcon}&, .${Oe.hasClearIcon}&`]:{paddingRight:39},[`.${Oe.hasPopupIcon}.${Oe.hasClearIcon}&`]:{paddingRight:65},[`& .${Oe.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Oe.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Oe.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Oe.hasPopupIcon}&, .${Oe.hasClearIcon}&`]:{paddingRight:39},[`.${Oe.hasPopupIcon}.${Oe.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Oe.endAdornment}`]:{right:9}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingBottom:1,[`& .${c.filledInputClasses.input}`]:{padding:"2.5px 4px"}},[`& .${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:8},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:0,paddingBottom:0,[`& .${Oe.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Oe.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Oe.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Oe.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Oe.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Oe.inputRoot}`]:{flexWrap:"wrap"}}}]}),Nh=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),Ph=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),zh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"PopupIndicator",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.popupIndicator,r.popupOpen&&n.popupIndicatorOpen]}})({padding:2,marginRight:-2,variants:[{props:{popupOpen:!0},style:{transform:"rotate(180deg)"}}]}),Wh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Oe.option}`]:n.option},n.popper,r.disablePortal&&n.popperDisablePortal]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.modal,variants:[{props:{disablePortal:!0},style:{position:"absolute"}}]}))),qh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Bh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Hh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Oe.option}`]:{minHeight:48,display:"flex",overflow:"hidden",justifyContent:"flex-start",alignItems:"center",cursor:"pointer",paddingTop:6,boxSizing:"border-box",outline:"0",WebkitTapHighlightColor:"transparent",paddingBottom:6,paddingLeft:16,paddingRight:16,[e.breakpoints.up("sm")]:{minHeight:"auto"},[`&.${Oe.focused}`]:{backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},'&[aria-disabled="true"]':{opacity:(e.vars||e).palette.action.disabledOpacity,pointerEvents:"none"},[`&.${Oe.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},'&[aria-selected="true"]':{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${Oe.focused}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:(e.vars||e).palette.action.selected}},[`&.${Oe.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Uh=c.styled(Ys,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Gh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Oe.option}`]:{paddingLeft:24}}),Ks=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:u=!1,ChipProps:d,className:h,clearIcon:y=Wi||(Wi=t.jsx(Ah,{fontSize:"small"})),clearOnBlur:b=!o.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:k="Close",componentsProps:C,defaultValue:S=o.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:O=!1,disabled:M=!1,disabledItemsFocusable:E=!1,disableListWrap:R=!1,disablePortal:P=!1,filterOptions:F,filterSelectedOptions:B=!1,forcePopupIcon:D="auto",freeSolo:_=!1,fullWidth:V=!1,getLimitTagsText:$=$e=>`+${$e}`,getOptionDisabled:W,getOptionKey:Z,getOptionLabel:ne,isOptionEqualToValue:J,groupBy:H,handleHomeEndKeys:Q=!o.freeSolo,id:re,includeInputInList:z=!1,inputValue:oe,limitTags:se=-1,ListboxComponent:ie,ListboxProps:De,loading:de=!1,loadingText:ue="Loading…",multiple:be=!1,noOptionsText:Me="No options",onChange:te,onClose:K,onHighlightChange:he,onInputChange:we,onOpen:ge,open:pe,openOnFocus:ye=!1,openText:Le="Open",options:st,PaperComponent:ce,PopperComponent:Y,popupIcon:ae=qi||(qi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Fe=!1,renderGroup:Ve,renderInput:St,renderOption:Ee,renderTags:at,renderValue:yt,selectOnFocus:xt=!o.freeSolo,size:Ot="medium",slots:pt={},slotProps:Ye={},value:fe,...Ke}=o,{getRootProps:ze,getInputProps:lt,getInputLabelProps:ct,getPopupIndicatorProps:Qe,getClearProps:me,getItemProps:He,getListboxProps:vt,getOptionProps:Ce,value:Re,dirty:Ie,expanded:We,id:dt,popupOpen:Pe,focused:tt,focusedItem:Mt,anchorEl:kt,setAnchorEl:Ft,inputValue:gn,groupedOptions:Ne}=Ih({...o,componentName:"Autocomplete"}),ut=!T&&!M&&Ie&&!Fe,Kt=(!_||D===!0)&&D!==!1,{onMouseDown:yn}=lt(),{ref:ht,...en}=vt(),Qt=ne||($e=>$e.label??$e),Ze={...o,disablePortal:P,expanded:We,focused:tt,fullWidth:V,getOptionLabel:Qt,hasClearIcon:ut,hasPopupIcon:Kt,inputFocused:Mt===-1,popupOpen:Pe,size:Ot},Xe=Lh(Ze),At={slots:{paper:ce,popper:Y,...pt},slotProps:{chip:d,listbox:De,...C,...Ye}},[tn,Zt]=c.useSlot("listbox",{elementType:Hh,externalForwardedProps:At,ownerState:Ze,className:Xe.listbox,additionalProps:en,ref:ht}),[nn,G]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:At,ownerState:Ze,className:Xe.paper}),[U,le]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:At,ownerState:Ze,className:Xe.popper,additionalProps:{disablePortal:P,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:Pe}});let ve;const ee=$e=>({className:Xe.tag,disabled:M,...He($e)});if(be?Re.length>0&&(at?ve=at(Re,ee,Ze):yt?ve=yt(Re,ee,Ze):ve=Re.map(($e,zt)=>{const{key:gt,...qt}=ee({index:zt});return t.jsx(c.Chip,{label:Qt($e),size:Ot,...qt,...At.slotProps.chip},gt)})):yt&&Re!=null&&(ve=yt(Re,ee,Ze)),se>-1&&Array.isArray(ve)){const $e=ve.length-se;!tt&&$e>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Xe.tag,children:$($e)},ve.length)))}const Ue=Ve||($e=>t.jsxs("li",{children:[t.jsx(Uh,{className:Xe.groupLabel,ownerState:Ze,component:"div",children:$e.group}),t.jsx(Gh,{className:Xe.groupUl,ownerState:Ze,children:$e.children})]},$e.key)),vn=Ee||(($e,zt)=>{const{key:gt,...qt}=$e;return t.jsx("li",{...qt,children:Qt(zt)},gt)}),zn=($e,zt)=>{const gt=Ce({option:$e,index:zt});return vn({...gt,className:Xe.option},$e,{selected:gt["aria-selected"],index:zt,inputValue:gn},Ze)},Wn=At.slotProps.clearIndicator,Dr=At.slotProps.popupIndicator;return t.jsxs(je.Fragment,{children:[t.jsx(_h,{ref:r,className:c.clsx(Xe.root,h),ownerState:Ze,...ze(Ke),children:St({id:dt,disabled:M,fullWidth:!0,size:Ot==="small"?"small":void 0,InputLabelProps:ct(),InputProps:{ref:Ft,className:Xe.inputRoot,startAdornment:ve,onMouseDown:$e=>{$e.target===$e.currentTarget&&yn($e)},...(ut||Kt)&&{endAdornment:t.jsxs(Nh,{className:Xe.endAdornment,ownerState:Ze,children:[ut?t.jsx(Ph,{...me(),"aria-label":v,title:v,ownerState:Ze,...Wn,className:c.clsx(Xe.clearIndicator,Wn?.className),children:y}):null,Kt?t.jsx(zh,{...Qe(),disabled:M,"aria-label":Pe?k:Le,title:Pe?k:Le,ownerState:Ze,...Dr,className:c.clsx(Xe.popupIndicator,Dr?.className),children:ae}):null]})}},inputProps:{className:Xe.input,disabled:M,readOnly:Fe,...lt()}})}),kt?t.jsx(Wh,{as:U,...le,children:t.jsxs(qh,{as:nn,...G,children:[de&&Ne.length===0?t.jsx(Bh,{className:Xe.loading,ownerState:Ze,children:ue}):null,Ne.length===0&&!_&&!de?t.jsx(Vh,{className:Xe.noOptions,ownerState:Ze,role:"presentation",onMouseDown:$e=>{$e.preventDefault()},children:Me}):null,Ne.length>0?t.jsx(tn,{as:ie,...Zt,children:Ne.map(($e,zt)=>H?Ue({key:$e.key,group:$e.group,children:$e.options.map((gt,qt)=>zn(gt,$e.index+qt))}):zn($e,zt))}):null]})}):null]})});c.dayjs.extend(c.utc);function Ts(e){switch(e){case"Star":return["Equals","Contains"];case"MinMax":return["Equals","Less Than","Greater Than","Between"];case"DateMinMax":return["Equals","Before","After","Between"];case"Retrieval":return["Semantic Search"];case"Boolean":return["Equals"];case"NONE":default:return[]}}function Yh(e){return e==="DateMinMax"}function Os(e){return e==="Between"}function Kh({spec:e,values:n,selection:r,onChange:o,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Ts(e.filterType)[0]||"Equals",[a,u]=j.useState(l()),[d,h]=j.useState(r?.value??""),[y,b]=j.useState(r?.value2??""),[x,v]=j.useState([]),[k,C]=j.useState(!1),[S,T]=j.useState(""),[O,M]=j.useState(!1),[E,R]=j.useState(!1),P=j.useRef(null),F=j.useRef(0),[B,D]=j.useState(!1);j.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),M(!1);return}return P.current&&clearTimeout(P.current),P.current=setTimeout(async()=>{F.current+=1;const oe=F.current;C(!0);try{const se=await i(z,e);oe===F.current&&v(se)}catch(se){oe===F.current&&(console.error("Retrieval failed",se),v([]))}finally{oe===F.current&&(C(!1),M(!0))}},500),()=>{P.current&&clearTimeout(P.current)}},[S,e,i]),j.useEffect(()=>{r===null?(h(""),b(""),u(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Ts(e.filterType)[0]||"Equals"))):r&&(u(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const _=Ts(e.filterType),V=Yh(e.filterType),$=Os(a),W=V&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,Z=V&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,ne=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,J=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(_.length===0)return null;const H=z=>{const oe=z.target.value;u(oe),Os(oe)||b(""),d&&o({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:oe,value:d,...Os(oe)&&y&&{value2:y}})},Q=(z,oe)=>{h(z??""),oe!==void 0&&b(oe??"");const se=Array.isArray(z)&&z.length===0;o(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...$&&oe&&{value2:oe}}:null)},re=()=>{h(""),b(""),o(null)};return t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1.5,fontSize:"0.75rem","& .MuiInputBase-root":{fontSize:"0.75rem"},"& .MuiInputBase-input":{padding:"6px 10px"},"& .MuiSelect-select":{padding:"6px 10px !important"},"& .MuiAutocomplete-input":{padding:"0 !important"},"& .MuiAutocomplete-root .MuiInputBase-root":{padding:"5px 10px",minHeight:"29.5px",boxSizing:"border-box",flexWrap:"wrap"},"& .MuiChip-root":{height:"16px",margin:"0 2px 0 0"},"& .MuiChip-label":{fontSize:"0.7rem",padding:"0 6px"},"& .MuiChip-deleteIcon":{fontSize:"14px",margin:"0 2px 0 -4px"},"& .MuiInputLabel-root":{fontSize:"0.75rem",transform:"translate(10px, 6px) scale(1)"},"& .MuiInputLabel-shrink":{fontSize:"0.85rem",transform:"translate(14px, -9px) scale(0.75)"},"& .MuiOutlinedInput-notchedOutline legend":{fontSize:"0.65rem"},"& .MuiFormHelperText-root":{fontSize:"0.65rem",marginTop:"2px"},"& .MuiSvgIcon-root":{fontSize:"1.25rem"}},children:[t.jsxs(Ge,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ge,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&_.length>1&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Match Type"}),t.jsx(c.Select,{value:a,label:"Match Type",onChange:H,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:_.map(z=>t.jsx(et,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Ks,{multiple:!0,size:"small",options:n,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(d)?d.map(z=>n.find(oe=>oe.value===z)||z):d?[n.find(z=>z.value===d)||d]:[],onChange:(z,oe)=>{const se=oe.map(ie=>typeof ie=="string"?ie:ie&&typeof ie=="object"&&"value"in ie?ie.value:ie);Q(se)},noOptionsText:"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!e.values||e.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="Star"&&a==="Contains"&&t.jsx(c.TextField,{size:"small",label:"Search Text",value:d,onChange:z=>h(z.target.value),onBlur:()=>Q(d),onKeyDown:z=>{z.key==="Enter"&&Q(d)},placeholder:"Enter text to search...",fullWidth:!0}),e.filterType==="Boolean"&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Value"}),t.jsxs(c.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:z=>{const oe=z.target.value;oe==="true"?Q(!0):oe==="false"?Q(!1):re()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(et,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(et,{value:"true",children:"True"}),t.jsx(et,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Ks,{multiple:!0,size:"small",options:x,loading:k,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(d)?d.map(z=>x.find(se=>se.value===z)||{value:z}):d?[{value:d}]:[],onInputChange:(z,oe)=>{T(oe)},onChange:(z,oe)=>{const se=oe.map(ie=>typeof ie=="string"?ie:ie&&typeof ie=="object"&&"value"in ie?ie.value:ie);Q(se)},noOptionsText:S.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>R(!0),onBlur:()=>R(!1),helperText:E&&!k&&O&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[k?t.jsx(c.CircularProgress,{color:"inherit",size:20}):null,z.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:z=>z,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="MinMax"&&!$&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:z=>Q(parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:ne,max:J},helperText:B&&ne!==void 0&&J!==void 0?`Valid range: [${ne} - ${J}]`:void 0}),e.filterType==="MinMax"&&$&&t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:d,onChange:z=>Q(parseFloat(z.target.value)||"",y),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:ne,max:y||J}}),t.jsx(Ge,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:y,onChange:z=>Q(d,parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||ne,max:J}})]}),B&&ne!==void 0&&J!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",ne," - ",J,"]"]})]}),V&&!$&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:d instanceof Date?c.dayjs.utc(d):null,onChange:z=>{z===null?Q(null):z.isValid()&&Q(z.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:W,maxDate:d instanceof Date?void 0:Z,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>D(!0),onBlur:()=>D(!1),helperText:B&&W&&Z?`Valid range: [${W.format("YYYY-MM-DD")} - ${Z.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),V&&$&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ge,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:d instanceof Date?c.dayjs.utc(d):null,onChange:z=>{z===null?Q(null,y):z.isValid()&&Q(z.utc().toDate(),y)},timezone:"UTC",minDate:d instanceof Date?void 0:W,maxDate:y instanceof Date?c.dayjs.utc(y):d instanceof Date?void 0:Z,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ge,{children:"to"}),t.jsx(Ge,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:y instanceof Date?c.dayjs.utc(y):null,onChange:z=>{z===null?Q(d,null):z.isValid()&&Q(d,z.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?c.dayjs.utc(d):y instanceof Date?void 0:W,maxDate:y instanceof Date?void 0:Z,referenceDate:d instanceof Date?c.dayjs.utc(d):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),B&&W&&Z&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",Z.format("YYYY-MM-DD"),"]"]})]})})]})}function os(e,n){const{matchType:r,value:o,value2:i}=n;if(Array.isArray(o))return r!=="Equals"&&r!=="Semantic Search"||o.length===0?"":`(${o.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(o)}`;case"Contains":if(typeof o=="string"){const l=Ju.StringFilterExpression.unparse({operator:"contains",values:[o]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(o)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(o)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(o)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(o)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(o)}`;default:return""}}function Qh(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const o of r)"kind"in o&&o.kind==="join"&&o.name&&n.add(o.name);return n}function Zh(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const o=JSON.parse(r);if(Array.isArray(o)){const i=[];for(const l of o)if(typeof l=="string"){const a=l.indexOf(".");a>0&&a<l.length-1&&i.push({source:l.substring(0,a),dimension:l.substring(a+1)})}if(i.length>0)return{filters:i}}}catch(o){console.error(`Failed to parse "${n}" annotation:`,o)}}return null}function rl(e){if(e.startsWith("#(filter)")){const n=e.slice(9).trim();try{const r=JSON.parse(n);if(r.type)return r}catch(r){console.error(`Failed to parse "${e}" annotation:`,r)}}return null}function Xh(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function Jh(e){const n=new Map;let r="";for(const o of e)if(o.type==="code"){if(!r&&o.text){const l=o.text.split(`
4
+ `).map(a=>a.trim()).find(a=>a.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);l&&(r=l[1])}if(o.newSources&&o.newSources.length>0)for(const i of o.newSources)try{const l=JSON.parse(i);l.name&&n.set(l.name,l)}catch(l){console.error("Failed to parse SourceInfo:",l)}}return{sourceInfoMap:n,modelPath:r}}function ef(e,n,r){const o=[];for(const{source:i,dimension:l}of n){const a=e.get(i);if(!a){console.warn(`Source "${i}" not found in notebook sources`),o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const u=a.schema?.fields;if(!u){o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const d=u.find(b=>b.name===l);if(!d){console.warn(`Dimension "${l}" not found in source "${i}"`),o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}let h="Star",y;if("annotations"in d&&d.annotations){for(const b of d.annotations)if(b.value){const x=rl(b.value);x&&(h=x.type);const v=Xh(b.value);v&&(y=v)}}o.push({source:i,model:r,dimensionName:l,filterType:h,label:y})}return o}function tf(e,n,r){return e.length===0?"":e.map(i=>{const{dimensionName:l,source:a}=i,d=a&&a!==r?`\`${a}\`.\`${l}\``:`\`${l}\``;return os(d,i)}).filter(i=>i.length>0).join(" and ")}function nf(e){const n=e.match(/run\s*:\s*(\w+)\s*->/);if(n)return n[1];const r=e.match(/^\s*(\w+)\s*->/m);return r?r[1]:null}function rf(e,n){return`${e.trimEnd()} + {where: ${n}}`}const sf=c.createSvgIcon(t.jsx("path",{d:"m9.17 6 2 2H20v10H4V6zM10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"})),sl=e=>{if(!e)return"Explore semantic models, run queries, and build reports";const n=e.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),o=n.split(/\n\s*\n/)[1]||n;if(o.length<=120)return o;const i=o.substring(0,120).split(" ");return i.pop(),i.join(" ")+"..."},ol=(e,n)=>{const r=(e.readme||void 0)?.split(`
5
5
  `)??[];return r.length===0&&(r.push(`# ${e.name}`),r.push("")),(e.readme?.length??0)>0&&n?r.splice(2,1,n):n&&r.push(n),r.join(`
6
- `)};function Vi(){const[e,n]=j.useState(!1),{apiClients:r}=q.useServer(),o=()=>{n(!0)},i=()=>{n(!1)},l=_n({mutationFn(d){return r.environments.createEnvironment({name:d.name,readme:ol({name:d.name,readme:""},d.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:i,resource:"environment",action:"create"}),a=async d=>{d.preventDefault();const u=new FormData(d.currentTarget),h=u.get("name")?.toString(),y=u.get("description")?.toString();if(!h)throw new Error("Name is required");l.mutate({name:h,description:y})};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Environment",onClick:o}),t.jsx(c.AppDialog,{open:e,onClose:i,title:"New environment",description:"An environment holds packages and the connections they query through.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:l.isPending,onClick:i,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:l.isPending,children:"Create environment"})]}),children:t.jsx("form",{onSubmit:a,id:"environment-form",children:t.jsxs(os,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",placeholder:"Explore semantic models, run queries, and build reports",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),l.notice]})}function af({environment:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},d=_n({mutationFn:()=>i.environments.deleteEnvironment(e.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete environment",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>d.mutate(),loading:d.isPending,children:"Delete environment"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Its packages stop being served and this cannot be undone."]})}),d.notice]})}function lf({environment:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},d=_n({mutationFn(h){return i.environments.updateEnvironment(e.name,{name:e.name,readme:ol({name:e.name,readme:e.readme},h.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"update"}),u=h=>{h.preventDefault();const b=new FormData(h.currentTarget).get("description")?.toString();d.mutate({description:b})};return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:d.isPending,onClick:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:d.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:u,id:"environment-form",children:t.jsxs(os,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:sl(e.readme),InputLabelProps:{shrink:!0}})]})})}),d.notice]})}const cf=[{title:"Model",body:"An agent writes what the data means in Malloy — sources, joins, measures — from a warehouse or a file, and validates each edit without a restart.",href:Vt.publishing},{title:"Analyze",body:"Claude, Cursor, Codex or an agent you build asks over MCP; applications and BI tools use REST. Every question runs against the model, never the raw tables.",href:Vt.mcpAgents},{title:"Surface",body:"Reports declared in Malloy, laid out as a grid or read top to bottom, and no-build HTML data apps, all shipped inside the package, plus this Console for browsing them.",href:Vt.surfaces},{title:"Govern",body:"Runtime parameters, row-level filters and per-source gates are declared in the model, so every surface reads the same rules rather than writing its own.",href:Vt.givens},{title:"Optimize",body:"One annotation materializes an expensive source into a table, and another rolls a measure up to a coarser grain, rebuilt on demand or on a schedule.",href:Vt.materialization},{title:"Run anywhere",body:"DuckDB is built in for CSV, Parquet, JSON and Excel; BigQuery, Snowflake, Postgres, Databricks, MotherDuck and more connect by configuration.",href:Vt.connections}];function uf({href:e,children:n}){return t.jsx(p.Box,{component:"a",href:e,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:n})}function df({onClickEnvironment:e}){const{apiClients:n,mutable:r}=q.useServer(),{data:o,isSuccess:i,isError:l,error:a}=c.useQueryWithApiError({queryKey:["environments"],queryFn:()=>n.environments.listEnvironments()});if(l)return t.jsx(c.ApiErrorDisplay,{error:a,context:"Environments List"});if(!i)return t.jsx(c.Loading,{text:"Loading environments..."});const d=o.data??[];return t.jsxs(p.Container,{maxWidth:"md",sx:{py:6},children:[t.jsxs(p.Box,{sx:{mb:5},children:[t.jsx(p.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),t.jsx(p.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6},children:"One data model, served over MCP and REST to AI agents, applications and BI tools. Write down what your data means — the sources, the joins, the measures, who may see what — and every surface asks the same model, so the same question returns the same numbers tomorrow."})]}),t.jsx(p.Grid,{container:!0,spacing:4,sx:{mb:5},children:cf.map(u=>t.jsx(p.Grid,{size:{xs:12,sm:6},children:t.jsxs(p.Stack,{spacing:1,children:[t.jsx(p.Typography,{variant:"body2",component:"a",href:u.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:u.title}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:u.body})]})},u.title))}),t.jsx(p.Divider,{sx:{my:4}}),d.length>0?t.jsx(_t,{title:"Environments",count:d.length,description:"Published environments available on this server",...r?{action:t.jsx(Vi,{})}:{},children:t.jsx(p.Stack,{children:d.map(u=>t.jsx(hf,{environment:u,...e?{onClickEnvironment:e}:{}},u.name))})}):t.jsxs(p.Box,{sx:{mb:4},children:[t.jsx(p.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:3,maxWidth:600},children:"Create your first Malloy environment to start exploring semantic models and building data experiences."}),r?t.jsx(Vi,{}):t.jsx(p.Button,{variant:"contained",color:"primary",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),t.jsx(p.Divider,{sx:{my:4}}),t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",t.jsx(uf,{href:"https://join.slack.com/t/malloy-community/shared_invite/zt-1kgfwgi5g-CrsdaRqs81QY67QW0~t_uw",children:"Malloy Slack community"})," ","to ask questions, share ideas, and contribute."]})]})}function hf({environment:e,onClickEnvironment:n}){const{mutable:r}=q.useServer(),[o,i]=j.useState(null),l=!!o,a=sl(e.readme),d=h=>{h.stopPropagation(),i(h.currentTarget)},u=()=>i(null);return t.jsx(ss,{icon:t.jsx(of,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.environment,label:e.name??"",ariaLabel:e.name??"",...a?{description:a}:{},...e.name&&n?{onClick:h=>n(`/${e.name}/`,h)}:{},...r?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:d,"aria-label":`Environment actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:o,open:l,onClose:u,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(lf,{environment:e,onCloseDialog:u}),t.jsx(af,{environment:e,onCloseDialog:u})]})]})}:{}})}var an={},jt={},tr={},ln={},Es={},Hi;function ff(){return Hi||(Hi=1,Object.defineProperty(Es,"__esModule",{value:!0})),Es}var nr={},rr={},Ui;function mn(){if(Ui)return rr;Ui=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.CronField=void 0;let e=class il{#e=!1;#n=!1;#o=!1;#s=[];options={rawValue:""};static get min(){throw new Error("min must be overridden")}static get max(){throw new Error("max must be overridden")}static get chars(){return Object.freeze([])}static get validChars(){return/^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}static get constraints(){return{min:this.min,max:this.max,chars:this.chars,validChars:this.validChars}}constructor(r,o={rawValue:""}){if(!Array.isArray(r))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(r.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...o,rawValue:o.rawValue??""},this.#s=r.sort(il.sorter),this.#o=this.options.wildcard!==void 0?this.options.wildcard:this.#r(),this.#e=this.options.rawValue.includes("L")||r.includes("L"),this.#n=this.options.rawValue.includes("?")||r.includes("?")}get min(){return this.constructor.min}get max(){return this.constructor.max}get chars(){return this.constructor.chars}get hasLastChar(){return this.#e}get hasQuestionMarkChar(){return this.#n}get isWildcard(){return this.#o}get values(){return this.#s}static sorter(r,o){const i=typeof r=="number",l=typeof o=="number";return i&&l?r-o:!i&&!l?r.localeCompare(o):i?-1:1}static findNearestValueInList(r,o,i){if(i){for(let l=r.length-1;l>=0;l--)if(r[l]<o)return r[l];return null}for(let l=0;l<r.length;l++)if(r[l]>o)return r[l];return null}findNearestValue(r,o){return this.constructor.findNearestValueInList(this.values,r,o)}serialize(){return{wildcard:this.#o,values:this.#s}}validate(){let r;const o=this.chars.length>0?` or chars ${this.chars.join("")}`:"",i=u=>h=>new RegExp(`^\\d{0,2}${h}$`).test(u),l=u=>(r=u,typeof u=="number"?u>=this.min&&u<=this.max:this.chars.some(i(u)));if(!this.#s.every(l))throw new Error(`${this.constructor.name} Validation error, got value ${r} expected range ${this.min}-${this.max}${o}`);const d=this.#s.find((u,h)=>this.#s.indexOf(u)!==h);if(d)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${d}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(r,o)=>o+this.min).every(r=>this.#s.includes(r))}};return rr.CronField=e,rr}var Gi;function mf(){if(Gi)return nr;Gi=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.CronDayOfMonth=void 0;const e=mn(),n=1,r=31,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return nr.CronDayOfMonth=i,nr}var sr={},Yi;function pf(){if(Yi)return sr;Yi=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.CronDayOfWeek=void 0;const e=mn(),n=0,r=7,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return sr.CronDayOfWeek=i,sr}var or={},Ki;function gf(){if(Ki)return or;Ki=1,Object.defineProperty(or,"__esModule",{value:!0}),or.CronHour=void 0;const e=mn(),n=0,r=23,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return or.CronHour=i,or}var ir={},Qi;function yf(){if(Qi)return ir;Qi=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.CronMinute=void 0;const e=mn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return ir.CronMinute=i,ir}var ar={},Is={},wt={},Zi;function xf(){if(Zi)return wt;Zi=1,Object.defineProperty(wt,"__esModule",{value:!0});class e extends Error{}class n extends e{constructor(s){super(`Invalid DateTime: ${s.toMessage()}`)}}class r extends e{constructor(s){super(`Invalid Interval: ${s.toMessage()}`)}}class o extends e{constructor(s){super(`Invalid Duration: ${s.toMessage()}`)}}class i extends e{}class l extends e{constructor(s){super(`Invalid unit ${s}`)}}class a extends e{}class d extends e{constructor(){super("Zone is an abstract class")}}const u="numeric",h="short",y="long",b={year:u,month:u,day:u},x={year:u,month:h,day:u},v={year:u,month:h,day:u,weekday:h},k={year:u,month:y,day:u},C={year:u,month:y,day:u,weekday:y},S={hour:u,minute:u},T={hour:u,minute:u,second:u},O={hour:u,minute:u,second:u,timeZoneName:h},M={hour:u,minute:u,second:u,timeZoneName:y},E={hour:u,minute:u,hourCycle:"h23"},R={hour:u,minute:u,second:u,hourCycle:"h23"},P={hour:u,minute:u,second:u,hourCycle:"h23",timeZoneName:h},A={hour:u,minute:u,second:u,hourCycle:"h23",timeZoneName:y},H={year:u,month:u,day:u,hour:u,minute:u},D={year:u,month:u,day:u,hour:u,minute:u,second:u},L={year:u,month:h,day:u,hour:u,minute:u},U={year:u,month:h,day:u,hour:u,minute:u,second:u},$={year:u,month:h,day:u,weekday:h,hour:u,minute:u},W={year:u,month:y,day:u,hour:u,minute:u,timeZoneName:h},Q={year:u,month:y,day:u,hour:u,minute:u,second:u,timeZoneName:h},te={year:u,month:y,day:u,weekday:y,hour:u,minute:u,timeZoneName:y},ee={year:u,month:y,day:u,weekday:y,hour:u,minute:u,second:u,timeZoneName:y};class G{get type(){throw new d}get name(){throw new d}get ianaName(){return this.name}get isUniversal(){throw new d}offsetName(s,f){throw new d}formatOffset(s,f){throw new d}offset(s){throw new d}equals(s){throw new d}get isValid(){throw new d}}let Z=null;class ae extends G{static get instance(){return Z===null&&(Z=new ae),Z}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Fo(s,f,g)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){return-new Date(s).getTimezoneOffset()}equals(s){return s.type==="system"}get isValid(){return!0}}const z=new Map;function re(m){let s=z.get(m);return s===void 0&&(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:m,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),z.set(m,s)),s}const se={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ne(m,s){const f=m.format(s).replace(/\u200E/g,""),g=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(f),[,w,I,F,N,_,X,xe]=g;return[F,w,I,N,_,X,xe]}function Ie(m,s){const f=m.formatToParts(s),g=[];for(let w=0;w<f.length;w++){const{type:I,value:F}=f[w],N=se[I];I==="era"?g[N]=F:J(N)||(g[N]=parseInt(F,10))}return g}const de=new Map;class pe extends G{static create(s){let f=de.get(s);return f===void 0&&de.set(s,f=new pe(s)),f}static resetCache(){de.clear(),z.clear()}static isValidSpecifier(s){return this.isValidZone(s)}static isValidZone(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}).format(),!0}catch{return!1}}constructor(s){super(),this.zoneName=s,this.valid=pe.isValidZone(s)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Fo(s,f,g,this.name)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){if(!this.valid)return NaN;const f=new Date(s);if(isNaN(f))return NaN;const g=re(this.name);let[w,I,F,N,_,X,xe]=g.formatToParts?Ie(g,f):ne(g,f);N==="BC"&&(w=-Math.abs(w)+1);const He=Ar({year:w,month:I,day:F,hour:_===24?0:_,minute:X,second:xe,millisecond:0});let we=+f;const it=we%1e3;return we-=it>=0?it:1e3+it,(He-we)/(60*1e3)}equals(s){return s.type==="iana"&&s.name===this.name}get isValid(){return this.valid}}let De={};function Le(m,s={}){const f=JSON.stringify([m,s]);let g=De[f];return g||(g=new Intl.ListFormat(m,s),De[f]=g),g}const oe=new Map;function K(m,s={}){const f=JSON.stringify([m,s]);let g=oe.get(f);return g===void 0&&(g=new Intl.DateTimeFormat(m,s),oe.set(f,g)),g}const le=new Map;function be(m,s={}){const f=JSON.stringify([m,s]);let g=le.get(f);return g===void 0&&(g=new Intl.NumberFormat(m,s),le.set(f,g)),g}const ge=new Map;function ue(m,s={}){const{base:f,...g}=s,w=JSON.stringify([m,g]);let I=ge.get(w);return I===void 0&&(I=new Intl.RelativeTimeFormat(m,s),ge.set(w,I)),I}let ye=null;function $e(){return ye||(ye=new Intl.DateTimeFormat().resolvedOptions().locale,ye)}const ze=new Map;function me(m){let s=ze.get(m);return s===void 0&&(s=new Intl.DateTimeFormat(m).resolvedOptions(),ze.set(m,s)),s}const Y=new Map;function ie(m){let s=Y.get(m);if(!s){const f=new Intl.Locale(m);s="getWeekInfo"in f?f.getWeekInfo():f.weekInfo,"minimalDays"in s||(s={...Ke,...s}),Y.set(m,s)}return s}function Oe(m){const s=m.indexOf("-x-");s!==-1&&(m=m.substring(0,s));const f=m.indexOf("-u-");if(f===-1)return[m];{let g,w;try{g=K(m).resolvedOptions(),w=m}catch{const _=m.substring(0,f);g=K(_).resolvedOptions(),w=_}const{numberingSystem:I,calendar:F}=g;return[w,I,F]}}function Fe(m,s,f){return(f||s)&&(m.includes("-u-")||(m+="-u"),f&&(m+=`-ca-${f}`),s&&(m+=`-nu-${s}`)),m}function at(m){const s=[];for(let f=1;f<=12;f++){const g=Se.utc(2009,f,1);s.push(m(g))}return s}function Me(m){const s=[];for(let f=1;f<=7;f++){const g=Se.utc(2016,11,13+f);s.push(m(g))}return s}function lt(m,s,f,g){const w=m.listingMode();return w==="error"?null:w==="en"?f(s):g(s)}function xt(m){return m.numberingSystem&&m.numberingSystem!=="latn"?!1:m.numberingSystem==="latn"||!m.locale||m.locale.startsWith("en")||me(m.locale).numberingSystem==="latn"}class vt{constructor(s,f,g){this.padTo=g.padTo||0,this.floor=g.floor||!1;const{padTo:w,floor:I,...F}=g;if(!f||Object.keys(F).length>0){const N={useGrouping:!1,...g};g.padTo>0&&(N.minimumIntegerDigits=g.padTo),this.inf=be(s,N)}}format(s){if(this.inf){const f=this.floor?Math.floor(s):s;return this.inf.format(f)}else{const f=this.floor?Math.floor(s):ms(s,3);return ot(f,this.padTo)}}}class Ot{constructor(s,f,g){this.opts=g,this.originalZone=void 0;let w;if(this.opts.timeZone)this.dt=s;else if(s.zone.type==="fixed"){const F=-1*(s.offset/60),N=F>=0?`Etc/GMT+${F}`:`Etc/GMT${F}`;s.offset!==0&&pe.create(N).valid?(w=N,this.dt=s):(w="UTC",this.dt=s.offset===0?s:s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone)}else s.zone.type==="system"?this.dt=s:s.zone.type==="iana"?(this.dt=s,w=s.zone.name):(w="UTC",this.dt=s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone);const I={...this.opts};I.timeZone=I.timeZone||w,this.dtf=K(f,I)}format(){return this.originalZone?this.formatToParts().map(({value:s})=>s).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const s=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?s.map(f=>{if(f.type==="timeZoneName"){const g=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...f,value:g}}else return f}):s}resolvedOptions(){return this.dtf.resolvedOptions()}}class pt{constructor(s,f,g){this.opts={style:"long",...g},!f&&zn()&&(this.rtf=ue(s,g))}format(s,f){return this.rtf?this.rtf.format(s,f):Ac(f,s,this.opts.numeric,this.opts.style!=="long")}formatToParts(s,f){return this.rtf?this.rtf.formatToParts(s,f):[]}}const Ke={firstDay:1,minimalDays:4,weekend:[6,7]};class he{static fromOpts(s){return he.create(s.locale,s.numberingSystem,s.outputCalendar,s.weekSettings,s.defaultToEN)}static create(s,f,g,w,I=!1){const F=s||Pe.defaultLocale,N=F||(I?"en-US":$e()),_=f||Pe.defaultNumberingSystem,X=g||Pe.defaultOutputCalendar,xe=qt(w)||Pe.defaultWeekSettings;return new he(N,_,X,xe,F)}static resetCache(){ye=null,oe.clear(),le.clear(),ge.clear(),ze.clear(),Y.clear()}static fromObject({locale:s,numberingSystem:f,outputCalendar:g,weekSettings:w}={}){return he.create(s,f,g,w)}constructor(s,f,g,w,I){const[F,N,_]=Oe(s);this.locale=F,this.numberingSystem=f||N||null,this.outputCalendar=g||_||null,this.weekSettings=w,this.intl=Fe(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=I,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=xt(this)),this.fastNumbersCached}listingMode(){const s=this.isEnglish(),f=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return s&&f?"en":"intl"}clone(s){return!s||Object.getOwnPropertyNames(s).length===0?this:he.create(s.locale||this.specifiedLocale,s.numberingSystem||this.numberingSystem,s.outputCalendar||this.outputCalendar,qt(s.weekSettings)||this.weekSettings,s.defaultToEN||!1)}redefaultToEN(s={}){return this.clone({...s,defaultToEN:!0})}redefaultToSystem(s={}){return this.clone({...s,defaultToEN:!1})}months(s,f=!1){return lt(this,s,Lo,()=>{const g=this.intl==="ja"||this.intl.startsWith("ja-");f&=!g;const w=f?{month:s,day:"numeric"}:{month:s},I=f?"format":"standalone";if(!this.monthsCache[I][s]){const F=g?N=>this.dtFormatter(N,w).format():N=>this.extract(N,w,"month");this.monthsCache[I][s]=at(F)}return this.monthsCache[I][s]})}weekdays(s,f=!1){return lt(this,s,zo,()=>{const g=f?{weekday:s,year:"numeric",month:"long",day:"numeric"}:{weekday:s},w=f?"format":"standalone";return this.weekdaysCache[w][s]||(this.weekdaysCache[w][s]=Me(I=>this.extract(I,g,"weekday"))),this.weekdaysCache[w][s]})}meridiems(){return lt(this,void 0,()=>Wo,()=>{if(!this.meridiemCache){const s={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[Se.utc(2016,11,13,9),Se.utc(2016,11,13,19)].map(f=>this.extract(f,s,"dayperiod"))}return this.meridiemCache})}eras(s){return lt(this,s,qo,()=>{const f={era:s};return this.eraCache[s]||(this.eraCache[s]=[Se.utc(-40,1,1),Se.utc(2017,1,1)].map(g=>this.extract(g,f,"era"))),this.eraCache[s]})}extract(s,f,g){const w=this.dtFormatter(s,f),I=w.formatToParts(),F=I.find(N=>N.type.toLowerCase()===g);return F?F.value:null}numberFormatter(s={}){return new vt(this.intl,s.forceSimple||this.fastNumbers,s)}dtFormatter(s,f={}){return new Ot(s,this.intl,f)}relFormatter(s={}){return new pt(this.intl,this.isEnglish(),s)}listFormatter(s={}){return Le(this.intl,s)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||me(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Wn()?ie(this.locale):Ke}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(s){return this.locale===s.locale&&this.numberingSystem===s.numberingSystem&&this.outputCalendar===s.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let Qe=null;class qe extends G{static get utcInstance(){return Qe===null&&(Qe=new qe(0)),Qe}static instance(s){return s===0?qe.utcInstance:new qe(s)}static parseSpecifier(s){if(s){const f=s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(f)return new qe(Fr(f[1],f[2]))}return null}constructor(s){super(),this.fixed=s}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Vn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Vn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(s,f){return Vn(this.fixed,f)}get isUniversal(){return!0}offset(){return this.fixed}equals(s){return s.type==="fixed"&&s.fixed===this.fixed}get isValid(){return!0}}class ct extends G{constructor(s){super(),this.zoneName=s}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function ut(m,s){if(J(m)||m===null)return s;if(m instanceof G)return m;if(Ct(m)){const f=m.toLowerCase();return f==="default"?s:f==="local"||f==="system"?ae.instance:f==="utc"||f==="gmt"?qe.utcInstance:qe.parseSpecifier(f)||pe.create(m)}else return Ve(m)?qe.instance(m):typeof m=="object"&&"offset"in m&&typeof m.offset=="function"?m:new ct(m)}const Ze={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},fe={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Ue=Ze.hanidec.replace(/[\[|\]]/g,"").split("");function bt(m){let s=parseInt(m,10);if(isNaN(s)){s="";for(let f=0;f<m.length;f++){const g=m.charCodeAt(f);if(m[f].search(Ze.hanidec)!==-1)s+=Ue.indexOf(m[f]);else for(const w in fe){const[I,F]=fe[w];g>=I&&g<=F&&(s+=g-I)}}return parseInt(s,10)}else return s}const ke=new Map;function Ne(){ke.clear()}function Ee({numberingSystem:m},s=""){const f=m||"latn";let g=ke.get(f);g===void 0&&(g=new Map,ke.set(f,g));let w=g.get(s);return w===void 0&&(w=new RegExp(`${Ze[f]}${s}`),g.set(s,w)),w}let Be=()=>Date.now(),ht="system",We=null,nt=null,Mt=null,kt=60,At,gn=null;class Pe{static get now(){return Be}static set now(s){Be=s}static set defaultZone(s){ht=s}static get defaultZone(){return ut(ht,ae.instance)}static get defaultLocale(){return We}static set defaultLocale(s){We=s}static get defaultNumberingSystem(){return nt}static set defaultNumberingSystem(s){nt=s}static get defaultOutputCalendar(){return Mt}static set defaultOutputCalendar(s){Mt=s}static get defaultWeekSettings(){return gn}static set defaultWeekSettings(s){gn=qt(s)}static get twoDigitCutoffYear(){return kt}static set twoDigitCutoffYear(s){kt=s%100}static get throwOnInvalid(){return At}static set throwOnInvalid(s){At=s}static resetCaches(){he.resetCache(),pe.resetCache(),Se.resetCache(),Ne()}}class dt{constructor(s,f){this.reason=s,this.explanation=f}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Kt=[0,31,59,90,120,151,181,212,243,273,304,334],yn=[0,31,60,91,121,152,182,213,244,274,305,335];function ft(m,s){return new dt("unit out of range",`you specified ${s} (of type ${typeof s}) as a ${m}, which is invalid`)}function en(m,s,f){const g=new Date(Date.UTC(m,s-1,f));m<100&&m>=0&&g.setUTCFullYear(g.getUTCFullYear()-1900);const w=g.getUTCDay();return w===0?7:w}function xn(m,s,f){return f+(qn(m)?yn:Kt)[s-1]}function Qt(m,s){const f=qn(m)?yn:Kt,g=f.findIndex(I=>I<s),w=s-f[g];return{month:g+1,day:w}}function Xe(m,s){return(m-s+7)%7+1}function Je(m,s=4,f=1){const{year:g,month:w,day:I}=m,F=xn(g,w,I),N=Xe(en(g,w,I),f);let _=Math.floor((F-N+14-s)/7),X;return _<1?(X=g-1,_=Bn(X,s,f)):_>Bn(g,s,f)?(X=g+1,_=1):X=g,{weekYear:X,weekNumber:_,weekday:N,...Nr(m)}}function Ft(m,s=4,f=1){const{weekYear:g,weekNumber:w,weekday:I}=m,F=Xe(en(g,1,s),f),N=bn(g);let _=w*7+I-F-7+s,X;_<1?(X=g-1,_+=bn(X)):_>N?(X=g+1,_-=bn(g)):X=g;const{month:xe,day:je}=Qt(X,_);return{year:X,month:xe,day:je,...Nr(m)}}function tn(m){const{year:s,month:f,day:g}=m,w=xn(s,f,g);return{year:s,ordinal:w,...Nr(m)}}function Zt(m){const{year:s,ordinal:f}=m,{month:g,day:w}=Qt(s,f);return{year:s,month:g,day:w,...Nr(m)}}function nn(m,s){if(!J(m.localWeekday)||!J(m.localWeekNumber)||!J(m.localWeekYear)){if(!J(m.weekday)||!J(m.weekNumber)||!J(m.weekYear))throw new i("Cannot mix locale-based week fields with ISO-based week fields");return J(m.localWeekday)||(m.weekday=m.localWeekday),J(m.localWeekNumber)||(m.weekNumber=m.localWeekNumber),J(m.localWeekYear)||(m.weekYear=m.localWeekYear),delete m.localWeekday,delete m.localWeekNumber,delete m.localWeekYear,{minDaysInFirstWeek:s.getMinDaysInFirstWeek(),startOfWeek:s.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function V(m,s=4,f=1){const g=Ge(m.weekYear),w=Et(m.weekNumber,1,Bn(m.weekYear,s,f)),I=Et(m.weekday,1,7);return g?w?I?!1:ft("weekday",m.weekday):ft("week",m.weekNumber):ft("weekYear",m.weekYear)}function B(m){const s=Ge(m.year),f=Et(m.ordinal,1,bn(m.year));return s?f?!1:ft("ordinal",m.ordinal):ft("year",m.year)}function ce(m){const s=Ge(m.year),f=Et(m.month,1,12),g=Et(m.day,1,$r(m.year,m.month));return s?f?g?!1:ft("day",m.day):ft("month",m.month):ft("year",m.year)}function ve(m){const{hour:s,minute:f,second:g,millisecond:w}=m,I=Et(s,0,23)||s===24&&f===0&&g===0&&w===0,F=Et(f,0,59),N=Et(g,0,59),_=Et(w,0,999);return I?F?N?_?!1:ft("millisecond",w):ft("second",g):ft("minute",f):ft("hour",s)}function J(m){return typeof m>"u"}function Ve(m){return typeof m=="number"}function Ge(m){return typeof m=="number"&&m%1===0}function Ct(m){return typeof m=="string"}function vn(m){return Object.prototype.toString.call(m)==="[object Date]"}function zn(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Wn(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Dr(m){return Array.isArray(m)?m:[m]}function Ae(m,s,f){if(m.length!==0)return m.reduce((g,w)=>{const I=[s(w),w];return g&&f(g[0],I[0])===g[0]?g:I},null)[1]}function zt(m,s){return s.reduce((f,g)=>(f[g]=m[g],f),{})}function gt(m,s){return Object.prototype.hasOwnProperty.call(m,s)}function qt(m){if(m==null)return null;if(typeof m!="object")throw new a("Week settings must be an object");if(!Et(m.firstDay,1,7)||!Et(m.minimalDays,1,7)||!Array.isArray(m.weekend)||m.weekend.some(s=>!Et(s,1,7)))throw new a("Invalid week settings");return{firstDay:m.firstDay,minimalDays:m.minimalDays,weekend:Array.from(m.weekend)}}function Et(m,s,f){return Ge(m)&&m>=s&&m<=f}function Sc(m,s){return m-s*Math.floor(m/s)}function ot(m,s=2){const f=m<0;let g;return f?g="-"+(""+-m).padStart(s,"0"):g=(""+m).padStart(s,"0"),g}function Xt(m){if(!(J(m)||m===null||m===""))return parseInt(m,10)}function rn(m){if(!(J(m)||m===null||m===""))return parseFloat(m)}function fs(m){if(!(J(m)||m===null||m==="")){const s=parseFloat("0."+m)*1e3;return Math.floor(s)}}function ms(m,s,f="round"){const g=10**s;switch(f){case"expand":return m>0?Math.ceil(m*g)/g:Math.floor(m*g)/g;case"trunc":return Math.trunc(m*g)/g;case"round":return Math.round(m*g)/g;case"floor":return Math.floor(m*g)/g;case"ceil":return Math.ceil(m*g)/g;default:throw new RangeError(`Value rounding ${f} is out of range`)}}function qn(m){return m%4===0&&(m%100!==0||m%400===0)}function bn(m){return qn(m)?366:365}function $r(m,s){const f=Sc(s-1,12)+1,g=m+(s-f)/12;return f===2?qn(g)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][f-1]}function Ar(m){let s=Date.UTC(m.year,m.month-1,m.day,m.hour,m.minute,m.second,m.millisecond);return m.year<100&&m.year>=0&&(s=new Date(s),s.setUTCFullYear(m.year,m.month-1,m.day)),+s}function Ao(m,s,f){return-Xe(en(m,1,s),f)+s-1}function Bn(m,s=4,f=1){const g=Ao(m,s,f),w=Ao(m+1,s,f);return(bn(m)-g+w)/7}function ps(m){return m>99?m:m>Pe.twoDigitCutoffYear?1900+m:2e3+m}function Fo(m,s,f,g=null){const w=new Date(m),I={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};g&&(I.timeZone=g);const F={timeZoneName:s,...I},N=new Intl.DateTimeFormat(f,F).formatToParts(w).find(_=>_.type.toLowerCase()==="timezonename");return N?N.value:null}function Fr(m,s){let f=parseInt(m,10);Number.isNaN(f)&&(f=0);const g=parseInt(s,10)||0,w=f<0||Object.is(f,-0)?-g:g;return f*60+w}function Ro(m){const s=Number(m);if(typeof m=="boolean"||m===""||!Number.isFinite(s))throw new a(`Invalid unit value ${m}`);return s}function Rr(m,s){const f={};for(const g in m)if(gt(m,g)){const w=m[g];if(w==null)continue;f[s(g)]=Ro(w)}return f}function Vn(m,s){const f=Math.trunc(Math.abs(m/60)),g=Math.trunc(Math.abs(m%60)),w=m>=0?"+":"-";switch(s){case"short":return`${w}${ot(f,2)}:${ot(g,2)}`;case"narrow":return`${w}${f}${g>0?`:${g}`:""}`;case"techie":return`${w}${ot(f,2)}${ot(g,2)}`;default:throw new RangeError(`Value format ${s} is out of range for property format`)}}function Nr(m){return zt(m,["hour","minute","second","millisecond"])}const kc=["January","February","March","April","May","June","July","August","September","October","November","December"],No=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Cc=["J","F","M","A","M","J","J","A","S","O","N","D"];function Lo(m){switch(m){case"narrow":return[...Cc];case"short":return[...No];case"long":return[...kc];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const _o=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Po=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],jc=["M","T","W","T","F","S","S"];function zo(m){switch(m){case"narrow":return[...jc];case"short":return[...Po];case"long":return[..._o];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Wo=["AM","PM"],Tc=["Before Christ","Anno Domini"],Oc=["BC","AD"],Mc=["B","A"];function qo(m){switch(m){case"narrow":return[...Mc];case"short":return[...Oc];case"long":return[...Tc];default:return null}}function Ec(m){return Wo[m.hour<12?0:1]}function Ic(m,s){return zo(s)[m.weekday-1]}function Dc(m,s){return Lo(s)[m.month-1]}function $c(m,s){return qo(s)[m.year<0?0:1]}function Ac(m,s,f="always",g=!1){const w={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},I=["hours","minutes","seconds"].indexOf(m)===-1;if(f==="auto"&&I){const je=m==="days";switch(s){case 1:return je?"tomorrow":`next ${w[m][0]}`;case-1:return je?"yesterday":`last ${w[m][0]}`;case 0:return je?"today":`this ${w[m][0]}`}}const F=Object.is(s,-0)||s<0,N=Math.abs(s),_=N===1,X=w[m],xe=g?_?X[1]:X[2]||X[1]:_?w[m][0]:m;return F?`${N} ${xe} ago`:`in ${N} ${xe}`}function Bo(m,s){let f="";for(const g of m)g.literal?f+=g.val:f+=s(g.val);return f}const Fc={D:b,DD:x,DDD:k,DDDD:C,t:S,tt:T,ttt:O,tttt:M,T:E,TT:R,TTT:P,TTTT:A,f:H,ff:L,fff:W,ffff:te,F:D,FF:U,FFF:Q,FFFF:ee};class mt{static create(s,f={}){return new mt(s,f)}static parseFormat(s){let f=null,g="",w=!1;const I=[];for(let F=0;F<s.length;F++){const N=s.charAt(F);N==="'"?((g.length>0||w)&&I.push({literal:w||/^\s+$/.test(g),val:g===""?"'":g}),f=null,g="",w=!w):w||N===f?g+=N:(g.length>0&&I.push({literal:/^\s+$/.test(g),val:g}),g=N,f=N)}return g.length>0&&I.push({literal:w||/^\s+$/.test(g),val:g}),I}static macroTokenToFormatOpts(s){return Fc[s]}constructor(s,f){this.opts=f,this.loc=s,this.systemLoc=null}formatWithSystemDefault(s,f){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(s,{...this.opts,...f}).format()}dtFormatter(s,f={}){return this.loc.dtFormatter(s,{...this.opts,...f})}formatDateTime(s,f){return this.dtFormatter(s,f).format()}formatDateTimeParts(s,f){return this.dtFormatter(s,f).formatToParts()}formatInterval(s,f){return this.dtFormatter(s.start,f).dtf.formatRange(s.start.toJSDate(),s.end.toJSDate())}resolvedOptions(s,f){return this.dtFormatter(s,f).resolvedOptions()}num(s,f=0,g=void 0){if(this.opts.forceSimple)return ot(s,f);const w={...this.opts};return f>0&&(w.padTo=f),g&&(w.signDisplay=g),this.loc.numberFormatter(w).format(s)}formatDateTimeFromString(s,f){const g=this.loc.listingMode()==="en",w=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",I=(we,it)=>this.loc.extract(s,we,it),F=we=>s.isOffsetFixed&&s.offset===0&&we.allowZ?"Z":s.isValid?s.zone.formatOffset(s.ts,we.format):"",N=()=>g?Ec(s):I({hour:"numeric",hourCycle:"h12"},"dayperiod"),_=(we,it)=>g?Dc(s,we):I(it?{month:we}:{month:we,day:"numeric"},"month"),X=(we,it)=>g?Ic(s,we):I(it?{weekday:we}:{weekday:we,month:"long",day:"numeric"},"weekday"),xe=we=>{const it=mt.macroTokenToFormatOpts(we);return it?this.formatWithSystemDefault(s,it):we},je=we=>g?$c(s,we):I({era:we},"era"),He=we=>{switch(we){case"S":return this.num(s.millisecond);case"u":case"SSS":return this.num(s.millisecond,3);case"s":return this.num(s.second);case"ss":return this.num(s.second,2);case"uu":return this.num(Math.floor(s.millisecond/10),2);case"uuu":return this.num(Math.floor(s.millisecond/100));case"m":return this.num(s.minute);case"mm":return this.num(s.minute,2);case"h":return this.num(s.hour%12===0?12:s.hour%12);case"hh":return this.num(s.hour%12===0?12:s.hour%12,2);case"H":return this.num(s.hour);case"HH":return this.num(s.hour,2);case"Z":return F({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return F({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return F({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return s.zone.offsetName(s.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return s.zone.offsetName(s.ts,{format:"long",locale:this.loc.locale});case"z":return s.zoneName;case"a":return N();case"d":return w?I({day:"numeric"},"day"):this.num(s.day);case"dd":return w?I({day:"2-digit"},"day"):this.num(s.day,2);case"c":return this.num(s.weekday);case"ccc":return X("short",!0);case"cccc":return X("long",!0);case"ccccc":return X("narrow",!0);case"E":return this.num(s.weekday);case"EEE":return X("short",!1);case"EEEE":return X("long",!1);case"EEEEE":return X("narrow",!1);case"L":return w?I({month:"numeric",day:"numeric"},"month"):this.num(s.month);case"LL":return w?I({month:"2-digit",day:"numeric"},"month"):this.num(s.month,2);case"LLL":return _("short",!0);case"LLLL":return _("long",!0);case"LLLLL":return _("narrow",!0);case"M":return w?I({month:"numeric"},"month"):this.num(s.month);case"MM":return w?I({month:"2-digit"},"month"):this.num(s.month,2);case"MMM":return _("short",!1);case"MMMM":return _("long",!1);case"MMMMM":return _("narrow",!1);case"y":return w?I({year:"numeric"},"year"):this.num(s.year);case"yy":return w?I({year:"2-digit"},"year"):this.num(s.year.toString().slice(-2),2);case"yyyy":return w?I({year:"numeric"},"year"):this.num(s.year,4);case"yyyyyy":return w?I({year:"numeric"},"year"):this.num(s.year,6);case"G":return je("short");case"GG":return je("long");case"GGGGG":return je("narrow");case"kk":return this.num(s.weekYear.toString().slice(-2),2);case"kkkk":return this.num(s.weekYear,4);case"W":return this.num(s.weekNumber);case"WW":return this.num(s.weekNumber,2);case"n":return this.num(s.localWeekNumber);case"nn":return this.num(s.localWeekNumber,2);case"ii":return this.num(s.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(s.localWeekYear,4);case"o":return this.num(s.ordinal);case"ooo":return this.num(s.ordinal,3);case"q":return this.num(s.quarter);case"qq":return this.num(s.quarter,2);case"X":return this.num(Math.floor(s.ts/1e3));case"x":return this.num(s.ts);default:return xe(we)}};return Bo(mt.parseFormat(f),He)}formatDurationFromString(s,f){const g=this.opts.signMode==="negativeLargestOnly"?-1:1,w=xe=>{switch(xe[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},I=(xe,je)=>He=>{const we=w(He);if(we){const it=je.isNegativeDuration&&we!==je.largestUnit?g:1;let Nt;return this.opts.signMode==="negativeLargestOnly"&&we!==je.largestUnit?Nt="never":this.opts.signMode==="all"?Nt="always":Nt="auto",this.num(xe.get(we)*it,He.length,Nt)}else return He},F=mt.parseFormat(f),N=F.reduce((xe,{literal:je,val:He})=>je?xe:xe.concat(He),[]),_=s.shiftTo(...N.map(w).filter(xe=>xe)),X={isNegativeDuration:_<0,largestUnit:Object.keys(_.values)[0]};return Bo(F,I(_,X))}}const Vo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function wn(...m){const s=m.reduce((f,g)=>f+g.source,"");return RegExp(`^${s}$`)}function Sn(...m){return s=>m.reduce(([f,g,w],I)=>{const[F,N,_]=I(s,w);return[{...f,...F},N||g,_]},[{},null,1]).slice(0,2)}function kn(m,...s){if(m==null)return[null,null];for(const[f,g]of s){const w=f.exec(m);if(w)return g(w)}return[null,null]}function Ho(...m){return(s,f)=>{const g={};let w;for(w=0;w<m.length;w++)g[m[w]]=Xt(s[f+w]);return[g,null,f+w]}}const Uo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Rc=`(?:${Uo.source}?(?:\\[(${Vo.source})\\])?)?`,gs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Go=RegExp(`${gs.source}${Rc}`),ys=RegExp(`(?:[Tt]${Go.source})?`),Nc=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Lc=/(\d{4})-?W(\d\d)(?:-?(\d))?/,_c=/(\d{4})-?(\d{3})/,Pc=Ho("weekYear","weekNumber","weekDay"),zc=Ho("year","ordinal"),Wc=/(\d{4})-(\d\d)-(\d\d)/,Yo=RegExp(`${gs.source} ?(?:${Uo.source}|(${Vo.source}))?`),qc=RegExp(`(?: ${Yo.source})?`);function Cn(m,s,f){const g=m[s];return J(g)?f:Xt(g)}function Bc(m,s){return[{year:Cn(m,s),month:Cn(m,s+1,1),day:Cn(m,s+2,1)},null,s+3]}function jn(m,s){return[{hours:Cn(m,s,0),minutes:Cn(m,s+1,0),seconds:Cn(m,s+2,0),milliseconds:fs(m[s+3])},null,s+4]}function Hn(m,s){const f=!m[s]&&!m[s+1],g=Fr(m[s+1],m[s+2]),w=f?null:qe.instance(g);return[{},w,s+3]}function Un(m,s){const f=m[s]?pe.create(m[s]):null;return[{},f,s+1]}const Vc=RegExp(`^T?${gs.source}$`),Hc=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Uc(m){const[s,f,g,w,I,F,N,_,X]=m,xe=s[0]==="-",je=_&&_[0]==="-",He=(we,it=!1)=>we!==void 0&&(it||we&&xe)?-we:we;return[{years:He(rn(f)),months:He(rn(g)),weeks:He(rn(w)),days:He(rn(I)),hours:He(rn(F)),minutes:He(rn(N)),seconds:He(rn(_),_==="-0"),milliseconds:He(fs(X),je)}]}const Gc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function xs(m,s,f,g,w,I,F){const N={year:s.length===2?ps(Xt(s)):Xt(s),month:No.indexOf(f)+1,day:Xt(g),hour:Xt(w),minute:Xt(I)};return F&&(N.second=Xt(F)),m&&(N.weekday=m.length>3?_o.indexOf(m)+1:Po.indexOf(m)+1),N}const Yc=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Kc(m){const[,s,f,g,w,I,F,N,_,X,xe,je]=m,He=xs(s,w,g,f,I,F,N);let we;return _?we=Gc[_]:X?we=0:we=Fr(xe,je),[He,new qe(we)]}function Qc(m){return m.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Zc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Xc=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Jc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Ko(m){const[,s,f,g,w,I,F,N]=m;return[xs(s,w,g,f,I,F,N),qe.utcInstance]}function eu(m){const[,s,f,g,w,I,F,N]=m;return[xs(s,N,f,g,w,I,F),qe.utcInstance]}const tu=wn(Nc,ys),nu=wn(Lc,ys),ru=wn(_c,ys),su=wn(Go),Qo=Sn(Bc,jn,Hn,Un),ou=Sn(Pc,jn,Hn,Un),iu=Sn(zc,jn,Hn,Un),au=Sn(jn,Hn,Un);function lu(m){return kn(m,[tu,Qo],[nu,ou],[ru,iu],[su,au])}function cu(m){return kn(Qc(m),[Yc,Kc])}function uu(m){return kn(m,[Zc,Ko],[Xc,Ko],[Jc,eu])}function du(m){return kn(m,[Hc,Uc])}const hu=Sn(jn);function fu(m){return kn(m,[Vc,hu])}const mu=wn(Wc,qc),pu=wn(Yo),gu=Sn(jn,Hn,Un);function yu(m){return kn(m,[mu,Qo],[pu,gu])}const Zo="Invalid Duration",Xo={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},xu={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...Xo},It=146097/400,Tn=146097/4800,vu={years:{quarters:4,months:12,weeks:It/7,days:It,hours:It*24,minutes:It*24*60,seconds:It*24*60*60,milliseconds:It*24*60*60*1e3},quarters:{months:3,weeks:It/28,days:It/4,hours:It*24/4,minutes:It*24*60/4,seconds:It*24*60*60/4,milliseconds:It*24*60*60*1e3/4},months:{weeks:Tn/7,days:Tn,hours:Tn*24,minutes:Tn*24*60,seconds:Tn*24*60*60,milliseconds:Tn*24*60*60*1e3},...Xo},sn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],bu=sn.slice(0).reverse();function Bt(m,s,f=!1){const g={values:f?s.values:{...m.values,...s.values||{}},loc:m.loc.clone(s.loc),conversionAccuracy:s.conversionAccuracy||m.conversionAccuracy,matrix:s.matrix||m.matrix};return new Re(g)}function Jo(m,s){var f;let g=(f=s.milliseconds)!=null?f:0;for(const w of bu.slice(1))s[w]&&(g+=s[w]*m[w].milliseconds);return g}function ei(m,s){const f=Jo(m,s)<0?-1:1;sn.reduceRight((g,w)=>{if(J(s[w]))return g;if(g){const I=s[g]*f,F=m[w][g],N=Math.floor(I/F);s[w]+=N*f,s[g]-=N*F*f}return w},null),sn.reduce((g,w)=>{if(J(s[w]))return g;if(g){const I=s[g]%1;s[g]-=I,s[w]+=I*m[g][w]}return w},null)}function ti(m){const s={};for(const[f,g]of Object.entries(m))g!==0&&(s[f]=g);return s}class Re{constructor(s){const f=s.conversionAccuracy==="longterm"||!1;let g=f?vu:xu;s.matrix&&(g=s.matrix),this.values=s.values,this.loc=s.loc||he.create(),this.conversionAccuracy=f?"longterm":"casual",this.invalid=s.invalid||null,this.matrix=g,this.isLuxonDuration=!0}static fromMillis(s,f){return Re.fromObject({milliseconds:s},f)}static fromObject(s,f={}){if(s==null||typeof s!="object")throw new a(`Duration.fromObject: argument expected to be an object, got ${s===null?"null":typeof s}`);return new Re({values:Rr(s,Re.normalizeUnit),loc:he.fromObject(f),conversionAccuracy:f.conversionAccuracy,matrix:f.matrix})}static fromDurationLike(s){if(Ve(s))return Re.fromMillis(s);if(Re.isDuration(s))return s;if(typeof s=="object")return Re.fromObject(s);throw new a(`Unknown duration argument ${s} of type ${typeof s}`)}static fromISO(s,f){const[g]=du(s);return g?Re.fromObject(g,f):Re.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static fromISOTime(s,f){const[g]=fu(s);return g?Re.fromObject(g,f):Re.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Duration is invalid");const g=s instanceof dt?s:new dt(s,f);if(Pe.throwOnInvalid)throw new o(g);return new Re({invalid:g})}static normalizeUnit(s){const f={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[s&&s.toLowerCase()];if(!f)throw new l(s);return f}static isDuration(s){return s&&s.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(s,f={}){const g={...f,floor:f.round!==!1&&f.floor!==!1};return this.isValid?mt.create(this.loc,g).formatDurationFromString(this,s):Zo}toHuman(s={}){if(!this.isValid)return Zo;const f=s.showZeros!==!1,g=sn.map(w=>{const I=this.values[w];return J(I)||I===0&&!f?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...s,unit:w.slice(0,-1)}).format(I)}).filter(w=>w);return this.loc.listFormatter({type:"conjunction",style:s.listStyle||"narrow",...s}).format(g)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s="P";return this.years!==0&&(s+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s+=this.weeks+"W"),this.days!==0&&(s+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s+="T"),this.hours!==0&&(s+=this.hours+"H"),this.minutes!==0&&(s+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s+=ms(this.seconds+this.milliseconds/1e3,3)+"S"),s==="P"&&(s+="T0S"),s}toISOTime(s={}){if(!this.isValid)return null;const f=this.toMillis();return f<0||f>=864e5?null:(s={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...s,includeOffset:!1},Se.fromMillis(f,{zone:"UTC"}).toISOTime(s))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Jo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(s){if(!this.isValid)return this;const f=Re.fromDurationLike(s),g={};for(const w of sn)(gt(f.values,w)||gt(this.values,w))&&(g[w]=f.get(w)+this.get(w));return Bt(this,{values:g},!0)}minus(s){if(!this.isValid)return this;const f=Re.fromDurationLike(s);return this.plus(f.negate())}mapUnits(s){if(!this.isValid)return this;const f={};for(const g of Object.keys(this.values))f[g]=Ro(s(this.values[g],g));return Bt(this,{values:f},!0)}get(s){return this[Re.normalizeUnit(s)]}set(s){if(!this.isValid)return this;const f={...this.values,...Rr(s,Re.normalizeUnit)};return Bt(this,{values:f})}reconfigure({locale:s,numberingSystem:f,conversionAccuracy:g,matrix:w}={}){const F={loc:this.loc.clone({locale:s,numberingSystem:f}),matrix:w,conversionAccuracy:g};return Bt(this,F)}as(s){return this.isValid?this.shiftTo(s).get(s):NaN}normalize(){if(!this.isValid)return this;const s=this.toObject();return ei(this.matrix,s),Bt(this,{values:s},!0)}rescale(){if(!this.isValid)return this;const s=ti(this.normalize().shiftToAll().toObject());return Bt(this,{values:s},!0)}shiftTo(...s){if(!this.isValid)return this;if(s.length===0)return this;s=s.map(F=>Re.normalizeUnit(F));const f={},g={},w=this.toObject();let I;for(const F of sn)if(s.indexOf(F)>=0){I=F;let N=0;for(const X in g)N+=this.matrix[X][F]*g[X],g[X]=0;Ve(w[F])&&(N+=w[F]);const _=Math.trunc(N);f[F]=_,g[F]=(N*1e3-_*1e3)/1e3}else Ve(w[F])&&(g[F]=w[F]);for(const F in g)g[F]!==0&&(f[I]+=F===I?g[F]:g[F]/this.matrix[I][F]);return ei(this.matrix,f),Bt(this,{values:f},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const s={};for(const f of Object.keys(this.values))s[f]=this.values[f]===0?0:-this.values[f];return Bt(this,{values:s},!0)}removeZeros(){if(!this.isValid)return this;const s=ti(this.values);return Bt(this,{values:s},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(s){if(!this.isValid||!s.isValid||!this.loc.equals(s.loc))return!1;function f(g,w){return g===void 0||g===0?w===void 0||w===0:g===w}for(const g of sn)if(!f(this.values[g],s.values[g]))return!1;return!0}}const On="Invalid Interval";function wu(m,s){return!m||!m.isValid?et.invalid("missing or invalid start"):!s||!s.isValid?et.invalid("missing or invalid end"):s<m?et.invalid("end before start",`The end of an interval must be after its start, but you had start=${m.toISO()} and end=${s.toISO()}`):null}class et{constructor(s){this.s=s.start,this.e=s.end,this.invalid=s.invalid||null,this.isLuxonInterval=!0}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Interval is invalid");const g=s instanceof dt?s:new dt(s,f);if(Pe.throwOnInvalid)throw new r(g);return new et({invalid:g})}static fromDateTimes(s,f){const g=Qn(s),w=Qn(f),I=wu(g,w);return I??new et({start:g,end:w})}static after(s,f){const g=Re.fromDurationLike(f),w=Qn(s);return et.fromDateTimes(w,w.plus(g))}static before(s,f){const g=Re.fromDurationLike(f),w=Qn(s);return et.fromDateTimes(w.minus(g),w)}static fromISO(s,f){const[g,w]=(s||"").split("/",2);if(g&&w){let I,F;try{I=Se.fromISO(g,f),F=I.isValid}catch{F=!1}let N,_;try{N=Se.fromISO(w,f),_=N.isValid}catch{_=!1}if(F&&_)return et.fromDateTimes(I,N);if(F){const X=Re.fromISO(w,f);if(X.isValid)return et.after(I,X)}else if(_){const X=Re.fromISO(g,f);if(X.isValid)return et.before(N,X)}}return et.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static isInterval(s){return s&&s.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(s="milliseconds"){return this.isValid?this.toDuration(s).get(s):NaN}count(s="milliseconds",f){if(!this.isValid)return NaN;const g=this.start.startOf(s,f);let w;return f!=null&&f.useLocaleWeeks?w=this.end.reconfigure({locale:g.locale}):w=this.end,w=w.startOf(s,f),Math.floor(w.diff(g,s).get(s))+(w.valueOf()!==this.end.valueOf())}hasSame(s){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,s):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(s){return this.isValid?this.s>s:!1}isBefore(s){return this.isValid?this.e<=s:!1}contains(s){return this.isValid?this.s<=s&&this.e>s:!1}set({start:s,end:f}={}){return this.isValid?et.fromDateTimes(s||this.s,f||this.e):this}splitAt(...s){if(!this.isValid)return[];const f=s.map(Qn).filter(F=>this.contains(F)).sort((F,N)=>F.toMillis()-N.toMillis()),g=[];let{s:w}=this,I=0;for(;w<this.e;){const F=f[I]||this.e,N=+F>+this.e?this.e:F;g.push(et.fromDateTimes(w,N)),w=N,I+=1}return g}splitBy(s){const f=Re.fromDurationLike(s);if(!this.isValid||!f.isValid||f.as("milliseconds")===0)return[];let{s:g}=this,w=1,I;const F=[];for(;g<this.e;){const N=this.start.plus(f.mapUnits(_=>_*w));I=+N>+this.e?this.e:N,F.push(et.fromDateTimes(g,I)),g=I,w+=1}return F}divideEqually(s){return this.isValid?this.splitBy(this.length()/s).slice(0,s):[]}overlaps(s){return this.e>s.s&&this.s<s.e}abutsStart(s){return this.isValid?+this.e==+s.s:!1}abutsEnd(s){return this.isValid?+s.e==+this.s:!1}engulfs(s){return this.isValid?this.s<=s.s&&this.e>=s.e:!1}equals(s){return!this.isValid||!s.isValid?!1:this.s.equals(s.s)&&this.e.equals(s.e)}intersection(s){if(!this.isValid)return this;const f=this.s>s.s?this.s:s.s,g=this.e<s.e?this.e:s.e;return f>=g?null:et.fromDateTimes(f,g)}union(s){if(!this.isValid)return this;const f=this.s<s.s?this.s:s.s,g=this.e>s.e?this.e:s.e;return et.fromDateTimes(f,g)}static merge(s){const[f,g]=s.sort((w,I)=>w.s-I.s).reduce(([w,I],F)=>I?I.overlaps(F)||I.abutsStart(F)?[w,I.union(F)]:[w.concat([I]),F]:[w,F],[[],null]);return g&&f.push(g),f}static xor(s){let f=null,g=0;const w=[],I=s.map(_=>[{time:_.s,type:"s"},{time:_.e,type:"e"}]),F=Array.prototype.concat(...I),N=F.sort((_,X)=>_.time-X.time);for(const _ of N)g+=_.type==="s"?1:-1,g===1?f=_.time:(f&&+f!=+_.time&&w.push(et.fromDateTimes(f,_.time)),f=null);return et.merge(w)}difference(...s){return et.xor([this].concat(s)).map(f=>this.intersection(f)).filter(f=>f&&!f.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:On}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(s=b,f={}){return this.isValid?mt.create(this.s.loc.clone(f),s).formatInterval(this):On}toISO(s){return this.isValid?`${this.s.toISO(s)}/${this.e.toISO(s)}`:On}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:On}toISOTime(s){return this.isValid?`${this.s.toISOTime(s)}/${this.e.toISOTime(s)}`:On}toFormat(s,{separator:f=" – "}={}){return this.isValid?`${this.s.toFormat(s)}${f}${this.e.toFormat(s)}`:On}toDuration(s,f){return this.isValid?this.e.diff(this.s,s,f):Re.invalid(this.invalidReason)}mapEndpoints(s){return et.fromDateTimes(s(this.s),s(this.e))}}class Gn{static hasDST(s=Pe.defaultZone){const f=Se.now().setZone(s).set({month:12});return!s.isUniversal&&f.offset!==f.set({month:6}).offset}static isValidIANAZone(s){return pe.isValidZone(s)}static normalizeZone(s){return ut(s,Pe.defaultZone)}static getStartOfWeek({locale:s=null,locObj:f=null}={}){return(f||he.create(s)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:s=null,locObj:f=null}={}){return(f||he.create(s)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:s=null,locObj:f=null}={}){return(f||he.create(s)).getWeekendDays().slice()}static months(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||he.create(f,g,I)).months(s)}static monthsFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||he.create(f,g,I)).months(s,!0)}static weekdays(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||he.create(f,g,null)).weekdays(s)}static weekdaysFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||he.create(f,g,null)).weekdays(s,!0)}static meridiems({locale:s=null}={}){return he.create(s).meridiems()}static eras(s="short",{locale:f=null}={}){return he.create(f,null,"gregory").eras(s)}static features(){return{relative:zn(),localeWeek:Wn()}}}function ni(m,s){const f=w=>w.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),g=f(s)-f(m);return Math.floor(Re.fromMillis(g).as("days"))}function Su(m,s,f){const g=[["years",(_,X)=>X.year-_.year],["quarters",(_,X)=>X.quarter-_.quarter+(X.year-_.year)*4],["months",(_,X)=>X.month-_.month+(X.year-_.year)*12],["weeks",(_,X)=>{const xe=ni(_,X);return(xe-xe%7)/7}],["days",ni]],w={},I=m;let F,N;for(const[_,X]of g)f.indexOf(_)>=0&&(F=_,w[_]=X(m,s),N=I.plus(w),N>s?(w[_]--,m=I.plus(w),m>s&&(N=m,w[_]--,m=I.plus(w))):m=N);return[m,w,N,F]}function ku(m,s,f,g){let[w,I,F,N]=Su(m,s,f);const _=s-w,X=f.filter(je=>["hours","minutes","seconds","milliseconds"].indexOf(je)>=0);X.length===0&&(F<s&&(F=w.plus({[N]:1})),F!==w&&(I[N]=(I[N]||0)+_/(F-w)));const xe=Re.fromObject(I,g);return X.length>0?Re.fromMillis(_,g).shiftTo(...X).plus(xe):xe}const Cu="missing Intl.DateTimeFormat.formatToParts support";function _e(m,s=f=>f){return{regex:m,deser:([f])=>s(bt(f))}}const ri="[  ]",si=new RegExp(ri,"g");function ju(m){return m.replace(/\./g,"\\.?").replace(si,ri)}function oi(m){return m.replace(/\./g,"").replace(si," ").toLowerCase()}function Rt(m,s){return m===null?null:{regex:RegExp(m.map(ju).join("|")),deser:([f])=>m.findIndex(g=>oi(f)===oi(g))+s}}function ii(m,s){return{regex:m,deser:([,f,g])=>Fr(f,g),groups:s}}function Lr(m){return{regex:m,deser:([s])=>s}}function Tu(m){return m.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Ou(m,s){const f=Ee(s),g=Ee(s,"{2}"),w=Ee(s,"{3}"),I=Ee(s,"{4}"),F=Ee(s,"{6}"),N=Ee(s,"{1,2}"),_=Ee(s,"{1,3}"),X=Ee(s,"{1,6}"),xe=Ee(s,"{1,9}"),je=Ee(s,"{2,4}"),He=Ee(s,"{4,6}"),we=Wt=>({regex:RegExp(Tu(Wt.val)),deser:([En])=>En,literal:!0}),Nt=(Wt=>{if(m.literal)return we(Wt);switch(Wt.val){case"G":return Rt(s.eras("short"),0);case"GG":return Rt(s.eras("long"),0);case"y":return _e(X);case"yy":return _e(je,ps);case"yyyy":return _e(I);case"yyyyy":return _e(He);case"yyyyyy":return _e(F);case"M":return _e(N);case"MM":return _e(g);case"MMM":return Rt(s.months("short",!0),1);case"MMMM":return Rt(s.months("long",!0),1);case"L":return _e(N);case"LL":return _e(g);case"LLL":return Rt(s.months("short",!1),1);case"LLLL":return Rt(s.months("long",!1),1);case"d":return _e(N);case"dd":return _e(g);case"o":return _e(_);case"ooo":return _e(w);case"HH":return _e(g);case"H":return _e(N);case"hh":return _e(g);case"h":return _e(N);case"mm":return _e(g);case"m":return _e(N);case"q":return _e(N);case"qq":return _e(g);case"s":return _e(N);case"ss":return _e(g);case"S":return _e(_);case"SSS":return _e(w);case"u":return Lr(xe);case"uu":return Lr(N);case"uuu":return _e(f);case"a":return Rt(s.meridiems(),0);case"kkkk":return _e(I);case"kk":return _e(je,ps);case"W":return _e(N);case"WW":return _e(g);case"E":case"c":return _e(f);case"EEE":return Rt(s.weekdays("short",!1),1);case"EEEE":return Rt(s.weekdays("long",!1),1);case"ccc":return Rt(s.weekdays("short",!0),1);case"cccc":return Rt(s.weekdays("long",!0),1);case"Z":case"ZZ":return ii(new RegExp(`([+-]${N.source})(?::(${g.source}))?`),2);case"ZZZ":return ii(new RegExp(`([+-]${N.source})(${g.source})?`),2);case"z":return Lr(/[a-z_+-/]{1,256}?/i);case" ":return Lr(/[^\S\n\r]/);default:return we(Wt)}})(m)||{invalidReason:Cu};return Nt.token=m,Nt}const Mu={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Eu(m,s,f){const{type:g,value:w}=m;if(g==="literal"){const _=/^\s+$/.test(w);return{literal:!_,val:_?" ":w}}const I=s[g];let F=g;g==="hour"&&(s.hour12!=null?F=s.hour12?"hour12":"hour24":s.hourCycle!=null?s.hourCycle==="h11"||s.hourCycle==="h12"?F="hour12":F="hour24":F=f.hour12?"hour12":"hour24");let N=Mu[F];if(typeof N=="object"&&(N=N[I]),N)return{literal:!1,val:N}}function Iu(m){return[`^${m.map(f=>f.regex).reduce((f,g)=>`${f}(${g.source})`,"")}$`,m]}function Du(m,s,f){const g=m.match(s);if(g){const w={};let I=1;for(const F in f)if(gt(f,F)){const N=f[F],_=N.groups?N.groups+1:1;!N.literal&&N.token&&(w[N.token.val[0]]=N.deser(g.slice(I,I+_))),I+=_}return[g,w]}else return[g,{}]}function $u(m){const s=I=>{switch(I){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let f=null,g;return J(m.z)||(f=pe.create(m.z)),J(m.Z)||(f||(f=new qe(m.Z)),g=m.Z),J(m.q)||(m.M=(m.q-1)*3+1),J(m.h)||(m.h<12&&m.a===1?m.h+=12:m.h===12&&m.a===0&&(m.h=0)),m.G===0&&m.y&&(m.y=-m.y),J(m.u)||(m.S=fs(m.u)),[Object.keys(m).reduce((I,F)=>{const N=s(F);return N&&(I[N]=m[F]),I},{}),f,g]}let vs=null;function Au(){return vs||(vs=Se.fromMillis(1555555555555)),vs}function Fu(m,s){if(m.literal)return m;const f=mt.macroTokenToFormatOpts(m.val),g=ui(f,s);return g==null||g.includes(void 0)?m:g}function ai(m,s){return Array.prototype.concat(...m.map(f=>Fu(f,s)))}class li{constructor(s,f){if(this.locale=s,this.format=f,this.tokens=ai(mt.parseFormat(f),s),this.units=this.tokens.map(g=>Ou(g,s)),this.disqualifyingUnit=this.units.find(g=>g.invalidReason),!this.disqualifyingUnit){const[g,w]=Iu(this.units);this.regex=RegExp(g,"i"),this.handlers=w}}explainFromTokens(s){if(this.isValid){const[f,g]=Du(s,this.regex,this.handlers),[w,I,F]=g?$u(g):[null,null,void 0];if(gt(g,"a")&&gt(g,"H"))throw new i("Can't include meridiem when specifying 24-hour format");return{input:s,tokens:this.tokens,regex:this.regex,rawMatches:f,matches:g,result:w,zone:I,specificOffset:F}}else return{input:s,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function ci(m,s,f){return new li(m,f).explainFromTokens(s)}function Ru(m,s,f){const{result:g,zone:w,specificOffset:I,invalidReason:F}=ci(m,s,f);return[g,w,I,F]}function ui(m,s){if(!m)return null;const g=mt.create(s,m).dtFormatter(Au()),w=g.formatToParts(),I=g.resolvedOptions();return w.map(F=>Eu(F,m,I))}const bs="Invalid DateTime",di=864e13;function Yn(m){return new dt("unsupported zone",`the zone "${m.name}" is not supported`)}function ws(m){return m.weekData===null&&(m.weekData=Je(m.c)),m.weekData}function Ss(m){return m.localWeekData===null&&(m.localWeekData=Je(m.c,m.loc.getMinDaysInFirstWeek(),m.loc.getStartOfWeek())),m.localWeekData}function on(m,s){const f={ts:m.ts,zone:m.zone,c:m.c,o:m.o,loc:m.loc,invalid:m.invalid};return new Se({...f,...s,old:f})}function hi(m,s,f){let g=m-s*60*1e3;const w=f.offset(g);if(s===w)return[g,s];g-=(w-s)*60*1e3;const I=f.offset(g);return w===I?[g,w]:[m-Math.min(w,I)*60*1e3,Math.max(w,I)]}function _r(m,s){m+=s*60*1e3;const f=new Date(m);return{year:f.getUTCFullYear(),month:f.getUTCMonth()+1,day:f.getUTCDate(),hour:f.getUTCHours(),minute:f.getUTCMinutes(),second:f.getUTCSeconds(),millisecond:f.getUTCMilliseconds()}}function Pr(m,s,f){return hi(Ar(m),s,f)}function fi(m,s){const f=m.o,g=m.c.year+Math.trunc(s.years),w=m.c.month+Math.trunc(s.months)+Math.trunc(s.quarters)*3,I={...m.c,year:g,month:w,day:Math.min(m.c.day,$r(g,w))+Math.trunc(s.days)+Math.trunc(s.weeks)*7},F=Re.fromObject({years:s.years-Math.trunc(s.years),quarters:s.quarters-Math.trunc(s.quarters),months:s.months-Math.trunc(s.months),weeks:s.weeks-Math.trunc(s.weeks),days:s.days-Math.trunc(s.days),hours:s.hours,minutes:s.minutes,seconds:s.seconds,milliseconds:s.milliseconds}).as("milliseconds"),N=Ar(I);let[_,X]=hi(N,f,m.zone);return F!==0&&(_+=F,X=m.zone.offset(_)),{ts:_,o:X}}function Mn(m,s,f,g,w,I){const{setZone:F,zone:N}=f;if(m&&Object.keys(m).length!==0||s){const _=s||N,X=Se.fromObject(m,{...f,zone:_,specificOffset:I});return F?X:X.setZone(N)}else return Se.invalid(new dt("unparsable",`the input "${w}" can't be parsed as ${g}`))}function zr(m,s,f=!0){return m.isValid?mt.create(he.create("en-US"),{allowZ:f,forceSimple:!0}).formatDateTimeFromString(m,s):null}function ks(m,s,f){const g=m.c.year>9999||m.c.year<0;let w="";if(g&&m.c.year>=0&&(w+="+"),w+=ot(m.c.year,g?6:4),f==="year")return w;if(s){if(w+="-",w+=ot(m.c.month),f==="month")return w;w+="-"}else if(w+=ot(m.c.month),f==="month")return w;return w+=ot(m.c.day),w}function mi(m,s,f,g,w,I,F){let N=!f||m.c.millisecond!==0||m.c.second!==0,_="";switch(F){case"day":case"month":case"year":break;default:if(_+=ot(m.c.hour),F==="hour")break;if(s){if(_+=":",_+=ot(m.c.minute),F==="minute")break;N&&(_+=":",_+=ot(m.c.second))}else{if(_+=ot(m.c.minute),F==="minute")break;N&&(_+=ot(m.c.second))}if(F==="second")break;N&&(!g||m.c.millisecond!==0)&&(_+=".",_+=ot(m.c.millisecond,3))}return w&&(m.isOffsetFixed&&m.offset===0&&!I?_+="Z":m.o<0?(_+="-",_+=ot(Math.trunc(-m.o/60)),_+=":",_+=ot(Math.trunc(-m.o%60))):(_+="+",_+=ot(Math.trunc(m.o/60)),_+=":",_+=ot(Math.trunc(m.o%60)))),I&&(_+="["+m.zone.ianaName+"]"),_}const pi={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Nu={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Lu={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Wr=["year","month","day","hour","minute","second","millisecond"],_u=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Pu=["year","ordinal","hour","minute","second","millisecond"];function qr(m){const s={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[m.toLowerCase()];if(!s)throw new l(m);return s}function gi(m){switch(m.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return qr(m)}}function zu(m){if(Kn===void 0&&(Kn=Pe.now()),m.type!=="iana")return m.offset(Kn);const s=m.name;let f=Cs.get(s);return f===void 0&&(f=m.offset(Kn),Cs.set(s,f)),f}function yi(m,s){const f=ut(s.zone,Pe.defaultZone);if(!f.isValid)return Se.invalid(Yn(f));const g=he.fromObject(s);let w,I;if(J(m.year))w=Pe.now();else{for(const _ of Wr)J(m[_])&&(m[_]=pi[_]);const F=ce(m)||ve(m);if(F)return Se.invalid(F);const N=zu(f);[w,I]=Pr(m,N,f)}return new Se({ts:w,zone:f,loc:g,o:I})}function xi(m,s,f){const g=J(f.round)?!0:f.round,w=J(f.rounding)?"trunc":f.rounding,I=(N,_)=>(N=ms(N,g||f.calendary?0:2,f.calendary?"round":w),s.loc.clone(f).relFormatter(f).format(N,_)),F=N=>f.calendary?s.hasSame(m,N)?0:s.startOf(N).diff(m.startOf(N),N).get(N):s.diff(m,N).get(N);if(f.unit)return I(F(f.unit),f.unit);for(const N of f.units){const _=F(N);if(Math.abs(_)>=1)return I(_,N)}return I(m>s?-0:0,f.units[f.units.length-1])}function vi(m){let s={},f;return m.length>0&&typeof m[m.length-1]=="object"?(s=m[m.length-1],f=Array.from(m).slice(0,m.length-1)):f=Array.from(m),[s,f]}let Kn;const Cs=new Map;class Se{constructor(s){const f=s.zone||Pe.defaultZone;let g=s.invalid||(Number.isNaN(s.ts)?new dt("invalid input"):null)||(f.isValid?null:Yn(f));this.ts=J(s.ts)?Pe.now():s.ts;let w=null,I=null;if(!g)if(s.old&&s.old.ts===this.ts&&s.old.zone.equals(f))[w,I]=[s.old.c,s.old.o];else{const N=Ve(s.o)&&!s.old?s.o:f.offset(this.ts);w=_r(this.ts,N),g=Number.isNaN(w.year)?new dt("invalid input"):null,w=g?null:w,I=g?null:N}this._zone=f,this.loc=s.loc||he.create(),this.invalid=g,this.weekData=null,this.localWeekData=null,this.c=w,this.o=I,this.isLuxonDateTime=!0}static now(){return new Se({})}static local(){const[s,f]=vi(arguments),[g,w,I,F,N,_,X]=f;return yi({year:g,month:w,day:I,hour:F,minute:N,second:_,millisecond:X},s)}static utc(){const[s,f]=vi(arguments),[g,w,I,F,N,_,X]=f;return s.zone=qe.utcInstance,yi({year:g,month:w,day:I,hour:F,minute:N,second:_,millisecond:X},s)}static fromJSDate(s,f={}){const g=vn(s)?s.valueOf():NaN;if(Number.isNaN(g))return Se.invalid("invalid input");const w=ut(f.zone,Pe.defaultZone);return w.isValid?new Se({ts:g,zone:w,loc:he.fromObject(f)}):Se.invalid(Yn(w))}static fromMillis(s,f={}){if(Ve(s))return s<-di||s>di?Se.invalid("Timestamp out of range"):new Se({ts:s,zone:ut(f.zone,Pe.defaultZone),loc:he.fromObject(f)});throw new a(`fromMillis requires a numerical input, but received a ${typeof s} with value ${s}`)}static fromSeconds(s,f={}){if(Ve(s))return new Se({ts:s*1e3,zone:ut(f.zone,Pe.defaultZone),loc:he.fromObject(f)});throw new a("fromSeconds requires a numerical input")}static fromObject(s,f={}){s=s||{};const g=ut(f.zone,Pe.defaultZone);if(!g.isValid)return Se.invalid(Yn(g));const w=he.fromObject(f),I=Rr(s,gi),{minDaysInFirstWeek:F,startOfWeek:N}=nn(I,w),_=Pe.now(),X=J(f.specificOffset)?g.offset(_):f.specificOffset,xe=!J(I.ordinal),je=!J(I.year),He=!J(I.month)||!J(I.day),we=je||He,it=I.weekYear||I.weekNumber;if((we||xe)&&it)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(He&&xe)throw new i("Can't mix ordinal dates with month/day");const Nt=it||I.weekday&&!we;let Wt,En,Zn=_r(_,X);Nt?(Wt=_u,En=Nu,Zn=Je(Zn,F,N)):xe?(Wt=Pu,En=Lu,Zn=tn(Zn)):(Wt=Wr,En=pi);let bi=!1;for(const Jn of Wt){const Uu=I[Jn];J(Uu)?bi?I[Jn]=En[Jn]:I[Jn]=Zn[Jn]:bi=!0}const qu=Nt?V(I,F,N):xe?B(I):ce(I),wi=qu||ve(I);if(wi)return Se.invalid(wi);const Bu=Nt?Ft(I,F,N):xe?Zt(I):I,[Vu,Hu]=Pr(Bu,X,g),Xn=new Se({ts:Vu,zone:g,o:Hu,loc:w});return I.weekday&&we&&s.weekday!==Xn.weekday?Se.invalid("mismatched weekday",`you can't specify both a weekday of ${I.weekday} and a date of ${Xn.toISO()}`):Xn.isValid?Xn:Se.invalid(Xn.invalid)}static fromISO(s,f={}){const[g,w]=lu(s);return Mn(g,w,f,"ISO 8601",s)}static fromRFC2822(s,f={}){const[g,w]=cu(s);return Mn(g,w,f,"RFC 2822",s)}static fromHTTP(s,f={}){const[g,w]=uu(s);return Mn(g,w,f,"HTTP",f)}static fromFormat(s,f,g={}){if(J(s)||J(f))throw new a("fromFormat requires an input string and a format");const{locale:w=null,numberingSystem:I=null}=g,F=he.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0}),[N,_,X,xe]=Ru(F,s,f);return xe?Se.invalid(xe):Mn(N,_,g,`format ${f}`,s,X)}static fromString(s,f,g={}){return Se.fromFormat(s,f,g)}static fromSQL(s,f={}){const[g,w]=yu(s);return Mn(g,w,f,"SQL",s)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the DateTime is invalid");const g=s instanceof dt?s:new dt(s,f);if(Pe.throwOnInvalid)throw new n(g);return new Se({invalid:g})}static isDateTime(s){return s&&s.isLuxonDateTime||!1}static parseFormatForOpts(s,f={}){const g=ui(s,he.fromObject(f));return g?g.map(w=>w?w.val:null).join(""):null}static expandFormat(s,f={}){return ai(mt.parseFormat(s),he.fromObject(f)).map(w=>w.val).join("")}static resetCache(){Kn=void 0,Cs.clear()}get(s){return this[s]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?ws(this).weekYear:NaN}get weekNumber(){return this.isValid?ws(this).weekNumber:NaN}get weekday(){return this.isValid?ws(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Ss(this).weekday:NaN}get localWeekNumber(){return this.isValid?Ss(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Ss(this).weekYear:NaN}get ordinal(){return this.isValid?tn(this.c).ordinal:NaN}get monthShort(){return this.isValid?Gn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Gn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Gn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Gn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const s=864e5,f=6e4,g=Ar(this.c),w=this.zone.offset(g-s),I=this.zone.offset(g+s),F=this.zone.offset(g-w*f),N=this.zone.offset(g-I*f);if(F===N)return[this];const _=g-F*f,X=g-N*f,xe=_r(_,F),je=_r(X,N);return xe.hour===je.hour&&xe.minute===je.minute&&xe.second===je.second&&xe.millisecond===je.millisecond?[on(this,{ts:_}),on(this,{ts:X})]:[this]}get isInLeapYear(){return qn(this.year)}get daysInMonth(){return $r(this.year,this.month)}get daysInYear(){return this.isValid?bn(this.year):NaN}get weeksInWeekYear(){return this.isValid?Bn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Bn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(s={}){const{locale:f,numberingSystem:g,calendar:w}=mt.create(this.loc.clone(s),s).resolvedOptions(this);return{locale:f,numberingSystem:g,outputCalendar:w}}toUTC(s=0,f={}){return this.setZone(qe.instance(s),f)}toLocal(){return this.setZone(Pe.defaultZone)}setZone(s,{keepLocalTime:f=!1,keepCalendarTime:g=!1}={}){if(s=ut(s,Pe.defaultZone),s.equals(this.zone))return this;if(s.isValid){let w=this.ts;if(f||g){const I=s.offset(this.ts),F=this.toObject();[w]=Pr(F,I,s)}return on(this,{ts:w,zone:s})}else return Se.invalid(Yn(s))}reconfigure({locale:s,numberingSystem:f,outputCalendar:g}={}){const w=this.loc.clone({locale:s,numberingSystem:f,outputCalendar:g});return on(this,{loc:w})}setLocale(s){return this.reconfigure({locale:s})}set(s){if(!this.isValid)return this;const f=Rr(s,gi),{minDaysInFirstWeek:g,startOfWeek:w}=nn(f,this.loc),I=!J(f.weekYear)||!J(f.weekNumber)||!J(f.weekday),F=!J(f.ordinal),N=!J(f.year),_=!J(f.month)||!J(f.day),X=N||_,xe=f.weekYear||f.weekNumber;if((X||F)&&xe)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(_&&F)throw new i("Can't mix ordinal dates with month/day");let je;I?je=Ft({...Je(this.c,g,w),...f},g,w):J(f.ordinal)?(je={...this.toObject(),...f},J(f.day)&&(je.day=Math.min($r(je.year,je.month),je.day))):je=Zt({...tn(this.c),...f});const[He,we]=Pr(je,this.o,this.zone);return on(this,{ts:He,o:we})}plus(s){if(!this.isValid)return this;const f=Re.fromDurationLike(s);return on(this,fi(this,f))}minus(s){if(!this.isValid)return this;const f=Re.fromDurationLike(s).negate();return on(this,fi(this,f))}startOf(s,{useLocaleWeeks:f=!1}={}){if(!this.isValid)return this;const g={},w=Re.normalizeUnit(s);switch(w){case"years":g.month=1;case"quarters":case"months":g.day=1;case"weeks":case"days":g.hour=0;case"hours":g.minute=0;case"minutes":g.second=0;case"seconds":g.millisecond=0;break}if(w==="weeks")if(f){const I=this.loc.getStartOfWeek(),{weekday:F}=this;F<I&&(g.weekNumber=this.weekNumber-1),g.weekday=I}else g.weekday=1;if(w==="quarters"){const I=Math.ceil(this.month/3);g.month=(I-1)*3+1}return this.set(g)}endOf(s,f){return this.isValid?this.plus({[s]:1}).startOf(s,f).minus(1):this}toFormat(s,f={}){return this.isValid?mt.create(this.loc.redefaultToEN(f)).formatDateTimeFromString(this,s):bs}toLocaleString(s=b,f={}){return this.isValid?mt.create(this.loc.clone(f),s).formatDateTime(this):bs}toLocaleParts(s={}){return this.isValid?mt.create(this.loc.clone(s),s).formatDateTimeParts(this):[]}toISO({format:s="extended",suppressSeconds:f=!1,suppressMilliseconds:g=!1,includeOffset:w=!0,extendedZone:I=!1,precision:F="milliseconds"}={}){if(!this.isValid)return null;F=qr(F);const N=s==="extended";let _=ks(this,N,F);return Wr.indexOf(F)>=3&&(_+="T"),_+=mi(this,N,f,g,w,I,F),_}toISODate({format:s="extended",precision:f="day"}={}){return this.isValid?ks(this,s==="extended",qr(f)):null}toISOWeekDate(){return zr(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:s=!1,suppressSeconds:f=!1,includeOffset:g=!0,includePrefix:w=!1,extendedZone:I=!1,format:F="extended",precision:N="milliseconds"}={}){return this.isValid?(N=qr(N),(w&&Wr.indexOf(N)>=3?"T":"")+mi(this,F==="extended",f,s,g,I,N)):null}toRFC2822(){return zr(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return zr(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?ks(this,!0):null}toSQLTime({includeOffset:s=!0,includeZone:f=!1,includeOffsetSpace:g=!0}={}){let w="HH:mm:ss.SSS";return(f||s)&&(g&&(w+=" "),f?w+="z":s&&(w+="ZZ")),zr(this,w,!0)}toSQL(s={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(s)}`:null}toString(){return this.isValid?this.toISO():bs}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(s={}){if(!this.isValid)return{};const f={...this.c};return s.includeConfig&&(f.outputCalendar=this.outputCalendar,f.numberingSystem=this.loc.numberingSystem,f.locale=this.loc.locale),f}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(s,f="milliseconds",g={}){if(!this.isValid||!s.isValid)return Re.invalid("created by diffing an invalid DateTime");const w={locale:this.locale,numberingSystem:this.numberingSystem,...g},I=Dr(f).map(Re.normalizeUnit),F=s.valueOf()>this.valueOf(),N=F?this:s,_=F?s:this,X=ku(N,_,I,w);return F?X.negate():X}diffNow(s="milliseconds",f={}){return this.diff(Se.now(),s,f)}until(s){return this.isValid?et.fromDateTimes(this,s):this}hasSame(s,f,g){if(!this.isValid)return!1;const w=s.valueOf(),I=this.setZone(s.zone,{keepLocalTime:!0});return I.startOf(f,g)<=w&&w<=I.endOf(f,g)}equals(s){return this.isValid&&s.isValid&&this.valueOf()===s.valueOf()&&this.zone.equals(s.zone)&&this.loc.equals(s.loc)}toRelative(s={}){if(!this.isValid)return null;const f=s.base||Se.fromObject({},{zone:this.zone}),g=s.padding?this<f?-s.padding:s.padding:0;let w=["years","months","days","hours","minutes","seconds"],I=s.unit;return Array.isArray(s.unit)&&(w=s.unit,I=void 0),xi(f,this.plus(g),{...s,numeric:"always",units:w,unit:I})}toRelativeCalendar(s={}){return this.isValid?xi(s.base||Se.fromObject({},{zone:this.zone}),this,{...s,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...s){if(!s.every(Se.isDateTime))throw new a("min requires all arguments be DateTimes");return Ae(s,f=>f.valueOf(),Math.min)}static max(...s){if(!s.every(Se.isDateTime))throw new a("max requires all arguments be DateTimes");return Ae(s,f=>f.valueOf(),Math.max)}static fromFormatExplain(s,f,g={}){const{locale:w=null,numberingSystem:I=null}=g,F=he.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});return ci(F,s,f)}static fromStringExplain(s,f,g={}){return Se.fromFormatExplain(s,f,g)}static buildFormatParser(s,f={}){const{locale:g=null,numberingSystem:w=null}=f,I=he.fromOpts({locale:g,numberingSystem:w,defaultToEN:!0});return new li(I,s)}static fromFormatParser(s,f,g={}){if(J(s)||J(f))throw new a("fromFormatParser requires an input string and a format parser");const{locale:w=null,numberingSystem:I=null}=g,F=he.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});if(!F.equals(f.locale))throw new a(`fromFormatParser called with a locale of ${F}, but the format parser was created for ${f.locale}`);const{result:N,zone:_,specificOffset:X,invalidReason:xe}=f.explainFromTokens(s);return xe?Se.invalid(xe):Mn(N,_,g,`format ${f.format}`,s,X)}static get DATE_SHORT(){return b}static get DATE_MED(){return x}static get DATE_MED_WITH_WEEKDAY(){return v}static get DATE_FULL(){return k}static get DATE_HUGE(){return C}static get TIME_SIMPLE(){return S}static get TIME_WITH_SECONDS(){return T}static get TIME_WITH_SHORT_OFFSET(){return O}static get TIME_WITH_LONG_OFFSET(){return M}static get TIME_24_SIMPLE(){return E}static get TIME_24_WITH_SECONDS(){return R}static get TIME_24_WITH_SHORT_OFFSET(){return P}static get TIME_24_WITH_LONG_OFFSET(){return A}static get DATETIME_SHORT(){return H}static get DATETIME_SHORT_WITH_SECONDS(){return D}static get DATETIME_MED(){return L}static get DATETIME_MED_WITH_SECONDS(){return U}static get DATETIME_MED_WITH_WEEKDAY(){return $}static get DATETIME_FULL(){return W}static get DATETIME_FULL_WITH_SECONDS(){return Q}static get DATETIME_HUGE(){return te}static get DATETIME_HUGE_WITH_SECONDS(){return ee}}function Qn(m){if(Se.isDateTime(m))return m;if(m&&m.valueOf&&Ve(m.valueOf()))return Se.fromJSDate(m);if(m&&typeof m=="object")return Se.fromObject(m);throw new a(`Unknown datetime argument: ${m}, of type ${typeof m}`)}const Wu="3.7.2";return wt.DateTime=Se,wt.Duration=Re,wt.FixedOffsetZone=qe,wt.IANAZone=pe,wt.Info=Gn,wt.Interval=et,wt.InvalidZone=ct,wt.Settings=Pe,wt.SystemZone=ae,wt.VERSION=Wu,wt.Zone=G,wt}var Xi;function co(){return Xi||(Xi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronDate=e.DAYS_IN_MONTH=e.DateMathOp=e.TimeUnit=void 0;const n=xf();var r;(function(l){l.Second="Second",l.Minute="Minute",l.Hour="Hour",l.Day="Day",l.Month="Month",l.Year="Year"})(r||(e.TimeUnit=r={}));var o;(function(l){l.Add="Add",l.Subtract="Subtract"})(o||(e.DateMathOp=o={})),e.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);class i{#e;#n=null;#o=null;constructor(a,d){const u={zone:d};if(a?a instanceof i?(this.#e=a.#e,this.#n=a.#n,this.#o=a.#o):a instanceof Date?this.#e=n.DateTime.fromJSDate(a,u):typeof a=="number"?this.#e=n.DateTime.fromMillis(a,u):(this.#e=n.DateTime.fromISO(a,u),this.#e.isValid||(this.#e=n.DateTime.fromRFC2822(a,u)),this.#e.isValid||(this.#e=n.DateTime.fromSQL(a,u)),this.#e.isValid||(this.#e=n.DateTime.fromFormat(a,"EEE, d MMM yyyy HH:mm:ss",u))):this.#e=n.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${a}`);d&&d!==this.#e.zoneName&&(this.#e=this.#e.setZone(d))}static#s(a){return a%4===0&&a%100!==0||a%400===0}get dstStart(){return this.#n}set dstStart(a){this.#n=a}get dstEnd(){return this.#o}set dstEnd(a){this.#o=a}addYear(){this.#e=this.#e.plus({years:1})}addMonth(){this.#e=this.#e.plus({months:1}).startOf("month")}addDay(){this.#e=this.#e.plus({days:1}).startOf("day")}addHour(){this.#e=this.#e.plus({hours:1}).startOf("hour")}addMinute(){this.#e=this.#e.plus({minutes:1}).startOf("minute")}addSecond(){this.#e=this.#e.plus({seconds:1})}subtractYear(){this.#e=this.#e.minus({years:1})}subtractMonth(){this.#e=this.#e.minus({months:1}).endOf("month").startOf("second")}subtractDay(){this.#e=this.#e.minus({days:1}).endOf("day").startOf("second")}subtractHour(){this.#e=this.#e.minus({hours:1}).endOf("hour").startOf("second")}subtractMinute(){this.#e=this.#e.minus({minutes:1}).endOf("minute").startOf("second")}subtractSecond(){this.#e=this.#e.minus({seconds:1})}addUnit(a){switch(a){case r.Year:return this.addYear();case r.Month:return this.addMonth();case r.Day:return this.addDay();case r.Hour:return this.addHour();case r.Minute:return this.addMinute();case r.Second:return this.addSecond()}}subtractUnit(a){switch(a){case r.Year:return this.subtractYear();case r.Month:return this.subtractMonth();case r.Day:return this.subtractDay();case r.Hour:return this.subtractHour();case r.Minute:return this.subtractMinute();case r.Second:return this.subtractSecond()}}invokeDateOperation(a,d){if(a===o.Add){this.addUnit(d);return}if(a===o.Subtract){this.subtractUnit(d);return}throw new Error(`Invalid verb: ${a}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const a=this.#e.weekday;return a===7?0:a}getMonth(){return this.#e.month-1}getHours(){return this.#e.hour}getMinutes(){return this.#e.minute}getSeconds(){return this.#e.second}getMilliseconds(){return this.#e.millisecond}getUTCOffset(){return this.#e.offset}setStartOfDay(){this.#e=this.#e.startOf("day")}setEndOfDay(){this.#e=this.#e.endOf("day")}getTime(){return this.#e.valueOf()}getUTCDate(){return this.#r().day}getUTCFullYear(){return this.#r().year}getUTCDay(){const a=this.#r().weekday;return a===7?0:a}getUTCMonth(){return this.#r().month-1}getUTCHours(){return this.#r().hour}getUTCMinutes(){return this.#r().minute}getUTCSeconds(){return this.#r().second}toISOString(){return this.#e.toUTC().toISO()}toJSON(){return this.#e.toJSON()}setDate(a){this.#e=this.#e.set({day:a})}setFullYear(a){this.#e=this.#e.set({year:a})}setDay(a){this.#e=this.#e.set({weekday:a})}setMonth(a){this.#e=this.#e.set({month:a+1})}setHours(a){this.#e=this.#e.set({hour:a})}setMinutes(a){this.#e=this.#e.set({minute:a})}setSeconds(a){this.#e=this.#e.set({second:a})}setMilliseconds(a){this.#e=this.#e.set({millisecond:a})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:a,month:d}=this.#e;if(d===2){const u=i.#s(this.#e.year);return a===e.DAYS_IN_MONTH[d-1]-(u?0:1)}return a===e.DAYS_IN_MONTH[d-1]}isLastWeekdayOfMonth(){const{day:a,month:d}=this.#e;let u;return d===2?u=e.DAYS_IN_MONTH[d-1]-(i.#s(this.#e.year)?0:1):u=e.DAYS_IN_MONTH[d-1],a>u-7}applyDateOperation(a,d,u){if(d===r.Month||d===r.Day){this.invokeDateOperation(a,d);return}const h=this.getHours();this.invokeDateOperation(a,d);const y=this.getHours(),b=y-h;b===2?u!==24&&(this.dstStart=h+1):b===0&&this.getMinutes()===0&&this.getSeconds()===0&&u!==24&&(this.dstEnd=y)}#r(){return this.#e.toUTC()}}e.CronDate=i,e.default=i})(Is)),Is}var Ji;function vf(){if(Ji)return ar;Ji=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.CronMonth=void 0;const e=co(),n=mn(),r=1,o=12,i=Object.freeze([]);let l=class extends n.CronField{static get min(){return r}static get max(){return o}static get chars(){return i}static get daysInMonth(){return e.DAYS_IN_MONTH}constructor(d,u){super(d,u),this.validate()}get values(){return super.values}};return ar.CronMonth=l,ar}var lr={},ea;function bf(){if(ea)return lr;ea=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.CronSecond=void 0;const e=mn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return lr.CronSecond=i,lr}var ta;function uo(){return ta||(ta=1,(function(e){var n=ln&&ln.__createBinding||(Object.create?(function(o,i,l,a){a===void 0&&(a=l);var d=Object.getOwnPropertyDescriptor(i,l);(!d||("get"in d?!i.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return i[l]}}),Object.defineProperty(o,a,d)}):(function(o,i,l,a){a===void 0&&(a=l),o[a]=i[l]})),r=ln&&ln.__exportStar||function(o,i){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(i,l)&&n(i,o,l)};Object.defineProperty(e,"__esModule",{value:!0}),r(ff(),e),r(mf(),e),r(pf(),e),r(mn(),e),r(gf(),e),r(yf(),e),r(vf(),e),r(bf(),e)})(ln)),ln}var na;function al(){if(na)return tr;na=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.CronFieldCollection=void 0;const e=uo();let n=class gr{#e;#n;#o;#s;#r;#t;static from(o,i){return new gr({second:this.resolveField(e.CronSecond,o.second,i.second),minute:this.resolveField(e.CronMinute,o.minute,i.minute),hour:this.resolveField(e.CronHour,o.hour,i.hour),dayOfMonth:this.resolveField(e.CronDayOfMonth,o.dayOfMonth,i.dayOfMonth),month:this.resolveField(e.CronMonth,o.month,i.month),dayOfWeek:this.resolveField(e.CronDayOfWeek,o.dayOfWeek,i.dayOfWeek)})}static resolveField(o,i,l){return l?l instanceof e.CronField?l:new o(l):i}constructor({second:o,minute:i,hour:l,dayOfMonth:a,month:d,dayOfWeek:u}){if(!o)throw new Error("Validation error, Field second is missing");if(!i)throw new Error("Validation error, Field minute is missing");if(!l)throw new Error("Validation error, Field hour is missing");if(!a)throw new Error("Validation error, Field dayOfMonth is missing");if(!d)throw new Error("Validation error, Field month is missing");if(!u)throw new Error("Validation error, Field dayOfWeek is missing");if(d.values.length===1&&!a.hasLastChar&&u.isWildcard&&!(parseInt(a.values[0],10)<=e.CronMonth.daysInMonth[d.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=o,this.#n=i,this.#o=l,this.#r=d,this.#t=u,this.#s=a}get second(){return this.#e}get minute(){return this.#n}get hour(){return this.#o}get dayOfMonth(){return this.#s}get month(){return this.#r}get dayOfWeek(){return this.#t}static compactField(o){if(o.length===0)return[];const i=[];let l;return o.forEach((a,d,u)=>{if(l===void 0){l={start:a,count:1};return}const h=u[d-1]||l.start,y=u[d+1];if(a==="L"||a==="W"){i.push(l),i.push({start:a,count:1}),l=void 0;return}if(l.step===void 0&&y!==void 0){const b=a-h,x=y-a;if(b<=x){l={...l,count:2,end:a,step:b};return}l.step=1}a-(l.end??0)===l.step?(l.count++,l.end=a):(l.count===1?i.push({start:l.start,count:1}):l.count===2?(i.push({start:l.start,count:1}),i.push({start:l.end??h,count:1})):i.push(l),l={start:a,count:1})}),l&&i.push(l),i}static#c(o,i,l){const a=i.step;return a?a===1&&i.start===o.min&&i.end&&i.end>=l?o.hasQuestionMarkChar?"?":"*":a!==1&&i.start===o.min&&i.end&&i.end>=l-a+1?`*/${a}`:null:null}static#l(o,i){const l=o.step;if(l===1)return`${o.start}-${o.end}`;const a=o.start===0?o.count-1:o.count;if(!l)throw new Error("Unexpected range step");if(!o.end)throw new Error("Unexpected range end");if(l*a>o.end){const d=(h,y)=>{if(typeof o.start!="number")throw new Error("Unexpected range start");return y%l===0?o.start+y:null};if(typeof o.start!="number")throw new Error("Unexpected range start");const u={length:o.end-o.start+1};return Array.from(u,d).filter(h=>h!==null).join(",")}return o.end===i-l+1?`${o.start}/${l}`:`${o.start}-${o.end}/${l}`}stringifyField(o){let i=o.max,l=o.values;if(o instanceof e.CronDayOfWeek){i=6;const d=this.#t.values;l=d[d.length-1]===7?d.slice(0,-1):d}o instanceof e.CronDayOfMonth&&(i=this.#r.values.length===1?e.CronMonth.daysInMonth[this.#r.values[0]-1]:o.max);const a=gr.compactField(l);if(a.length===1){const d=gr.#c(o,a[0],i);if(d)return d}return a.map(d=>{const u=d.count===1?d.start.toString():gr.#l(d,i);return o instanceof e.CronDayOfWeek&&o.nthDay>0?`${u}#${o.nthDay}`:u}).join(",")}stringify(o=!1){const i=[];return o&&i.push(this.stringifyField(this.#e)),i.push(this.stringifyField(this.#n),this.stringifyField(this.#o),this.stringifyField(this.#s),this.stringifyField(this.#r),this.stringifyField(this.#t)),i.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#n.serialize(),hour:this.#o.serialize(),dayOfMonth:this.#s.serialize(),month:this.#r.serialize(),dayOfWeek:this.#t.serialize()}}};return tr.CronFieldCollection=n,tr}var Ds={},ra;function ll(){return ra||(ra=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronExpression=e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;const n=co();e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range",e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";const r=1e4;class o{#e;#n;#o;#s;#r;#t;#c=null;#l=!1;constructor(l,a){this.#e=a,this.#n=a.tz,this.#s=a.startDate?new n.CronDate(a.startDate,this.#n):null,this.#r=a.endDate?new n.CronDate(a.endDate,this.#n):null;let d=a.currentDate??a.startDate;if(d){const u=new n.CronDate(d,this.#n);this.#s&&u.getTime()<this.#s.getTime()?d=this.#s:this.#r&&u.getTime()>this.#r.getTime()&&(d=this.#r)}this.#o=new n.CronDate(d,this.#n),this.#t=l}get fields(){return this.#t}static fieldsToExpression(l,a){return new o(l,a||{})}static#i(l,a){return a.some(d=>d===l)}#a(l,a){return l[a?l.length-1:0]}#d(l){const a=`${l.getFullYear()}-${l.getMonth()+1}-${l.getDate()}`;if(this.#c===a)return this.#l;const d=new n.CronDate(l);d.setStartOfDay();const u=new n.CronDate(l);return u.setEndOfDay(),this.#c=a,this.#l=d.getUTCOffset()!==u.getUTCOffset(),this.#l}#h(l,a,d){const u=this.#t.second.values,h=l.getSeconds(),y=this.#t.second.findNearestValue(h,d);if(y!==null){l.setSeconds(y);return}l.applyDateOperation(a,n.TimeUnit.Minute,this.#t.hour.values.length),l.setSeconds(this.#a(u,d))}#m(l,a,d){const u=this.#t.minute.values,h=this.#t.second.values,y=l.getMinutes(),b=this.#t.minute.findNearestValue(y,d);if(b!==null){l.setMinutes(b),l.setSeconds(this.#a(h,d));return}l.applyDateOperation(a,n.TimeUnit.Hour,this.#t.hour.values.length),l.setMinutes(this.#a(u,d)),l.setSeconds(this.#a(h,d))}static#p(l,a){const d=a.isLastWeekdayOfMonth();return l.some(u=>{const h=parseInt(u.toString().charAt(0),10)%7;if(Number.isNaN(h))throw new Error(`Invalid last weekday of the month expression: ${u}`);return a.getDay()===h&&d})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const l=this.#o;try{return this.#u(),!0}catch{return!1}finally{this.#o=l}}hasPrev(){const l=this.#o;try{return this.#u(!0),!0}catch{return!1}finally{this.#o=l}}take(l){const a=[];if(l>=0)for(let d=0;d<l;d++)try{a.push(this.next())}catch{return a}else for(let d=0;d>l;d--)try{a.push(this.prev())}catch{return a}return a}reset(l){this.#o=new n.CronDate(l||this.#e.currentDate,this.#n)}stringify(l=!1){return this.#t.stringify(l)}includesDate(l){const{second:a,minute:d,hour:u,month:h}=this.#t,y=new n.CronDate(l,this.#n);return!(!a.values.includes(y.getSeconds())||!d.values.includes(y.getMinutes())||!u.values.includes(y.getHours())||!h.values.includes(y.getMonth()+1)||!this.#f(y)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(y.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(l){const a=this.#t.dayOfMonth.isWildcard,d=!a,u=this.#t.dayOfWeek.isWildcard,h=!u,y=o.#i(l.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&l.isLastDayOfMonth(),b=o.#i(l.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&o.#p(this.#t.dayOfWeek.values,l);return!!(d&&h&&(y||b)||y&&!h||a&&!u&&b)}#g(l,a,d){const u=this.#t.hour.values,h=u,y=l.getHours(),b=o.#i(y,u),x=l.dstEnd===y;if(l.dstStart!==null&&l.dstStart===y-1&&o.#i(l.dstStart,u))return!0;if(x&&!d)return l.dstEnd=null,l.applyDateOperation(n.DateMathOp.Add,n.TimeUnit.Hour,h.length),!1;if(b)return!0;l.dstStart=null;const v=this.#t.hour.findNearestValue(y,d);if(v===null)return l.applyDateOperation(a,n.TimeUnit.Day,h.length),!1;if(this.#d(l)){const k=d?y-v:v-y;for(let C=0;C<k&&(l.applyDateOperation(a,n.TimeUnit.Hour,h.length),!(!d&&l.getHours()>=v||d&&l.getHours()<=v));C++);}else l.setHours(v);return l.setMinutes(this.#a(this.#t.minute.values,d)),l.setSeconds(this.#a(this.#t.second.values,d)),!1}#y(l){if(!this.#s&&!this.#r)return;const a=l.getTime();if(this.#s&&a<this.#s.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&a>this.#r.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(l=!1){const a=l?n.DateMathOp.Subtract:n.DateMathOp.Add,d=new n.CronDate(this.#o),u=d.getTime();let h=0;for(;++h<r;){if(this.#y(d),!this.#f(d)){d.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(d.getDate()/7)===this.#t.dayOfWeek.nthDay)){d.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!o.#i(d.getMonth()+1,this.#t.month.values)){d.applyDateOperation(a,n.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#g(d,a,l)){if(!o.#i(d.getMinutes(),this.#t.minute.values)){this.#m(d,a,l);continue}if(!o.#i(d.getSeconds(),this.#t.second.values)){this.#h(d,a,l);continue}if(u===d.getTime()){(a==="Add"||d.getMilliseconds()===0)&&d.applyDateOperation(a,n.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(h>r)throw new Error(e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return d.getMilliseconds()!==0&&d.setMilliseconds(0),this.#o=d,d}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}e.CronExpression=o,e.default=o})(Ds)),Ds}var Br={},sa;function wf(){if(sa)return Br;sa=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.seededRandom=r;function e(o){let i=2166136261;for(let l=0;l<o.length;l++)i^=o.charCodeAt(l),i=Math.imul(i,16777619);return()=>i>>>0}function n(o){return()=>{let i=o+=1831565813;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}function r(o){const i=o?e(o)():Math.floor(Math.random()*1e10);return n(i)}return Br}var oa;function Zs(){if(oa)return jt;oa=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.CronExpressionParser=jt.DayOfWeek=jt.Months=jt.CronUnit=jt.PredefinedExpressions=void 0;const e=al(),n=ll(),r=wf(),o=uo();var i;(function(h){h["@yearly"]="0 0 0 1 1 *",h["@annually"]="0 0 0 1 1 *",h["@monthly"]="0 0 0 1 * *",h["@weekly"]="0 0 0 * * 0",h["@daily"]="0 0 0 * * *",h["@hourly"]="0 0 * * * *",h["@minutely"]="0 * * * * *",h["@secondly"]="* * * * * *",h["@weekdays"]="0 0 0 * * 1-5",h["@weekends"]="0 0 0 * * 0,6"})(i||(jt.PredefinedExpressions=i={}));var l;(function(h){h.Second="Second",h.Minute="Minute",h.Hour="Hour",h.DayOfMonth="DayOfMonth",h.Month="Month",h.DayOfWeek="DayOfWeek"})(l||(jt.CronUnit=l={}));var a;(function(h){h[h.jan=1]="jan",h[h.feb=2]="feb",h[h.mar=3]="mar",h[h.apr=4]="apr",h[h.may=5]="may",h[h.jun=6]="jun",h[h.jul=7]="jul",h[h.aug=8]="aug",h[h.sep=9]="sep",h[h.oct=10]="oct",h[h.nov=11]="nov",h[h.dec=12]="dec"})(a||(jt.Months=a={}));var d;(function(h){h[h.sun=0]="sun",h[h.mon=1]="mon",h[h.tue=2]="tue",h[h.wed=3]="wed",h[h.thu=4]="thu",h[h.fri=5]="fri",h[h.sat=6]="sat"})(d||(jt.DayOfWeek=d={}));let u=class Tt{static parse(y,b={}){const{strict:x=!1,hashSeed:v}=b,k=(0,r.seededRandom)(v);y=i[y]||y;const C=Tt.#e(y,x);if(!(C.dayOfMonth==="*"||C.dayOfWeek==="*"||!x))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const S=Tt.#n(l.Second,C.second,o.CronSecond.constraints,k),T=Tt.#n(l.Minute,C.minute,o.CronMinute.constraints,k),O=Tt.#n(l.Hour,C.hour,o.CronHour.constraints,k),M=Tt.#n(l.Month,C.month,o.CronMonth.constraints,k),E=Tt.#n(l.DayOfMonth,C.dayOfMonth,o.CronDayOfMonth.constraints,k),{dayOfWeek:R,nthDayOfWeek:P}=Tt.#d(C.dayOfWeek),A=Tt.#n(l.DayOfWeek,R,o.CronDayOfWeek.constraints,k),H=new e.CronFieldCollection({second:new o.CronSecond(S,{rawValue:C.second}),minute:new o.CronMinute(T,{rawValue:C.minute}),hour:new o.CronHour(O,{rawValue:C.hour}),dayOfMonth:new o.CronDayOfMonth(E,{rawValue:C.dayOfMonth}),month:new o.CronMonth(M,{rawValue:C.month}),dayOfWeek:new o.CronDayOfWeek(A,{rawValue:C.dayOfWeek,nthDayOfWeek:P})});return new n.CronExpression(H,{...b,expression:y})}static#e(y,b){if(b&&!y.length)throw new Error("Invalid cron expression");y=y||"0 * * * * *";const x=y.trim().split(/\s+/);if(b&&x.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(x.length>6)throw new Error("Invalid cron expression, too many fields");const v=["*","*","*","*","*","0"];x.length<v.length&&x.unshift(...v.slice(x.length));const[k,C,S,T,O,M]=x;return{second:k,minute:C,hour:S,dayOfMonth:T,month:O,dayOfWeek:M}}static#n(y,b,x,v){if((y===l.Month||y===l.DayOfWeek)&&(b=b.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const C=a[k]||d[k];if(C===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return C.toString()})),!x.validChars.test(b))throw new Error(`Invalid characters, got value: ${b}`);return b=this.#o(b,x),b=this.#s(b,x,v),this.#r(y,b,x)}static#o(y,b){return y.replace(/[*?]/g,b.min+"-"+b.max)}static#s(y,b,x){const v=x();return y.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(k,C,S,T)=>{if(C&&S&&T){const O=parseInt(C,10),M=parseInt(S,10),E=parseInt(T,10);if(O>M)throw new Error(`Invalid range: ${O}-${M}, min > max`);if(E<=0)throw new Error(`Invalid step: ${E}, must be positive`);const R=Math.max(O,b.min),P=Math.floor(v*E),A=[];for(let H=Math.floor(R/E)*E+P;H<=M;H+=E)H>=R&&A.push(H);return A.join(",")}else if(C&&S){const O=parseInt(C,10),M=parseInt(S,10);if(O>M)throw new Error(`Invalid range: ${O}-${M}, min > max`);return String(Math.floor(v*(M-O+1))+O)}else if(T){const O=parseInt(T,10);if(O<=0)throw new Error(`Invalid step: ${O}, must be positive`);const M=Math.floor(v*O),E=[];for(let R=Math.floor(b.min/O)*O+M;R<=b.max;R+=O)R>=b.min&&E.push(R);return E.join(",")}else return String(Math.floor(v*(b.max-b.min+1)+b.min))})}static#r(y,b,x){const v=[];function k(S,T){if(Array.isArray(S))v.push(...S);else if(Tt.#h(T,S))v.push(S);else{const O=parseInt(S.toString(),10);if(!(O>=T.min&&O<=T.max))throw new Error(`Constraint error, got value ${S} expected range ${T.min}-${T.max}`);v.push(y===l.DayOfWeek?O%7:S)}}return b.split(",").forEach(S=>{if(!(S.length>0))throw new Error("Invalid list value format");k(Tt.#t(y,S,x),x)}),v}static#t(y,b,x){const v=b.split("/");if(v.length>2)throw new Error(`Invalid repeat: ${b}`);return v.length===2?(v[0].includes("-")||(v[0]=`${v[0]}-${x.max}`),Tt.#a(y,v[0],parseInt(v[1],10),x)):Tt.#a(y,b,1,x)}static#c(y,b,x){if(!(!isNaN(y)&&!isNaN(b)&&y>=x.min&&b<=x.max))throw new Error(`Constraint error, got range ${y}-${b} expected range ${x.min}-${x.max}`);if(y>b)throw new Error(`Invalid range: ${y}-${b}, min(${y}) > max(${b})`)}static#l(y){if(!(!isNaN(y)&&y>0))throw new Error(`Constraint error, cannot repeat at every ${y} time.`)}static#i(y,b,x,v){const k=[];y===l.DayOfWeek&&x%7===0&&k.push(0);for(let C=b;C<=x;C+=v)k.indexOf(C)===-1&&k.push(C);return k}static#a(y,b,x,v){const k=b.split("-");if(k.length<=1)return isNaN(+b)?b:+b;const[C,S]=k.map(T=>parseInt(T,10));return this.#c(C,S,v),this.#l(x),this.#i(y,C,S,x)}static#d(y){const b=y.split("#");if(b.length<=1)return{dayOfWeek:b[0]};const x=+b[b.length-1],v=y.match(/([,-/])/);if(v!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${v?.[0]}\` special characters are incompatible`);if(!(b.length<=2&&!isNaN(x)&&x>=1&&x<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:b[0],nthDayOfWeek:x}}static#h(y,b){return y.chars.some(x=>b.toString().includes(x))}};return jt.CronExpressionParser=u,jt}var Lt={};const Sf={},kf=Object.freeze(Object.defineProperty({__proto__:null,default:Sf},Symbol.toStringTag,{value:"Module"})),ia=c.getAugmentedNamespace(kf);var aa;function Cf(){if(aa)return Lt;aa=1;var e=Lt&&Lt.__createBinding||(Object.create?(function(l,a,d,u){u===void 0&&(u=d);var h=Object.getOwnPropertyDescriptor(a,d);(!h||("get"in h?!a.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return a[d]}}),Object.defineProperty(l,u,h)}):(function(l,a,d,u){u===void 0&&(u=d),l[u]=a[d]})),n=Lt&&Lt.__setModuleDefault||(Object.create?(function(l,a){Object.defineProperty(l,"default",{enumerable:!0,value:a})}):function(l,a){l.default=a}),r=Lt&&Lt.__importStar||(function(){var l=function(a){return l=Object.getOwnPropertyNames||function(d){var u=[];for(var h in d)Object.prototype.hasOwnProperty.call(d,h)&&(u[u.length]=h);return u},l(a)};return function(a){if(a&&a.__esModule)return a;var d={};if(a!=null)for(var u=l(a),h=0;h<u.length;h++)u[h]!=="default"&&e(d,a,u[h]);return n(d,a),d}})();Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.CronFileParser=void 0;const o=Zs();let i=class Yr{static async parseFile(a){const{readFile:d}=await Promise.resolve().then(()=>r(ia)),u=await d(a,"utf8");return Yr.#e(u)}static parseFileSync(a){const{readFileSync:d}=ia,u=d(a,"utf8");return Yr.#e(u)}static#e(a){const d=a.split(`
7
- `),u={variables:{},expressions:[],errors:{}};for(const h of d){const y=h.trim();if(y.length===0||y.startsWith("#"))continue;const b=y.match(/^(.*)=(.*)$/);if(b){const[,x,v]=b;u.variables[x]=v.replace(/["']/g,"");continue}try{const x=Yr.#n(y);u.expressions.push(x.interval)}catch(x){u.errors[y]=x}}return u}static#n(a){const d=a.split(" ");return{interval:o.CronExpressionParser.parse(d.slice(0,5).join(" ")),command:d.slice(5,d.length)}}};return Lt.CronFileParser=i,Lt}var la;function jf(){return la||(la=1,(function(e){var n=an&&an.__createBinding||(Object.create?(function(h,y,b,x){x===void 0&&(x=b);var v=Object.getOwnPropertyDescriptor(y,b);(!v||("get"in v?!y.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return y[b]}}),Object.defineProperty(h,x,v)}):(function(h,y,b,x){x===void 0&&(x=b),h[x]=y[b]})),r=an&&an.__exportStar||function(h,y){for(var b in h)b!=="default"&&!Object.prototype.hasOwnProperty.call(y,b)&&n(y,h,b)};Object.defineProperty(e,"__esModule",{value:!0}),e.CronFileParser=e.CronExpressionParser=e.CronExpression=e.CronFieldCollection=e.CronDate=void 0;const o=Zs();var i=co();Object.defineProperty(e,"CronDate",{enumerable:!0,get:function(){return i.CronDate}});var l=al();Object.defineProperty(e,"CronFieldCollection",{enumerable:!0,get:function(){return l.CronFieldCollection}});var a=ll();Object.defineProperty(e,"CronExpression",{enumerable:!0,get:function(){return a.CronExpression}});var d=Zs();Object.defineProperty(e,"CronExpressionParser",{enumerable:!0,get:function(){return d.CronExpressionParser}});var u=Cf();Object.defineProperty(e,"CronFileParser",{enumerable:!0,get:function(){return u.CronFileParser}}),r(uo(),e),e.default=o.CronExpressionParser})(an)),an}var Tf=jf(),$s={exports:{}},ca;function Of(){return ca||(ca=1,(function(e,n){(function(o,i){e.exports=i()})(globalThis,()=>(()=>{var r={949:((a,d,u)=>{Object.defineProperty(d,"__esModule",{value:!0}),d.CronParser=void 0;var h=u(515),y=(function(){function b(x,v,k){v===void 0&&(v=!0),k===void 0&&(k=!1),this.expression=x,this.dayOfWeekStartIndexZero=v,this.monthStartIndexZero=k}return b.prototype.parse=function(){var x,v,k=(x=this.expression)!==null&&x!==void 0?x:"";if(k==="@reboot")return v=["@reboot","","","","","",""],v;if(k.startsWith("@")){var C=this.parseSpecial(this.expression);v=this.extractParts(C)}else v=this.extractParts(this.expression);return this.normalize(v),this.validate(v),v},b.prototype.parseSpecial=function(x){var v={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},k=v[x];if(!k)throw new Error("Unknown special expression.");return k},b.prototype.extractParts=function(x){if(!this.expression)throw new Error("cron expression is empty");for(var v=x.trim().split(/[ ]+/),k=0;k<v.length;k++)if(v[k].includes(",")){var C=v[k].split(",").map(function(T){return T.trim()}).filter(function(T){return T!==""}).map(function(T){return isNaN(Number(T))?T:Number(T)}).filter(function(T){return T!==null&&T!==""});C.length===0&&C.push("*"),C.sort(function(T,O){return T!==null&&O!==null?T-O:0}),v[k]=C.map(function(T){return T!==null?T.toString():""}).join(",")}if(v.length<5)throw new Error("Expression has only ".concat(v.length," part").concat(v.length==1?"":"s",". At least 5 parts are required."));if(v.length==5)v.unshift(""),v.push("");else if(v.length==6){var S=/\d{4}$/.test(v[5])||v[4]=="?"||v[2]=="?";S?v.unshift(""):v.push("")}else if(v.length>7)throw new Error("Expression has ".concat(v.length," parts; too many!"));return v},b.prototype.normalize=function(x){var v=this;if(x[3]=x[3].replace("?","*"),x[5]=x[5].replace("?","*"),x[2]=x[2].replace("?","*"),x[0].indexOf("0/")==0&&(x[0]=x[0].replace("0/","*/")),x[1].indexOf("0/")==0&&(x[1]=x[1].replace("0/","*/")),x[2].indexOf("0/")==0&&(x[2]=x[2].replace("0/","*/")),x[3].indexOf("1/")==0&&(x[3]=x[3].replace("1/","*/")),x[4].indexOf("1/")==0&&(x[4]=x[4].replace("1/","*/")),x[6].indexOf("1/")==0&&(x[6]=x[6].replace("1/","*/")),x[5]=x[5].replace(/(^\d)|([^#/\s]\d)/g,function(R){var P=R.replace(/\D/,""),A=P;return v.dayOfWeekStartIndexZero?P=="7"&&(A="0"):A=(parseInt(P)-1).toString(),R.replace(P,A)}),x[5]=="L"&&(x[5]="6"),x[3]=="?"&&(x[3]="*"),x[3].indexOf("W")>-1&&(x[3].indexOf(",")>-1||x[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var k={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var C in k)x[5]=x[5].replace(new RegExp(C,"gi"),k[C].toString());x[4]=x[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(R){var P=R.replace(/\D/,""),A=P;return v.monthStartIndexZero&&(A=(parseInt(P)+1).toString()),R.replace(P,A)});var S={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var T in S)x[4]=x[4].replace(new RegExp(T,"gi"),S[T].toString());x[0]=="0"&&(x[0]=""),!/\*|\-|\,|\//.test(x[2])&&(/\*|\//.test(x[1])||/\*|\//.test(x[0]))&&(x[2]+="-".concat(x[2]));for(var O=0;O<x.length;O++)if(x[O].indexOf(",")!=-1&&(x[O]=x[O].split(",").filter(function(R){return R!==""}).join(",")||"*"),x[O]=="*/1"&&(x[O]="*"),x[O].indexOf("/")>-1&&!/^\*|\-|\,/.test(x[O])){var M=null;switch(O){case 4:M="12";break;case 5:M="6";break;case 6:M="9999";break;default:M=null;break}if(M!==null){var E=x[O].split("/");x[O]="".concat(E[0],"-").concat(M,"/").concat(E[1])}}},b.prototype.validate=function(x){var v="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(x[0],v),this.validateOnlyExpectedCharactersFound(x[1],v),this.validateOnlyExpectedCharactersFound(x[2],v),this.validateOnlyExpectedCharactersFound(x[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(x[4],v),this.validateOnlyExpectedCharactersFound(x[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(x[6],v),this.validateAnyRanges(x)},b.prototype.validateAnyRanges=function(x){h.default.secondRange(x[0]),h.default.minuteRange(x[1]),h.default.hourRange(x[2]),h.default.dayOfMonthRange(x[3]),h.default.monthRange(x[4],this.monthStartIndexZero),h.default.dayOfWeekRange(x[5],this.dayOfWeekStartIndexZero)},b.prototype.validateOnlyExpectedCharactersFound=function(x,v){var k=x.match(new RegExp("[^".concat(v,"]+"),"gi"));if(k&&k.length)throw new Error("Expression contains invalid values: '".concat(k.toString(),"'"))},b})();d.CronParser=y}),333:((a,d,u)=>{Object.defineProperty(d,"__esModule",{value:!0}),d.ExpressionDescriptor=void 0;var h=u(823),y=u(949),b=(function(){function x(v,k){if(this.expression=v,this.options=k,this.expressionParts=new Array(5),!this.options.locale&&x.defaultLocale&&(this.options.locale=x.defaultLocale),!x.locales[this.options.locale]){var C=Object.keys(x.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(C,"'.")),this.options.locale=C}this.i18n=x.locales[this.options.locale],k.use24HourTimeFormat===void 0&&(k.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return x.toString=function(v,k){var C=k===void 0?{}:k,S=C.throwExceptionOnParseError,T=S===void 0?!0:S,O=C.verbose,M=O===void 0?!1:O,E=C.dayOfWeekStartIndexZero,R=E===void 0?!0:E,P=C.monthStartIndexZero,A=P===void 0?!1:P,H=C.use24HourTimeFormat,D=C.locale,L=D===void 0?null:D,U={throwExceptionOnParseError:T,verbose:M,dayOfWeekStartIndexZero:R,monthStartIndexZero:A,use24HourTimeFormat:H,locale:L};U.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var $=new x(v,U);return $.getFullDescription()},x.initialize=function(v,k){k===void 0&&(k="en"),x.specialCharacters=["/","-",",","*"],x.defaultLocale=k,v.load(x.locales)},x.prototype.getFullDescription=function(){var v,k,C="";try{var S=new y.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=S.parse(),this.expressionParts[0]==="@reboot")return((k=(v=this.i18n).atReboot)===null||k===void 0?void 0:k.call(v))||"Run once, at startup";var T=this.getTimeOfDayDescription(),O=this.getDayOfMonthDescription(),M=this.getMonthDescription(),E=this.getDayOfWeekDescription(),R=this.getYearDescription();C+=T+O+E+M+R,C=this.transformVerbosity(C,!!this.options.verbose),C=C.charAt(0).toLocaleUpperCase()+C.substr(1)}catch(P){if(!this.options.throwExceptionOnParseError)C=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(P)}return C},x.prototype.getTimeOfDayDescription=function(){var v=this.expressionParts[0],k=this.expressionParts[1],C=this.expressionParts[2],S="";if(!h.StringUtilities.containsAny(k,x.specialCharacters)&&!h.StringUtilities.containsAny(C,x.specialCharacters)&&!h.StringUtilities.containsAny(v,x.specialCharacters))S+=this.i18n.atSpace()+this.formatTime(C,k,v);else if(!v&&k.indexOf("-")>-1&&!(k.indexOf(",")>-1)&&!(k.indexOf("/")>-1)&&!h.StringUtilities.containsAny(C,x.specialCharacters)){var T=k.split("-");S+=h.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(C,T[0],""),this.formatTime(C,T[1],""))}else if(!v&&C.indexOf(",")>-1&&C.indexOf("-")==-1&&C.indexOf("/")==-1&&!h.StringUtilities.containsAny(k,x.specialCharacters)){var O=C.split(",");S+=this.i18n.at();for(var M=0;M<O.length;M++)S+=" ",S+=this.formatTime(O[M],k,""),M<O.length-2&&(S+=","),M==O.length-2&&(S+=this.i18n.spaceAnd())}else{var E=this.getSecondsDescription(),R=this.getMinutesDescription(),P=this.getHoursDescription();if(S+=E,S&&R&&(S+=", "),S+=R,R===P)return S;S&&P&&(S+=", "),S+=P}return S},x.prototype.getSecondsDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(C){return C},function(C){return h.StringUtilities.format(v.i18n.everyX0Seconds(C),C)},function(C){return v.i18n.secondsX0ThroughX1PastTheMinute()},function(C){return C=="0"?"":parseInt(C)<20?v.i18n.atX0SecondsPastTheMinute(C):v.i18n.atX0SecondsPastTheMinuteGt20()||v.i18n.atX0SecondsPastTheMinute(C)});return k},x.prototype.getMinutesDescription=function(){var v=this,k=this.expressionParts[0],C=this.expressionParts[2],S=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(T){return T},function(T){return h.StringUtilities.format(v.i18n.everyX0Minutes(T),T)},function(T){return v.i18n.minutesX0ThroughX1PastTheHour()},function(T){try{return T=="0"&&C.indexOf("/")==-1&&k==""?v.i18n.everyHour():parseInt(T)<20?v.i18n.atX0MinutesPastTheHour(T):v.i18n.atX0MinutesPastTheHourGt20()||v.i18n.atX0MinutesPastTheHour(T)}catch{return v.i18n.atX0MinutesPastTheHour(T)}});return S},x.prototype.getHoursDescription=function(){var v=this,k=this.expressionParts[2],C=0,S=[];k.split("/")[0].split(",").forEach(function(M){var E=M.split("-");E.length===2&&S.push({value:E[1],index:C+1}),C+=E.length});var T=0,O=this.getSegmentDescription(k,this.i18n.everyHour(),function(M){var E=S.find(function(P){return P.value===M&&P.index===T}),R=E&&v.expressionParts[1]!=="0";return T++,R?v.formatTime(M,"59",""):v.formatTime(M,"0","")},function(M){return h.StringUtilities.format(v.i18n.everyX0Hours(M),M)},function(M){return v.i18n.betweenX0AndX1()},function(M){return v.i18n.atX0()});return O},x.prototype.getDayOfWeekDescription=function(){var v=this,k=this.i18n.daysOfTheWeek(),C=null;return this.expressionParts[5]=="*"?C="":C=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(S,T){var O=S;S.indexOf("#")>-1?O=S.substring(0,S.indexOf("#")):S.indexOf("L")>-1&&(O=O.replace("L",""));var M=parseInt(O),E=v.i18n.daysOfTheWeekInCase?v.i18n.daysOfTheWeekInCase(T)[M]:k[M];if(S.indexOf("#")>-1){var R=null,P=S.substring(S.indexOf("#")+1),A=S.substring(0,S.indexOf("#"));switch(P){case"1":R=v.i18n.first(A);break;case"2":R=v.i18n.second(A);break;case"3":R=v.i18n.third(A);break;case"4":R=v.i18n.fourth(A);break;case"5":R=v.i18n.fifth(A);break}E=R+" "+E}return E},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0DaysOfTheWeek(S),S)},function(S){var T=S.substring(0,S.indexOf("-")),O=v.expressionParts[3]!="*";return O?v.i18n.commaAndX0ThroughX1(T):v.i18n.commaX0ThroughX1(T)},function(S){var T=null;if(S.indexOf("#")>-1){var O=S.substring(S.indexOf("#")+1),M=S.substring(0,S.indexOf("#"));T=v.i18n.commaOnThe(O,M).trim()+v.i18n.spaceX0OfTheMonth()}else if(S.indexOf("L")>-1)T=v.i18n.commaOnTheLastX0OfTheMonth(S.replace("L",""));else{var E=v.expressionParts[3]!="*";T=E?v.i18n.commaAndOnX0():v.i18n.commaOnlyOnX0(S)}return T}),C},x.prototype.getMonthDescription=function(){var v=this,k=this.i18n.monthsOfTheYear(),C=this.getSegmentDescription(this.expressionParts[4],"",function(S,T){return T&&v.i18n.monthsOfTheYearInCase?v.i18n.monthsOfTheYearInCase(T)[parseInt(S)-1]:k[parseInt(S)-1]},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0Months(S),S)},function(S){return v.i18n.commaMonthX0ThroughMonthX1()||v.i18n.commaX0ThroughX1()},function(S){return v.i18n.commaOnlyInMonthX0?v.i18n.commaOnlyInMonthX0():v.i18n.commaOnlyInX0()});return C},x.prototype.getDayOfMonthDescription=function(){var v=this,k=null,C=this.expressionParts[3];switch(C){case"L":k=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":k=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var S=C.match(/(\d{1,2}W)|(W\d{1,2})/);if(S){var T=parseInt(S[0].replace("W","")),O=T==1?this.i18n.firstWeekday():h.StringUtilities.format(this.i18n.weekdayNearestDayX0(),T.toString());k=h.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),O);break}else{var M=C.match(/L-(\d{1,2})/);if(M){var E=M[1];k=h.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(E),E);break}else{if(C=="*"&&this.expressionParts[5]!="*")return"";k=this.getSegmentDescription(C,this.i18n.commaEveryDay(),function(R){return R=="L"?v.i18n.lastDay():v.i18n.dayX0?h.StringUtilities.format(v.i18n.dayX0(),R):R},function(R){return R=="1"?v.i18n.commaEveryDay():v.i18n.commaEveryX0Days(R)},function(R){return v.i18n.commaBetweenDayX0AndX1OfTheMonth(R)},function(R){return v.i18n.commaOnDayX0OfTheMonth(R)})}break}}return k},x.prototype.getYearDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[6],"",function(C){return/^\d+$/.test(C)?new Date(parseInt(C),1).getFullYear().toString():C},function(C){return h.StringUtilities.format(v.i18n.commaEveryX0Years(C),C)},function(C){return v.i18n.commaYearX0ThroughYearX1()||v.i18n.commaX0ThroughX1()},function(C){return v.i18n.commaOnlyInYearX0?v.i18n.commaOnlyInYearX0():v.i18n.commaOnlyInX0()});return k},x.prototype.getSegmentDescription=function(v,k,C,S,T,O){var M=null,E=v.indexOf("/")>-1,R=v.indexOf("-")>-1,P=v.indexOf(",")>-1;if(!v)M="";else if(v==="*")M=k;else if(!E&&!R&&!P)M=h.StringUtilities.format(O(v),C(v));else if(P){for(var A=v.split(","),H="",D=0;D<A.length;D++)if(D>0&&A.length>2&&(H+=",",D<A.length-1&&(H+=" ")),D>0&&A.length>1&&(D==A.length-1||A.length==2)&&(H+="".concat(this.i18n.spaceAnd()," ")),A[D].indexOf("/")>-1||A[D].indexOf("-")>-1){var L=A[D].indexOf("-")>-1&&A[D].indexOf("/")==-1,U=this.getSegmentDescription(A[D],k,C,S,L?this.i18n.commaX0ThroughX1:T,O);L&&(U=U.replace(", ","")),H+=U}else E?H+=this.getSegmentDescription(A[D],k,C,S,T,O):H+=C(A[D]);E?M=H:M=h.StringUtilities.format(O(v),H)}else if(E){var A=v.split("/");if(M=h.StringUtilities.format(S(A[1]),A[1]),A[0].indexOf("-")>-1){var $=this.generateRangeSegmentDescription(A[0],T,C);$.indexOf(", ")!=0&&(M+=", "),M+=$}else if(A[0].indexOf("*")==-1){var W=h.StringUtilities.format(O(A[0]),C(A[0]));W=W.replace(", ",""),M+=h.StringUtilities.format(this.i18n.commaStartingX0(),W)}}else R&&(M=this.generateRangeSegmentDescription(v,T,C));return M},x.prototype.generateRangeSegmentDescription=function(v,k,C){var S="",T=v.split("-"),O=C(T[0],1),M=C(T[1],2),E=k(v);return S+=h.StringUtilities.format(E,O,M),S},x.prototype.formatTime=function(v,k,C){var S=0,T=0,O=parseInt(v)+S,M=parseInt(k)+T;M>=60?(M-=60,O+=1):M<0&&(M+=60,O-=1),O>=24?O=O-24:O<0&&(O=24+O);var E="",R=!1;this.options.use24HourTimeFormat||(R=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),E=R?"".concat(this.getPeriod(O)," "):" ".concat(this.getPeriod(O)),O>12&&(O-=12),O===0&&(O=12));var P="";return C&&(P=":".concat(("00"+C).substring(C.length))),"".concat(R?E:"").concat(("00"+O.toString()).substring(O.toString().length),":").concat(("00"+M.toString()).substring(M.toString().length)).concat(P).concat(R?"":E)},x.prototype.transformVerbosity=function(v,k){if(!k&&(v=v.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),v=v.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),v=v.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),v=v.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var C=0,S=Object.entries(this.i18n.conciseVerbosityReplacements());C<S.length;C++){var T=S[C],O=T[0],M=T[1];v=v.replace(new RegExp(O,"g"),M)}return v},x.prototype.getPeriod=function(v){return v>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},x.locales={},x})();d.ExpressionDescriptor=b}),747:((a,d,u)=>{Object.defineProperty(d,"__esModule",{value:!0}),d.enLocaleLoader=void 0;var h=u(486),y=(function(){function b(){}return b.prototype.load=function(x){x.en=new h.en},b})();d.enLocaleLoader=y}),486:((a,d)=>{Object.defineProperty(d,"__esModule",{value:!0}),d.en=void 0;var u=(function(){function h(){}return h.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},h.prototype.atX0MinutesPastTheHourGt20=function(){return null},h.prototype.commaMonthX0ThroughMonthX1=function(){return null},h.prototype.commaYearX0ThroughYearX1=function(){return null},h.prototype.use24HourTimeFormatByDefault=function(){return!1},h.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},h.prototype.everyMinute=function(){return"every minute"},h.prototype.everyHour=function(){return"every hour"},h.prototype.atSpace=function(){return"At "},h.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},h.prototype.at=function(){return"At"},h.prototype.spaceAnd=function(){return" and"},h.prototype.everySecond=function(){return"every second"},h.prototype.everyX0Seconds=function(){return"every %s seconds"},h.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},h.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},h.prototype.everyX0Minutes=function(){return"every %s minutes"},h.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},h.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},h.prototype.everyX0Hours=function(){return"every %s hours"},h.prototype.betweenX0AndX1=function(){return"between %s and %s"},h.prototype.atX0=function(){return"at %s"},h.prototype.commaEveryDay=function(){return", every day"},h.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},h.prototype.commaX0ThroughX1=function(){return", %s through %s"},h.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},h.prototype.first=function(){return"first"},h.prototype.second=function(){return"second"},h.prototype.third=function(){return"third"},h.prototype.fourth=function(){return"fourth"},h.prototype.fifth=function(){return"fifth"},h.prototype.commaOnThe=function(){return", on the "},h.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},h.prototype.lastDay=function(){return"the last day"},h.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},h.prototype.commaOnlyOnX0=function(){return", only on %s"},h.prototype.commaAndOnX0=function(){return", and on %s"},h.prototype.commaEveryX0Months=function(){return", every %s months"},h.prototype.commaOnlyInX0=function(){return", only in %s"},h.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},h.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},h.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},h.prototype.firstWeekday=function(){return"first weekday"},h.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},h.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},h.prototype.commaEveryX0Days=function(){return", every %s days"},h.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},h.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},h.prototype.commaEveryHour=function(){return", every hour"},h.prototype.commaEveryX0Years=function(){return", every %s years"},h.prototype.commaStartingX0=function(){return", starting %s"},h.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},h.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},h.prototype.atReboot=function(){return"Run once, at startup"},h})();d.en=u}),515:((a,d)=>{Object.defineProperty(d,"__esModule",{value:!0});function u(y,b){if(!y)throw new Error(b)}var h=(function(){function y(){}return y.secondRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);u(k>=0&&k<=59,"seconds part must be >= 0 and <= 59")}},y.minuteRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);u(k>=0&&k<=59,"minutes part must be >= 0 and <= 59")}},y.hourRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);u(k>=0&&k<=23,"hours part must be >= 0 and <= 23")}},y.dayOfMonthRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);u(k>=1&&k<=31,"DOM part must be >= 1 and <= 31")}},y.monthRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);u(C>=1&&C<=12,x?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},y.dayOfWeekRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);u(C>=0&&C<=6,x?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},y})();d.default=h}),823:((a,d)=>{Object.defineProperty(d,"__esModule",{value:!0}),d.StringUtilities=void 0;var u=(function(){function h(){}return h.format=function(y){for(var b=[],x=1;x<arguments.length;x++)b[x-1]=arguments[x];return y.replace(/%s/g,function(v){return b.shift()})},h.containsAny=function(y,b){return b.some(function(x){return y.indexOf(x)>-1})},h})();d.StringUtilities=u})},o={};function i(a){var d=o[a];if(d!==void 0)return d.exports;var u=o[a]={exports:{}};return r[a](u,u.exports,i),u.exports}var l={};return(()=>{var a=l;Object.defineProperty(a,"__esModule",{value:!0}),a.toString=void 0;var d=i(333),u=i(747);d.ExpressionDescriptor.initialize(new u.enLocaleLoader),a.default=d.ExpressionDescriptor;var h=d.ExpressionDescriptor.toString;a.toString=h})(),l})())})($s)),$s.exports}var Mf=Of();const Ef=c.getDefaultExportFromCjs(Mf),If=new Set(["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC","SUN","MON","TUE","WED","THU","FRI","SAT"]);function Df(e){for(const n of e.trim().split(/\s+/)){if(/[#?]/.test(n))return!1;for(const r of n.split(/[,\-/]/))if(!(r===""||r==="*")&&/[A-Za-z]/.test(r)&&!If.has(r.toUpperCase()))return!1}return!0}function ho(e){const n=(e??"").trim();if(n.split(/\s+/).filter(Boolean).length!==5)return{valid:!1,description:"",nextRun:null,error:"Expected a 5-field UNIX cron: minute hour day-of-month month day-of-week."};if(!Df(n))return{valid:!1,description:"",nextRun:null,error:"Unsupported cron syntax: L, W, #, and ? extensions are not allowed (plain 5-field UNIX cron only)."};try{const r=Ef.toString(n,{use24HourTimeFormat:!0,verbose:!1}),o=Tf.CronExpressionParser.parse(n,{tz:"UTC"}).next().toDate();return{valid:!0,description:r,nextRun:o}}catch(r){return{valid:!1,description:"",nextRun:null,error:r instanceof Error?r.message:"Invalid cron expression."}}}function cl(e){return e?e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC",hour12:!1})+" UTC":"—"}function $f({onSubmit:e,isSubmitting:n,disabled:r,disabledReason:o}){const[i,l]=j.useState(!1),[a,d]=j.useState(!1),u=()=>l(!1),h=async()=>{try{await e({forceRefresh:a}),l(!1)}catch{}},y=t.jsx("span",{children:t.jsx(c.AddButton,{label:"Materialization",onClick:()=>l(!0),disabled:r})});return t.jsxs(t.Fragment,{children:[r&&o?t.jsx(p.Tooltip,{title:o,children:y}):y,t.jsx(c.AppDialog,{open:i,onClose:u,title:"New materialization",description:"Compile the package, build a table for every persist source, and load them so queries serve from the tables.",actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{onClick:u,children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:n,onClick:h,children:"Materialize"})]}),children:t.jsx(p.FormGroup,{children:t.jsx(p.FormControlLabel,{control:t.jsx(p.Switch,{checked:a,onChange:b=>d(b.target.checked)}),label:"Force refresh (rebuild even if unchanged)"})})})]})}function Kr({children:e}){return t.jsx(p.Typography,{variant:"caption",component:"h6",sx:{display:"block",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600,color:"text.secondary",mb:1},children:e})}function es(e){return e===q.MaterializationStatus.Pending||e===q.MaterializationStatus.ManifestRowsReady}function Af(e){return e===q.MaterializationStatus.ManifestFileReady||e===q.MaterializationStatus.Failed||e===q.MaterializationStatus.Cancelled}function Ff(e){switch(e){case q.MaterializationStatus.ManifestFileReady:return"Done";case q.MaterializationStatus.Failed:return"Failed";case q.MaterializationStatus.Cancelled:return"Cancelled";case q.MaterializationStatus.Pending:case q.MaterializationStatus.ManifestRowsReady:return"Pending";default:return"Unknown"}}function Rf(e){switch(e){case q.MaterializationStatus.ManifestRowsReady:return"info";case q.MaterializationStatus.ManifestFileReady:return"success";case q.MaterializationStatus.Failed:return"error";case q.MaterializationStatus.Cancelled:return"warning";case q.MaterializationStatus.Pending:default:return"default"}}function ul(e){return e.status===q.MaterializationStatus.ManifestFileReady&&as(e).autoLoad==="failed"}function dl(e){return ul(e)?"Built, not served":Ff(e.status)}function Xs(e){return ul(e)?"warning":Rf(e.status)}function Nf(e){const n=Object.values(as(e).refusedSources??{}).map(o=>({name:o.name,message:o.message})),r=Object.values(e.manifest?.failures??{}).filter(o=>o.refused).map(o=>({name:o.sourceName??o.sourceEntityId,message:o.reason}));return[...n,...r].sort((o,i)=>o.name.localeCompare(i.name))}function hl(e,n){const r=[`${e.sourcesBuilt??0} built`,`${e.sourcesReused??0} reused`];return e.sourcesRefused&&r.push(`${e.sourcesRefused} refused`),r.join(n)}function as(e){return e.metadata??{}}function fl(e){return e.trigger==="scheduler"||e.trigger==="SCHEDULER"}function Lf(e){return fl(e)?"Scheduled":"Manual"}function ml(e,n){if(!e)return"-";const r=new Date(e).getTime(),o=n?new Date(n).getTime():Date.now(),i=Math.max(0,o-r);if(i<1e3)return`${i}ms`;const l=Math.round(i/1e3);if(l<60)return`${l}s`;const a=Math.floor(l/60),d=l%60;if(a<60)return`${a}m ${d}s`;const u=Math.floor(a/60),h=a%60;return`${u}h ${h}m`}function Js(e){if(!e)return"—";const n=new Date(e);return Number.isNaN(n.getTime())?"—":n.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function _f(e){if(!e)return"-";const n=new Date(e).getTime(),r=Math.round((Date.now()-n)/1e3);if(r<60)return"just now";const o=Math.floor(r/60);if(o<60)return`${o}m ago`;const i=Math.floor(o/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Pf({entries:e,builtAt:n}){const r=Object.entries(e??{});return t.jsxs(p.Box,{children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",justifyContent:"space-between",children:[t.jsx(Kr,{children:"Build manifest"}),n&&t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",children:["Built ",Js(n)]})]}),r.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"No materialized tables yet."}):t.jsxs(p.Table,{size:"small",children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Source"}),t.jsx(p.TableCell,{children:"Table name"}),t.jsx(p.TableCell,{children:"Connection"}),t.jsx(p.TableCell,{children:"Realization"}),t.jsx(p.TableCell,{align:"right",children:"Rows"})]})}),t.jsx(p.TableBody,{children:r.map(([o,i])=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.sourceName??o}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.physicalTableName??"-"}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.connectionName??"-"}),t.jsx(p.TableCell,{children:i.realization??"-"}),t.jsx(p.TableCell,{align:"right",children:i.rowCount??"-"})]},o))})]})]})}function pl({meta:e}){const n=fl(e);return t.jsx(p.Tooltip,{title:n?"Fired by the materialization schedule":"Triggered manually",children:t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:Lf(e)})})}function zf({materialization:e,buildPlan:n,onClose:r}){const o=e?as(e):{},i=e?Nf(e):[],l=n.status==="ready"?Object.values(n.plan?.sources??{}):[];return t.jsx(p.Dialog,{open:e!==null,onClose:r,maxWidth:"md",fullWidth:!0,"aria-labelledby":"materialization-detail-title",children:e&&t.jsxs(t.Fragment,{children:[t.jsxs(p.DialogTitle,{sx:{pr:6,pb:1.5},id:"materialization-detail-title",children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{mb:.75},children:[t.jsx(p.Chip,{size:"small",label:dl(e),color:Xs(e),variant:es(e.status)?"filled":"outlined"}),t.jsx(pl,{meta:o})]}),t.jsx(p.Typography,{variant:"subtitle1",sx:{fontWeight:600},children:e.packageName??"Materialization"}),t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY,wordBreak:"break-all"},children:e.id}),t.jsx(p.IconButton,{"aria-label":"close",onClick:r,sx:{position:"absolute",right:8,top:8},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]}),t.jsxs(p.DialogContent,{dividers:!0,children:[t.jsxs(p.Box,{sx:{bgcolor:"action.hover",borderRadius:2,p:2,mb:3,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:2},children:[t.jsx(cr,{label:"Started",value:Js(e.startedAt??e.createdAt)}),t.jsx(cr,{label:"Completed",value:Js(e.completedAt)}),t.jsx(cr,{label:"Duration",value:ml(e.startedAt,e.completedAt)}),t.jsx(cr,{label:"Sources",value:hl(o," · ")}),t.jsx(cr,{label:"Force refresh",value:o.forceRefresh?"Yes":"No"})]}),e.error&&t.jsxs(p.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"error.main"},children:[t.jsx(Kr,{children:t.jsx(p.Box,{component:"span",sx:{color:"error.main"},children:"Error"})}),t.jsx(p.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY,whiteSpace:"pre-wrap"},children:e.error})]}),i.length>0&&t.jsxs(p.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"warning.main"},children:[t.jsx(Kr,{children:t.jsx(p.Box,{component:"span",sx:{color:"warning.main"},children:"Refused sources"})}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1},children:"Not built, because materializing them would be unsafe. They serve live until the model changes."}),i.map(a=>t.jsxs(p.Box,{sx:{mt:1},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{whiteSpace:"pre-wrap"},children:a.message})]},a.name))]}),t.jsxs(p.Box,{sx:{mb:3},children:[t.jsx(Kr,{children:"Build plan"}),n.status==="loading"?t.jsx(c.Loading,{text:c.LOADING_COPY.loading,size:16,centered:!1}):n.status==="unavailable"?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"The build plan is unavailable."}):l.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"This package has no persist sources."}):t.jsxs(p.Table,{size:"small",children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Source"}),t.jsx(p.TableCell,{children:"Connection"}),t.jsx(p.TableCell,{children:"Dialect"}),t.jsx(p.TableCell,{align:"right",children:"Columns"}),t.jsx(p.TableCell,{children:"Source Entity ID"})]})}),t.jsx(p.TableBody,{children:l.map(a=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.connectionName}),t.jsx(p.TableCell,{children:a.dialect??"-"}),t.jsx(p.TableCell,{align:"right",children:a.columns?.length??0}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.75rem",wordBreak:"break-all",maxWidth:220},children:a.sourceEntityId})]},a.sourceID))})]})]}),t.jsx(Pf,{entries:e.manifest?.entries,builtAt:e.manifest?.builtAt})]})]})})}function cr({label:e,value:n}){return t.jsxs(p.Box,{children:[t.jsx(p.Typography,{variant:"caption",color:"text.secondary",display:"block",children:e}),t.jsx(p.Typography,{variant:"body2",children:n})]})}const Wf=c.createSvgIcon(t.jsx("path",{d:"M6 6h12v12H6z"}));function qf({materialization:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=j.useState(!1),a=()=>l(!0),d=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Delete materialization ${e?.id??""}`.trim(),onClick:u=>{u.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(ao,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(lo,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:d,title:"Delete materialization",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:d,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete run"})]}),children:t.jsx(c.Typography,{variant:"body2",children:"Delete this run's record? This cannot be undone. The tables it built stay in place: drop any you no longer need through their connection."})})]})}function Bf({materializations:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){return e.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{py:1,fontStyle:"italic"},children:"No materializations yet."}):t.jsxs(p.Table,{size:"small",sx:{"& td, & th":{borderColor:"divider"},"& td:first-of-type, & th:first-of-type":{pl:0},"& td:last-of-type, & th:last-of-type":{pr:0},"& th":{color:"text.secondary",fontWeight:600}},children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Status"}),t.jsx(p.TableCell,{children:"Trigger"}),t.jsx(p.TableCell,{children:"Started"}),t.jsx(p.TableCell,{children:"Duration"}),t.jsx(p.TableCell,{children:"Sources"}),t.jsx(p.TableCell,{align:"right",children:"Actions"})]})}),t.jsx(p.TableBody,{children:e.map(a=>t.jsx(Vf,{materialization:a,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l},a.id))})]})}function Vf({materialization:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){const[a,d]=j.useState(null),u=!!a,h=()=>d(null),y=as(e),b=y.sourcesBuilt!==void 0||y.sourcesReused!==void 0?hl(y,", "):"-",x=es(e.status),v=Af(e.status),k=e.error??void 0,C=n&&(x||v);return t.jsxs(p.TableRow,{hover:!0,sx:{cursor:"pointer","&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},onClick:()=>l(e),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l(e))},role:"button",tabIndex:0,"aria-label":`View materialization ${e.id??""} details`.trim(),children:[t.jsx(p.TableCell,{children:t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:.5},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontWeight:500,color:Xs(e)==="default"?"text.primary":`${Xs(e)}.main`},children:dl(e)}),k&&t.jsx(p.Tooltip,{title:k,children:t.jsx(c.InfoOutlinedIcon,{fontSize:"small",color:"error"})})]})}),t.jsx(p.TableCell,{children:t.jsx(pl,{meta:y})}),t.jsx(p.TableCell,{children:_f(e.startedAt??e.createdAt)}),t.jsx(p.TableCell,{children:ml(e.startedAt,e.completedAt)}),t.jsx(p.TableCell,{children:b}),t.jsx(p.TableCell,{align:"right",onClick:S=>S.stopPropagation(),children:C&&t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small","aria-label":`Materialization actions for ${e.id??""}`.trim(),onClick:S=>d(S.currentTarget),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:a,open:u,onClose:h,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n&&x&&t.jsxs(p.MenuItem,{"aria-label":`Stop materialization ${e.id??""}`.trim(),disabled:r,onClick:()=>{h(),o(e)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(Wf,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Stop"})]}),n&&v&&t.jsx(qf,{materialization:e,isMutating:r,onCloseDialog:h,onDelete:()=>i(e)})]})]})})]})}const Hf=c.createSvgIcon(t.jsx("path",{d:"m11.99 18.54-7.37-5.73L3 14.07l9 7 9-7-1.63-1.27zM12 16l7.36-5.73L21 9l-9-7-9 7 1.63 1.27zm0-11.47L17.74 9 12 13.47 6.26 9z"})),Uf={package:"Materialized artifacts are shared across versions",version:"Materialized artifacts are per published version"};function Gf({scope:e,disabled:n,disabledReason:r,isSubmitting:o,onChange:i}){const[l,a]=j.useState(null),d=async u=>{a(null),u!==e&&await i(u).catch(()=>{})};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Scope",icon:t.jsx(Hf,{}),onClick:u=>a(u.currentTarget),disabled:n||o,...r?{disabledReason:r}:{},ariaHasPopup:"menu",ariaLabel:`Scope: ${e}`}),t.jsx(p.Menu,{anchorEl:l,open:!!l,onClose:()=>a(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:["package","version"].map(u=>t.jsxs(p.MenuItem,{selected:u===e,onClick:()=>void d(u),children:[t.jsx(p.ListItemIcon,{sx:{minWidth:32},children:u===e&&t.jsx(c.CheckIcon,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:u,secondary:Uf[u]})]},u))})]})}const Yf=c.createSvgIcon([t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),t.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")]),ua="0 6 * * *";function Kf({currentSchedule:e,isSubmitting:n,disabled:r,disabledReason:o,onSubmit:i}){const[l,a]=j.useState(!1),[d,u]=j.useState(e??ua),h=()=>{u(e??ua),a(!0)},y=()=>a(!1),b=ho(d),x=async v=>{try{await i(v),a(!1)}catch{}};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Schedule",icon:t.jsx(Yf,{}),onClick:h,disabled:r,...o?{disabledReason:o}:{},ariaHasPopup:"dialog",ariaLabel:e?"Edit schedule":"Set schedule"}),t.jsxs(c.AppDialog,{open:l,onClose:y,title:e?"Edit schedule":"Set schedule",description:"The publisher rebuilds this package's materializations on this cadence: a 5-field UNIX cron, in UTC. In a hosted deployment the change takes effect on your next publish.",actions:t.jsxs(t.Fragment,{children:[e&&t.jsx(p.Button,{color:"error",loading:n,onClick:()=>x(null),sx:{mr:"auto"},children:"Clear schedule"}),t.jsx(p.Button,{onClick:y,children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:n,disabled:!b.valid,onClick:()=>x(d.trim()),children:"Save schedule"})]}),children:[t.jsx(p.TextField,{autoFocus:!0,fullWidth:!0,size:"small",label:"Cron expression",value:d,onChange:v=>u(v.target.value),error:d.trim()!==""&&!b.valid,helperText:b.valid?`${b.description} · next run ${cl(b.nextRun)}`:b.error,slotProps:{htmlInput:{style:{fontFamily:q.MONO_FONT_FAMILY}}}}),t.jsxs(p.Alert,{severity:"info",children:["A schedule runs only on version-scoped packages, so saving one sets ",t.jsx("code",{children:"scope: version"})," for this package."]})]})]})}const Qf=3e3;function gl({resourceUri:e,versioned:n=!1}){const{apiClients:r,mutable:o}=q.useServer(),i=yt.useQueryClient(),{environmentName:l,packageName:a,versionId:d}=c.parseResourceUri(e),[u,h]=j.useState(""),[y,b]=j.useState(null);if(!a)throw new Error("Materializations requires a package in the resource URI");const x=c.useQueryWithApiError({queryKey:["materializations",l,a,d],queryFn:()=>r.materializations.listMaterializations(l,a,void 0,void 0,d),refetchInterval:G=>(G.state.data?.data??[]).some(z=>es(z.status))?Qf:!1}),v=c.useQueryWithApiError({queryKey:["package",l,a,d],queryFn:()=>r.packages.getPackage(l,a,d)}),k=c.useQueryWithApiError({queryKey:["package-build-plan",l,a,d],queryFn:async({signal:G})=>{try{return{inline:!1,plan:(await r.packages.getPackageBuildPlan(l,a,d,{signal:G})).data}}catch(Z){if(Z?.response?.status===404)return{inline:!0,plan:null};throw Z}},enabled:y!==null}),C=()=>i.invalidateQueries({queryKey:["materializations",l,a]}),S=c.useMutationWithApiError({mutationFn:Ht("materialization","create",G=>r.materializations.createMaterialization(l,a,{forceRefresh:G.forceRefresh,...d!==void 0?{versionId:d}:{}})),onSuccess(){h("Materialization requested"),C()},onError(G){h(G.message),C()}}),T=c.useMutationWithApiError({mutationFn:Ht("materialization","update",G=>r.materializations.materializationAction(l,a,G.id,q.MaterializationActionActionEnum.Stop,d)),onSuccess(){h("Materialization stopped"),C()},onError(G){h(G.message)}}),O=c.useMutationWithApiError({mutationFn:Ht("materialization","delete",G=>r.materializations.deleteMaterialization(l,a,G.id,d)),onSuccess(){h("Materialization deleted"),C()},onError(G){h(G.message)}}),M=v.data?.data,E=c.useMutationWithApiError({mutationFn:Ht("schedule","update",G=>r.packages.updatePackage(l,a,{name:a,description:M?.description,...G?{scope:q.PackageScopeEnum.Version}:{},materialization:{schedule:G}})),onSuccess(G,Z){h(Z?"Schedule updated":"Schedule cleared"),i.invalidateQueries({queryKey:["package",l,a]})},onError(G){h(G.message)}}),R=c.useMutationWithApiError({mutationFn:Ht("scope","update",G=>r.packages.updatePackage(l,a,{name:a,description:M?.description,scope:G})),onSuccess(){h("Scope updated"),i.invalidateQueries({queryKey:["package",l,a]})},onError(G){h(G.message)}}),P=x.data?.data??[],A=P.find(G=>G.id===y)??null,H=P.some(G=>es(G.status)),D=S.isPending||T.isPending||O.isPending,L=k.isError?{status:"unavailable"}:k.isSuccess?k.data.inline?v.isSuccess?{status:"ready",plan:M?.buildPlan??null}:v.isError?{status:"unavailable"}:{status:"loading"}:{status:"ready",plan:k.data.plan}:{status:"loading"},U=M?.materialization?.schedule??null,$=M?.scope===q.PackageScopeEnum.Version?"version":"package",W=!!M?.manifestLocation,Q=!!M?.materialization?.freshness,te=U?ho(U):null,ee=W?"Control-plane managed: refresh is driven by the control plane, not the built-in scheduler.":[te?te.valid?`${te.description} (${U}), next run ${cl(te.nextRun)}`:`Unrecognized cron expression (${U})`:Q?"Refreshed by a freshness policy; a cron schedule does not apply":"On demand only, no schedule set",`scope: ${$}`].join(" · ");return t.jsxs(t.Fragment,{children:[t.jsxs(_t,{title:"Materializations",count:x.isSuccess?P.length:void 0,action:o&&t.jsxs(p.Stack,{direction:"row",spacing:1,alignItems:"center",children:[!W&&!n&&t.jsx(Gf,{scope:$,disabled:!!U,disabledReason:"A schedule requires version scope. Clear the schedule to change it.",isSubmitting:R.isPending,onChange:G=>R.mutateAsync(G==="version"?q.PackageScopeEnum.Version:q.PackageScopeEnum.Package)}),!W&&!n&&t.jsx(Kf,{currentSchedule:U,isSubmitting:E.isPending,disabled:Q,disabledReason:"This package declares a freshness policy; a schedule and freshness are mutually exclusive.",onSubmit:G=>E.mutateAsync(G)}),t.jsx($f,{onSubmit:G=>S.mutateAsync(G),isSubmitting:S.isPending,disabled:H,disabledReason:"A materialization is already pending or running for this package."})]}),children:[v.isSuccess&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:ee}),x.isError&&t.jsx(c.ApiErrorDisplay,{error:x.error,context:`${l} > ${a} > Materializations`}),!x.isSuccess&&!x.isError&&t.jsx(c.Loading,{text:"Loading materializations..."}),x.isSuccess&&t.jsx(Bf,{materializations:P,mutable:o,isMutating:D,onStop:G=>T.mutate(G),onDelete:G=>O.mutate(G),onViewDetails:G=>b(G.id??null)})]}),t.jsx(zf,{materialization:A,buildPlan:L,onClose:()=>b(null)}),t.jsx(p.Snackbar,{open:u!=="",autoHideDuration:6e3,onClose:()=>h(""),message:u})]})}const fo=c.createSvgIcon(t.jsx("path",{d:"M17 7h-4v2h4c1.65 0 3 1.35 3 3s-1.35 3-3 3h-4v2h4c2.76 0 5-2.24 5-5s-2.24-5-5-5m-6 8H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4zm-3-4h8v2H8z"}));function Nn(e){return yl(e).join(`
8
- `).trim()||void 0}function yl(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(o){if(o.startsWith('#"'))n.push(o.slice(2).trim());else if(o.startsWith("#(doc)")){let i=o.slice(6).trim();i.length>=2&&i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),n.push(i)}}}return n.filter(r=>r.trim()!=="")}function da(e){const n=(e??[]).map(r=>({...r,value:r.value?.trim()??""})).filter(r=>r.value.startsWith('##"')||r.value.startsWith("##(doc)")).map(r=>({...r,value:r.value.slice(1)}));return Nn(n)}function Zf(e,n){const r=e.docParts??[],o=n?.docParts??[];return(o.length>0&&o.length<r.length&&o.every((a,d)=>a===r[d])?r.slice(o.length):r).join(`
9
- `).trim()||void 0}function mo(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||o.startsWith('#"')||o.startsWith("#(doc)"))continue;const i=o.replace(/^#+@?\s*/,"").trim();i&&!i.startsWith("(")&&n.push(i)}return n}function Xf(e){const n=new Set;for(const r of e){const{tag:o,log:i}=Ju.parseAnnotation([`# ${r}`]);if(i.length>0){const l=/^[A-Za-z_][\w.]*/.exec(r.trim())?.[0];l&&!/^\s*[\w.]+\s*=/.test(r)&&n.add(l);continue}for(const[l,a]of o.entries())a.deleted||(a.eq===void 0?n.add(l):l==="viz"&&typeof a.eq=="string"&&n.add(a.eq))}return[...n]}function Jf(e){return xl(e,"persist")}function em(e){return xl(e,"preaggregate")}function xl(e,n){const r=new RegExp(`^#@?\\s*${n}\\b`);return(e??[]).some(o=>r.test(o.value?.trim()??""))}function po(e){const n=rm(e);if(!e||!n)return n;switch(e.kind){case"number_type":return e.subtype?`${n} · ${e.subtype}`:n;case"date_type":case"timestamp_type":case"timestamptz_type":return e.timeframe?`${n} · ${e.timeframe}`:n;case"sql_native_type":return e.sql_type?`sql native · ${e.sql_type}`:"sql native";case"array_type":return`array<${po(e.element_type)??"unknown"}>`;case"record_type":{const r=e.fields.length;return`record · ${r} ${r===1?"field":"fields"}`}default:return n}}function tm(e){if(e?.kind==="record_type")return e.fields.map(n=>`${n.name} ${po(n.type)??""}`.trim()).join(`
10
- `)}function nm(e){const n=(e??[]).filter(r=>/^#@/.test(r.value?.trim()??""));return mo((e??[]).filter(r=>!n.includes(r)))}function rm(e){return e?.kind?.replace(/_type$/,"")}const un=j.forwardRef(function(n,r){return t.jsx(p.Typography,{ref:r,variant:"body2",...n,sx:{color:"text.secondary",...n.sx}})}),Cr=j.forwardRef(function(n,r){return t.jsx(p.Typography,{ref:r,variant:"caption",...n,sx:{color:"text.secondary",...n.sx}})});function xr({message:e,secondary:n,actions:r}){return t.jsxs(p.Box,{"data-testid":"empty-row",sx:{display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",p:2,border:"1px dashed",borderColor:"divider",borderRadius:2},children:[t.jsxs(p.Box,{sx:{flex:1,minWidth:200},children:[t.jsx(un,{children:e}),n&&t.jsx(un,{sx:{color:"text.secondary",mt:.5},children:n})]}),r&&t.jsx(p.Box,{sx:{display:"flex",gap:1,flexShrink:0,alignItems:"center"},children:r})]})}const vl="--model-viewer-mono",Dt=`var(${vl}, ${q.MONO_FONT_FAMILY})`,bl="inherit",St={micro:"0.6875rem",caption:"0.75rem",small:"0.8125rem",body:"0.875rem",bodyLarge:"1rem"},eo={strong:500},Vr=e=>({tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),rt={text:{secondary:"text.secondary",tertiary:"text.disabled"},background:{muted:"action.hover",strong:"action.selected"},accent:{sage:Vr(q.PALETTE.lime)},warning:Vr(q.PALETTE.amber),error:Vr(q.PALETTE.red),info:Vr(q.PALETTE.blue)},ls=rt.text.tertiary,sm={positive:{bg:rt.accent.sage.tint,fg:rt.accent.sage.onTint},neutral:{bg:rt.background.strong,fg:rt.text.secondary},warning:{bg:rt.warning.tint,fg:rt.warning.onTint},negative:{bg:rt.error.tint,fg:rt.error.onTint},info:{bg:rt.info.tint,fg:rt.info.onTint},quiet:{bg:rt.background.muted,fg:rt.text.secondary}},$t=j.forwardRef(function({tone:n="neutral",voice:r="state",size:o="inline",busy:i=!1,children:l,sx:a,...d},u){const{bg:h,fg:y}=sm[n],b=St.micro;return t.jsxs(Ye,{ref:u,component:"span","data-pill-tone":n,"data-pill-placement":o,...d,sx:[{display:"inline-flex",alignItems:"center",gap:i?"4px":0,padding:"2px 8px",borderRadius:"999px",bgcolor:h,color:y,flexShrink:0,whiteSpace:"nowrap",...r==="token"?{fontFamily:Dt,fontSize:b}:{fontFamily:bl,fontSize:b,fontWeight:eo.strong}},...Array.isArray(a)?a:[a]],children:[i&&t.jsx(c.CircularProgress,{size:9,thickness:5,sx:{color:"info.main",flexShrink:0},"aria-hidden":!0}),l]})}),om={width:"100%",maxWidth:"1200px",mx:"auto"},to=3,jr=1.5,Pn={display:"flex",flexDirection:"column",minWidth:0,minHeight:0,border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",cursor:"default"},im={...Pn,border:"none",borderRadius:0,bgcolor:"transparent",overflow:"visible"};function Ut({label:e,value:n,mono:r}){return t.jsxs(t.Fragment,{children:[t.jsx(p.Box,{component:"span",sx:{color:ls,fontSize:St.caption},children:e}),t.jsx(p.Box,{component:"span",sx:{fontFamily:r?Dt:void 0,wordBreak:"break-all"},children:n})]})}function am(e){const n=e.map(r=>r.name).join(", ");return`Reads the ${e.length===1?"given":"givens"} ${n}, set in the Givens section above`}function wl({givens:e}){return e.length===0?null:t.jsx(p.Tooltip,{title:am(e),children:t.jsx($t,{voice:"token",tone:"quiet",sx:{alignSelf:"center",flexShrink:0},children:"given"})})}function lm(e){const n=c.renderGivenDefault(e.type,e.default);return n===void 0?"none — a value is required":n===""?"(empty)":n}function go({givens:e,framed:n=!0}){return e.length===0?null:t.jsx(p.Box,{"data-testid":"model-viewer-given-card",sx:{...n?Pn:{},p:jr,display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline",fontFamily:bl,fontSize:St.small,color:"text.primary"},children:e.map(r=>t.jsxs(p.Box,{sx:{display:"contents"},children:[t.jsx(Ut,{label:"Given",value:r.name,mono:!0}),r.label&&t.jsx(Ut,{label:"Label",value:r.label}),t.jsx(Ut,{label:"Type",value:r.type,mono:!0}),t.jsx(Ut,{label:"Default",value:lm(r)}),r.description&&t.jsx(Ut,{label:"Description",value:r.description})]},r.name))})}const Sl=j.createContext({});function cs(){return j.useContext(Sl)}function cm(e,n,r=new Set){const o=n?.givens;if(!Array.isArray(o))return[];const i=[];for(const l of o){if(!l||typeof l!="object")continue;const a=l;if(typeof a.name!="string"||!a.name||typeof a.type!="string"||!a.type||r.has(a.name))continue;const d=Array.isArray(a.annotations)?a.annotations.filter(u=>typeof u=="string"):void 0;i.push({name:a.name,type:a.type,modelFile:e,...d&&{annotations:d},...typeof a.default=="string"&&{default:a.default},...a.required===!0&&{required:!0},...typeof a.label=="string"&&a.label&&{label:a.label},...typeof a.description=="string"&&a.description&&{description:a.description},...(a.control==="select"||a.control==="multiselect")&&{control:a.control},...typeof a.rangeMin=="number"&&{rangeMin:a.rangeMin},...typeof a.rangeMax=="number"&&{rangeMax:a.rangeMax},...a.suggest&&typeof a.suggest=="object"&&{suggest:a.suggest}})}return i}function um(e){return new Map(e.map(n=>[n.name,n.type]))}function dm(e,n){const r=new Map(Array.from(e).filter(([l,a])=>n.has(l)&&!(a===""&&n.get(l)==="string"))),o=c.givensToRequest(r,n),i=Object.entries(o).sort(([l],[a])=>l<a?-1:l>a?1:0);return i.length>0?Object.fromEntries(i):void 0}function yo(e){return e&&Object.keys(e).length>0?JSON.stringify(e):""}function hm(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||!o.startsWith("#(filter)"))continue;const i=mm(o.slice(9).trim());i&&n.push(i)}return n}const fm=new Set(["equal","in","like","greater_than","less_than"]);function mm(e){let n,r,o,i=!1,l=!1;for(const a of pm(e)){if(a==="implicit"){i=!0;continue}if(a==="required"){l=!0;continue}const d=a.indexOf("=");if(d<=0)continue;const u=a.slice(0,d).trim();let h=a.slice(d+1).trim();h.length>=2&&h.startsWith('"')&&h.endsWith('"')&&(h=h.slice(1,-1)),u==="name"?n=h:u==="dimension"?r=h:u==="type"&&fm.has(h)&&(o=h)}return!r||!o?null:{name:n??r,dimension:r,type:o,implicit:i,required:l}}function pm(e){const n=[];let r="",o=!1;for(const i of e){if(i==='"'){o=!o,r+=i;continue}if(!o&&/\s/.test(i)){r&&n.push(r),r="";continue}r+=i}return r&&n.push(r),n}const gm=/^#\(index(_values)?\b/;function ym(e){return!("annotations"in e)||!e.annotations?!1:e.annotations.some(n=>gm.test(n.value?.trim()??""))}function xm(e){const n=new Map;for(const r of e){const o=hm(r.annotations).filter(i=>i.required&&!i.implicit).map(i=>i.name);o.length>0&&n.set(r.name,o)}return n}function vm(e){return new Set(e.map(n=>n.name))}function kl(e){const n=new Map;for(const r of e){if(!r.source)continue;let o=n.get(r.source);o||(o=new Map,n.set(r.source,o)),o.set(r.name,r)}return n}function Ir(e){let n="",r=0;const o=(i,l)=>{n+=e.slice(i,l).replace(/[^\n]/g," "),r=l};for(;r<e.length;){const i=e[r],l=e.slice(r,r+2);if(l==="//"||l==="--"){const a=e.indexOf(`
11
- `,r);o(r,a===-1?e.length:a)}else if(l==="/*"){const a=e.indexOf("*/",r+2);o(r,a===-1?e.length:a+2)}else if(e.startsWith('"""',r)){const a=e.indexOf('"""',r+3),d=a===-1?e.length:a;n+='"""',r+=3,o(r,d),a!==-1&&(n+='"""',r+=3)}else if(i==="'"||i==='"'){n+=i;let a=r+1;for(;a<e.length&&e[a]!==i&&e[a]!==`
6
+ `)};function Bi(){const[e,n]=j.useState(!1),{apiClients:r}=q.useServer(),o=()=>{n(!0)},i=()=>{n(!1)},l=Nn({mutationFn(u){return r.environments.createEnvironment({name:u.name,readme:ol({name:u.name,readme:""},u.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:i,resource:"environment",action:"create"}),a=async u=>{u.preventDefault();const d=new FormData(u.currentTarget),h=d.get("name")?.toString(),y=d.get("description")?.toString();if(!h)throw new Error("Name is required");l.mutate({name:h,description:y})};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Environment",onClick:o}),t.jsx(c.AppDialog,{open:e,onClose:i,title:"New environment",description:"An environment holds packages and the connections they query through.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:l.isPending,onClick:i,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:l.isPending,children:"Create environment"})]}),children:t.jsx("form",{onSubmit:a,id:"environment-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",placeholder:"Explore semantic models, run queries, and build reports",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),l.notice]})}function of({environment:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},u=Nn({mutationFn:()=>i.environments.deleteEnvironment(e.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete environment",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>u.mutate(),loading:u.isPending,children:"Delete environment"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Its packages stop being served and this cannot be undone."]})}),u.notice]})}function af({environment:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},u=Nn({mutationFn(h){return i.environments.updateEnvironment(e.name,{name:e.name,readme:ol({name:e.name,readme:e.readme},h.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"update"}),d=h=>{h.preventDefault();const b=new FormData(h.currentTarget).get("description")?.toString();u.mutate({description:b})};return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:u.isPending,onClick:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:u.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:d,id:"environment-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:sl(e.readme),InputLabelProps:{shrink:!0}})]})})}),u.notice]})}const lf=[{title:"Model",body:"An agent writes what the data means in Malloy — sources, joins, measures — from a warehouse or a file, and validates each edit without a restart.",href:Vt.publishing},{title:"Analyze",body:"Claude, Cursor, Codex or an agent you build asks over MCP; applications and BI tools use REST. Every question runs against the model, never the raw tables.",href:Vt.mcpAgents},{title:"Surface",body:"Reports declared in Malloy, laid out as a grid or read top to bottom, and no-build HTML data apps, all shipped inside the package, plus this Console for browsing them.",href:Vt.surfaces},{title:"Govern",body:"Runtime parameters, row-level filters and per-source gates are declared in the model, so every surface reads the same rules rather than writing its own.",href:Vt.givens},{title:"Optimize",body:"One annotation materializes an expensive source into a table, and another rolls a measure up to a coarser grain, rebuilt on demand or on a schedule.",href:Vt.materialization},{title:"Run anywhere",body:"DuckDB is built in for CSV, Parquet, JSON and Excel; BigQuery, Snowflake, Postgres, Databricks, MotherDuck and more connect by configuration.",href:Vt.connections}];function cf({href:e,children:n}){return t.jsx(p.Box,{component:"a",href:e,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:n})}function uf({onClickEnvironment:e}){const{apiClients:n,mutable:r}=q.useServer(),{data:o,isSuccess:i,isError:l,error:a}=c.useQueryWithApiError({queryKey:["environments"],queryFn:()=>n.environments.listEnvironments()});if(l)return t.jsx(c.ApiErrorDisplay,{error:a,context:"Environments List"});if(!i)return t.jsx(c.Loading,{text:"Loading environments..."});const u=o.data??[];return t.jsxs(p.Container,{maxWidth:"md",sx:{py:6},children:[t.jsxs(p.Box,{sx:{mb:5},children:[t.jsx(p.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),t.jsx(p.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6},children:"One data model, served over MCP and REST to AI agents, applications and BI tools. Write down what your data means — the sources, the joins, the measures, who may see what — and every surface asks the same model, so the same question returns the same numbers tomorrow."})]}),t.jsx(p.Grid,{container:!0,spacing:4,sx:{mb:5},children:lf.map(d=>t.jsx(p.Grid,{size:{xs:12,sm:6},children:t.jsxs(p.Stack,{spacing:1,children:[t.jsx(p.Typography,{variant:"body2",component:"a",href:d.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:d.title}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:d.body})]})},d.title))}),t.jsx(p.Divider,{sx:{my:4}}),u.length>0?t.jsx(Nt,{title:"Environments",count:u.length,description:"Published environments available on this server",...r?{action:t.jsx(Bi,{})}:{},children:t.jsx(p.Stack,{children:u.map(d=>t.jsx(df,{environment:d,...e?{onClickEnvironment:e}:{}},d.name))})}):t.jsxs(p.Box,{sx:{mb:4},children:[t.jsx(p.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:3,maxWidth:600},children:"Create your first Malloy environment to start exploring semantic models and building data experiences."}),r?t.jsx(Bi,{}):t.jsx(p.Button,{variant:"contained",color:"primary",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),t.jsx(p.Divider,{sx:{my:4}}),t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",t.jsx(cf,{href:"https://join.slack.com/t/malloy-community/shared_invite/zt-1kgfwgi5g-CrsdaRqs81QY67QW0~t_uw",children:"Malloy Slack community"})," ","to ask questions, share ideas, and contribute."]})]})}function df({environment:e,onClickEnvironment:n}){const{mutable:r}=q.useServer(),[o,i]=j.useState(null),l=!!o,a=sl(e.readme),u=h=>{h.stopPropagation(),i(h.currentTarget)},d=()=>i(null);return t.jsx(rs,{icon:t.jsx(sf,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.environment,label:e.name??"",ariaLabel:e.name??"",...a?{description:a}:{},...e.name&&n?{onClick:h=>n(`/${e.name}/`,h)}:{},...r?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:u,"aria-label":`Environment actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:o,open:l,onClose:d,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(af,{environment:e,onCloseDialog:d}),t.jsx(of,{environment:e,onCloseDialog:d})]})]})}:{}})}var an={},jt={},tr={},ln={},Ms={},Vi;function hf(){return Vi||(Vi=1,Object.defineProperty(Ms,"__esModule",{value:!0})),Ms}var nr={},rr={},Hi;function mn(){if(Hi)return rr;Hi=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.CronField=void 0;let e=class il{#e=!1;#n=!1;#o=!1;#s=[];options={rawValue:""};static get min(){throw new Error("min must be overridden")}static get max(){throw new Error("max must be overridden")}static get chars(){return Object.freeze([])}static get validChars(){return/^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}static get constraints(){return{min:this.min,max:this.max,chars:this.chars,validChars:this.validChars}}constructor(r,o={rawValue:""}){if(!Array.isArray(r))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(r.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...o,rawValue:o.rawValue??""},this.#s=r.sort(il.sorter),this.#o=this.options.wildcard!==void 0?this.options.wildcard:this.#r(),this.#e=this.options.rawValue.includes("L")||r.includes("L"),this.#n=this.options.rawValue.includes("?")||r.includes("?")}get min(){return this.constructor.min}get max(){return this.constructor.max}get chars(){return this.constructor.chars}get hasLastChar(){return this.#e}get hasQuestionMarkChar(){return this.#n}get isWildcard(){return this.#o}get values(){return this.#s}static sorter(r,o){const i=typeof r=="number",l=typeof o=="number";return i&&l?r-o:!i&&!l?r.localeCompare(o):i?-1:1}static findNearestValueInList(r,o,i){if(i){for(let l=r.length-1;l>=0;l--)if(r[l]<o)return r[l];return null}for(let l=0;l<r.length;l++)if(r[l]>o)return r[l];return null}findNearestValue(r,o){return this.constructor.findNearestValueInList(this.values,r,o)}serialize(){return{wildcard:this.#o,values:this.#s}}validate(){let r;const o=this.chars.length>0?` or chars ${this.chars.join("")}`:"",i=d=>h=>new RegExp(`^\\d{0,2}${h}$`).test(d),l=d=>(r=d,typeof d=="number"?d>=this.min&&d<=this.max:this.chars.some(i(d)));if(!this.#s.every(l))throw new Error(`${this.constructor.name} Validation error, got value ${r} expected range ${this.min}-${this.max}${o}`);const u=this.#s.find((d,h)=>this.#s.indexOf(d)!==h);if(u)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${u}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(r,o)=>o+this.min).every(r=>this.#s.includes(r))}};return rr.CronField=e,rr}var Ui;function ff(){if(Ui)return nr;Ui=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.CronDayOfMonth=void 0;const e=mn(),n=1,r=31,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return nr.CronDayOfMonth=i,nr}var sr={},Gi;function mf(){if(Gi)return sr;Gi=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.CronDayOfWeek=void 0;const e=mn(),n=0,r=7,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return sr.CronDayOfWeek=i,sr}var or={},Yi;function pf(){if(Yi)return or;Yi=1,Object.defineProperty(or,"__esModule",{value:!0}),or.CronHour=void 0;const e=mn(),n=0,r=23,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return or.CronHour=i,or}var ir={},Ki;function gf(){if(Ki)return ir;Ki=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.CronMinute=void 0;const e=mn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return ir.CronMinute=i,ir}var ar={},Es={},bt={},Qi;function yf(){if(Qi)return bt;Qi=1,Object.defineProperty(bt,"__esModule",{value:!0});class e extends Error{}class n extends e{constructor(s){super(`Invalid DateTime: ${s.toMessage()}`)}}class r extends e{constructor(s){super(`Invalid Interval: ${s.toMessage()}`)}}class o extends e{constructor(s){super(`Invalid Duration: ${s.toMessage()}`)}}class i extends e{}class l extends e{constructor(s){super(`Invalid unit ${s}`)}}class a extends e{}class u extends e{constructor(){super("Zone is an abstract class")}}const d="numeric",h="short",y="long",b={year:d,month:d,day:d},x={year:d,month:h,day:d},v={year:d,month:h,day:d,weekday:h},k={year:d,month:y,day:d},C={year:d,month:y,day:d,weekday:y},S={hour:d,minute:d},T={hour:d,minute:d,second:d},O={hour:d,minute:d,second:d,timeZoneName:h},M={hour:d,minute:d,second:d,timeZoneName:y},E={hour:d,minute:d,hourCycle:"h23"},R={hour:d,minute:d,second:d,hourCycle:"h23"},P={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:h},F={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:y},B={year:d,month:d,day:d,hour:d,minute:d},D={year:d,month:d,day:d,hour:d,minute:d,second:d},_={year:d,month:h,day:d,hour:d,minute:d},V={year:d,month:h,day:d,hour:d,minute:d,second:d},$={year:d,month:h,day:d,weekday:h,hour:d,minute:d},W={year:d,month:y,day:d,hour:d,minute:d,timeZoneName:h},Z={year:d,month:y,day:d,hour:d,minute:d,second:d,timeZoneName:h},ne={year:d,month:y,day:d,weekday:y,hour:d,minute:d,timeZoneName:y},J={year:d,month:y,day:d,weekday:y,hour:d,minute:d,second:d,timeZoneName:y};class H{get type(){throw new u}get name(){throw new u}get ianaName(){return this.name}get isUniversal(){throw new u}offsetName(s,f){throw new u}formatOffset(s,f){throw new u}offset(s){throw new u}equals(s){throw new u}get isValid(){throw new u}}let Q=null;class re extends H{static get instance(){return Q===null&&(Q=new re),Q}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Fo(s,f,g)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){return-new Date(s).getTimezoneOffset()}equals(s){return s.type==="system"}get isValid(){return!0}}const z=new Map;function oe(m){let s=z.get(m);return s===void 0&&(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:m,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),z.set(m,s)),s}const se={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ie(m,s){const f=m.format(s).replace(/\u200E/g,""),g=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(f),[,w,I,A,L,N,X,xe]=g;return[A,w,I,L,N,X,xe]}function De(m,s){const f=m.formatToParts(s),g=[];for(let w=0;w<f.length;w++){const{type:I,value:A}=f[w],L=se[I];I==="era"?g[L]=A:ee(L)||(g[L]=parseInt(A,10))}return g}const de=new Map;class ue extends H{static create(s){let f=de.get(s);return f===void 0&&de.set(s,f=new ue(s)),f}static resetCache(){de.clear(),z.clear()}static isValidSpecifier(s){return this.isValidZone(s)}static isValidZone(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}).format(),!0}catch{return!1}}constructor(s){super(),this.zoneName=s,this.valid=ue.isValidZone(s)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Fo(s,f,g,this.name)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){if(!this.valid)return NaN;const f=new Date(s);if(isNaN(f))return NaN;const g=oe(this.name);let[w,I,A,L,N,X,xe]=g.formatToParts?De(g,f):ie(g,f);L==="BC"&&(w=-Math.abs(w)+1);const Be=Fr({year:w,month:I,day:A,hour:N===24?0:N,minute:X,second:xe,millisecond:0});let Se=+f;const it=Se%1e3;return Se-=it>=0?it:1e3+it,(Be-Se)/(60*1e3)}equals(s){return s.type==="iana"&&s.name===this.name}get isValid(){return this.valid}}let be={};function Me(m,s={}){const f=JSON.stringify([m,s]);let g=be[f];return g||(g=new Intl.ListFormat(m,s),be[f]=g),g}const te=new Map;function K(m,s={}){const f=JSON.stringify([m,s]);let g=te.get(f);return g===void 0&&(g=new Intl.DateTimeFormat(m,s),te.set(f,g)),g}const he=new Map;function we(m,s={}){const f=JSON.stringify([m,s]);let g=he.get(f);return g===void 0&&(g=new Intl.NumberFormat(m,s),he.set(f,g)),g}const ge=new Map;function pe(m,s={}){const{base:f,...g}=s,w=JSON.stringify([m,g]);let I=ge.get(w);return I===void 0&&(I=new Intl.RelativeTimeFormat(m,s),ge.set(w,I)),I}let ye=null;function Le(){return ye||(ye=new Intl.DateTimeFormat().resolvedOptions().locale,ye)}const st=new Map;function ce(m){let s=st.get(m);return s===void 0&&(s=new Intl.DateTimeFormat(m).resolvedOptions(),st.set(m,s)),s}const Y=new Map;function ae(m){let s=Y.get(m);if(!s){const f=new Intl.Locale(m);s="getWeekInfo"in f?f.getWeekInfo():f.weekInfo,"minimalDays"in s||(s={...Ye,...s}),Y.set(m,s)}return s}function Fe(m){const s=m.indexOf("-x-");s!==-1&&(m=m.substring(0,s));const f=m.indexOf("-u-");if(f===-1)return[m];{let g,w;try{g=K(m).resolvedOptions(),w=m}catch{const N=m.substring(0,f);g=K(N).resolvedOptions(),w=N}const{numberingSystem:I,calendar:A}=g;return[w,I,A]}}function Ve(m,s,f){return(f||s)&&(m.includes("-u-")||(m+="-u"),f&&(m+=`-ca-${f}`),s&&(m+=`-nu-${s}`)),m}function St(m){const s=[];for(let f=1;f<=12;f++){const g=ke.utc(2009,f,1);s.push(m(g))}return s}function Ee(m){const s=[];for(let f=1;f<=7;f++){const g=ke.utc(2016,11,13+f);s.push(m(g))}return s}function at(m,s,f,g){const w=m.listingMode();return w==="error"?null:w==="en"?f(s):g(s)}function yt(m){return m.numberingSystem&&m.numberingSystem!=="latn"?!1:m.numberingSystem==="latn"||!m.locale||m.locale.startsWith("en")||ce(m.locale).numberingSystem==="latn"}class xt{constructor(s,f,g){this.padTo=g.padTo||0,this.floor=g.floor||!1;const{padTo:w,floor:I,...A}=g;if(!f||Object.keys(A).length>0){const L={useGrouping:!1,...g};g.padTo>0&&(L.minimumIntegerDigits=g.padTo),this.inf=we(s,L)}}format(s){if(this.inf){const f=this.floor?Math.floor(s):s;return this.inf.format(f)}else{const f=this.floor?Math.floor(s):fs(s,3);return ot(f,this.padTo)}}}class Ot{constructor(s,f,g){this.opts=g,this.originalZone=void 0;let w;if(this.opts.timeZone)this.dt=s;else if(s.zone.type==="fixed"){const A=-1*(s.offset/60),L=A>=0?`Etc/GMT+${A}`:`Etc/GMT${A}`;s.offset!==0&&ue.create(L).valid?(w=L,this.dt=s):(w="UTC",this.dt=s.offset===0?s:s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone)}else s.zone.type==="system"?this.dt=s:s.zone.type==="iana"?(this.dt=s,w=s.zone.name):(w="UTC",this.dt=s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone);const I={...this.opts};I.timeZone=I.timeZone||w,this.dtf=K(f,I)}format(){return this.originalZone?this.formatToParts().map(({value:s})=>s).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const s=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?s.map(f=>{if(f.type==="timeZoneName"){const g=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...f,value:g}}else return f}):s}resolvedOptions(){return this.dtf.resolvedOptions()}}class pt{constructor(s,f,g){this.opts={style:"long",...g},!f&&zn()&&(this.rtf=pe(s,g))}format(s,f){return this.rtf?this.rtf.format(s,f):$c(f,s,this.opts.numeric,this.opts.style!=="long")}formatToParts(s,f){return this.rtf?this.rtf.formatToParts(s,f):[]}}const Ye={firstDay:1,minimalDays:4,weekend:[6,7]};class fe{static fromOpts(s){return fe.create(s.locale,s.numberingSystem,s.outputCalendar,s.weekSettings,s.defaultToEN)}static create(s,f,g,w,I=!1){const A=s||Ne.defaultLocale,L=A||(I?"en-US":Le()),N=f||Ne.defaultNumberingSystem,X=g||Ne.defaultOutputCalendar,xe=qt(w)||Ne.defaultWeekSettings;return new fe(L,N,X,xe,A)}static resetCache(){ye=null,te.clear(),he.clear(),ge.clear(),st.clear(),Y.clear()}static fromObject({locale:s,numberingSystem:f,outputCalendar:g,weekSettings:w}={}){return fe.create(s,f,g,w)}constructor(s,f,g,w,I){const[A,L,N]=Fe(s);this.locale=A,this.numberingSystem=f||L||null,this.outputCalendar=g||N||null,this.weekSettings=w,this.intl=Ve(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=I,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=yt(this)),this.fastNumbersCached}listingMode(){const s=this.isEnglish(),f=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return s&&f?"en":"intl"}clone(s){return!s||Object.getOwnPropertyNames(s).length===0?this:fe.create(s.locale||this.specifiedLocale,s.numberingSystem||this.numberingSystem,s.outputCalendar||this.outputCalendar,qt(s.weekSettings)||this.weekSettings,s.defaultToEN||!1)}redefaultToEN(s={}){return this.clone({...s,defaultToEN:!0})}redefaultToSystem(s={}){return this.clone({...s,defaultToEN:!1})}months(s,f=!1){return at(this,s,Lo,()=>{const g=this.intl==="ja"||this.intl.startsWith("ja-");f&=!g;const w=f?{month:s,day:"numeric"}:{month:s},I=f?"format":"standalone";if(!this.monthsCache[I][s]){const A=g?L=>this.dtFormatter(L,w).format():L=>this.extract(L,w,"month");this.monthsCache[I][s]=St(A)}return this.monthsCache[I][s]})}weekdays(s,f=!1){return at(this,s,Po,()=>{const g=f?{weekday:s,year:"numeric",month:"long",day:"numeric"}:{weekday:s},w=f?"format":"standalone";return this.weekdaysCache[w][s]||(this.weekdaysCache[w][s]=Ee(I=>this.extract(I,g,"weekday"))),this.weekdaysCache[w][s]})}meridiems(){return at(this,void 0,()=>zo,()=>{if(!this.meridiemCache){const s={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ke.utc(2016,11,13,9),ke.utc(2016,11,13,19)].map(f=>this.extract(f,s,"dayperiod"))}return this.meridiemCache})}eras(s){return at(this,s,Wo,()=>{const f={era:s};return this.eraCache[s]||(this.eraCache[s]=[ke.utc(-40,1,1),ke.utc(2017,1,1)].map(g=>this.extract(g,f,"era"))),this.eraCache[s]})}extract(s,f,g){const w=this.dtFormatter(s,f),I=w.formatToParts(),A=I.find(L=>L.type.toLowerCase()===g);return A?A.value:null}numberFormatter(s={}){return new xt(this.intl,s.forceSimple||this.fastNumbers,s)}dtFormatter(s,f={}){return new Ot(s,this.intl,f)}relFormatter(s={}){return new pt(this.intl,this.isEnglish(),s)}listFormatter(s={}){return Me(this.intl,s)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||ce(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Wn()?ae(this.locale):Ye}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(s){return this.locale===s.locale&&this.numberingSystem===s.numberingSystem&&this.outputCalendar===s.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let Ke=null;class ze extends H{static get utcInstance(){return Ke===null&&(Ke=new ze(0)),Ke}static instance(s){return s===0?ze.utcInstance:new ze(s)}static parseSpecifier(s){if(s){const f=s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(f)return new ze(Ar(f[1],f[2]))}return null}constructor(s){super(),this.fixed=s}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Vn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Vn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(s,f){return Vn(this.fixed,f)}get isUniversal(){return!0}offset(){return this.fixed}equals(s){return s.type==="fixed"&&s.fixed===this.fixed}get isValid(){return!0}}class lt extends H{constructor(s){super(),this.zoneName=s}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function ct(m,s){if(ee(m)||m===null)return s;if(m instanceof H)return m;if(Ct(m)){const f=m.toLowerCase();return f==="default"?s:f==="local"||f==="system"?re.instance:f==="utc"||f==="gmt"?ze.utcInstance:ze.parseSpecifier(f)||ue.create(m)}else return qe(m)?ze.instance(m):typeof m=="object"&&"offset"in m&&typeof m.offset=="function"?m:new lt(m)}const Qe={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},me={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},He=Qe.hanidec.replace(/[\[|\]]/g,"").split("");function vt(m){let s=parseInt(m,10);if(isNaN(s)){s="";for(let f=0;f<m.length;f++){const g=m.charCodeAt(f);if(m[f].search(Qe.hanidec)!==-1)s+=He.indexOf(m[f]);else for(const w in me){const[I,A]=me[w];g>=I&&g<=A&&(s+=g-I)}}return parseInt(s,10)}else return s}const Ce=new Map;function Re(){Ce.clear()}function Ie({numberingSystem:m},s=""){const f=m||"latn";let g=Ce.get(f);g===void 0&&(g=new Map,Ce.set(f,g));let w=g.get(s);return w===void 0&&(w=new RegExp(`${Qe[f]}${s}`),g.set(s,w)),w}let We=()=>Date.now(),dt="system",Pe=null,tt=null,Mt=null,kt=60,Ft,gn=null;class Ne{static get now(){return We}static set now(s){We=s}static set defaultZone(s){dt=s}static get defaultZone(){return ct(dt,re.instance)}static get defaultLocale(){return Pe}static set defaultLocale(s){Pe=s}static get defaultNumberingSystem(){return tt}static set defaultNumberingSystem(s){tt=s}static get defaultOutputCalendar(){return Mt}static set defaultOutputCalendar(s){Mt=s}static get defaultWeekSettings(){return gn}static set defaultWeekSettings(s){gn=qt(s)}static get twoDigitCutoffYear(){return kt}static set twoDigitCutoffYear(s){kt=s%100}static get throwOnInvalid(){return Ft}static set throwOnInvalid(s){Ft=s}static resetCaches(){fe.resetCache(),ue.resetCache(),ke.resetCache(),Re()}}class ut{constructor(s,f){this.reason=s,this.explanation=f}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Kt=[0,31,59,90,120,151,181,212,243,273,304,334],yn=[0,31,60,91,121,152,182,213,244,274,305,335];function ht(m,s){return new ut("unit out of range",`you specified ${s} (of type ${typeof s}) as a ${m}, which is invalid`)}function en(m,s,f){const g=new Date(Date.UTC(m,s-1,f));m<100&&m>=0&&g.setUTCFullYear(g.getUTCFullYear()-1900);const w=g.getUTCDay();return w===0?7:w}function xn(m,s,f){return f+(qn(m)?yn:Kt)[s-1]}function Qt(m,s){const f=qn(m)?yn:Kt,g=f.findIndex(I=>I<s),w=s-f[g];return{month:g+1,day:w}}function Ze(m,s){return(m-s+7)%7+1}function Xe(m,s=4,f=1){const{year:g,month:w,day:I}=m,A=xn(g,w,I),L=Ze(en(g,w,I),f);let N=Math.floor((A-L+14-s)/7),X;return N<1?(X=g-1,N=Bn(X,s,f)):N>Bn(g,s,f)?(X=g+1,N=1):X=g,{weekYear:X,weekNumber:N,weekday:L,...Lr(m)}}function At(m,s=4,f=1){const{weekYear:g,weekNumber:w,weekday:I}=m,A=Ze(en(g,1,s),f),L=bn(g);let N=w*7+I-A-7+s,X;N<1?(X=g-1,N+=bn(X)):N>L?(X=g+1,N-=bn(g)):X=g;const{month:xe,day:Te}=Qt(X,N);return{year:X,month:xe,day:Te,...Lr(m)}}function tn(m){const{year:s,month:f,day:g}=m,w=xn(s,f,g);return{year:s,ordinal:w,...Lr(m)}}function Zt(m){const{year:s,ordinal:f}=m,{month:g,day:w}=Qt(s,f);return{year:s,month:g,day:w,...Lr(m)}}function nn(m,s){if(!ee(m.localWeekday)||!ee(m.localWeekNumber)||!ee(m.localWeekYear)){if(!ee(m.weekday)||!ee(m.weekNumber)||!ee(m.weekYear))throw new i("Cannot mix locale-based week fields with ISO-based week fields");return ee(m.localWeekday)||(m.weekday=m.localWeekday),ee(m.localWeekNumber)||(m.weekNumber=m.localWeekNumber),ee(m.localWeekYear)||(m.weekYear=m.localWeekYear),delete m.localWeekday,delete m.localWeekNumber,delete m.localWeekYear,{minDaysInFirstWeek:s.getMinDaysInFirstWeek(),startOfWeek:s.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function G(m,s=4,f=1){const g=Ue(m.weekYear),w=Et(m.weekNumber,1,Bn(m.weekYear,s,f)),I=Et(m.weekday,1,7);return g?w?I?!1:ht("weekday",m.weekday):ht("week",m.weekNumber):ht("weekYear",m.weekYear)}function U(m){const s=Ue(m.year),f=Et(m.ordinal,1,bn(m.year));return s?f?!1:ht("ordinal",m.ordinal):ht("year",m.year)}function le(m){const s=Ue(m.year),f=Et(m.month,1,12),g=Et(m.day,1,$r(m.year,m.month));return s?f?g?!1:ht("day",m.day):ht("month",m.month):ht("year",m.year)}function ve(m){const{hour:s,minute:f,second:g,millisecond:w}=m,I=Et(s,0,23)||s===24&&f===0&&g===0&&w===0,A=Et(f,0,59),L=Et(g,0,59),N=Et(w,0,999);return I?A?L?N?!1:ht("millisecond",w):ht("second",g):ht("minute",f):ht("hour",s)}function ee(m){return typeof m>"u"}function qe(m){return typeof m=="number"}function Ue(m){return typeof m=="number"&&m%1===0}function Ct(m){return typeof m=="string"}function vn(m){return Object.prototype.toString.call(m)==="[object Date]"}function zn(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Wn(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Dr(m){return Array.isArray(m)?m:[m]}function $e(m,s,f){if(m.length!==0)return m.reduce((g,w)=>{const I=[s(w),w];return g&&f(g[0],I[0])===g[0]?g:I},null)[1]}function zt(m,s){return s.reduce((f,g)=>(f[g]=m[g],f),{})}function gt(m,s){return Object.prototype.hasOwnProperty.call(m,s)}function qt(m){if(m==null)return null;if(typeof m!="object")throw new a("Week settings must be an object");if(!Et(m.firstDay,1,7)||!Et(m.minimalDays,1,7)||!Array.isArray(m.weekend)||m.weekend.some(s=>!Et(s,1,7)))throw new a("Invalid week settings");return{firstDay:m.firstDay,minimalDays:m.minimalDays,weekend:Array.from(m.weekend)}}function Et(m,s,f){return Ue(m)&&m>=s&&m<=f}function wc(m,s){return m-s*Math.floor(m/s)}function ot(m,s=2){const f=m<0;let g;return f?g="-"+(""+-m).padStart(s,"0"):g=(""+m).padStart(s,"0"),g}function Xt(m){if(!(ee(m)||m===null||m===""))return parseInt(m,10)}function rn(m){if(!(ee(m)||m===null||m===""))return parseFloat(m)}function hs(m){if(!(ee(m)||m===null||m==="")){const s=parseFloat("0."+m)*1e3;return Math.floor(s)}}function fs(m,s,f="round"){const g=10**s;switch(f){case"expand":return m>0?Math.ceil(m*g)/g:Math.floor(m*g)/g;case"trunc":return Math.trunc(m*g)/g;case"round":return Math.round(m*g)/g;case"floor":return Math.floor(m*g)/g;case"ceil":return Math.ceil(m*g)/g;default:throw new RangeError(`Value rounding ${f} is out of range`)}}function qn(m){return m%4===0&&(m%100!==0||m%400===0)}function bn(m){return qn(m)?366:365}function $r(m,s){const f=wc(s-1,12)+1,g=m+(s-f)/12;return f===2?qn(g)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][f-1]}function Fr(m){let s=Date.UTC(m.year,m.month-1,m.day,m.hour,m.minute,m.second,m.millisecond);return m.year<100&&m.year>=0&&(s=new Date(s),s.setUTCFullYear(m.year,m.month-1,m.day)),+s}function $o(m,s,f){return-Ze(en(m,1,s),f)+s-1}function Bn(m,s=4,f=1){const g=$o(m,s,f),w=$o(m+1,s,f);return(bn(m)-g+w)/7}function ms(m){return m>99?m:m>Ne.twoDigitCutoffYear?1900+m:2e3+m}function Fo(m,s,f,g=null){const w=new Date(m),I={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};g&&(I.timeZone=g);const A={timeZoneName:s,...I},L=new Intl.DateTimeFormat(f,A).formatToParts(w).find(N=>N.type.toLowerCase()==="timezonename");return L?L.value:null}function Ar(m,s){let f=parseInt(m,10);Number.isNaN(f)&&(f=0);const g=parseInt(s,10)||0,w=f<0||Object.is(f,-0)?-g:g;return f*60+w}function Ao(m){const s=Number(m);if(typeof m=="boolean"||m===""||!Number.isFinite(s))throw new a(`Invalid unit value ${m}`);return s}function Rr(m,s){const f={};for(const g in m)if(gt(m,g)){const w=m[g];if(w==null)continue;f[s(g)]=Ao(w)}return f}function Vn(m,s){const f=Math.trunc(Math.abs(m/60)),g=Math.trunc(Math.abs(m%60)),w=m>=0?"+":"-";switch(s){case"short":return`${w}${ot(f,2)}:${ot(g,2)}`;case"narrow":return`${w}${f}${g>0?`:${g}`:""}`;case"techie":return`${w}${ot(f,2)}${ot(g,2)}`;default:throw new RangeError(`Value format ${s} is out of range for property format`)}}function Lr(m){return zt(m,["hour","minute","second","millisecond"])}const Sc=["January","February","March","April","May","June","July","August","September","October","November","December"],Ro=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],kc=["J","F","M","A","M","J","J","A","S","O","N","D"];function Lo(m){switch(m){case"narrow":return[...kc];case"short":return[...Ro];case"long":return[...Sc];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const _o=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],No=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Cc=["M","T","W","T","F","S","S"];function Po(m){switch(m){case"narrow":return[...Cc];case"short":return[...No];case"long":return[..._o];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const zo=["AM","PM"],jc=["Before Christ","Anno Domini"],Tc=["BC","AD"],Oc=["B","A"];function Wo(m){switch(m){case"narrow":return[...Oc];case"short":return[...Tc];case"long":return[...jc];default:return null}}function Mc(m){return zo[m.hour<12?0:1]}function Ec(m,s){return Po(s)[m.weekday-1]}function Ic(m,s){return Lo(s)[m.month-1]}function Dc(m,s){return Wo(s)[m.year<0?0:1]}function $c(m,s,f="always",g=!1){const w={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},I=["hours","minutes","seconds"].indexOf(m)===-1;if(f==="auto"&&I){const Te=m==="days";switch(s){case 1:return Te?"tomorrow":`next ${w[m][0]}`;case-1:return Te?"yesterday":`last ${w[m][0]}`;case 0:return Te?"today":`this ${w[m][0]}`}}const A=Object.is(s,-0)||s<0,L=Math.abs(s),N=L===1,X=w[m],xe=g?N?X[1]:X[2]||X[1]:N?w[m][0]:m;return A?`${L} ${xe} ago`:`in ${L} ${xe}`}function qo(m,s){let f="";for(const g of m)g.literal?f+=g.val:f+=s(g.val);return f}const Fc={D:b,DD:x,DDD:k,DDDD:C,t:S,tt:T,ttt:O,tttt:M,T:E,TT:R,TTT:P,TTTT:F,f:B,ff:_,fff:W,ffff:ne,F:D,FF:V,FFF:Z,FFFF:J};class ft{static create(s,f={}){return new ft(s,f)}static parseFormat(s){let f=null,g="",w=!1;const I=[];for(let A=0;A<s.length;A++){const L=s.charAt(A);L==="'"?((g.length>0||w)&&I.push({literal:w||/^\s+$/.test(g),val:g===""?"'":g}),f=null,g="",w=!w):w||L===f?g+=L:(g.length>0&&I.push({literal:/^\s+$/.test(g),val:g}),g=L,f=L)}return g.length>0&&I.push({literal:w||/^\s+$/.test(g),val:g}),I}static macroTokenToFormatOpts(s){return Fc[s]}constructor(s,f){this.opts=f,this.loc=s,this.systemLoc=null}formatWithSystemDefault(s,f){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(s,{...this.opts,...f}).format()}dtFormatter(s,f={}){return this.loc.dtFormatter(s,{...this.opts,...f})}formatDateTime(s,f){return this.dtFormatter(s,f).format()}formatDateTimeParts(s,f){return this.dtFormatter(s,f).formatToParts()}formatInterval(s,f){return this.dtFormatter(s.start,f).dtf.formatRange(s.start.toJSDate(),s.end.toJSDate())}resolvedOptions(s,f){return this.dtFormatter(s,f).resolvedOptions()}num(s,f=0,g=void 0){if(this.opts.forceSimple)return ot(s,f);const w={...this.opts};return f>0&&(w.padTo=f),g&&(w.signDisplay=g),this.loc.numberFormatter(w).format(s)}formatDateTimeFromString(s,f){const g=this.loc.listingMode()==="en",w=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",I=(Se,it)=>this.loc.extract(s,Se,it),A=Se=>s.isOffsetFixed&&s.offset===0&&Se.allowZ?"Z":s.isValid?s.zone.formatOffset(s.ts,Se.format):"",L=()=>g?Mc(s):I({hour:"numeric",hourCycle:"h12"},"dayperiod"),N=(Se,it)=>g?Ic(s,Se):I(it?{month:Se}:{month:Se,day:"numeric"},"month"),X=(Se,it)=>g?Ec(s,Se):I(it?{weekday:Se}:{weekday:Se,month:"long",day:"numeric"},"weekday"),xe=Se=>{const it=ft.macroTokenToFormatOpts(Se);return it?this.formatWithSystemDefault(s,it):Se},Te=Se=>g?Dc(s,Se):I({era:Se},"era"),Be=Se=>{switch(Se){case"S":return this.num(s.millisecond);case"u":case"SSS":return this.num(s.millisecond,3);case"s":return this.num(s.second);case"ss":return this.num(s.second,2);case"uu":return this.num(Math.floor(s.millisecond/10),2);case"uuu":return this.num(Math.floor(s.millisecond/100));case"m":return this.num(s.minute);case"mm":return this.num(s.minute,2);case"h":return this.num(s.hour%12===0?12:s.hour%12);case"hh":return this.num(s.hour%12===0?12:s.hour%12,2);case"H":return this.num(s.hour);case"HH":return this.num(s.hour,2);case"Z":return A({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return A({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return A({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return s.zone.offsetName(s.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return s.zone.offsetName(s.ts,{format:"long",locale:this.loc.locale});case"z":return s.zoneName;case"a":return L();case"d":return w?I({day:"numeric"},"day"):this.num(s.day);case"dd":return w?I({day:"2-digit"},"day"):this.num(s.day,2);case"c":return this.num(s.weekday);case"ccc":return X("short",!0);case"cccc":return X("long",!0);case"ccccc":return X("narrow",!0);case"E":return this.num(s.weekday);case"EEE":return X("short",!1);case"EEEE":return X("long",!1);case"EEEEE":return X("narrow",!1);case"L":return w?I({month:"numeric",day:"numeric"},"month"):this.num(s.month);case"LL":return w?I({month:"2-digit",day:"numeric"},"month"):this.num(s.month,2);case"LLL":return N("short",!0);case"LLLL":return N("long",!0);case"LLLLL":return N("narrow",!0);case"M":return w?I({month:"numeric"},"month"):this.num(s.month);case"MM":return w?I({month:"2-digit"},"month"):this.num(s.month,2);case"MMM":return N("short",!1);case"MMMM":return N("long",!1);case"MMMMM":return N("narrow",!1);case"y":return w?I({year:"numeric"},"year"):this.num(s.year);case"yy":return w?I({year:"2-digit"},"year"):this.num(s.year.toString().slice(-2),2);case"yyyy":return w?I({year:"numeric"},"year"):this.num(s.year,4);case"yyyyyy":return w?I({year:"numeric"},"year"):this.num(s.year,6);case"G":return Te("short");case"GG":return Te("long");case"GGGGG":return Te("narrow");case"kk":return this.num(s.weekYear.toString().slice(-2),2);case"kkkk":return this.num(s.weekYear,4);case"W":return this.num(s.weekNumber);case"WW":return this.num(s.weekNumber,2);case"n":return this.num(s.localWeekNumber);case"nn":return this.num(s.localWeekNumber,2);case"ii":return this.num(s.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(s.localWeekYear,4);case"o":return this.num(s.ordinal);case"ooo":return this.num(s.ordinal,3);case"q":return this.num(s.quarter);case"qq":return this.num(s.quarter,2);case"X":return this.num(Math.floor(s.ts/1e3));case"x":return this.num(s.ts);default:return xe(Se)}};return qo(ft.parseFormat(f),Be)}formatDurationFromString(s,f){const g=this.opts.signMode==="negativeLargestOnly"?-1:1,w=xe=>{switch(xe[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},I=(xe,Te)=>Be=>{const Se=w(Be);if(Se){const it=Te.isNegativeDuration&&Se!==Te.largestUnit?g:1;let Lt;return this.opts.signMode==="negativeLargestOnly"&&Se!==Te.largestUnit?Lt="never":this.opts.signMode==="all"?Lt="always":Lt="auto",this.num(xe.get(Se)*it,Be.length,Lt)}else return Be},A=ft.parseFormat(f),L=A.reduce((xe,{literal:Te,val:Be})=>Te?xe:xe.concat(Be),[]),N=s.shiftTo(...L.map(w).filter(xe=>xe)),X={isNegativeDuration:N<0,largestUnit:Object.keys(N.values)[0]};return qo(A,I(N,X))}}const Bo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function wn(...m){const s=m.reduce((f,g)=>f+g.source,"");return RegExp(`^${s}$`)}function Sn(...m){return s=>m.reduce(([f,g,w],I)=>{const[A,L,N]=I(s,w);return[{...f,...A},L||g,N]},[{},null,1]).slice(0,2)}function kn(m,...s){if(m==null)return[null,null];for(const[f,g]of s){const w=f.exec(m);if(w)return g(w)}return[null,null]}function Vo(...m){return(s,f)=>{const g={};let w;for(w=0;w<m.length;w++)g[m[w]]=Xt(s[f+w]);return[g,null,f+w]}}const Ho=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Ac=`(?:${Ho.source}?(?:\\[(${Bo.source})\\])?)?`,ps=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Uo=RegExp(`${ps.source}${Ac}`),gs=RegExp(`(?:[Tt]${Uo.source})?`),Rc=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Lc=/(\d{4})-?W(\d\d)(?:-?(\d))?/,_c=/(\d{4})-?(\d{3})/,Nc=Vo("weekYear","weekNumber","weekDay"),Pc=Vo("year","ordinal"),zc=/(\d{4})-(\d\d)-(\d\d)/,Go=RegExp(`${ps.source} ?(?:${Ho.source}|(${Bo.source}))?`),Wc=RegExp(`(?: ${Go.source})?`);function Cn(m,s,f){const g=m[s];return ee(g)?f:Xt(g)}function qc(m,s){return[{year:Cn(m,s),month:Cn(m,s+1,1),day:Cn(m,s+2,1)},null,s+3]}function jn(m,s){return[{hours:Cn(m,s,0),minutes:Cn(m,s+1,0),seconds:Cn(m,s+2,0),milliseconds:hs(m[s+3])},null,s+4]}function Hn(m,s){const f=!m[s]&&!m[s+1],g=Ar(m[s+1],m[s+2]),w=f?null:ze.instance(g);return[{},w,s+3]}function Un(m,s){const f=m[s]?ue.create(m[s]):null;return[{},f,s+1]}const Bc=RegExp(`^T?${ps.source}$`),Vc=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Hc(m){const[s,f,g,w,I,A,L,N,X]=m,xe=s[0]==="-",Te=N&&N[0]==="-",Be=(Se,it=!1)=>Se!==void 0&&(it||Se&&xe)?-Se:Se;return[{years:Be(rn(f)),months:Be(rn(g)),weeks:Be(rn(w)),days:Be(rn(I)),hours:Be(rn(A)),minutes:Be(rn(L)),seconds:Be(rn(N),N==="-0"),milliseconds:Be(hs(X),Te)}]}const Uc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ys(m,s,f,g,w,I,A){const L={year:s.length===2?ms(Xt(s)):Xt(s),month:Ro.indexOf(f)+1,day:Xt(g),hour:Xt(w),minute:Xt(I)};return A&&(L.second=Xt(A)),m&&(L.weekday=m.length>3?_o.indexOf(m)+1:No.indexOf(m)+1),L}const Gc=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Yc(m){const[,s,f,g,w,I,A,L,N,X,xe,Te]=m,Be=ys(s,w,g,f,I,A,L);let Se;return N?Se=Uc[N]:X?Se=0:Se=Ar(xe,Te),[Be,new ze(Se)]}function Kc(m){return m.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Qc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Zc=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Xc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Yo(m){const[,s,f,g,w,I,A,L]=m;return[ys(s,w,g,f,I,A,L),ze.utcInstance]}function Jc(m){const[,s,f,g,w,I,A,L]=m;return[ys(s,L,f,g,w,I,A),ze.utcInstance]}const eu=wn(Rc,gs),tu=wn(Lc,gs),nu=wn(_c,gs),ru=wn(Uo),Ko=Sn(qc,jn,Hn,Un),su=Sn(Nc,jn,Hn,Un),ou=Sn(Pc,jn,Hn,Un),iu=Sn(jn,Hn,Un);function au(m){return kn(m,[eu,Ko],[tu,su],[nu,ou],[ru,iu])}function lu(m){return kn(Kc(m),[Gc,Yc])}function cu(m){return kn(m,[Qc,Yo],[Zc,Yo],[Xc,Jc])}function uu(m){return kn(m,[Vc,Hc])}const du=Sn(jn);function hu(m){return kn(m,[Bc,du])}const fu=wn(zc,Wc),mu=wn(Go),pu=Sn(jn,Hn,Un);function gu(m){return kn(m,[fu,Ko],[mu,pu])}const Qo="Invalid Duration",Zo={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},yu={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...Zo},It=146097/400,Tn=146097/4800,xu={years:{quarters:4,months:12,weeks:It/7,days:It,hours:It*24,minutes:It*24*60,seconds:It*24*60*60,milliseconds:It*24*60*60*1e3},quarters:{months:3,weeks:It/28,days:It/4,hours:It*24/4,minutes:It*24*60/4,seconds:It*24*60*60/4,milliseconds:It*24*60*60*1e3/4},months:{weeks:Tn/7,days:Tn,hours:Tn*24,minutes:Tn*24*60,seconds:Tn*24*60*60,milliseconds:Tn*24*60*60*1e3},...Zo},sn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],vu=sn.slice(0).reverse();function Bt(m,s,f=!1){const g={values:f?s.values:{...m.values,...s.values||{}},loc:m.loc.clone(s.loc),conversionAccuracy:s.conversionAccuracy||m.conversionAccuracy,matrix:s.matrix||m.matrix};return new Ae(g)}function Xo(m,s){var f;let g=(f=s.milliseconds)!=null?f:0;for(const w of vu.slice(1))s[w]&&(g+=s[w]*m[w].milliseconds);return g}function Jo(m,s){const f=Xo(m,s)<0?-1:1;sn.reduceRight((g,w)=>{if(ee(s[w]))return g;if(g){const I=s[g]*f,A=m[w][g],L=Math.floor(I/A);s[w]+=L*f,s[g]-=L*A*f}return w},null),sn.reduce((g,w)=>{if(ee(s[w]))return g;if(g){const I=s[g]%1;s[g]-=I,s[w]+=I*m[g][w]}return w},null)}function ei(m){const s={};for(const[f,g]of Object.entries(m))g!==0&&(s[f]=g);return s}class Ae{constructor(s){const f=s.conversionAccuracy==="longterm"||!1;let g=f?xu:yu;s.matrix&&(g=s.matrix),this.values=s.values,this.loc=s.loc||fe.create(),this.conversionAccuracy=f?"longterm":"casual",this.invalid=s.invalid||null,this.matrix=g,this.isLuxonDuration=!0}static fromMillis(s,f){return Ae.fromObject({milliseconds:s},f)}static fromObject(s,f={}){if(s==null||typeof s!="object")throw new a(`Duration.fromObject: argument expected to be an object, got ${s===null?"null":typeof s}`);return new Ae({values:Rr(s,Ae.normalizeUnit),loc:fe.fromObject(f),conversionAccuracy:f.conversionAccuracy,matrix:f.matrix})}static fromDurationLike(s){if(qe(s))return Ae.fromMillis(s);if(Ae.isDuration(s))return s;if(typeof s=="object")return Ae.fromObject(s);throw new a(`Unknown duration argument ${s} of type ${typeof s}`)}static fromISO(s,f){const[g]=uu(s);return g?Ae.fromObject(g,f):Ae.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static fromISOTime(s,f){const[g]=hu(s);return g?Ae.fromObject(g,f):Ae.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Duration is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new o(g);return new Ae({invalid:g})}static normalizeUnit(s){const f={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[s&&s.toLowerCase()];if(!f)throw new l(s);return f}static isDuration(s){return s&&s.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(s,f={}){const g={...f,floor:f.round!==!1&&f.floor!==!1};return this.isValid?ft.create(this.loc,g).formatDurationFromString(this,s):Qo}toHuman(s={}){if(!this.isValid)return Qo;const f=s.showZeros!==!1,g=sn.map(w=>{const I=this.values[w];return ee(I)||I===0&&!f?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...s,unit:w.slice(0,-1)}).format(I)}).filter(w=>w);return this.loc.listFormatter({type:"conjunction",style:s.listStyle||"narrow",...s}).format(g)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s="P";return this.years!==0&&(s+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s+=this.weeks+"W"),this.days!==0&&(s+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s+="T"),this.hours!==0&&(s+=this.hours+"H"),this.minutes!==0&&(s+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s+=fs(this.seconds+this.milliseconds/1e3,3)+"S"),s==="P"&&(s+="T0S"),s}toISOTime(s={}){if(!this.isValid)return null;const f=this.toMillis();return f<0||f>=864e5?null:(s={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...s,includeOffset:!1},ke.fromMillis(f,{zone:"UTC"}).toISOTime(s))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s),g={};for(const w of sn)(gt(f.values,w)||gt(this.values,w))&&(g[w]=f.get(w)+this.get(w));return Bt(this,{values:g},!0)}minus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s);return this.plus(f.negate())}mapUnits(s){if(!this.isValid)return this;const f={};for(const g of Object.keys(this.values))f[g]=Ao(s(this.values[g],g));return Bt(this,{values:f},!0)}get(s){return this[Ae.normalizeUnit(s)]}set(s){if(!this.isValid)return this;const f={...this.values,...Rr(s,Ae.normalizeUnit)};return Bt(this,{values:f})}reconfigure({locale:s,numberingSystem:f,conversionAccuracy:g,matrix:w}={}){const A={loc:this.loc.clone({locale:s,numberingSystem:f}),matrix:w,conversionAccuracy:g};return Bt(this,A)}as(s){return this.isValid?this.shiftTo(s).get(s):NaN}normalize(){if(!this.isValid)return this;const s=this.toObject();return Jo(this.matrix,s),Bt(this,{values:s},!0)}rescale(){if(!this.isValid)return this;const s=ei(this.normalize().shiftToAll().toObject());return Bt(this,{values:s},!0)}shiftTo(...s){if(!this.isValid)return this;if(s.length===0)return this;s=s.map(A=>Ae.normalizeUnit(A));const f={},g={},w=this.toObject();let I;for(const A of sn)if(s.indexOf(A)>=0){I=A;let L=0;for(const X in g)L+=this.matrix[X][A]*g[X],g[X]=0;qe(w[A])&&(L+=w[A]);const N=Math.trunc(L);f[A]=N,g[A]=(L*1e3-N*1e3)/1e3}else qe(w[A])&&(g[A]=w[A]);for(const A in g)g[A]!==0&&(f[I]+=A===I?g[A]:g[A]/this.matrix[I][A]);return Jo(this.matrix,f),Bt(this,{values:f},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const s={};for(const f of Object.keys(this.values))s[f]=this.values[f]===0?0:-this.values[f];return Bt(this,{values:s},!0)}removeZeros(){if(!this.isValid)return this;const s=ei(this.values);return Bt(this,{values:s},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(s){if(!this.isValid||!s.isValid||!this.loc.equals(s.loc))return!1;function f(g,w){return g===void 0||g===0?w===void 0||w===0:g===w}for(const g of sn)if(!f(this.values[g],s.values[g]))return!1;return!0}}const On="Invalid Interval";function bu(m,s){return!m||!m.isValid?Je.invalid("missing or invalid start"):!s||!s.isValid?Je.invalid("missing or invalid end"):s<m?Je.invalid("end before start",`The end of an interval must be after its start, but you had start=${m.toISO()} and end=${s.toISO()}`):null}class Je{constructor(s){this.s=s.start,this.e=s.end,this.invalid=s.invalid||null,this.isLuxonInterval=!0}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Interval is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new r(g);return new Je({invalid:g})}static fromDateTimes(s,f){const g=Qn(s),w=Qn(f),I=bu(g,w);return I??new Je({start:g,end:w})}static after(s,f){const g=Ae.fromDurationLike(f),w=Qn(s);return Je.fromDateTimes(w,w.plus(g))}static before(s,f){const g=Ae.fromDurationLike(f),w=Qn(s);return Je.fromDateTimes(w.minus(g),w)}static fromISO(s,f){const[g,w]=(s||"").split("/",2);if(g&&w){let I,A;try{I=ke.fromISO(g,f),A=I.isValid}catch{A=!1}let L,N;try{L=ke.fromISO(w,f),N=L.isValid}catch{N=!1}if(A&&N)return Je.fromDateTimes(I,L);if(A){const X=Ae.fromISO(w,f);if(X.isValid)return Je.after(I,X)}else if(N){const X=Ae.fromISO(g,f);if(X.isValid)return Je.before(L,X)}}return Je.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static isInterval(s){return s&&s.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(s="milliseconds"){return this.isValid?this.toDuration(s).get(s):NaN}count(s="milliseconds",f){if(!this.isValid)return NaN;const g=this.start.startOf(s,f);let w;return f!=null&&f.useLocaleWeeks?w=this.end.reconfigure({locale:g.locale}):w=this.end,w=w.startOf(s,f),Math.floor(w.diff(g,s).get(s))+(w.valueOf()!==this.end.valueOf())}hasSame(s){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,s):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(s){return this.isValid?this.s>s:!1}isBefore(s){return this.isValid?this.e<=s:!1}contains(s){return this.isValid?this.s<=s&&this.e>s:!1}set({start:s,end:f}={}){return this.isValid?Je.fromDateTimes(s||this.s,f||this.e):this}splitAt(...s){if(!this.isValid)return[];const f=s.map(Qn).filter(A=>this.contains(A)).sort((A,L)=>A.toMillis()-L.toMillis()),g=[];let{s:w}=this,I=0;for(;w<this.e;){const A=f[I]||this.e,L=+A>+this.e?this.e:A;g.push(Je.fromDateTimes(w,L)),w=L,I+=1}return g}splitBy(s){const f=Ae.fromDurationLike(s);if(!this.isValid||!f.isValid||f.as("milliseconds")===0)return[];let{s:g}=this,w=1,I;const A=[];for(;g<this.e;){const L=this.start.plus(f.mapUnits(N=>N*w));I=+L>+this.e?this.e:L,A.push(Je.fromDateTimes(g,I)),g=I,w+=1}return A}divideEqually(s){return this.isValid?this.splitBy(this.length()/s).slice(0,s):[]}overlaps(s){return this.e>s.s&&this.s<s.e}abutsStart(s){return this.isValid?+this.e==+s.s:!1}abutsEnd(s){return this.isValid?+s.e==+this.s:!1}engulfs(s){return this.isValid?this.s<=s.s&&this.e>=s.e:!1}equals(s){return!this.isValid||!s.isValid?!1:this.s.equals(s.s)&&this.e.equals(s.e)}intersection(s){if(!this.isValid)return this;const f=this.s>s.s?this.s:s.s,g=this.e<s.e?this.e:s.e;return f>=g?null:Je.fromDateTimes(f,g)}union(s){if(!this.isValid)return this;const f=this.s<s.s?this.s:s.s,g=this.e>s.e?this.e:s.e;return Je.fromDateTimes(f,g)}static merge(s){const[f,g]=s.sort((w,I)=>w.s-I.s).reduce(([w,I],A)=>I?I.overlaps(A)||I.abutsStart(A)?[w,I.union(A)]:[w.concat([I]),A]:[w,A],[[],null]);return g&&f.push(g),f}static xor(s){let f=null,g=0;const w=[],I=s.map(N=>[{time:N.s,type:"s"},{time:N.e,type:"e"}]),A=Array.prototype.concat(...I),L=A.sort((N,X)=>N.time-X.time);for(const N of L)g+=N.type==="s"?1:-1,g===1?f=N.time:(f&&+f!=+N.time&&w.push(Je.fromDateTimes(f,N.time)),f=null);return Je.merge(w)}difference(...s){return Je.xor([this].concat(s)).map(f=>this.intersection(f)).filter(f=>f&&!f.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:On}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(s=b,f={}){return this.isValid?ft.create(this.s.loc.clone(f),s).formatInterval(this):On}toISO(s){return this.isValid?`${this.s.toISO(s)}/${this.e.toISO(s)}`:On}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:On}toISOTime(s){return this.isValid?`${this.s.toISOTime(s)}/${this.e.toISOTime(s)}`:On}toFormat(s,{separator:f=" – "}={}){return this.isValid?`${this.s.toFormat(s)}${f}${this.e.toFormat(s)}`:On}toDuration(s,f){return this.isValid?this.e.diff(this.s,s,f):Ae.invalid(this.invalidReason)}mapEndpoints(s){return Je.fromDateTimes(s(this.s),s(this.e))}}class Gn{static hasDST(s=Ne.defaultZone){const f=ke.now().setZone(s).set({month:12});return!s.isUniversal&&f.offset!==f.set({month:6}).offset}static isValidIANAZone(s){return ue.isValidZone(s)}static normalizeZone(s){return ct(s,Ne.defaultZone)}static getStartOfWeek({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getWeekendDays().slice()}static months(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||fe.create(f,g,I)).months(s)}static monthsFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||fe.create(f,g,I)).months(s,!0)}static weekdays(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||fe.create(f,g,null)).weekdays(s)}static weekdaysFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||fe.create(f,g,null)).weekdays(s,!0)}static meridiems({locale:s=null}={}){return fe.create(s).meridiems()}static eras(s="short",{locale:f=null}={}){return fe.create(f,null,"gregory").eras(s)}static features(){return{relative:zn(),localeWeek:Wn()}}}function ti(m,s){const f=w=>w.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),g=f(s)-f(m);return Math.floor(Ae.fromMillis(g).as("days"))}function wu(m,s,f){const g=[["years",(N,X)=>X.year-N.year],["quarters",(N,X)=>X.quarter-N.quarter+(X.year-N.year)*4],["months",(N,X)=>X.month-N.month+(X.year-N.year)*12],["weeks",(N,X)=>{const xe=ti(N,X);return(xe-xe%7)/7}],["days",ti]],w={},I=m;let A,L;for(const[N,X]of g)f.indexOf(N)>=0&&(A=N,w[N]=X(m,s),L=I.plus(w),L>s?(w[N]--,m=I.plus(w),m>s&&(L=m,w[N]--,m=I.plus(w))):m=L);return[m,w,L,A]}function Su(m,s,f,g){let[w,I,A,L]=wu(m,s,f);const N=s-w,X=f.filter(Te=>["hours","minutes","seconds","milliseconds"].indexOf(Te)>=0);X.length===0&&(A<s&&(A=w.plus({[L]:1})),A!==w&&(I[L]=(I[L]||0)+N/(A-w)));const xe=Ae.fromObject(I,g);return X.length>0?Ae.fromMillis(N,g).shiftTo(...X).plus(xe):xe}const ku="missing Intl.DateTimeFormat.formatToParts support";function _e(m,s=f=>f){return{regex:m,deser:([f])=>s(vt(f))}}const ni="[  ]",ri=new RegExp(ni,"g");function Cu(m){return m.replace(/\./g,"\\.?").replace(ri,ni)}function si(m){return m.replace(/\./g,"").replace(ri," ").toLowerCase()}function Rt(m,s){return m===null?null:{regex:RegExp(m.map(Cu).join("|")),deser:([f])=>m.findIndex(g=>si(f)===si(g))+s}}function oi(m,s){return{regex:m,deser:([,f,g])=>Ar(f,g),groups:s}}function _r(m){return{regex:m,deser:([s])=>s}}function ju(m){return m.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Tu(m,s){const f=Ie(s),g=Ie(s,"{2}"),w=Ie(s,"{3}"),I=Ie(s,"{4}"),A=Ie(s,"{6}"),L=Ie(s,"{1,2}"),N=Ie(s,"{1,3}"),X=Ie(s,"{1,6}"),xe=Ie(s,"{1,9}"),Te=Ie(s,"{2,4}"),Be=Ie(s,"{4,6}"),Se=Wt=>({regex:RegExp(ju(Wt.val)),deser:([En])=>En,literal:!0}),Lt=(Wt=>{if(m.literal)return Se(Wt);switch(Wt.val){case"G":return Rt(s.eras("short"),0);case"GG":return Rt(s.eras("long"),0);case"y":return _e(X);case"yy":return _e(Te,ms);case"yyyy":return _e(I);case"yyyyy":return _e(Be);case"yyyyyy":return _e(A);case"M":return _e(L);case"MM":return _e(g);case"MMM":return Rt(s.months("short",!0),1);case"MMMM":return Rt(s.months("long",!0),1);case"L":return _e(L);case"LL":return _e(g);case"LLL":return Rt(s.months("short",!1),1);case"LLLL":return Rt(s.months("long",!1),1);case"d":return _e(L);case"dd":return _e(g);case"o":return _e(N);case"ooo":return _e(w);case"HH":return _e(g);case"H":return _e(L);case"hh":return _e(g);case"h":return _e(L);case"mm":return _e(g);case"m":return _e(L);case"q":return _e(L);case"qq":return _e(g);case"s":return _e(L);case"ss":return _e(g);case"S":return _e(N);case"SSS":return _e(w);case"u":return _r(xe);case"uu":return _r(L);case"uuu":return _e(f);case"a":return Rt(s.meridiems(),0);case"kkkk":return _e(I);case"kk":return _e(Te,ms);case"W":return _e(L);case"WW":return _e(g);case"E":case"c":return _e(f);case"EEE":return Rt(s.weekdays("short",!1),1);case"EEEE":return Rt(s.weekdays("long",!1),1);case"ccc":return Rt(s.weekdays("short",!0),1);case"cccc":return Rt(s.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${L.source})(?::(${g.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${L.source})(${g.source})?`),2);case"z":return _r(/[a-z_+-/]{1,256}?/i);case" ":return _r(/[^\S\n\r]/);default:return Se(Wt)}})(m)||{invalidReason:ku};return Lt.token=m,Lt}const Ou={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Mu(m,s,f){const{type:g,value:w}=m;if(g==="literal"){const N=/^\s+$/.test(w);return{literal:!N,val:N?" ":w}}const I=s[g];let A=g;g==="hour"&&(s.hour12!=null?A=s.hour12?"hour12":"hour24":s.hourCycle!=null?s.hourCycle==="h11"||s.hourCycle==="h12"?A="hour12":A="hour24":A=f.hour12?"hour12":"hour24");let L=Ou[A];if(typeof L=="object"&&(L=L[I]),L)return{literal:!1,val:L}}function Eu(m){return[`^${m.map(f=>f.regex).reduce((f,g)=>`${f}(${g.source})`,"")}$`,m]}function Iu(m,s,f){const g=m.match(s);if(g){const w={};let I=1;for(const A in f)if(gt(f,A)){const L=f[A],N=L.groups?L.groups+1:1;!L.literal&&L.token&&(w[L.token.val[0]]=L.deser(g.slice(I,I+N))),I+=N}return[g,w]}else return[g,{}]}function Du(m){const s=I=>{switch(I){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let f=null,g;return ee(m.z)||(f=ue.create(m.z)),ee(m.Z)||(f||(f=new ze(m.Z)),g=m.Z),ee(m.q)||(m.M=(m.q-1)*3+1),ee(m.h)||(m.h<12&&m.a===1?m.h+=12:m.h===12&&m.a===0&&(m.h=0)),m.G===0&&m.y&&(m.y=-m.y),ee(m.u)||(m.S=hs(m.u)),[Object.keys(m).reduce((I,A)=>{const L=s(A);return L&&(I[L]=m[A]),I},{}),f,g]}let xs=null;function $u(){return xs||(xs=ke.fromMillis(1555555555555)),xs}function Fu(m,s){if(m.literal)return m;const f=ft.macroTokenToFormatOpts(m.val),g=ci(f,s);return g==null||g.includes(void 0)?m:g}function ii(m,s){return Array.prototype.concat(...m.map(f=>Fu(f,s)))}class ai{constructor(s,f){if(this.locale=s,this.format=f,this.tokens=ii(ft.parseFormat(f),s),this.units=this.tokens.map(g=>Tu(g,s)),this.disqualifyingUnit=this.units.find(g=>g.invalidReason),!this.disqualifyingUnit){const[g,w]=Eu(this.units);this.regex=RegExp(g,"i"),this.handlers=w}}explainFromTokens(s){if(this.isValid){const[f,g]=Iu(s,this.regex,this.handlers),[w,I,A]=g?Du(g):[null,null,void 0];if(gt(g,"a")&&gt(g,"H"))throw new i("Can't include meridiem when specifying 24-hour format");return{input:s,tokens:this.tokens,regex:this.regex,rawMatches:f,matches:g,result:w,zone:I,specificOffset:A}}else return{input:s,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function li(m,s,f){return new ai(m,f).explainFromTokens(s)}function Au(m,s,f){const{result:g,zone:w,specificOffset:I,invalidReason:A}=li(m,s,f);return[g,w,I,A]}function ci(m,s){if(!m)return null;const g=ft.create(s,m).dtFormatter($u()),w=g.formatToParts(),I=g.resolvedOptions();return w.map(A=>Mu(A,m,I))}const vs="Invalid DateTime",ui=864e13;function Yn(m){return new ut("unsupported zone",`the zone "${m.name}" is not supported`)}function bs(m){return m.weekData===null&&(m.weekData=Xe(m.c)),m.weekData}function ws(m){return m.localWeekData===null&&(m.localWeekData=Xe(m.c,m.loc.getMinDaysInFirstWeek(),m.loc.getStartOfWeek())),m.localWeekData}function on(m,s){const f={ts:m.ts,zone:m.zone,c:m.c,o:m.o,loc:m.loc,invalid:m.invalid};return new ke({...f,...s,old:f})}function di(m,s,f){let g=m-s*60*1e3;const w=f.offset(g);if(s===w)return[g,s];g-=(w-s)*60*1e3;const I=f.offset(g);return w===I?[g,w]:[m-Math.min(w,I)*60*1e3,Math.max(w,I)]}function Nr(m,s){m+=s*60*1e3;const f=new Date(m);return{year:f.getUTCFullYear(),month:f.getUTCMonth()+1,day:f.getUTCDate(),hour:f.getUTCHours(),minute:f.getUTCMinutes(),second:f.getUTCSeconds(),millisecond:f.getUTCMilliseconds()}}function Pr(m,s,f){return di(Fr(m),s,f)}function hi(m,s){const f=m.o,g=m.c.year+Math.trunc(s.years),w=m.c.month+Math.trunc(s.months)+Math.trunc(s.quarters)*3,I={...m.c,year:g,month:w,day:Math.min(m.c.day,$r(g,w))+Math.trunc(s.days)+Math.trunc(s.weeks)*7},A=Ae.fromObject({years:s.years-Math.trunc(s.years),quarters:s.quarters-Math.trunc(s.quarters),months:s.months-Math.trunc(s.months),weeks:s.weeks-Math.trunc(s.weeks),days:s.days-Math.trunc(s.days),hours:s.hours,minutes:s.minutes,seconds:s.seconds,milliseconds:s.milliseconds}).as("milliseconds"),L=Fr(I);let[N,X]=di(L,f,m.zone);return A!==0&&(N+=A,X=m.zone.offset(N)),{ts:N,o:X}}function Mn(m,s,f,g,w,I){const{setZone:A,zone:L}=f;if(m&&Object.keys(m).length!==0||s){const N=s||L,X=ke.fromObject(m,{...f,zone:N,specificOffset:I});return A?X:X.setZone(L)}else return ke.invalid(new ut("unparsable",`the input "${w}" can't be parsed as ${g}`))}function zr(m,s,f=!0){return m.isValid?ft.create(fe.create("en-US"),{allowZ:f,forceSimple:!0}).formatDateTimeFromString(m,s):null}function Ss(m,s,f){const g=m.c.year>9999||m.c.year<0;let w="";if(g&&m.c.year>=0&&(w+="+"),w+=ot(m.c.year,g?6:4),f==="year")return w;if(s){if(w+="-",w+=ot(m.c.month),f==="month")return w;w+="-"}else if(w+=ot(m.c.month),f==="month")return w;return w+=ot(m.c.day),w}function fi(m,s,f,g,w,I,A){let L=!f||m.c.millisecond!==0||m.c.second!==0,N="";switch(A){case"day":case"month":case"year":break;default:if(N+=ot(m.c.hour),A==="hour")break;if(s){if(N+=":",N+=ot(m.c.minute),A==="minute")break;L&&(N+=":",N+=ot(m.c.second))}else{if(N+=ot(m.c.minute),A==="minute")break;L&&(N+=ot(m.c.second))}if(A==="second")break;L&&(!g||m.c.millisecond!==0)&&(N+=".",N+=ot(m.c.millisecond,3))}return w&&(m.isOffsetFixed&&m.offset===0&&!I?N+="Z":m.o<0?(N+="-",N+=ot(Math.trunc(-m.o/60)),N+=":",N+=ot(Math.trunc(-m.o%60))):(N+="+",N+=ot(Math.trunc(m.o/60)),N+=":",N+=ot(Math.trunc(m.o%60)))),I&&(N+="["+m.zone.ianaName+"]"),N}const mi={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ru={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Lu={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Wr=["year","month","day","hour","minute","second","millisecond"],_u=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Nu=["year","ordinal","hour","minute","second","millisecond"];function qr(m){const s={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[m.toLowerCase()];if(!s)throw new l(m);return s}function pi(m){switch(m.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return qr(m)}}function Pu(m){if(Kn===void 0&&(Kn=Ne.now()),m.type!=="iana")return m.offset(Kn);const s=m.name;let f=ks.get(s);return f===void 0&&(f=m.offset(Kn),ks.set(s,f)),f}function gi(m,s){const f=ct(s.zone,Ne.defaultZone);if(!f.isValid)return ke.invalid(Yn(f));const g=fe.fromObject(s);let w,I;if(ee(m.year))w=Ne.now();else{for(const N of Wr)ee(m[N])&&(m[N]=mi[N]);const A=le(m)||ve(m);if(A)return ke.invalid(A);const L=Pu(f);[w,I]=Pr(m,L,f)}return new ke({ts:w,zone:f,loc:g,o:I})}function yi(m,s,f){const g=ee(f.round)?!0:f.round,w=ee(f.rounding)?"trunc":f.rounding,I=(L,N)=>(L=fs(L,g||f.calendary?0:2,f.calendary?"round":w),s.loc.clone(f).relFormatter(f).format(L,N)),A=L=>f.calendary?s.hasSame(m,L)?0:s.startOf(L).diff(m.startOf(L),L).get(L):s.diff(m,L).get(L);if(f.unit)return I(A(f.unit),f.unit);for(const L of f.units){const N=A(L);if(Math.abs(N)>=1)return I(N,L)}return I(m>s?-0:0,f.units[f.units.length-1])}function xi(m){let s={},f;return m.length>0&&typeof m[m.length-1]=="object"?(s=m[m.length-1],f=Array.from(m).slice(0,m.length-1)):f=Array.from(m),[s,f]}let Kn;const ks=new Map;class ke{constructor(s){const f=s.zone||Ne.defaultZone;let g=s.invalid||(Number.isNaN(s.ts)?new ut("invalid input"):null)||(f.isValid?null:Yn(f));this.ts=ee(s.ts)?Ne.now():s.ts;let w=null,I=null;if(!g)if(s.old&&s.old.ts===this.ts&&s.old.zone.equals(f))[w,I]=[s.old.c,s.old.o];else{const L=qe(s.o)&&!s.old?s.o:f.offset(this.ts);w=Nr(this.ts,L),g=Number.isNaN(w.year)?new ut("invalid input"):null,w=g?null:w,I=g?null:L}this._zone=f,this.loc=s.loc||fe.create(),this.invalid=g,this.weekData=null,this.localWeekData=null,this.c=w,this.o=I,this.isLuxonDateTime=!0}static now(){return new ke({})}static local(){const[s,f]=xi(arguments),[g,w,I,A,L,N,X]=f;return gi({year:g,month:w,day:I,hour:A,minute:L,second:N,millisecond:X},s)}static utc(){const[s,f]=xi(arguments),[g,w,I,A,L,N,X]=f;return s.zone=ze.utcInstance,gi({year:g,month:w,day:I,hour:A,minute:L,second:N,millisecond:X},s)}static fromJSDate(s,f={}){const g=vn(s)?s.valueOf():NaN;if(Number.isNaN(g))return ke.invalid("invalid input");const w=ct(f.zone,Ne.defaultZone);return w.isValid?new ke({ts:g,zone:w,loc:fe.fromObject(f)}):ke.invalid(Yn(w))}static fromMillis(s,f={}){if(qe(s))return s<-ui||s>ui?ke.invalid("Timestamp out of range"):new ke({ts:s,zone:ct(f.zone,Ne.defaultZone),loc:fe.fromObject(f)});throw new a(`fromMillis requires a numerical input, but received a ${typeof s} with value ${s}`)}static fromSeconds(s,f={}){if(qe(s))return new ke({ts:s*1e3,zone:ct(f.zone,Ne.defaultZone),loc:fe.fromObject(f)});throw new a("fromSeconds requires a numerical input")}static fromObject(s,f={}){s=s||{};const g=ct(f.zone,Ne.defaultZone);if(!g.isValid)return ke.invalid(Yn(g));const w=fe.fromObject(f),I=Rr(s,pi),{minDaysInFirstWeek:A,startOfWeek:L}=nn(I,w),N=Ne.now(),X=ee(f.specificOffset)?g.offset(N):f.specificOffset,xe=!ee(I.ordinal),Te=!ee(I.year),Be=!ee(I.month)||!ee(I.day),Se=Te||Be,it=I.weekYear||I.weekNumber;if((Se||xe)&&it)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(Be&&xe)throw new i("Can't mix ordinal dates with month/day");const Lt=it||I.weekday&&!Se;let Wt,En,Zn=Nr(N,X);Lt?(Wt=_u,En=Ru,Zn=Xe(Zn,A,L)):xe?(Wt=Nu,En=Lu,Zn=tn(Zn)):(Wt=Wr,En=mi);let vi=!1;for(const Jn of Wt){const Hu=I[Jn];ee(Hu)?vi?I[Jn]=En[Jn]:I[Jn]=Zn[Jn]:vi=!0}const Wu=Lt?G(I,A,L):xe?U(I):le(I),bi=Wu||ve(I);if(bi)return ke.invalid(bi);const qu=Lt?At(I,A,L):xe?Zt(I):I,[Bu,Vu]=Pr(qu,X,g),Xn=new ke({ts:Bu,zone:g,o:Vu,loc:w});return I.weekday&&Se&&s.weekday!==Xn.weekday?ke.invalid("mismatched weekday",`you can't specify both a weekday of ${I.weekday} and a date of ${Xn.toISO()}`):Xn.isValid?Xn:ke.invalid(Xn.invalid)}static fromISO(s,f={}){const[g,w]=au(s);return Mn(g,w,f,"ISO 8601",s)}static fromRFC2822(s,f={}){const[g,w]=lu(s);return Mn(g,w,f,"RFC 2822",s)}static fromHTTP(s,f={}){const[g,w]=cu(s);return Mn(g,w,f,"HTTP",f)}static fromFormat(s,f,g={}){if(ee(s)||ee(f))throw new a("fromFormat requires an input string and a format");const{locale:w=null,numberingSystem:I=null}=g,A=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0}),[L,N,X,xe]=Au(A,s,f);return xe?ke.invalid(xe):Mn(L,N,g,`format ${f}`,s,X)}static fromString(s,f,g={}){return ke.fromFormat(s,f,g)}static fromSQL(s,f={}){const[g,w]=gu(s);return Mn(g,w,f,"SQL",s)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the DateTime is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new n(g);return new ke({invalid:g})}static isDateTime(s){return s&&s.isLuxonDateTime||!1}static parseFormatForOpts(s,f={}){const g=ci(s,fe.fromObject(f));return g?g.map(w=>w?w.val:null).join(""):null}static expandFormat(s,f={}){return ii(ft.parseFormat(s),fe.fromObject(f)).map(w=>w.val).join("")}static resetCache(){Kn=void 0,ks.clear()}get(s){return this[s]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?bs(this).weekYear:NaN}get weekNumber(){return this.isValid?bs(this).weekNumber:NaN}get weekday(){return this.isValid?bs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ws(this).weekday:NaN}get localWeekNumber(){return this.isValid?ws(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ws(this).weekYear:NaN}get ordinal(){return this.isValid?tn(this.c).ordinal:NaN}get monthShort(){return this.isValid?Gn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Gn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Gn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Gn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const s=864e5,f=6e4,g=Fr(this.c),w=this.zone.offset(g-s),I=this.zone.offset(g+s),A=this.zone.offset(g-w*f),L=this.zone.offset(g-I*f);if(A===L)return[this];const N=g-A*f,X=g-L*f,xe=Nr(N,A),Te=Nr(X,L);return xe.hour===Te.hour&&xe.minute===Te.minute&&xe.second===Te.second&&xe.millisecond===Te.millisecond?[on(this,{ts:N}),on(this,{ts:X})]:[this]}get isInLeapYear(){return qn(this.year)}get daysInMonth(){return $r(this.year,this.month)}get daysInYear(){return this.isValid?bn(this.year):NaN}get weeksInWeekYear(){return this.isValid?Bn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Bn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(s={}){const{locale:f,numberingSystem:g,calendar:w}=ft.create(this.loc.clone(s),s).resolvedOptions(this);return{locale:f,numberingSystem:g,outputCalendar:w}}toUTC(s=0,f={}){return this.setZone(ze.instance(s),f)}toLocal(){return this.setZone(Ne.defaultZone)}setZone(s,{keepLocalTime:f=!1,keepCalendarTime:g=!1}={}){if(s=ct(s,Ne.defaultZone),s.equals(this.zone))return this;if(s.isValid){let w=this.ts;if(f||g){const I=s.offset(this.ts),A=this.toObject();[w]=Pr(A,I,s)}return on(this,{ts:w,zone:s})}else return ke.invalid(Yn(s))}reconfigure({locale:s,numberingSystem:f,outputCalendar:g}={}){const w=this.loc.clone({locale:s,numberingSystem:f,outputCalendar:g});return on(this,{loc:w})}setLocale(s){return this.reconfigure({locale:s})}set(s){if(!this.isValid)return this;const f=Rr(s,pi),{minDaysInFirstWeek:g,startOfWeek:w}=nn(f,this.loc),I=!ee(f.weekYear)||!ee(f.weekNumber)||!ee(f.weekday),A=!ee(f.ordinal),L=!ee(f.year),N=!ee(f.month)||!ee(f.day),X=L||N,xe=f.weekYear||f.weekNumber;if((X||A)&&xe)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(N&&A)throw new i("Can't mix ordinal dates with month/day");let Te;I?Te=At({...Xe(this.c,g,w),...f},g,w):ee(f.ordinal)?(Te={...this.toObject(),...f},ee(f.day)&&(Te.day=Math.min($r(Te.year,Te.month),Te.day))):Te=Zt({...tn(this.c),...f});const[Be,Se]=Pr(Te,this.o,this.zone);return on(this,{ts:Be,o:Se})}plus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s);return on(this,hi(this,f))}minus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s).negate();return on(this,hi(this,f))}startOf(s,{useLocaleWeeks:f=!1}={}){if(!this.isValid)return this;const g={},w=Ae.normalizeUnit(s);switch(w){case"years":g.month=1;case"quarters":case"months":g.day=1;case"weeks":case"days":g.hour=0;case"hours":g.minute=0;case"minutes":g.second=0;case"seconds":g.millisecond=0;break}if(w==="weeks")if(f){const I=this.loc.getStartOfWeek(),{weekday:A}=this;A<I&&(g.weekNumber=this.weekNumber-1),g.weekday=I}else g.weekday=1;if(w==="quarters"){const I=Math.ceil(this.month/3);g.month=(I-1)*3+1}return this.set(g)}endOf(s,f){return this.isValid?this.plus({[s]:1}).startOf(s,f).minus(1):this}toFormat(s,f={}){return this.isValid?ft.create(this.loc.redefaultToEN(f)).formatDateTimeFromString(this,s):vs}toLocaleString(s=b,f={}){return this.isValid?ft.create(this.loc.clone(f),s).formatDateTime(this):vs}toLocaleParts(s={}){return this.isValid?ft.create(this.loc.clone(s),s).formatDateTimeParts(this):[]}toISO({format:s="extended",suppressSeconds:f=!1,suppressMilliseconds:g=!1,includeOffset:w=!0,extendedZone:I=!1,precision:A="milliseconds"}={}){if(!this.isValid)return null;A=qr(A);const L=s==="extended";let N=Ss(this,L,A);return Wr.indexOf(A)>=3&&(N+="T"),N+=fi(this,L,f,g,w,I,A),N}toISODate({format:s="extended",precision:f="day"}={}){return this.isValid?Ss(this,s==="extended",qr(f)):null}toISOWeekDate(){return zr(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:s=!1,suppressSeconds:f=!1,includeOffset:g=!0,includePrefix:w=!1,extendedZone:I=!1,format:A="extended",precision:L="milliseconds"}={}){return this.isValid?(L=qr(L),(w&&Wr.indexOf(L)>=3?"T":"")+fi(this,A==="extended",f,s,g,I,L)):null}toRFC2822(){return zr(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return zr(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Ss(this,!0):null}toSQLTime({includeOffset:s=!0,includeZone:f=!1,includeOffsetSpace:g=!0}={}){let w="HH:mm:ss.SSS";return(f||s)&&(g&&(w+=" "),f?w+="z":s&&(w+="ZZ")),zr(this,w,!0)}toSQL(s={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(s)}`:null}toString(){return this.isValid?this.toISO():vs}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(s={}){if(!this.isValid)return{};const f={...this.c};return s.includeConfig&&(f.outputCalendar=this.outputCalendar,f.numberingSystem=this.loc.numberingSystem,f.locale=this.loc.locale),f}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(s,f="milliseconds",g={}){if(!this.isValid||!s.isValid)return Ae.invalid("created by diffing an invalid DateTime");const w={locale:this.locale,numberingSystem:this.numberingSystem,...g},I=Dr(f).map(Ae.normalizeUnit),A=s.valueOf()>this.valueOf(),L=A?this:s,N=A?s:this,X=Su(L,N,I,w);return A?X.negate():X}diffNow(s="milliseconds",f={}){return this.diff(ke.now(),s,f)}until(s){return this.isValid?Je.fromDateTimes(this,s):this}hasSame(s,f,g){if(!this.isValid)return!1;const w=s.valueOf(),I=this.setZone(s.zone,{keepLocalTime:!0});return I.startOf(f,g)<=w&&w<=I.endOf(f,g)}equals(s){return this.isValid&&s.isValid&&this.valueOf()===s.valueOf()&&this.zone.equals(s.zone)&&this.loc.equals(s.loc)}toRelative(s={}){if(!this.isValid)return null;const f=s.base||ke.fromObject({},{zone:this.zone}),g=s.padding?this<f?-s.padding:s.padding:0;let w=["years","months","days","hours","minutes","seconds"],I=s.unit;return Array.isArray(s.unit)&&(w=s.unit,I=void 0),yi(f,this.plus(g),{...s,numeric:"always",units:w,unit:I})}toRelativeCalendar(s={}){return this.isValid?yi(s.base||ke.fromObject({},{zone:this.zone}),this,{...s,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...s){if(!s.every(ke.isDateTime))throw new a("min requires all arguments be DateTimes");return $e(s,f=>f.valueOf(),Math.min)}static max(...s){if(!s.every(ke.isDateTime))throw new a("max requires all arguments be DateTimes");return $e(s,f=>f.valueOf(),Math.max)}static fromFormatExplain(s,f,g={}){const{locale:w=null,numberingSystem:I=null}=g,A=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});return li(A,s,f)}static fromStringExplain(s,f,g={}){return ke.fromFormatExplain(s,f,g)}static buildFormatParser(s,f={}){const{locale:g=null,numberingSystem:w=null}=f,I=fe.fromOpts({locale:g,numberingSystem:w,defaultToEN:!0});return new ai(I,s)}static fromFormatParser(s,f,g={}){if(ee(s)||ee(f))throw new a("fromFormatParser requires an input string and a format parser");const{locale:w=null,numberingSystem:I=null}=g,A=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});if(!A.equals(f.locale))throw new a(`fromFormatParser called with a locale of ${A}, but the format parser was created for ${f.locale}`);const{result:L,zone:N,specificOffset:X,invalidReason:xe}=f.explainFromTokens(s);return xe?ke.invalid(xe):Mn(L,N,g,`format ${f.format}`,s,X)}static get DATE_SHORT(){return b}static get DATE_MED(){return x}static get DATE_MED_WITH_WEEKDAY(){return v}static get DATE_FULL(){return k}static get DATE_HUGE(){return C}static get TIME_SIMPLE(){return S}static get TIME_WITH_SECONDS(){return T}static get TIME_WITH_SHORT_OFFSET(){return O}static get TIME_WITH_LONG_OFFSET(){return M}static get TIME_24_SIMPLE(){return E}static get TIME_24_WITH_SECONDS(){return R}static get TIME_24_WITH_SHORT_OFFSET(){return P}static get TIME_24_WITH_LONG_OFFSET(){return F}static get DATETIME_SHORT(){return B}static get DATETIME_SHORT_WITH_SECONDS(){return D}static get DATETIME_MED(){return _}static get DATETIME_MED_WITH_SECONDS(){return V}static get DATETIME_MED_WITH_WEEKDAY(){return $}static get DATETIME_FULL(){return W}static get DATETIME_FULL_WITH_SECONDS(){return Z}static get DATETIME_HUGE(){return ne}static get DATETIME_HUGE_WITH_SECONDS(){return J}}function Qn(m){if(ke.isDateTime(m))return m;if(m&&m.valueOf&&qe(m.valueOf()))return ke.fromJSDate(m);if(m&&typeof m=="object")return ke.fromObject(m);throw new a(`Unknown datetime argument: ${m}, of type ${typeof m}`)}const zu="3.7.2";return bt.DateTime=ke,bt.Duration=Ae,bt.FixedOffsetZone=ze,bt.IANAZone=ue,bt.Info=Gn,bt.Interval=Je,bt.InvalidZone=lt,bt.Settings=Ne,bt.SystemZone=re,bt.VERSION=zu,bt.Zone=H,bt}var Zi;function lo(){return Zi||(Zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronDate=e.DAYS_IN_MONTH=e.DateMathOp=e.TimeUnit=void 0;const n=yf();var r;(function(l){l.Second="Second",l.Minute="Minute",l.Hour="Hour",l.Day="Day",l.Month="Month",l.Year="Year"})(r||(e.TimeUnit=r={}));var o;(function(l){l.Add="Add",l.Subtract="Subtract"})(o||(e.DateMathOp=o={})),e.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);class i{#e;#n=null;#o=null;constructor(a,u){const d={zone:u};if(a?a instanceof i?(this.#e=a.#e,this.#n=a.#n,this.#o=a.#o):a instanceof Date?this.#e=n.DateTime.fromJSDate(a,d):typeof a=="number"?this.#e=n.DateTime.fromMillis(a,d):(this.#e=n.DateTime.fromISO(a,d),this.#e.isValid||(this.#e=n.DateTime.fromRFC2822(a,d)),this.#e.isValid||(this.#e=n.DateTime.fromSQL(a,d)),this.#e.isValid||(this.#e=n.DateTime.fromFormat(a,"EEE, d MMM yyyy HH:mm:ss",d))):this.#e=n.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${a}`);u&&u!==this.#e.zoneName&&(this.#e=this.#e.setZone(u))}static#s(a){return a%4===0&&a%100!==0||a%400===0}get dstStart(){return this.#n}set dstStart(a){this.#n=a}get dstEnd(){return this.#o}set dstEnd(a){this.#o=a}addYear(){this.#e=this.#e.plus({years:1})}addMonth(){this.#e=this.#e.plus({months:1}).startOf("month")}addDay(){this.#e=this.#e.plus({days:1}).startOf("day")}addHour(){this.#e=this.#e.plus({hours:1}).startOf("hour")}addMinute(){this.#e=this.#e.plus({minutes:1}).startOf("minute")}addSecond(){this.#e=this.#e.plus({seconds:1})}subtractYear(){this.#e=this.#e.minus({years:1})}subtractMonth(){this.#e=this.#e.minus({months:1}).endOf("month").startOf("second")}subtractDay(){this.#e=this.#e.minus({days:1}).endOf("day").startOf("second")}subtractHour(){this.#e=this.#e.minus({hours:1}).endOf("hour").startOf("second")}subtractMinute(){this.#e=this.#e.minus({minutes:1}).endOf("minute").startOf("second")}subtractSecond(){this.#e=this.#e.minus({seconds:1})}addUnit(a){switch(a){case r.Year:return this.addYear();case r.Month:return this.addMonth();case r.Day:return this.addDay();case r.Hour:return this.addHour();case r.Minute:return this.addMinute();case r.Second:return this.addSecond()}}subtractUnit(a){switch(a){case r.Year:return this.subtractYear();case r.Month:return this.subtractMonth();case r.Day:return this.subtractDay();case r.Hour:return this.subtractHour();case r.Minute:return this.subtractMinute();case r.Second:return this.subtractSecond()}}invokeDateOperation(a,u){if(a===o.Add){this.addUnit(u);return}if(a===o.Subtract){this.subtractUnit(u);return}throw new Error(`Invalid verb: ${a}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const a=this.#e.weekday;return a===7?0:a}getMonth(){return this.#e.month-1}getHours(){return this.#e.hour}getMinutes(){return this.#e.minute}getSeconds(){return this.#e.second}getMilliseconds(){return this.#e.millisecond}getUTCOffset(){return this.#e.offset}setStartOfDay(){this.#e=this.#e.startOf("day")}setEndOfDay(){this.#e=this.#e.endOf("day")}getTime(){return this.#e.valueOf()}getUTCDate(){return this.#r().day}getUTCFullYear(){return this.#r().year}getUTCDay(){const a=this.#r().weekday;return a===7?0:a}getUTCMonth(){return this.#r().month-1}getUTCHours(){return this.#r().hour}getUTCMinutes(){return this.#r().minute}getUTCSeconds(){return this.#r().second}toISOString(){return this.#e.toUTC().toISO()}toJSON(){return this.#e.toJSON()}setDate(a){this.#e=this.#e.set({day:a})}setFullYear(a){this.#e=this.#e.set({year:a})}setDay(a){this.#e=this.#e.set({weekday:a})}setMonth(a){this.#e=this.#e.set({month:a+1})}setHours(a){this.#e=this.#e.set({hour:a})}setMinutes(a){this.#e=this.#e.set({minute:a})}setSeconds(a){this.#e=this.#e.set({second:a})}setMilliseconds(a){this.#e=this.#e.set({millisecond:a})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:a,month:u}=this.#e;if(u===2){const d=i.#s(this.#e.year);return a===e.DAYS_IN_MONTH[u-1]-(d?0:1)}return a===e.DAYS_IN_MONTH[u-1]}isLastWeekdayOfMonth(){const{day:a,month:u}=this.#e;let d;return u===2?d=e.DAYS_IN_MONTH[u-1]-(i.#s(this.#e.year)?0:1):d=e.DAYS_IN_MONTH[u-1],a>d-7}applyDateOperation(a,u,d){if(u===r.Month||u===r.Day){this.invokeDateOperation(a,u);return}const h=this.getHours();this.invokeDateOperation(a,u);const y=this.getHours(),b=y-h;b===2?d!==24&&(this.dstStart=h+1):b===0&&this.getMinutes()===0&&this.getSeconds()===0&&d!==24&&(this.dstEnd=y)}#r(){return this.#e.toUTC()}}e.CronDate=i,e.default=i})(Es)),Es}var Xi;function xf(){if(Xi)return ar;Xi=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.CronMonth=void 0;const e=lo(),n=mn(),r=1,o=12,i=Object.freeze([]);let l=class extends n.CronField{static get min(){return r}static get max(){return o}static get chars(){return i}static get daysInMonth(){return e.DAYS_IN_MONTH}constructor(u,d){super(u,d),this.validate()}get values(){return super.values}};return ar.CronMonth=l,ar}var lr={},Ji;function vf(){if(Ji)return lr;Ji=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.CronSecond=void 0;const e=mn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return lr.CronSecond=i,lr}var ea;function co(){return ea||(ea=1,(function(e){var n=ln&&ln.__createBinding||(Object.create?(function(o,i,l,a){a===void 0&&(a=l);var u=Object.getOwnPropertyDescriptor(i,l);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[l]}}),Object.defineProperty(o,a,u)}):(function(o,i,l,a){a===void 0&&(a=l),o[a]=i[l]})),r=ln&&ln.__exportStar||function(o,i){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(i,l)&&n(i,o,l)};Object.defineProperty(e,"__esModule",{value:!0}),r(hf(),e),r(ff(),e),r(mf(),e),r(mn(),e),r(pf(),e),r(gf(),e),r(xf(),e),r(vf(),e)})(ln)),ln}var ta;function al(){if(ta)return tr;ta=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.CronFieldCollection=void 0;const e=co();let n=class gr{#e;#n;#o;#s;#r;#t;static from(o,i){return new gr({second:this.resolveField(e.CronSecond,o.second,i.second),minute:this.resolveField(e.CronMinute,o.minute,i.minute),hour:this.resolveField(e.CronHour,o.hour,i.hour),dayOfMonth:this.resolveField(e.CronDayOfMonth,o.dayOfMonth,i.dayOfMonth),month:this.resolveField(e.CronMonth,o.month,i.month),dayOfWeek:this.resolveField(e.CronDayOfWeek,o.dayOfWeek,i.dayOfWeek)})}static resolveField(o,i,l){return l?l instanceof e.CronField?l:new o(l):i}constructor({second:o,minute:i,hour:l,dayOfMonth:a,month:u,dayOfWeek:d}){if(!o)throw new Error("Validation error, Field second is missing");if(!i)throw new Error("Validation error, Field minute is missing");if(!l)throw new Error("Validation error, Field hour is missing");if(!a)throw new Error("Validation error, Field dayOfMonth is missing");if(!u)throw new Error("Validation error, Field month is missing");if(!d)throw new Error("Validation error, Field dayOfWeek is missing");if(u.values.length===1&&!a.hasLastChar&&d.isWildcard&&!(parseInt(a.values[0],10)<=e.CronMonth.daysInMonth[u.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=o,this.#n=i,this.#o=l,this.#r=u,this.#t=d,this.#s=a}get second(){return this.#e}get minute(){return this.#n}get hour(){return this.#o}get dayOfMonth(){return this.#s}get month(){return this.#r}get dayOfWeek(){return this.#t}static compactField(o){if(o.length===0)return[];const i=[];let l;return o.forEach((a,u,d)=>{if(l===void 0){l={start:a,count:1};return}const h=d[u-1]||l.start,y=d[u+1];if(a==="L"||a==="W"){i.push(l),i.push({start:a,count:1}),l=void 0;return}if(l.step===void 0&&y!==void 0){const b=a-h,x=y-a;if(b<=x){l={...l,count:2,end:a,step:b};return}l.step=1}a-(l.end??0)===l.step?(l.count++,l.end=a):(l.count===1?i.push({start:l.start,count:1}):l.count===2?(i.push({start:l.start,count:1}),i.push({start:l.end??h,count:1})):i.push(l),l={start:a,count:1})}),l&&i.push(l),i}static#c(o,i,l){const a=i.step;return a?a===1&&i.start===o.min&&i.end&&i.end>=l?o.hasQuestionMarkChar?"?":"*":a!==1&&i.start===o.min&&i.end&&i.end>=l-a+1?`*/${a}`:null:null}static#l(o,i){const l=o.step;if(l===1)return`${o.start}-${o.end}`;const a=o.start===0?o.count-1:o.count;if(!l)throw new Error("Unexpected range step");if(!o.end)throw new Error("Unexpected range end");if(l*a>o.end){const u=(h,y)=>{if(typeof o.start!="number")throw new Error("Unexpected range start");return y%l===0?o.start+y:null};if(typeof o.start!="number")throw new Error("Unexpected range start");const d={length:o.end-o.start+1};return Array.from(d,u).filter(h=>h!==null).join(",")}return o.end===i-l+1?`${o.start}/${l}`:`${o.start}-${o.end}/${l}`}stringifyField(o){let i=o.max,l=o.values;if(o instanceof e.CronDayOfWeek){i=6;const u=this.#t.values;l=u[u.length-1]===7?u.slice(0,-1):u}o instanceof e.CronDayOfMonth&&(i=this.#r.values.length===1?e.CronMonth.daysInMonth[this.#r.values[0]-1]:o.max);const a=gr.compactField(l);if(a.length===1){const u=gr.#c(o,a[0],i);if(u)return u}return a.map(u=>{const d=u.count===1?u.start.toString():gr.#l(u,i);return o instanceof e.CronDayOfWeek&&o.nthDay>0?`${d}#${o.nthDay}`:d}).join(",")}stringify(o=!1){const i=[];return o&&i.push(this.stringifyField(this.#e)),i.push(this.stringifyField(this.#n),this.stringifyField(this.#o),this.stringifyField(this.#s),this.stringifyField(this.#r),this.stringifyField(this.#t)),i.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#n.serialize(),hour:this.#o.serialize(),dayOfMonth:this.#s.serialize(),month:this.#r.serialize(),dayOfWeek:this.#t.serialize()}}};return tr.CronFieldCollection=n,tr}var Is={},na;function ll(){return na||(na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronExpression=e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;const n=lo();e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range",e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";const r=1e4;class o{#e;#n;#o;#s;#r;#t;#c=null;#l=!1;constructor(l,a){this.#e=a,this.#n=a.tz,this.#s=a.startDate?new n.CronDate(a.startDate,this.#n):null,this.#r=a.endDate?new n.CronDate(a.endDate,this.#n):null;let u=a.currentDate??a.startDate;if(u){const d=new n.CronDate(u,this.#n);this.#s&&d.getTime()<this.#s.getTime()?u=this.#s:this.#r&&d.getTime()>this.#r.getTime()&&(u=this.#r)}this.#o=new n.CronDate(u,this.#n),this.#t=l}get fields(){return this.#t}static fieldsToExpression(l,a){return new o(l,a||{})}static#i(l,a){return a.some(u=>u===l)}#a(l,a){return l[a?l.length-1:0]}#d(l){const a=`${l.getFullYear()}-${l.getMonth()+1}-${l.getDate()}`;if(this.#c===a)return this.#l;const u=new n.CronDate(l);u.setStartOfDay();const d=new n.CronDate(l);return d.setEndOfDay(),this.#c=a,this.#l=u.getUTCOffset()!==d.getUTCOffset(),this.#l}#h(l,a,u){const d=this.#t.second.values,h=l.getSeconds(),y=this.#t.second.findNearestValue(h,u);if(y!==null){l.setSeconds(y);return}l.applyDateOperation(a,n.TimeUnit.Minute,this.#t.hour.values.length),l.setSeconds(this.#a(d,u))}#m(l,a,u){const d=this.#t.minute.values,h=this.#t.second.values,y=l.getMinutes(),b=this.#t.minute.findNearestValue(y,u);if(b!==null){l.setMinutes(b),l.setSeconds(this.#a(h,u));return}l.applyDateOperation(a,n.TimeUnit.Hour,this.#t.hour.values.length),l.setMinutes(this.#a(d,u)),l.setSeconds(this.#a(h,u))}static#p(l,a){const u=a.isLastWeekdayOfMonth();return l.some(d=>{const h=parseInt(d.toString().charAt(0),10)%7;if(Number.isNaN(h))throw new Error(`Invalid last weekday of the month expression: ${d}`);return a.getDay()===h&&u})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const l=this.#o;try{return this.#u(),!0}catch{return!1}finally{this.#o=l}}hasPrev(){const l=this.#o;try{return this.#u(!0),!0}catch{return!1}finally{this.#o=l}}take(l){const a=[];if(l>=0)for(let u=0;u<l;u++)try{a.push(this.next())}catch{return a}else for(let u=0;u>l;u--)try{a.push(this.prev())}catch{return a}return a}reset(l){this.#o=new n.CronDate(l||this.#e.currentDate,this.#n)}stringify(l=!1){return this.#t.stringify(l)}includesDate(l){const{second:a,minute:u,hour:d,month:h}=this.#t,y=new n.CronDate(l,this.#n);return!(!a.values.includes(y.getSeconds())||!u.values.includes(y.getMinutes())||!d.values.includes(y.getHours())||!h.values.includes(y.getMonth()+1)||!this.#f(y)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(y.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(l){const a=this.#t.dayOfMonth.isWildcard,u=!a,d=this.#t.dayOfWeek.isWildcard,h=!d,y=o.#i(l.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&l.isLastDayOfMonth(),b=o.#i(l.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&o.#p(this.#t.dayOfWeek.values,l);return!!(u&&h&&(y||b)||y&&!h||a&&!d&&b)}#g(l,a,u){const d=this.#t.hour.values,h=d,y=l.getHours(),b=o.#i(y,d),x=l.dstEnd===y;if(l.dstStart!==null&&l.dstStart===y-1&&o.#i(l.dstStart,d))return!0;if(x&&!u)return l.dstEnd=null,l.applyDateOperation(n.DateMathOp.Add,n.TimeUnit.Hour,h.length),!1;if(b)return!0;l.dstStart=null;const v=this.#t.hour.findNearestValue(y,u);if(v===null)return l.applyDateOperation(a,n.TimeUnit.Day,h.length),!1;if(this.#d(l)){const k=u?y-v:v-y;for(let C=0;C<k&&(l.applyDateOperation(a,n.TimeUnit.Hour,h.length),!(!u&&l.getHours()>=v||u&&l.getHours()<=v));C++);}else l.setHours(v);return l.setMinutes(this.#a(this.#t.minute.values,u)),l.setSeconds(this.#a(this.#t.second.values,u)),!1}#y(l){if(!this.#s&&!this.#r)return;const a=l.getTime();if(this.#s&&a<this.#s.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&a>this.#r.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(l=!1){const a=l?n.DateMathOp.Subtract:n.DateMathOp.Add,u=new n.CronDate(this.#o),d=u.getTime();let h=0;for(;++h<r;){if(this.#y(u),!this.#f(u)){u.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(u.getDate()/7)===this.#t.dayOfWeek.nthDay)){u.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!o.#i(u.getMonth()+1,this.#t.month.values)){u.applyDateOperation(a,n.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#g(u,a,l)){if(!o.#i(u.getMinutes(),this.#t.minute.values)){this.#m(u,a,l);continue}if(!o.#i(u.getSeconds(),this.#t.second.values)){this.#h(u,a,l);continue}if(d===u.getTime()){(a==="Add"||u.getMilliseconds()===0)&&u.applyDateOperation(a,n.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(h>r)throw new Error(e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return u.getMilliseconds()!==0&&u.setMilliseconds(0),this.#o=u,u}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}e.CronExpression=o,e.default=o})(Is)),Is}var Br={},ra;function bf(){if(ra)return Br;ra=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.seededRandom=r;function e(o){let i=2166136261;for(let l=0;l<o.length;l++)i^=o.charCodeAt(l),i=Math.imul(i,16777619);return()=>i>>>0}function n(o){return()=>{let i=o+=1831565813;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}function r(o){const i=o?e(o)():Math.floor(Math.random()*1e10);return n(i)}return Br}var sa;function Qs(){if(sa)return jt;sa=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.CronExpressionParser=jt.DayOfWeek=jt.Months=jt.CronUnit=jt.PredefinedExpressions=void 0;const e=al(),n=ll(),r=bf(),o=co();var i;(function(h){h["@yearly"]="0 0 0 1 1 *",h["@annually"]="0 0 0 1 1 *",h["@monthly"]="0 0 0 1 * *",h["@weekly"]="0 0 0 * * 0",h["@daily"]="0 0 0 * * *",h["@hourly"]="0 0 * * * *",h["@minutely"]="0 * * * * *",h["@secondly"]="* * * * * *",h["@weekdays"]="0 0 0 * * 1-5",h["@weekends"]="0 0 0 * * 0,6"})(i||(jt.PredefinedExpressions=i={}));var l;(function(h){h.Second="Second",h.Minute="Minute",h.Hour="Hour",h.DayOfMonth="DayOfMonth",h.Month="Month",h.DayOfWeek="DayOfWeek"})(l||(jt.CronUnit=l={}));var a;(function(h){h[h.jan=1]="jan",h[h.feb=2]="feb",h[h.mar=3]="mar",h[h.apr=4]="apr",h[h.may=5]="may",h[h.jun=6]="jun",h[h.jul=7]="jul",h[h.aug=8]="aug",h[h.sep=9]="sep",h[h.oct=10]="oct",h[h.nov=11]="nov",h[h.dec=12]="dec"})(a||(jt.Months=a={}));var u;(function(h){h[h.sun=0]="sun",h[h.mon=1]="mon",h[h.tue=2]="tue",h[h.wed=3]="wed",h[h.thu=4]="thu",h[h.fri=5]="fri",h[h.sat=6]="sat"})(u||(jt.DayOfWeek=u={}));let d=class Tt{static parse(y,b={}){const{strict:x=!1,hashSeed:v}=b,k=(0,r.seededRandom)(v);y=i[y]||y;const C=Tt.#e(y,x);if(!(C.dayOfMonth==="*"||C.dayOfWeek==="*"||!x))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const S=Tt.#n(l.Second,C.second,o.CronSecond.constraints,k),T=Tt.#n(l.Minute,C.minute,o.CronMinute.constraints,k),O=Tt.#n(l.Hour,C.hour,o.CronHour.constraints,k),M=Tt.#n(l.Month,C.month,o.CronMonth.constraints,k),E=Tt.#n(l.DayOfMonth,C.dayOfMonth,o.CronDayOfMonth.constraints,k),{dayOfWeek:R,nthDayOfWeek:P}=Tt.#d(C.dayOfWeek),F=Tt.#n(l.DayOfWeek,R,o.CronDayOfWeek.constraints,k),B=new e.CronFieldCollection({second:new o.CronSecond(S,{rawValue:C.second}),minute:new o.CronMinute(T,{rawValue:C.minute}),hour:new o.CronHour(O,{rawValue:C.hour}),dayOfMonth:new o.CronDayOfMonth(E,{rawValue:C.dayOfMonth}),month:new o.CronMonth(M,{rawValue:C.month}),dayOfWeek:new o.CronDayOfWeek(F,{rawValue:C.dayOfWeek,nthDayOfWeek:P})});return new n.CronExpression(B,{...b,expression:y})}static#e(y,b){if(b&&!y.length)throw new Error("Invalid cron expression");y=y||"0 * * * * *";const x=y.trim().split(/\s+/);if(b&&x.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(x.length>6)throw new Error("Invalid cron expression, too many fields");const v=["*","*","*","*","*","0"];x.length<v.length&&x.unshift(...v.slice(x.length));const[k,C,S,T,O,M]=x;return{second:k,minute:C,hour:S,dayOfMonth:T,month:O,dayOfWeek:M}}static#n(y,b,x,v){if((y===l.Month||y===l.DayOfWeek)&&(b=b.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const C=a[k]||u[k];if(C===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return C.toString()})),!x.validChars.test(b))throw new Error(`Invalid characters, got value: ${b}`);return b=this.#o(b,x),b=this.#s(b,x,v),this.#r(y,b,x)}static#o(y,b){return y.replace(/[*?]/g,b.min+"-"+b.max)}static#s(y,b,x){const v=x();return y.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(k,C,S,T)=>{if(C&&S&&T){const O=parseInt(C,10),M=parseInt(S,10),E=parseInt(T,10);if(O>M)throw new Error(`Invalid range: ${O}-${M}, min > max`);if(E<=0)throw new Error(`Invalid step: ${E}, must be positive`);const R=Math.max(O,b.min),P=Math.floor(v*E),F=[];for(let B=Math.floor(R/E)*E+P;B<=M;B+=E)B>=R&&F.push(B);return F.join(",")}else if(C&&S){const O=parseInt(C,10),M=parseInt(S,10);if(O>M)throw new Error(`Invalid range: ${O}-${M}, min > max`);return String(Math.floor(v*(M-O+1))+O)}else if(T){const O=parseInt(T,10);if(O<=0)throw new Error(`Invalid step: ${O}, must be positive`);const M=Math.floor(v*O),E=[];for(let R=Math.floor(b.min/O)*O+M;R<=b.max;R+=O)R>=b.min&&E.push(R);return E.join(",")}else return String(Math.floor(v*(b.max-b.min+1)+b.min))})}static#r(y,b,x){const v=[];function k(S,T){if(Array.isArray(S))v.push(...S);else if(Tt.#h(T,S))v.push(S);else{const O=parseInt(S.toString(),10);if(!(O>=T.min&&O<=T.max))throw new Error(`Constraint error, got value ${S} expected range ${T.min}-${T.max}`);v.push(y===l.DayOfWeek?O%7:S)}}return b.split(",").forEach(S=>{if(!(S.length>0))throw new Error("Invalid list value format");k(Tt.#t(y,S,x),x)}),v}static#t(y,b,x){const v=b.split("/");if(v.length>2)throw new Error(`Invalid repeat: ${b}`);return v.length===2?(v[0].includes("-")||(v[0]=`${v[0]}-${x.max}`),Tt.#a(y,v[0],parseInt(v[1],10),x)):Tt.#a(y,b,1,x)}static#c(y,b,x){if(!(!isNaN(y)&&!isNaN(b)&&y>=x.min&&b<=x.max))throw new Error(`Constraint error, got range ${y}-${b} expected range ${x.min}-${x.max}`);if(y>b)throw new Error(`Invalid range: ${y}-${b}, min(${y}) > max(${b})`)}static#l(y){if(!(!isNaN(y)&&y>0))throw new Error(`Constraint error, cannot repeat at every ${y} time.`)}static#i(y,b,x,v){const k=[];y===l.DayOfWeek&&x%7===0&&k.push(0);for(let C=b;C<=x;C+=v)k.indexOf(C)===-1&&k.push(C);return k}static#a(y,b,x,v){const k=b.split("-");if(k.length<=1)return isNaN(+b)?b:+b;const[C,S]=k.map(T=>parseInt(T,10));return this.#c(C,S,v),this.#l(x),this.#i(y,C,S,x)}static#d(y){const b=y.split("#");if(b.length<=1)return{dayOfWeek:b[0]};const x=+b[b.length-1],v=y.match(/([,-/])/);if(v!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${v?.[0]}\` special characters are incompatible`);if(!(b.length<=2&&!isNaN(x)&&x>=1&&x<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:b[0],nthDayOfWeek:x}}static#h(y,b){return y.chars.some(x=>b.toString().includes(x))}};return jt.CronExpressionParser=d,jt}var _t={};const wf={},Sf=Object.freeze(Object.defineProperty({__proto__:null,default:wf},Symbol.toStringTag,{value:"Module"})),oa=c.getAugmentedNamespace(Sf);var ia;function kf(){if(ia)return _t;ia=1;var e=_t&&_t.__createBinding||(Object.create?(function(l,a,u,d){d===void 0&&(d=u);var h=Object.getOwnPropertyDescriptor(a,u);(!h||("get"in h?!a.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return a[u]}}),Object.defineProperty(l,d,h)}):(function(l,a,u,d){d===void 0&&(d=u),l[d]=a[u]})),n=_t&&_t.__setModuleDefault||(Object.create?(function(l,a){Object.defineProperty(l,"default",{enumerable:!0,value:a})}):function(l,a){l.default=a}),r=_t&&_t.__importStar||(function(){var l=function(a){return l=Object.getOwnPropertyNames||function(u){var d=[];for(var h in u)Object.prototype.hasOwnProperty.call(u,h)&&(d[d.length]=h);return d},l(a)};return function(a){if(a&&a.__esModule)return a;var u={};if(a!=null)for(var d=l(a),h=0;h<d.length;h++)d[h]!=="default"&&e(u,a,d[h]);return n(u,a),u}})();Object.defineProperty(_t,"__esModule",{value:!0}),_t.CronFileParser=void 0;const o=Qs();let i=class Yr{static async parseFile(a){const{readFile:u}=await Promise.resolve().then(()=>r(oa)),d=await u(a,"utf8");return Yr.#e(d)}static parseFileSync(a){const{readFileSync:u}=oa,d=u(a,"utf8");return Yr.#e(d)}static#e(a){const u=a.split(`
7
+ `),d={variables:{},expressions:[],errors:{}};for(const h of u){const y=h.trim();if(y.length===0||y.startsWith("#"))continue;const b=y.match(/^(.*)=(.*)$/);if(b){const[,x,v]=b;d.variables[x]=v.replace(/["']/g,"");continue}try{const x=Yr.#n(y);d.expressions.push(x.interval)}catch(x){d.errors[y]=x}}return d}static#n(a){const u=a.split(" ");return{interval:o.CronExpressionParser.parse(u.slice(0,5).join(" ")),command:u.slice(5,u.length)}}};return _t.CronFileParser=i,_t}var aa;function Cf(){return aa||(aa=1,(function(e){var n=an&&an.__createBinding||(Object.create?(function(h,y,b,x){x===void 0&&(x=b);var v=Object.getOwnPropertyDescriptor(y,b);(!v||("get"in v?!y.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return y[b]}}),Object.defineProperty(h,x,v)}):(function(h,y,b,x){x===void 0&&(x=b),h[x]=y[b]})),r=an&&an.__exportStar||function(h,y){for(var b in h)b!=="default"&&!Object.prototype.hasOwnProperty.call(y,b)&&n(y,h,b)};Object.defineProperty(e,"__esModule",{value:!0}),e.CronFileParser=e.CronExpressionParser=e.CronExpression=e.CronFieldCollection=e.CronDate=void 0;const o=Qs();var i=lo();Object.defineProperty(e,"CronDate",{enumerable:!0,get:function(){return i.CronDate}});var l=al();Object.defineProperty(e,"CronFieldCollection",{enumerable:!0,get:function(){return l.CronFieldCollection}});var a=ll();Object.defineProperty(e,"CronExpression",{enumerable:!0,get:function(){return a.CronExpression}});var u=Qs();Object.defineProperty(e,"CronExpressionParser",{enumerable:!0,get:function(){return u.CronExpressionParser}});var d=kf();Object.defineProperty(e,"CronFileParser",{enumerable:!0,get:function(){return d.CronFileParser}}),r(co(),e),e.default=o.CronExpressionParser})(an)),an}var jf=Cf(),Ds={exports:{}},la;function Tf(){return la||(la=1,(function(e,n){(function(o,i){e.exports=i()})(globalThis,()=>(()=>{var r={949:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.CronParser=void 0;var h=d(515),y=(function(){function b(x,v,k){v===void 0&&(v=!0),k===void 0&&(k=!1),this.expression=x,this.dayOfWeekStartIndexZero=v,this.monthStartIndexZero=k}return b.prototype.parse=function(){var x,v,k=(x=this.expression)!==null&&x!==void 0?x:"";if(k==="@reboot")return v=["@reboot","","","","","",""],v;if(k.startsWith("@")){var C=this.parseSpecial(this.expression);v=this.extractParts(C)}else v=this.extractParts(this.expression);return this.normalize(v),this.validate(v),v},b.prototype.parseSpecial=function(x){var v={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},k=v[x];if(!k)throw new Error("Unknown special expression.");return k},b.prototype.extractParts=function(x){if(!this.expression)throw new Error("cron expression is empty");for(var v=x.trim().split(/[ ]+/),k=0;k<v.length;k++)if(v[k].includes(",")){var C=v[k].split(",").map(function(T){return T.trim()}).filter(function(T){return T!==""}).map(function(T){return isNaN(Number(T))?T:Number(T)}).filter(function(T){return T!==null&&T!==""});C.length===0&&C.push("*"),C.sort(function(T,O){return T!==null&&O!==null?T-O:0}),v[k]=C.map(function(T){return T!==null?T.toString():""}).join(",")}if(v.length<5)throw new Error("Expression has only ".concat(v.length," part").concat(v.length==1?"":"s",". At least 5 parts are required."));if(v.length==5)v.unshift(""),v.push("");else if(v.length==6){var S=/\d{4}$/.test(v[5])||v[4]=="?"||v[2]=="?";S?v.unshift(""):v.push("")}else if(v.length>7)throw new Error("Expression has ".concat(v.length," parts; too many!"));return v},b.prototype.normalize=function(x){var v=this;if(x[3]=x[3].replace("?","*"),x[5]=x[5].replace("?","*"),x[2]=x[2].replace("?","*"),x[0].indexOf("0/")==0&&(x[0]=x[0].replace("0/","*/")),x[1].indexOf("0/")==0&&(x[1]=x[1].replace("0/","*/")),x[2].indexOf("0/")==0&&(x[2]=x[2].replace("0/","*/")),x[3].indexOf("1/")==0&&(x[3]=x[3].replace("1/","*/")),x[4].indexOf("1/")==0&&(x[4]=x[4].replace("1/","*/")),x[6].indexOf("1/")==0&&(x[6]=x[6].replace("1/","*/")),x[5]=x[5].replace(/(^\d)|([^#/\s]\d)/g,function(R){var P=R.replace(/\D/,""),F=P;return v.dayOfWeekStartIndexZero?P=="7"&&(F="0"):F=(parseInt(P)-1).toString(),R.replace(P,F)}),x[5]=="L"&&(x[5]="6"),x[3]=="?"&&(x[3]="*"),x[3].indexOf("W")>-1&&(x[3].indexOf(",")>-1||x[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var k={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var C in k)x[5]=x[5].replace(new RegExp(C,"gi"),k[C].toString());x[4]=x[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(R){var P=R.replace(/\D/,""),F=P;return v.monthStartIndexZero&&(F=(parseInt(P)+1).toString()),R.replace(P,F)});var S={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var T in S)x[4]=x[4].replace(new RegExp(T,"gi"),S[T].toString());x[0]=="0"&&(x[0]=""),!/\*|\-|\,|\//.test(x[2])&&(/\*|\//.test(x[1])||/\*|\//.test(x[0]))&&(x[2]+="-".concat(x[2]));for(var O=0;O<x.length;O++)if(x[O].indexOf(",")!=-1&&(x[O]=x[O].split(",").filter(function(R){return R!==""}).join(",")||"*"),x[O]=="*/1"&&(x[O]="*"),x[O].indexOf("/")>-1&&!/^\*|\-|\,/.test(x[O])){var M=null;switch(O){case 4:M="12";break;case 5:M="6";break;case 6:M="9999";break;default:M=null;break}if(M!==null){var E=x[O].split("/");x[O]="".concat(E[0],"-").concat(M,"/").concat(E[1])}}},b.prototype.validate=function(x){var v="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(x[0],v),this.validateOnlyExpectedCharactersFound(x[1],v),this.validateOnlyExpectedCharactersFound(x[2],v),this.validateOnlyExpectedCharactersFound(x[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(x[4],v),this.validateOnlyExpectedCharactersFound(x[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(x[6],v),this.validateAnyRanges(x)},b.prototype.validateAnyRanges=function(x){h.default.secondRange(x[0]),h.default.minuteRange(x[1]),h.default.hourRange(x[2]),h.default.dayOfMonthRange(x[3]),h.default.monthRange(x[4],this.monthStartIndexZero),h.default.dayOfWeekRange(x[5],this.dayOfWeekStartIndexZero)},b.prototype.validateOnlyExpectedCharactersFound=function(x,v){var k=x.match(new RegExp("[^".concat(v,"]+"),"gi"));if(k&&k.length)throw new Error("Expression contains invalid values: '".concat(k.toString(),"'"))},b})();u.CronParser=y}),333:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ExpressionDescriptor=void 0;var h=d(823),y=d(949),b=(function(){function x(v,k){if(this.expression=v,this.options=k,this.expressionParts=new Array(5),!this.options.locale&&x.defaultLocale&&(this.options.locale=x.defaultLocale),!x.locales[this.options.locale]){var C=Object.keys(x.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(C,"'.")),this.options.locale=C}this.i18n=x.locales[this.options.locale],k.use24HourTimeFormat===void 0&&(k.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return x.toString=function(v,k){var C=k===void 0?{}:k,S=C.throwExceptionOnParseError,T=S===void 0?!0:S,O=C.verbose,M=O===void 0?!1:O,E=C.dayOfWeekStartIndexZero,R=E===void 0?!0:E,P=C.monthStartIndexZero,F=P===void 0?!1:P,B=C.use24HourTimeFormat,D=C.locale,_=D===void 0?null:D,V={throwExceptionOnParseError:T,verbose:M,dayOfWeekStartIndexZero:R,monthStartIndexZero:F,use24HourTimeFormat:B,locale:_};V.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var $=new x(v,V);return $.getFullDescription()},x.initialize=function(v,k){k===void 0&&(k="en"),x.specialCharacters=["/","-",",","*"],x.defaultLocale=k,v.load(x.locales)},x.prototype.getFullDescription=function(){var v,k,C="";try{var S=new y.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=S.parse(),this.expressionParts[0]==="@reboot")return((k=(v=this.i18n).atReboot)===null||k===void 0?void 0:k.call(v))||"Run once, at startup";var T=this.getTimeOfDayDescription(),O=this.getDayOfMonthDescription(),M=this.getMonthDescription(),E=this.getDayOfWeekDescription(),R=this.getYearDescription();C+=T+O+E+M+R,C=this.transformVerbosity(C,!!this.options.verbose),C=C.charAt(0).toLocaleUpperCase()+C.substr(1)}catch(P){if(!this.options.throwExceptionOnParseError)C=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(P)}return C},x.prototype.getTimeOfDayDescription=function(){var v=this.expressionParts[0],k=this.expressionParts[1],C=this.expressionParts[2],S="";if(!h.StringUtilities.containsAny(k,x.specialCharacters)&&!h.StringUtilities.containsAny(C,x.specialCharacters)&&!h.StringUtilities.containsAny(v,x.specialCharacters))S+=this.i18n.atSpace()+this.formatTime(C,k,v);else if(!v&&k.indexOf("-")>-1&&!(k.indexOf(",")>-1)&&!(k.indexOf("/")>-1)&&!h.StringUtilities.containsAny(C,x.specialCharacters)){var T=k.split("-");S+=h.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(C,T[0],""),this.formatTime(C,T[1],""))}else if(!v&&C.indexOf(",")>-1&&C.indexOf("-")==-1&&C.indexOf("/")==-1&&!h.StringUtilities.containsAny(k,x.specialCharacters)){var O=C.split(",");S+=this.i18n.at();for(var M=0;M<O.length;M++)S+=" ",S+=this.formatTime(O[M],k,""),M<O.length-2&&(S+=","),M==O.length-2&&(S+=this.i18n.spaceAnd())}else{var E=this.getSecondsDescription(),R=this.getMinutesDescription(),P=this.getHoursDescription();if(S+=E,S&&R&&(S+=", "),S+=R,R===P)return S;S&&P&&(S+=", "),S+=P}return S},x.prototype.getSecondsDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(C){return C},function(C){return h.StringUtilities.format(v.i18n.everyX0Seconds(C),C)},function(C){return v.i18n.secondsX0ThroughX1PastTheMinute()},function(C){return C=="0"?"":parseInt(C)<20?v.i18n.atX0SecondsPastTheMinute(C):v.i18n.atX0SecondsPastTheMinuteGt20()||v.i18n.atX0SecondsPastTheMinute(C)});return k},x.prototype.getMinutesDescription=function(){var v=this,k=this.expressionParts[0],C=this.expressionParts[2],S=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(T){return T},function(T){return h.StringUtilities.format(v.i18n.everyX0Minutes(T),T)},function(T){return v.i18n.minutesX0ThroughX1PastTheHour()},function(T){try{return T=="0"&&C.indexOf("/")==-1&&k==""?v.i18n.everyHour():parseInt(T)<20?v.i18n.atX0MinutesPastTheHour(T):v.i18n.atX0MinutesPastTheHourGt20()||v.i18n.atX0MinutesPastTheHour(T)}catch{return v.i18n.atX0MinutesPastTheHour(T)}});return S},x.prototype.getHoursDescription=function(){var v=this,k=this.expressionParts[2],C=0,S=[];k.split("/")[0].split(",").forEach(function(M){var E=M.split("-");E.length===2&&S.push({value:E[1],index:C+1}),C+=E.length});var T=0,O=this.getSegmentDescription(k,this.i18n.everyHour(),function(M){var E=S.find(function(P){return P.value===M&&P.index===T}),R=E&&v.expressionParts[1]!=="0";return T++,R?v.formatTime(M,"59",""):v.formatTime(M,"0","")},function(M){return h.StringUtilities.format(v.i18n.everyX0Hours(M),M)},function(M){return v.i18n.betweenX0AndX1()},function(M){return v.i18n.atX0()});return O},x.prototype.getDayOfWeekDescription=function(){var v=this,k=this.i18n.daysOfTheWeek(),C=null;return this.expressionParts[5]=="*"?C="":C=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(S,T){var O=S;S.indexOf("#")>-1?O=S.substring(0,S.indexOf("#")):S.indexOf("L")>-1&&(O=O.replace("L",""));var M=parseInt(O),E=v.i18n.daysOfTheWeekInCase?v.i18n.daysOfTheWeekInCase(T)[M]:k[M];if(S.indexOf("#")>-1){var R=null,P=S.substring(S.indexOf("#")+1),F=S.substring(0,S.indexOf("#"));switch(P){case"1":R=v.i18n.first(F);break;case"2":R=v.i18n.second(F);break;case"3":R=v.i18n.third(F);break;case"4":R=v.i18n.fourth(F);break;case"5":R=v.i18n.fifth(F);break}E=R+" "+E}return E},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0DaysOfTheWeek(S),S)},function(S){var T=S.substring(0,S.indexOf("-")),O=v.expressionParts[3]!="*";return O?v.i18n.commaAndX0ThroughX1(T):v.i18n.commaX0ThroughX1(T)},function(S){var T=null;if(S.indexOf("#")>-1){var O=S.substring(S.indexOf("#")+1),M=S.substring(0,S.indexOf("#"));T=v.i18n.commaOnThe(O,M).trim()+v.i18n.spaceX0OfTheMonth()}else if(S.indexOf("L")>-1)T=v.i18n.commaOnTheLastX0OfTheMonth(S.replace("L",""));else{var E=v.expressionParts[3]!="*";T=E?v.i18n.commaAndOnX0():v.i18n.commaOnlyOnX0(S)}return T}),C},x.prototype.getMonthDescription=function(){var v=this,k=this.i18n.monthsOfTheYear(),C=this.getSegmentDescription(this.expressionParts[4],"",function(S,T){return T&&v.i18n.monthsOfTheYearInCase?v.i18n.monthsOfTheYearInCase(T)[parseInt(S)-1]:k[parseInt(S)-1]},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0Months(S),S)},function(S){return v.i18n.commaMonthX0ThroughMonthX1()||v.i18n.commaX0ThroughX1()},function(S){return v.i18n.commaOnlyInMonthX0?v.i18n.commaOnlyInMonthX0():v.i18n.commaOnlyInX0()});return C},x.prototype.getDayOfMonthDescription=function(){var v=this,k=null,C=this.expressionParts[3];switch(C){case"L":k=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":k=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var S=C.match(/(\d{1,2}W)|(W\d{1,2})/);if(S){var T=parseInt(S[0].replace("W","")),O=T==1?this.i18n.firstWeekday():h.StringUtilities.format(this.i18n.weekdayNearestDayX0(),T.toString());k=h.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),O);break}else{var M=C.match(/L-(\d{1,2})/);if(M){var E=M[1];k=h.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(E),E);break}else{if(C=="*"&&this.expressionParts[5]!="*")return"";k=this.getSegmentDescription(C,this.i18n.commaEveryDay(),function(R){return R=="L"?v.i18n.lastDay():v.i18n.dayX0?h.StringUtilities.format(v.i18n.dayX0(),R):R},function(R){return R=="1"?v.i18n.commaEveryDay():v.i18n.commaEveryX0Days(R)},function(R){return v.i18n.commaBetweenDayX0AndX1OfTheMonth(R)},function(R){return v.i18n.commaOnDayX0OfTheMonth(R)})}break}}return k},x.prototype.getYearDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[6],"",function(C){return/^\d+$/.test(C)?new Date(parseInt(C),1).getFullYear().toString():C},function(C){return h.StringUtilities.format(v.i18n.commaEveryX0Years(C),C)},function(C){return v.i18n.commaYearX0ThroughYearX1()||v.i18n.commaX0ThroughX1()},function(C){return v.i18n.commaOnlyInYearX0?v.i18n.commaOnlyInYearX0():v.i18n.commaOnlyInX0()});return k},x.prototype.getSegmentDescription=function(v,k,C,S,T,O){var M=null,E=v.indexOf("/")>-1,R=v.indexOf("-")>-1,P=v.indexOf(",")>-1;if(!v)M="";else if(v==="*")M=k;else if(!E&&!R&&!P)M=h.StringUtilities.format(O(v),C(v));else if(P){for(var F=v.split(","),B="",D=0;D<F.length;D++)if(D>0&&F.length>2&&(B+=",",D<F.length-1&&(B+=" ")),D>0&&F.length>1&&(D==F.length-1||F.length==2)&&(B+="".concat(this.i18n.spaceAnd()," ")),F[D].indexOf("/")>-1||F[D].indexOf("-")>-1){var _=F[D].indexOf("-")>-1&&F[D].indexOf("/")==-1,V=this.getSegmentDescription(F[D],k,C,S,_?this.i18n.commaX0ThroughX1:T,O);_&&(V=V.replace(", ","")),B+=V}else E?B+=this.getSegmentDescription(F[D],k,C,S,T,O):B+=C(F[D]);E?M=B:M=h.StringUtilities.format(O(v),B)}else if(E){var F=v.split("/");if(M=h.StringUtilities.format(S(F[1]),F[1]),F[0].indexOf("-")>-1){var $=this.generateRangeSegmentDescription(F[0],T,C);$.indexOf(", ")!=0&&(M+=", "),M+=$}else if(F[0].indexOf("*")==-1){var W=h.StringUtilities.format(O(F[0]),C(F[0]));W=W.replace(", ",""),M+=h.StringUtilities.format(this.i18n.commaStartingX0(),W)}}else R&&(M=this.generateRangeSegmentDescription(v,T,C));return M},x.prototype.generateRangeSegmentDescription=function(v,k,C){var S="",T=v.split("-"),O=C(T[0],1),M=C(T[1],2),E=k(v);return S+=h.StringUtilities.format(E,O,M),S},x.prototype.formatTime=function(v,k,C){var S=0,T=0,O=parseInt(v)+S,M=parseInt(k)+T;M>=60?(M-=60,O+=1):M<0&&(M+=60,O-=1),O>=24?O=O-24:O<0&&(O=24+O);var E="",R=!1;this.options.use24HourTimeFormat||(R=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),E=R?"".concat(this.getPeriod(O)," "):" ".concat(this.getPeriod(O)),O>12&&(O-=12),O===0&&(O=12));var P="";return C&&(P=":".concat(("00"+C).substring(C.length))),"".concat(R?E:"").concat(("00"+O.toString()).substring(O.toString().length),":").concat(("00"+M.toString()).substring(M.toString().length)).concat(P).concat(R?"":E)},x.prototype.transformVerbosity=function(v,k){if(!k&&(v=v.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),v=v.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),v=v.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),v=v.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var C=0,S=Object.entries(this.i18n.conciseVerbosityReplacements());C<S.length;C++){var T=S[C],O=T[0],M=T[1];v=v.replace(new RegExp(O,"g"),M)}return v},x.prototype.getPeriod=function(v){return v>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},x.locales={},x})();u.ExpressionDescriptor=b}),747:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.enLocaleLoader=void 0;var h=d(486),y=(function(){function b(){}return b.prototype.load=function(x){x.en=new h.en},b})();u.enLocaleLoader=y}),486:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.en=void 0;var d=(function(){function h(){}return h.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},h.prototype.atX0MinutesPastTheHourGt20=function(){return null},h.prototype.commaMonthX0ThroughMonthX1=function(){return null},h.prototype.commaYearX0ThroughYearX1=function(){return null},h.prototype.use24HourTimeFormatByDefault=function(){return!1},h.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},h.prototype.everyMinute=function(){return"every minute"},h.prototype.everyHour=function(){return"every hour"},h.prototype.atSpace=function(){return"At "},h.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},h.prototype.at=function(){return"At"},h.prototype.spaceAnd=function(){return" and"},h.prototype.everySecond=function(){return"every second"},h.prototype.everyX0Seconds=function(){return"every %s seconds"},h.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},h.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},h.prototype.everyX0Minutes=function(){return"every %s minutes"},h.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},h.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},h.prototype.everyX0Hours=function(){return"every %s hours"},h.prototype.betweenX0AndX1=function(){return"between %s and %s"},h.prototype.atX0=function(){return"at %s"},h.prototype.commaEveryDay=function(){return", every day"},h.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},h.prototype.commaX0ThroughX1=function(){return", %s through %s"},h.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},h.prototype.first=function(){return"first"},h.prototype.second=function(){return"second"},h.prototype.third=function(){return"third"},h.prototype.fourth=function(){return"fourth"},h.prototype.fifth=function(){return"fifth"},h.prototype.commaOnThe=function(){return", on the "},h.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},h.prototype.lastDay=function(){return"the last day"},h.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},h.prototype.commaOnlyOnX0=function(){return", only on %s"},h.prototype.commaAndOnX0=function(){return", and on %s"},h.prototype.commaEveryX0Months=function(){return", every %s months"},h.prototype.commaOnlyInX0=function(){return", only in %s"},h.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},h.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},h.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},h.prototype.firstWeekday=function(){return"first weekday"},h.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},h.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},h.prototype.commaEveryX0Days=function(){return", every %s days"},h.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},h.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},h.prototype.commaEveryHour=function(){return", every hour"},h.prototype.commaEveryX0Years=function(){return", every %s years"},h.prototype.commaStartingX0=function(){return", starting %s"},h.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},h.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},h.prototype.atReboot=function(){return"Run once, at startup"},h})();u.en=d}),515:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0});function d(y,b){if(!y)throw new Error(b)}var h=(function(){function y(){}return y.secondRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=59,"seconds part must be >= 0 and <= 59")}},y.minuteRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=59,"minutes part must be >= 0 and <= 59")}},y.hourRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=23,"hours part must be >= 0 and <= 23")}},y.dayOfMonthRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=1&&k<=31,"DOM part must be >= 1 and <= 31")}},y.monthRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);d(C>=1&&C<=12,x?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},y.dayOfWeekRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);d(C>=0&&C<=6,x?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},y})();u.default=h}),823:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.StringUtilities=void 0;var d=(function(){function h(){}return h.format=function(y){for(var b=[],x=1;x<arguments.length;x++)b[x-1]=arguments[x];return y.replace(/%s/g,function(v){return b.shift()})},h.containsAny=function(y,b){return b.some(function(x){return y.indexOf(x)>-1})},h})();u.StringUtilities=d})},o={};function i(a){var u=o[a];if(u!==void 0)return u.exports;var d=o[a]={exports:{}};return r[a](d,d.exports,i),d.exports}var l={};return(()=>{var a=l;Object.defineProperty(a,"__esModule",{value:!0}),a.toString=void 0;var u=i(333),d=i(747);u.ExpressionDescriptor.initialize(new d.enLocaleLoader),a.default=u.ExpressionDescriptor;var h=u.ExpressionDescriptor.toString;a.toString=h})(),l})())})(Ds)),Ds.exports}var Of=Tf();const Mf=c.getDefaultExportFromCjs(Of),Ef=new Set(["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC","SUN","MON","TUE","WED","THU","FRI","SAT"]);function If(e){for(const n of e.trim().split(/\s+/)){if(/[#?]/.test(n))return!1;for(const r of n.split(/[,\-/]/))if(!(r===""||r==="*")&&/[A-Za-z]/.test(r)&&!Ef.has(r.toUpperCase()))return!1}return!0}function uo(e){const n=(e??"").trim();if(n.split(/\s+/).filter(Boolean).length!==5)return{valid:!1,description:"",nextRun:null,error:"Expected a 5-field UNIX cron: minute hour day-of-month month day-of-week."};if(!If(n))return{valid:!1,description:"",nextRun:null,error:"Unsupported cron syntax: L, W, #, and ? extensions are not allowed (plain 5-field UNIX cron only)."};try{const r=Mf.toString(n,{use24HourTimeFormat:!0,verbose:!1}),o=jf.CronExpressionParser.parse(n,{tz:"UTC"}).next().toDate();return{valid:!0,description:r,nextRun:o}}catch(r){return{valid:!1,description:"",nextRun:null,error:r instanceof Error?r.message:"Invalid cron expression."}}}function cl(e){return e?e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC",hour12:!1})+" UTC":"—"}function Df({onSubmit:e,isSubmitting:n,disabled:r,disabledReason:o}){const[i,l]=j.useState(!1),[a,u]=j.useState(!1),d=()=>l(!1),h=async()=>{try{await e({forceRefresh:a}),l(!1)}catch{}},y=t.jsx("span",{children:t.jsx(c.AddButton,{label:"Materialization",onClick:()=>l(!0),disabled:r})});return t.jsxs(t.Fragment,{children:[r&&o?t.jsx(p.Tooltip,{title:o,children:y}):y,t.jsx(c.AppDialog,{open:i,onClose:d,title:"New materialization",description:"Compile the package, build a table for every persist source, and load them so queries serve from the tables.",actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{onClick:d,children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:n,onClick:h,children:"Materialize"})]}),children:t.jsx(p.FormGroup,{children:t.jsx(p.FormControlLabel,{control:t.jsx(p.Switch,{checked:a,onChange:b=>u(b.target.checked)}),label:"Force refresh (rebuild even if unchanged)"})})})]})}function Kr({children:e}){return t.jsx(p.Typography,{variant:"caption",component:"h6",sx:{display:"block",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600,color:"text.secondary",mb:1},children:e})}function es(e){return e===q.MaterializationStatus.Pending||e===q.MaterializationStatus.ManifestRowsReady}function $f(e){return e===q.MaterializationStatus.ManifestFileReady||e===q.MaterializationStatus.Failed||e===q.MaterializationStatus.Cancelled}function Ff(e){switch(e){case q.MaterializationStatus.ManifestFileReady:return"Done";case q.MaterializationStatus.Failed:return"Failed";case q.MaterializationStatus.Cancelled:return"Cancelled";case q.MaterializationStatus.Pending:case q.MaterializationStatus.ManifestRowsReady:return"Pending";default:return"Unknown"}}function Af(e){switch(e){case q.MaterializationStatus.ManifestRowsReady:return"info";case q.MaterializationStatus.ManifestFileReady:return"success";case q.MaterializationStatus.Failed:return"error";case q.MaterializationStatus.Cancelled:return"warning";case q.MaterializationStatus.Pending:default:return"default"}}function ul(e){return e.status===q.MaterializationStatus.ManifestFileReady&&is(e).autoLoad==="failed"}function dl(e){return ul(e)?"Built, not served":Ff(e.status)}function Zs(e){return ul(e)?"warning":Af(e.status)}function Rf(e){const n=Object.values(is(e).refusedSources??{}).map(o=>({name:o.name,message:o.message})),r=Object.values(e.manifest?.failures??{}).filter(o=>o.refused).map(o=>({name:o.sourceName??o.sourceEntityId,message:o.reason}));return[...n,...r].sort((o,i)=>o.name.localeCompare(i.name))}function hl(e,n){const r=[`${e.sourcesBuilt??0} built`,`${e.sourcesReused??0} reused`];return e.sourcesRefused&&r.push(`${e.sourcesRefused} refused`),r.join(n)}function is(e){return e.metadata??{}}function fl(e){return e.trigger==="scheduler"||e.trigger==="SCHEDULER"}function Lf(e){return fl(e)?"Scheduled":"Manual"}function ml(e,n){if(!e)return"-";const r=new Date(e).getTime(),o=n?new Date(n).getTime():Date.now(),i=Math.max(0,o-r);if(i<1e3)return`${i}ms`;const l=Math.round(i/1e3);if(l<60)return`${l}s`;const a=Math.floor(l/60),u=l%60;if(a<60)return`${a}m ${u}s`;const d=Math.floor(a/60),h=a%60;return`${d}h ${h}m`}function Xs(e){if(!e)return"—";const n=new Date(e);return Number.isNaN(n.getTime())?"—":n.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function _f(e){if(!e)return"-";const n=new Date(e).getTime(),r=Math.round((Date.now()-n)/1e3);if(r<60)return"just now";const o=Math.floor(r/60);if(o<60)return`${o}m ago`;const i=Math.floor(o/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Nf({entries:e,builtAt:n}){const r=Object.entries(e??{});return t.jsxs(p.Box,{children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",justifyContent:"space-between",children:[t.jsx(Kr,{children:"Build manifest"}),n&&t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",children:["Built ",Xs(n)]})]}),r.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"No materialized tables yet."}):t.jsxs(p.Table,{size:"small",children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Source"}),t.jsx(p.TableCell,{children:"Table name"}),t.jsx(p.TableCell,{children:"Connection"}),t.jsx(p.TableCell,{children:"Realization"}),t.jsx(p.TableCell,{align:"right",children:"Rows"})]})}),t.jsx(p.TableBody,{children:r.map(([o,i])=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.sourceName??o}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.physicalTableName??"-"}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.connectionName??"-"}),t.jsx(p.TableCell,{children:i.realization??"-"}),t.jsx(p.TableCell,{align:"right",children:i.rowCount??"-"})]},o))})]})]})}function pl({meta:e}){const n=fl(e);return t.jsx(p.Tooltip,{title:n?"Fired by the materialization schedule":"Triggered manually",children:t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:Lf(e)})})}function Pf({materialization:e,buildPlan:n,onClose:r}){const o=e?is(e):{},i=e?Rf(e):[],l=n.status==="ready"?Object.values(n.plan?.sources??{}):[];return t.jsx(p.Dialog,{open:e!==null,onClose:r,maxWidth:"md",fullWidth:!0,"aria-labelledby":"materialization-detail-title",children:e&&t.jsxs(t.Fragment,{children:[t.jsxs(p.DialogTitle,{sx:{pr:6,pb:1.5},id:"materialization-detail-title",children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{mb:.75},children:[t.jsx(p.Chip,{size:"small",label:dl(e),color:Zs(e),variant:es(e.status)?"filled":"outlined"}),t.jsx(pl,{meta:o})]}),t.jsx(p.Typography,{variant:"subtitle1",sx:{fontWeight:600},children:e.packageName??"Materialization"}),t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY,wordBreak:"break-all"},children:e.id}),t.jsx(p.IconButton,{"aria-label":"close",onClick:r,sx:{position:"absolute",right:8,top:8},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]}),t.jsxs(p.DialogContent,{dividers:!0,children:[t.jsxs(p.Box,{sx:{bgcolor:"action.hover",borderRadius:2,p:2,mb:3,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:2},children:[t.jsx(cr,{label:"Started",value:Xs(e.startedAt??e.createdAt)}),t.jsx(cr,{label:"Completed",value:Xs(e.completedAt)}),t.jsx(cr,{label:"Duration",value:ml(e.startedAt,e.completedAt)}),t.jsx(cr,{label:"Sources",value:hl(o," · ")}),t.jsx(cr,{label:"Force refresh",value:o.forceRefresh?"Yes":"No"})]}),e.error&&t.jsxs(p.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"error.main"},children:[t.jsx(Kr,{children:t.jsx(p.Box,{component:"span",sx:{color:"error.main"},children:"Error"})}),t.jsx(p.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY,whiteSpace:"pre-wrap"},children:e.error})]}),i.length>0&&t.jsxs(p.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"warning.main"},children:[t.jsx(Kr,{children:t.jsx(p.Box,{component:"span",sx:{color:"warning.main"},children:"Refused sources"})}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1},children:"Not built, because materializing them would be unsafe. They serve live until the model changes."}),i.map(a=>t.jsxs(p.Box,{sx:{mt:1},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{whiteSpace:"pre-wrap"},children:a.message})]},a.name))]}),t.jsxs(p.Box,{sx:{mb:3},children:[t.jsx(Kr,{children:"Build plan"}),n.status==="loading"?t.jsx(c.Loading,{text:c.LOADING_COPY.loading,size:16,centered:!1}):n.status==="unavailable"?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"The build plan is unavailable."}):l.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"This package has no persist sources."}):t.jsxs(p.Table,{size:"small",children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Source"}),t.jsx(p.TableCell,{children:"Connection"}),t.jsx(p.TableCell,{children:"Dialect"}),t.jsx(p.TableCell,{align:"right",children:"Columns"}),t.jsx(p.TableCell,{children:"Source Entity ID"})]})}),t.jsx(p.TableBody,{children:l.map(a=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.connectionName}),t.jsx(p.TableCell,{children:a.dialect??"-"}),t.jsx(p.TableCell,{align:"right",children:a.columns?.length??0}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.75rem",wordBreak:"break-all",maxWidth:220},children:a.sourceEntityId})]},a.sourceID))})]})]}),t.jsx(Nf,{entries:e.manifest?.entries,builtAt:e.manifest?.builtAt})]})]})})}function cr({label:e,value:n}){return t.jsxs(p.Box,{children:[t.jsx(p.Typography,{variant:"caption",color:"text.secondary",display:"block",children:e}),t.jsx(p.Typography,{variant:"body2",children:n})]})}const zf=c.createSvgIcon(t.jsx("path",{d:"M6 6h12v12H6z"}));function Wf({materialization:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=j.useState(!1),a=()=>l(!0),u=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(et,{"aria-label":`Delete materialization ${e?.id??""}`.trim(),onClick:d=>{d.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(io,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(ao,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:u,title:"Delete materialization",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:u,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete run"})]}),children:t.jsx(c.Typography,{variant:"body2",children:"Delete this run's record? This cannot be undone. The tables it built stay in place: drop any you no longer need through their connection."})})]})}function qf({materializations:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){return e.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{py:1,fontStyle:"italic"},children:"No materializations yet."}):t.jsxs(p.Table,{size:"small",sx:{"& td, & th":{borderColor:"divider"},"& td:first-of-type, & th:first-of-type":{pl:0},"& td:last-of-type, & th:last-of-type":{pr:0},"& th":{color:"text.secondary",fontWeight:600}},children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Status"}),t.jsx(p.TableCell,{children:"Trigger"}),t.jsx(p.TableCell,{children:"Started"}),t.jsx(p.TableCell,{children:"Duration"}),t.jsx(p.TableCell,{children:"Sources"}),t.jsx(p.TableCell,{align:"right",children:"Actions"})]})}),t.jsx(p.TableBody,{children:e.map(a=>t.jsx(Bf,{materialization:a,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l},a.id))})]})}function Bf({materialization:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){const[a,u]=j.useState(null),d=!!a,h=()=>u(null),y=is(e),b=y.sourcesBuilt!==void 0||y.sourcesReused!==void 0?hl(y,", "):"-",x=es(e.status),v=$f(e.status),k=e.error??void 0,C=n&&(x||v);return t.jsxs(p.TableRow,{hover:!0,sx:{cursor:"pointer","&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},onClick:()=>l(e),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l(e))},role:"button",tabIndex:0,"aria-label":`View materialization ${e.id??""} details`.trim(),children:[t.jsx(p.TableCell,{children:t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:.5},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontWeight:500,color:Zs(e)==="default"?"text.primary":`${Zs(e)}.main`},children:dl(e)}),k&&t.jsx(p.Tooltip,{title:k,children:t.jsx(c.InfoOutlinedIcon,{fontSize:"small",color:"error"})})]})}),t.jsx(p.TableCell,{children:t.jsx(pl,{meta:y})}),t.jsx(p.TableCell,{children:_f(e.startedAt??e.createdAt)}),t.jsx(p.TableCell,{children:ml(e.startedAt,e.completedAt)}),t.jsx(p.TableCell,{children:b}),t.jsx(p.TableCell,{align:"right",onClick:S=>S.stopPropagation(),children:C&&t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small","aria-label":`Materialization actions for ${e.id??""}`.trim(),onClick:S=>u(S.currentTarget),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:a,open:d,onClose:h,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n&&x&&t.jsxs(p.MenuItem,{"aria-label":`Stop materialization ${e.id??""}`.trim(),disabled:r,onClick:()=>{h(),o(e)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(zf,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Stop"})]}),n&&v&&t.jsx(Wf,{materialization:e,isMutating:r,onCloseDialog:h,onDelete:()=>i(e)})]})]})})]})}const Vf=c.createSvgIcon(t.jsx("path",{d:"m11.99 18.54-7.37-5.73L3 14.07l9 7 9-7-1.63-1.27zM12 16l7.36-5.73L21 9l-9-7-9 7 1.63 1.27zm0-11.47L17.74 9 12 13.47 6.26 9z"})),Hf={package:"Materialized artifacts are shared across versions",version:"Materialized artifacts are per published version"};function Uf({scope:e,disabled:n,disabledReason:r,isSubmitting:o,onChange:i}){const[l,a]=j.useState(null),u=async d=>{a(null),d!==e&&await i(d).catch(()=>{})};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Scope",icon:t.jsx(Vf,{}),onClick:d=>a(d.currentTarget),disabled:n||o,...r?{disabledReason:r}:{},ariaHasPopup:"menu",ariaLabel:`Scope: ${e}`}),t.jsx(p.Menu,{anchorEl:l,open:!!l,onClose:()=>a(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:["package","version"].map(d=>t.jsxs(p.MenuItem,{selected:d===e,onClick:()=>void u(d),children:[t.jsx(p.ListItemIcon,{sx:{minWidth:32},children:d===e&&t.jsx(c.CheckIcon,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:d,secondary:Hf[d]})]},d))})]})}const Gf=c.createSvgIcon([t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),t.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")]),ca="0 6 * * *";function Yf({currentSchedule:e,isSubmitting:n,disabled:r,disabledReason:o,onSubmit:i}){const[l,a]=j.useState(!1),[u,d]=j.useState(e??ca),h=()=>{d(e??ca),a(!0)},y=()=>a(!1),b=uo(u),x=async v=>{try{await i(v),a(!1)}catch{}};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Schedule",icon:t.jsx(Gf,{}),onClick:h,disabled:r,...o?{disabledReason:o}:{},ariaHasPopup:"dialog",ariaLabel:e?"Edit schedule":"Set schedule"}),t.jsxs(c.AppDialog,{open:l,onClose:y,title:e?"Edit schedule":"Set schedule",description:"The publisher rebuilds this package's materializations on this cadence: a 5-field UNIX cron, in UTC. In a hosted deployment the change takes effect on your next publish.",actions:t.jsxs(t.Fragment,{children:[e&&t.jsx(p.Button,{color:"error",loading:n,onClick:()=>x(null),sx:{mr:"auto"},children:"Clear schedule"}),t.jsx(p.Button,{onClick:y,children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:n,disabled:!b.valid,onClick:()=>x(u.trim()),children:"Save schedule"})]}),children:[t.jsx(p.TextField,{autoFocus:!0,fullWidth:!0,size:"small",label:"Cron expression",value:u,onChange:v=>d(v.target.value),error:u.trim()!==""&&!b.valid,helperText:b.valid?`${b.description} · next run ${cl(b.nextRun)}`:b.error,slotProps:{htmlInput:{style:{fontFamily:q.MONO_FONT_FAMILY}}}}),t.jsxs(p.Alert,{severity:"info",children:["A schedule runs only on version-scoped packages, so saving one sets ",t.jsx("code",{children:"scope: version"})," for this package."]})]})]})}const Kf=3e3;function gl({resourceUri:e,versioned:n=!1}){const{apiClients:r,mutable:o}=q.useServer(),i=mt.useQueryClient(),{environmentName:l,packageName:a,versionId:u}=c.parseResourceUri(e),[d,h]=j.useState(""),[y,b]=j.useState(null);if(!a)throw new Error("Materializations requires a package in the resource URI");const x=c.useQueryWithApiError({queryKey:["materializations",l,a,u],queryFn:()=>r.materializations.listMaterializations(l,a,void 0,void 0,u),refetchInterval:H=>(H.state.data?.data??[]).some(z=>es(z.status))?Kf:!1}),v=c.useQueryWithApiError({queryKey:["package",l,a,u],queryFn:()=>r.packages.getPackage(l,a,u)}),k=c.useQueryWithApiError({queryKey:["package-build-plan",l,a,u],queryFn:async({signal:H})=>{try{return{inline:!1,plan:(await r.packages.getPackageBuildPlan(l,a,u,{signal:H})).data}}catch(Q){if(Q?.response?.status===404)return{inline:!0,plan:null};throw Q}},enabled:y!==null}),C=()=>i.invalidateQueries({queryKey:["materializations",l,a]}),S=c.useMutationWithApiError({mutationFn:Ht("materialization","create",H=>r.materializations.createMaterialization(l,a,{forceRefresh:H.forceRefresh,...u!==void 0?{versionId:u}:{}})),onSuccess(){h("Materialization requested"),C()},onError(H){h(H.message),C()}}),T=c.useMutationWithApiError({mutationFn:Ht("materialization","update",H=>r.materializations.materializationAction(l,a,H.id,q.MaterializationActionActionEnum.Stop,u)),onSuccess(){h("Materialization stopped"),C()},onError(H){h(H.message)}}),O=c.useMutationWithApiError({mutationFn:Ht("materialization","delete",H=>r.materializations.deleteMaterialization(l,a,H.id,u)),onSuccess(){h("Materialization deleted"),C()},onError(H){h(H.message)}}),M=v.data?.data,E=c.useMutationWithApiError({mutationFn:Ht("schedule","update",H=>r.packages.updatePackage(l,a,{name:a,description:M?.description,...H?{scope:q.PackageScopeEnum.Version}:{},materialization:{schedule:H}})),onSuccess(H,Q){h(Q?"Schedule updated":"Schedule cleared"),i.invalidateQueries({queryKey:["package",l,a]})},onError(H){h(H.message)}}),R=c.useMutationWithApiError({mutationFn:Ht("scope","update",H=>r.packages.updatePackage(l,a,{name:a,description:M?.description,scope:H})),onSuccess(){h("Scope updated"),i.invalidateQueries({queryKey:["package",l,a]})},onError(H){h(H.message)}}),P=x.data?.data??[],F=P.find(H=>H.id===y)??null,B=P.some(H=>es(H.status)),D=S.isPending||T.isPending||O.isPending,_=k.isError?{status:"unavailable"}:k.isSuccess?k.data.inline?v.isSuccess?{status:"ready",plan:M?.buildPlan??null}:v.isError?{status:"unavailable"}:{status:"loading"}:{status:"ready",plan:k.data.plan}:{status:"loading"},V=M?.materialization?.schedule??null,$=M?.scope===q.PackageScopeEnum.Version?"version":"package",W=!!M?.manifestLocation,Z=!!M?.materialization?.freshness,ne=V?uo(V):null,J=W?"Control-plane managed: refresh is driven by the control plane, not the built-in scheduler.":[ne?ne.valid?`${ne.description} (${V}), next run ${cl(ne.nextRun)}`:`Unrecognized cron expression (${V})`:Z?"Refreshed by a freshness policy; a cron schedule does not apply":"On demand only, no schedule set",`scope: ${$}`].join(" · ");return t.jsxs(t.Fragment,{children:[t.jsxs(Nt,{title:"Materializations",count:x.isSuccess?P.length:void 0,action:o&&t.jsxs(p.Stack,{direction:"row",spacing:1,alignItems:"center",children:[!W&&!n&&t.jsx(Uf,{scope:$,disabled:!!V,disabledReason:"A schedule requires version scope. Clear the schedule to change it.",isSubmitting:R.isPending,onChange:H=>R.mutateAsync(H==="version"?q.PackageScopeEnum.Version:q.PackageScopeEnum.Package)}),!W&&!n&&t.jsx(Yf,{currentSchedule:V,isSubmitting:E.isPending,disabled:Z,disabledReason:"This package declares a freshness policy; a schedule and freshness are mutually exclusive.",onSubmit:H=>E.mutateAsync(H)}),t.jsx(Df,{onSubmit:H=>S.mutateAsync(H),isSubmitting:S.isPending,disabled:B,disabledReason:"A materialization is already pending or running for this package."})]}),children:[v.isSuccess&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:J}),x.isError&&t.jsx(c.ApiErrorDisplay,{error:x.error,context:`${l} > ${a} > Materializations`}),!x.isSuccess&&!x.isError&&t.jsx(c.Loading,{text:"Loading materializations..."}),x.isSuccess&&t.jsx(qf,{materializations:P,mutable:o,isMutating:D,onStop:H=>T.mutate(H),onDelete:H=>O.mutate(H),onViewDetails:H=>b(H.id??null)})]}),t.jsx(Pf,{materialization:F,buildPlan:_,onClose:()=>b(null)}),t.jsx(p.Snackbar,{open:d!=="",autoHideDuration:6e3,onClose:()=>h(""),message:d})]})}const ho=c.createSvgIcon(t.jsx("path",{d:"M17 7h-4v2h4c1.65 0 3 1.35 3 3s-1.35 3-3 3h-4v2h4c2.76 0 5-2.24 5-5s-2.24-5-5-5m-6 8H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4zm-3-4h8v2H8z"}));function Ln(e){return yl(e).join(`
8
+ `).trim()||void 0}function yl(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(o){if(o.startsWith('#"'))n.push(o.slice(2).trim());else if(o.startsWith("#(doc)")){let i=o.slice(6).trim();i.length>=2&&i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),n.push(i)}}}return n.filter(r=>r.trim()!=="")}function ua(e){const n=(e??[]).map(r=>({...r,value:r.value?.trim()??""})).filter(r=>r.value.startsWith('##"')||r.value.startsWith("##(doc)")).map(r=>({...r,value:r.value.slice(1)}));return Ln(n)}function Qf(e,n){const r=e.docParts??[],o=n?.docParts??[];return(o.length>0&&o.length<r.length&&o.every((a,u)=>a===r[u])?r.slice(o.length):r).join(`
9
+ `).trim()||void 0}function fo(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||o.startsWith('#"')||o.startsWith("#(doc)"))continue;const i=o.replace(/^#+@?\s*/,"").trim();i&&!i.startsWith("(")&&n.push(i)}return n}function Zf(e){const n=new Set;for(const r of e){const{tag:o,log:i}=Xu.parseAnnotation([`# ${r}`]);if(i.length>0){const l=/^[A-Za-z_][\w.]*/.exec(r.trim())?.[0];l&&!/^\s*[\w.]+\s*=/.test(r)&&n.add(l);continue}for(const[l,a]of o.entries())a.deleted||(a.eq===void 0?n.add(l):l==="viz"&&typeof a.eq=="string"&&n.add(a.eq))}return[...n]}function Xf(e){return xl(e,"persist")}function Jf(e){return xl(e,"preaggregate")}function xl(e,n){const r=new RegExp(`^#@?\\s*${n}\\b`);return(e??[]).some(o=>r.test(o.value?.trim()??""))}function mo(e){const n=nm(e);if(!e||!n)return n;switch(e.kind){case"number_type":return e.subtype?`${n} · ${e.subtype}`:n;case"date_type":case"timestamp_type":case"timestamptz_type":return e.timeframe?`${n} · ${e.timeframe}`:n;case"sql_native_type":return e.sql_type?`sql native · ${e.sql_type}`:"sql native";case"array_type":return`array<${mo(e.element_type)??"unknown"}>`;case"record_type":{const r=e.fields.length;return`record · ${r} ${r===1?"field":"fields"}`}default:return n}}function em(e){if(e?.kind==="record_type")return e.fields.map(n=>`${n.name} ${mo(n.type)??""}`.trim()).join(`
10
+ `)}function tm(e){const n=(e??[]).filter(r=>/^#@/.test(r.value?.trim()??""));return fo((e??[]).filter(r=>!n.includes(r)))}function nm(e){return e?.kind?.replace(/_type$/,"")}const un=j.forwardRef(function(n,r){return t.jsx(p.Typography,{ref:r,variant:"body2",...n,sx:{color:"text.secondary",...n.sx}})}),Cr=j.forwardRef(function(n,r){return t.jsx(p.Typography,{ref:r,variant:"caption",...n,sx:{color:"text.secondary",...n.sx}})});function xr({message:e,secondary:n,actions:r}){return t.jsxs(p.Box,{"data-testid":"empty-row",sx:{display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",p:2,border:"1px dashed",borderColor:"divider",borderRadius:2},children:[t.jsxs(p.Box,{sx:{flex:1,minWidth:200},children:[t.jsx(un,{children:e}),n&&t.jsx(un,{sx:{color:"text.secondary",mt:.5},children:n})]}),r&&t.jsx(p.Box,{sx:{display:"flex",gap:1,flexShrink:0,alignItems:"center"},children:r})]})}const vl="--model-viewer-mono",Dt=`var(${vl}, ${q.MONO_FONT_FAMILY})`,bl="inherit",wt={micro:"0.6875rem",caption:"0.75rem",small:"0.8125rem",body:"0.875rem",bodyLarge:"1rem"},Js={strong:500},Vr=e=>({tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),nt={text:{secondary:"text.secondary",tertiary:"text.disabled"},background:{muted:"action.hover",strong:"action.selected"},accent:{sage:Vr(q.PALETTE.lime)},warning:Vr(q.PALETTE.amber),error:Vr(q.PALETTE.red),info:Vr(q.PALETTE.blue)},as=nt.text.tertiary,rm={positive:{bg:nt.accent.sage.tint,fg:nt.accent.sage.onTint},neutral:{bg:nt.background.strong,fg:nt.text.secondary},warning:{bg:nt.warning.tint,fg:nt.warning.onTint},negative:{bg:nt.error.tint,fg:nt.error.onTint},info:{bg:nt.info.tint,fg:nt.info.onTint},quiet:{bg:nt.background.muted,fg:nt.text.secondary}},$t=j.forwardRef(function({tone:n="neutral",voice:r="state",size:o="inline",busy:i=!1,children:l,sx:a,...u},d){const{bg:h,fg:y}=rm[n],b=wt.micro;return t.jsxs(Ge,{ref:d,component:"span","data-pill-tone":n,"data-pill-placement":o,...u,sx:[{display:"inline-flex",alignItems:"center",gap:i?"4px":0,padding:"2px 8px",borderRadius:"999px",bgcolor:h,color:y,flexShrink:0,whiteSpace:"nowrap",...r==="token"?{fontFamily:Dt,fontSize:b}:{fontFamily:bl,fontSize:b,fontWeight:Js.strong}},...Array.isArray(a)?a:[a]],children:[i&&t.jsx(c.CircularProgress,{size:9,thickness:5,sx:{color:"info.main",flexShrink:0},"aria-hidden":!0}),l]})}),sm={width:"100%",maxWidth:"1200px",mx:"auto"},eo=3,jr=1.5,Pn={display:"flex",flexDirection:"column",minWidth:0,minHeight:0,border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",cursor:"default"},om={...Pn,border:"none",borderRadius:0,bgcolor:"transparent",overflow:"visible"};function Ut({label:e,value:n,mono:r}){return t.jsxs(t.Fragment,{children:[t.jsx(p.Box,{component:"span",sx:{color:as,fontSize:wt.caption},children:e}),t.jsx(p.Box,{component:"span",sx:{fontFamily:r?Dt:void 0,wordBreak:"break-all"},children:n})]})}function im(e){const n=e.map(r=>r.name).join(", ");return`Reads the ${e.length===1?"given":"givens"} ${n}, set in the Givens section above`}function wl({givens:e}){return e.length===0?null:t.jsx(p.Tooltip,{title:im(e),children:t.jsx($t,{voice:"token",tone:"quiet",sx:{alignSelf:"center",flexShrink:0},children:"given"})})}function am(e){const n=c.renderGivenDefault(e.type,e.default);return n===void 0?"none — a value is required":n===""?"(empty)":n}function po({givens:e,framed:n=!0}){return e.length===0?null:t.jsx(p.Box,{"data-testid":"model-viewer-given-card",sx:{...n?Pn:{},p:jr,display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline",fontFamily:bl,fontSize:wt.small,color:"text.primary"},children:e.map(r=>t.jsxs(p.Box,{sx:{display:"contents"},children:[t.jsx(Ut,{label:"Given",value:r.name,mono:!0}),r.label&&t.jsx(Ut,{label:"Label",value:r.label}),t.jsx(Ut,{label:"Type",value:r.type,mono:!0}),t.jsx(Ut,{label:"Default",value:am(r)}),r.description&&t.jsx(Ut,{label:"Description",value:r.description})]},r.name))})}const Sl=j.createContext({});function ls(){return j.useContext(Sl)}function lm(e,n,r=new Set){const o=n?.givens;if(!Array.isArray(o))return[];const i=[];for(const l of o){if(!l||typeof l!="object")continue;const a=l;if(typeof a.name!="string"||!a.name||typeof a.type!="string"||!a.type||r.has(a.name))continue;const u=Array.isArray(a.annotations)?a.annotations.filter(d=>typeof d=="string"):void 0;i.push({name:a.name,type:a.type,modelFile:e,...u&&{annotations:u},...typeof a.default=="string"&&{default:a.default},...a.required===!0&&{required:!0},...typeof a.label=="string"&&a.label&&{label:a.label},...typeof a.description=="string"&&a.description&&{description:a.description},...(a.control==="select"||a.control==="multiselect")&&{control:a.control},...typeof a.rangeMin=="number"&&{rangeMin:a.rangeMin},...typeof a.rangeMax=="number"&&{rangeMax:a.rangeMax},...a.suggest&&typeof a.suggest=="object"&&{suggest:a.suggest}})}return i}function cm(e){return new Map(e.map(n=>[n.name,n.type]))}function um(e,n){const r=new Map(Array.from(e).filter(([l,a])=>n.has(l)&&!(a===""&&n.get(l)==="string"))),o=c.givensToRequest(r,n),i=Object.entries(o).sort(([l],[a])=>l<a?-1:l>a?1:0);return i.length>0?Object.fromEntries(i):void 0}function go(e){return e&&Object.keys(e).length>0?JSON.stringify(e):""}function dm(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||!o.startsWith("#(filter)"))continue;const i=fm(o.slice(9).trim());i&&n.push(i)}return n}const hm=new Set(["equal","in","like","greater_than","less_than"]);function fm(e){let n,r,o,i=!1,l=!1;for(const a of mm(e)){if(a==="implicit"){i=!0;continue}if(a==="required"){l=!0;continue}const u=a.indexOf("=");if(u<=0)continue;const d=a.slice(0,u).trim();let h=a.slice(u+1).trim();h.length>=2&&h.startsWith('"')&&h.endsWith('"')&&(h=h.slice(1,-1)),d==="name"?n=h:d==="dimension"?r=h:d==="type"&&hm.has(h)&&(o=h)}return!r||!o?null:{name:n??r,dimension:r,type:o,implicit:i,required:l}}function mm(e){const n=[];let r="",o=!1;for(const i of e){if(i==='"'){o=!o,r+=i;continue}if(!o&&/\s/.test(i)){r&&n.push(r),r="";continue}r+=i}return r&&n.push(r),n}const pm=/^#\(index(_values)?\b/;function gm(e){return!("annotations"in e)||!e.annotations?!1:e.annotations.some(n=>pm.test(n.value?.trim()??""))}function ym(e){const n=new Map;for(const r of e){const o=dm(r.annotations).filter(i=>i.required&&!i.implicit).map(i=>i.name);o.length>0&&n.set(r.name,o)}return n}function xm(e){return new Set(e.map(n=>n.name))}function kl(e){const n=new Map;for(const r of e){if(!r.source)continue;let o=n.get(r.source);o||(o=new Map,n.set(r.source,o)),o.set(r.name,r)}return n}function Ir(e){let n="",r=0;const o=(i,l)=>{n+=e.slice(i,l).replace(/[^\n]/g," "),r=l};for(;r<e.length;){const i=e[r],l=e.slice(r,r+2);if(l==="//"||l==="--"){const a=e.indexOf(`
11
+ `,r);o(r,a===-1?e.length:a)}else if(l==="/*"){const a=e.indexOf("*/",r+2);o(r,a===-1?e.length:a+2)}else if(e.startsWith('"""',r)){const a=e.indexOf('"""',r+3),u=a===-1?e.length:a;n+='"""',r+=3,o(r,u),a!==-1&&(n+='"""',r+=3)}else if(i==="'"||i==='"'){n+=i;let a=r+1;for(;a<e.length&&e[a]!==i&&e[a]!==`
12
12
  `;)a+=e[a]==="\\"&&e[a+1]!==`
13
13
  `?2:1;o(r+1,Math.min(a,e.length)),e[r]===i&&(n+=i,r+=1)}else if(i==="`"){let a=r+1;for(;a<e.length&&e[a]!=="`"&&e[a]!==`
14
- `;)a+=e[a]==="\\"?2:1;const d=Math.min(a+1,e.length);n+=e.slice(r,d),r=d}else n+=i,r+=1}return n}function pn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,n){if(!e||n.length===0)return[];const r=Ir(e);return n.filter(o=>new RegExp(`\\$${pn(o.name)}(?![A-Za-z0-9_])`).test(r))}function bm(e,n){if(!e)return new Set;const r=Ir(e);return new Set(n.filter(o=>new RegExp(`(?<![A-Za-z0-9_$.])\`?${pn(o.name)}\`?\\s*::`).test(r)).map(o=>o.name))}function wm(e,n,r,o){if(!e)return{givens:[...n],unknown:new Set(n.map(b=>b.name))};const i=Ir(e),l=new Set(dn(e,n).map(b=>b.name)),a=new Set(l),d=new Set,u=b=>{a.add(b),l.has(b)||d.add(b)};for(const[b,x]of r??[])if(new RegExp(`(?<![A-Za-z0-9_$.])\`?${pn(b)}\`?(?![A-Za-z0-9_])`).test(i)){for(const k of x)a.add(k.name);for(const k of o?.get(b)??[])u(k)}const h=/^\s*query\s*:\s*`?[A-Za-z_]\w*`?\s+is\s+/.exec(i),y=h?no(i.slice(h[0].length)):void 0;if(y===void 0||y!==null&&!r?.has(y))for(const b of n)u(b.name);return{givens:n.filter(b=>a.has(b.name)),unknown:d}}function Sm(e,n,r){if(r.length===0)return{givens:[],unknown:new Set};const o=Cl(e,n,r);return o?o.unresolved?{givens:[...r],unknown:new Set(r.filter(i=>!o.readHere.has(i.name)).map(i=>i.name))}:{givens:r.filter(i=>o.readHere.has(i.name)||!o.readByAnySource.has(i.name)),unknown:new Set}:{givens:[...r],unknown:new Set(r.map(i=>i.name))}}function km(e,n,r,o){const i=new Map,l=Cl(e,n,r);if(!l)return i;const a=new Set;for(const d of l.reached)if(!(d!==n&&!o.has(d)))for(const u of dn(l.blocks.get(d),r))a.add(u.name);for(const d of l.reached)if(!(d===n||o.has(d)))for(const u of dn(l.blocks.get(d),r))a.has(u.name)||i.set(u.name,[...i.get(u.name)??[],d]);return i}function Cl(e,n,r){if(!e||r.length===0)return;const o=jm(Ir(e));if(!o.has(n))return;const i=new Set;for(const h of o.values())for(const y of dn(h,r))i.add(y.name);const l=new Set;let a=!1;const d=h=>{if(l.has(h))return;l.add(h);const y=o.get(h);if(!y)return;const b=Tm(y,h,o);b.unresolved&&(a=!0);for(const x of b.sources)d(x)};d(n);const u=new Set;for(const h of l)for(const y of dn(o.get(h),r))u.add(y.name);return{blocks:o,reached:l,readHere:u,readByAnySource:i,unresolved:a}}const Cm=/^(?:source|query|run|given|import)\b|^#/;function jm(e){const n=new Map;let r,o=0;const i=()=>{r&&n.set(r.name,r.lines.join(`
14
+ `;)a+=e[a]==="\\"?2:1;const u=Math.min(a+1,e.length);n+=e.slice(r,u),r=u}else n+=i,r+=1}return n}function pn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,n){if(!e||n.length===0)return[];const r=Ir(e);return n.filter(o=>new RegExp(`\\$${pn(o.name)}(?![A-Za-z0-9_])`).test(r))}function vm(e,n){if(!e)return new Set;const r=Ir(e);return new Set(n.filter(o=>new RegExp(`(?<![A-Za-z0-9_$.])\`?${pn(o.name)}\`?\\s*::`).test(r)).map(o=>o.name))}function bm(e,n,r,o){if(!e)return{givens:[...n],unknown:new Set(n.map(b=>b.name))};const i=Ir(e),l=new Set(dn(e,n).map(b=>b.name)),a=new Set(l),u=new Set,d=b=>{a.add(b),l.has(b)||u.add(b)};for(const[b,x]of r??[])if(new RegExp(`(?<![A-Za-z0-9_$.])\`?${pn(b)}\`?(?![A-Za-z0-9_])`).test(i)){for(const k of x)a.add(k.name);for(const k of o?.get(b)??[])d(k)}const h=/^\s*query\s*:\s*`?[A-Za-z_]\w*`?\s+is\s+/.exec(i),y=h?to(i.slice(h[0].length)):void 0;if(y===void 0||y!==null&&!r?.has(y))for(const b of n)d(b.name);return{givens:n.filter(b=>a.has(b.name)),unknown:u}}function wm(e,n,r){if(r.length===0)return{givens:[],unknown:new Set};const o=Cl(e,n,r);return o?o.unresolved?{givens:[...r],unknown:new Set(r.filter(i=>!o.readHere.has(i.name)).map(i=>i.name))}:{givens:r.filter(i=>o.readHere.has(i.name)||!o.readByAnySource.has(i.name)),unknown:new Set}:{givens:[...r],unknown:new Set(r.map(i=>i.name))}}function Sm(e,n,r,o){const i=new Map,l=Cl(e,n,r);if(!l)return i;const a=new Set;for(const u of l.reached)if(!(u!==n&&!o.has(u)))for(const d of dn(l.blocks.get(u),r))a.add(d.name);for(const u of l.reached)if(!(u===n||o.has(u)))for(const d of dn(l.blocks.get(u),r))a.has(d.name)||i.set(d.name,[...i.get(d.name)??[],u]);return i}function Cl(e,n,r){if(!e||r.length===0)return;const o=Cm(Ir(e));if(!o.has(n))return;const i=new Set;for(const h of o.values())for(const y of dn(h,r))i.add(y.name);const l=new Set;let a=!1;const u=h=>{if(l.has(h))return;l.add(h);const y=o.get(h);if(!y)return;const b=jm(y,h,o);b.unresolved&&(a=!0);for(const x of b.sources)u(x)};u(n);const d=new Set;for(const h of l)for(const y of dn(o.get(h),r))d.add(y.name);return{blocks:o,reached:l,readHere:d,readByAnySource:i,unresolved:a}}const km=/^(?:source|query|run|given|import)\b|^#/;function Cm(e){const n=new Map;let r,o=0;const i=()=>{r&&n.set(r.name,r.lines.join(`
15
15
  `)),r=void 0};for(const l of e.split(`
16
- `)){const a=o===0?/^source\s*:\s*`?([A-Za-z_]\w*)`?\s+is\b/.exec(l):null;a?(i(),r={name:a[1],lines:[l]}):o===0&&Cm.test(l)?i():r&&r.lines.push(l);for(const d of l)d==="{"?o+=1:d==="}"&&(o=Math.max(0,o-1))}return i(),n}function Tm(e,n,r){const o=[];let i=!1;const l=u=>{u===null||u===n||(u!==void 0&&r.has(u)?o.push(u):i=!0)},a=new RegExp(`source\\s*:\\s*\`?${pn(n)}\`?\\s+is\\s+`).exec(e);a&&l(no(e.slice(a.index+a[0].length)));const d=/join_\w+\s*:\s*`?([A-Za-z_]\w*)`?(\s+is\s+)?/g;for(let u=d.exec(e);u;u=d.exec(e))l(u[2]?no(e.slice(u.index+u[0].length)):u[1]);return{sources:o,unresolved:i}}function no(e){const n=/^`?([A-Za-z_]\w*)`?/.exec(e);if(!n)return;const r=e.slice(n[0].length).trimStart();if(r.startsWith("."))return null;if(!r.startsWith("("))return n[1]}const Tr={"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},jl=j.createContext(void 0);function xo({layer:e,title:n,children:r,testId:o}){const i=j.useContext(jl);if(!i||!e||!i.layers.includes(e))return t.jsx(p.Tooltip,{title:n,children:t.jsx(p.Box,{component:"span",tabIndex:0,role:"img","aria-label":n,"data-testid":o,sx:{display:"inline-flex",borderRadius:1,...Tr},children:r})});const l=i.openLayer===e;return t.jsx(p.Tooltip,{title:n,children:t.jsx(p.Box,{component:"button",type:"button",onClick:()=>i.toggle(e),"aria-expanded":l,"aria-controls":i.cardId,"aria-label":`${n} ${l?"Hide":"Show"} details.`,"data-testid":o,"data-header-chip":e,sx:{appearance:"none",border:"none",background:"none",font:"inherit",p:0,cursor:"pointer",display:"inline-flex",alignItems:"center",borderRadius:1,"& [data-pill-tone]":{transition:"filter 120ms ease",...l?{filter:"brightness(0.9)"}:{}},"&:hover [data-pill-tone]":{filter:l?"brightness(0.9)":"brightness(0.94)"},...Tr},children:r})})}function Om(e){try{const{data:n}=JSON.parse(e);return n?.kind==="array_cell"?n.array_value.length:n?.kind==="record_cell"?1:0}catch{return}}const Mm={authorize:[],accessFilter:[]};function ha(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim()!==""):[]}function Em(e){const n=new Map,r=e?.sources;if(!Array.isArray(r))return n;for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(typeof i.name!="string"||!i.name)continue;const l=ha(i.authorize),a=ha(i.accessFilter);l.length===0&&a.length===0||n.set(i.name,{authorize:l,accessFilter:a})}return n}function Qr(e,n){return n&&e?.get(n)||Mm}function Yt(e){return!!e&&e.authorize.some(n=>n.trim()!=="true")}function Jt(e){return!!e&&e.accessFilter.length>0}const fa=/^\(?\s*(?:'([^']*)'|"([^"]*)")\s+in\s+\$GROUPS\s*\)?$/;function Im(e){const n=e.trim();if(n==="false")return"no one";const r=fa.exec(n);if(r)return`members of ${r[1]??r[2]}`;for(const o of["or","and"]){const i=n.split(new RegExp(`\\s+${o}\\s+`));if(i.length<2)continue;const l=i.map(a=>fa.exec(a.trim()));if(l.every(a=>a)){const a=l.map(d=>d[1]??d[2]);return o==="or"?`members of ${a.slice(0,-1).join(", ")} or ${a[a.length-1]}`:`members of all of ${a.join(", ")}`}}}function Tl(e){const n=e.authorize.filter(o=>o.trim()!=="true").map(o=>Im(o)??"readers its access rule admits");return Array.from(new Set(n)).join(", and ")}const Ol="Only some readers can query this source",Ml="Each reader sees only the rows they're allowed to see";function Dm(e,n){return e?Yt(n)?`You can't access ${e}. It is restricted to ${Tl(n)}; ask an administrator of this package for access.`:`You can't access ${e}. Ask an administrator of this package for access.`:"You don't have access to run this. Ask an administrator of this package for access."}function $m(e,n){if(!(!Jt(e)||n===void 0))return Om(n)===0?"Filtered to your rows: this source shows each reader only the rows they're allowed to see.":void 0}function El(e){return Yt(e)||Jt(e)}function Am(e,n){return`This join doesn't apply the ${Yt(n)&&Jt(n)?"access rule and row filter":Yt(n)?"access rule":"row filter"} on ${e}: its rows are read under this source's rules.`}function Fm({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(ma,{label:"Restricted",meaning:Ol}),Jt(e)&&t.jsx(ma,{label:"Row filtered",meaning:Ml})]})}function ma({label:e,meaning:n}){return t.jsx(xo,{layer:"access",title:`${e}: ${n}`,testId:`source-access-chip-${e==="Restricted"?"restricted":"row-filtered"}`,children:t.jsx($t,{tone:"neutral",size:"header",children:e})})}function Il({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(p.Tooltip,{title:`Restricted: ${Ol}`,children:t.jsx($t,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Restricted"})}),Jt(e)&&t.jsx(p.Tooltip,{title:`Row filtered: ${Ml}`,children:t.jsx($t,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Row filtered"})})]})}function Rm(e){return[Yt(e)&&"restricted",Jt(e)&&"row filtered"].filter(Boolean).map(n=>`, ${n}`).join("")}function Nm({access:e,showRules:n}){const r=Yt(e),o=Jt(e);return!r&&!o?null:t.jsxs(p.Box,{"data-testid":"source-access-facts",sx:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline"},children:[r&&t.jsx(Ut,{label:"Restricted to",value:Tl(e)}),r&&n&&e.authorize.filter(i=>i.trim()!=="true").map((i,l)=>t.jsx(Ut,{label:"Access rule",value:i,mono:!0},`a${l}`)),o&&t.jsx(Ut,{label:"Rows",value:"Rows are filtered for each reader"}),o&&n&&e.accessFilter.map((i,l)=>t.jsx(Ut,{label:"Row filter",value:i,mono:!0},`f${l}`))]})}const pa="Private",Lm="index.malloy doesn't export this file, so only people who can edit the package see it.";function ga(){return t.jsx(xo,{title:`${pa}: ${Lm}`,testId:"model-viewer-off-surface",children:t.jsx($t,{tone:"warning",size:"header",children:pa})})}const ya="Public",_m="index.malloy exports this source, so everyone who can read the package can query it.";function Pm(){return t.jsx(xo,{title:`${ya}: ${_m}`,testId:"model-viewer-public-surface",children:t.jsx($t,{tone:"positive",size:"header",children:ya})})}function zm(e){const n=j.useRef(e);return e!==void 0&&(n.current=e),n.current}function As({title:e,titleAdornments:n,kindLabel:r,meta:o,doc:i,provenance:l,actions:a,status:d,headingLevel:u="h1",modelDoc:h,access:y,showRules:b=!1,isSource:x=!0,offSurface:v,publicSurface:k=!1}){const C=Yt(y)||Jt(y),S=C?["access"]:[],[T,O]=j.useState(void 0),M=T!==void 0&&S.includes(T)?T:void 0,E=zm(M),R=j.useId(),P={openLayer:M,layers:S,toggle:L=>O(U=>U===L?void 0:L),cardId:R},A=C||v||k||!!d,H=q.usePublisherTheme().theme.ui.type.pageTitle,D=typeof H.fontSize=="number"?`${H.fontSize}px`:H.fontSize;return t.jsxs(p.Box,{children:[t.jsxs(p.Box,{"data-testid":"model-viewer-source-heading",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:to,pb:.5},children:[t.jsx(p.Box,{component:u,sx:{m:0,fontSize:u==="h1"?D:`calc(${D} * 0.8)`,fontWeight:H.fontWeight??600,lineHeight:1.25,color:"text.primary",fontFamily:Dt,minWidth:0,overflowWrap:"anywhere"},children:e}),n,a&&t.jsx(p.Box,{sx:{ml:"auto",display:"flex",alignItems:"center",gap:1},children:a})]}),!x&&v&&t.jsx(p.Box,{sx:{display:"flex",alignItems:"center",pt:.5,pb:1},children:t.jsx(ga,{})}),x&&A&&t.jsx(jl.Provider,{value:P,children:t.jsxs(p.Box,{"data-testid":"model-viewer-status-row",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:.5,pb:1},children:[t.jsx(Fm,{access:y}),v&&t.jsx(ga,{}),k&&t.jsx(Pm,{}),d]})}),h&&t.jsx(xa,{doc:h,label:"model description",testId:"model-viewer-model-doc"},`model:${h}`),i&&t.jsx(xa,{doc:i},i),(r!==void 0||o!==void 0||l)&&t.jsxs(p.Box,{"data-testid":"model-viewer-source-meta",sx:{display:"flex",alignItems:"center",gap:.75,minWidth:0,pb:2,fontSize:St.body,color:"text.secondary",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[r!==void 0&&t.jsx(p.Box,{component:"span","data-testid":"model-viewer-source-kind",children:r}),r!==void 0&&(o!==void 0||l)&&t.jsx(p.Box,{component:"span","aria-hidden":!0,children:"·"}),o!==void 0&&t.jsx(p.Box,{component:"span",children:o}),o!==void 0&&l&&t.jsx(p.Box,{component:"span","aria-hidden":!0,children:"·"}),l&&t.jsx(p.Box,{component:"span",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:l})]}),t.jsx(p.Collapse,{in:M!==void 0,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{id:R,"data-testid":"model-viewer-source-detail","data-layer":E??void 0,sx:{...Pn,p:jr,mb:2},children:E==="access"&&y&&t.jsx(Nm,{access:y,showRules:b})})})]})}const Wm=2;function xa({doc:e,label:n="description",testId:r="model-viewer-source-doc"}){const[o,i]=j.useState(!1),[l,a]=j.useState(!1),d=j.useRef(null);return j.useEffect(()=>{const u=d.current;if(!u||o)return;const h=()=>a(u.scrollHeight>u.clientHeight+1);if(h(),typeof ResizeObserver>"u")return;const y=new ResizeObserver(h);return y.observe(u),()=>y.disconnect()},[o,e]),t.jsxs(p.Box,{"data-testid":r,sx:{pb:.5},children:[t.jsx(p.Box,{ref:d,sx:{fontSize:St.body,lineHeight:1.5,color:"text.secondary",whiteSpace:"pre-line",...o?{}:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:Wm,overflow:"hidden"}},children:Dl(e)}),(l||o)&&t.jsx(p.Box,{component:"button",type:"button",onClick:()=>i(!o),"aria-expanded":o,"aria-label":o?`Show less of the ${n}`:`Show the full ${n}`,sx:{all:"unset",cursor:"pointer",fontSize:St.small,color:"text.secondary",textDecoration:"underline","&:hover":{color:"text.primary"},"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}},children:o?"Less":"More"})]})}function Dl(e){return e.split(/(`[^`\n]+`)/g).map((n,r)=>/^`[^`]+`$/.test(n)?t.jsx(p.Box,{component:"code",sx:{fontFamily:Dt,fontSize:"0.92em",color:"text.primary"},children:n.slice(1,-1)},r):n)}function us(e){const n=e?.response?.status;return typeof n=="number"?n:void 0}function qm(e){const n=us(e);return n===403||n===404}function Bm(e,n){if(!e?.modelPath||!e.sourceName)return{kind:"unknown"};const r=n.get(e.modelPath);return r?r.has(e.sourceName)?{kind:"link"}:{kind:"join-only"}:{kind:"unknown"}}const vo=j.createContext([]),ts="text.primary",ur=e=>({main:e,tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),An={steel:ur(q.PALETTE.cyan),sage:ur(q.PALETTE.lime),brown:ur(q.PALETTE.slate),olive:ur(q.PALETTE.violet),amber:ur(q.PALETTE.amber)};function va(e){return e==="measure"?An.sage:e==="calculate"?An.amber:e==="view"?An.olive:An.steel}const ba=["steel","brown","olive","sage"];function Vm(e){return ba[e%ba.length]}const $l={small:13,caption:12},Hm={fontFamily:Dt,fontSize:$l.small,fontWeight:500,color:ts},Al={fontSize:$l.caption,color:"text.secondary"};function Ln({label:e,count:n,level:r="h2",testId:o,action:i,children:l}){return n===0?null:r==="h3"?t.jsxs(p.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:2},children:[t.jsx(p.Box,{component:"h3",sx:{m:0,mb:1,fontSize:St.bodyLarge,fontWeight:eo.strong,color:ts},children:e}),l]}):t.jsxs(p.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:3},children:[t.jsxs(p.Box,{sx:{mb:2},children:[t.jsx(p.Box,{component:"h2",sx:{m:0,fontSize:"1.25rem",fontWeight:eo.strong,color:ts},children:e}),i&&t.jsx(p.Box,{sx:{...Al,mt:.25,display:"flex",alignItems:"center"},children:i})]}),l]})}function vr(e,n){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${n} ${e.at(-1)}`}function wa(e,n){return`${e.label??e.name}: ${c.describeGivenValue(e,n)}`}const Hr=e=>e.label??e.name;function Fl(e,n,r=void 0,o=void 0,i=!1,l="source"){const a=e??[],d=M=>r?.[M.name]!==void 0,u=M=>o?.has(M.name)===!0,h=a.filter(M=>!d(M)&&M.default===void 0),y=n??[],b=y.length===0&&h.length>0&&h.every(M=>u(M)),x=i&&b?h:[];if(x.length===0&&(h.length>0||y.length>0)){const M=h.length>0?`a value for ${h.length===1?"the given":"the givens"} ${h.map(Hr).join(", ")}`:"",E=y.length>0?`${y.length===1?"the required filter":"the required filters"} ${y.join(", ")}`:"",R=h.filter(u),P=R.length===0?"":R.length===h.length?` This page can't tell whether this ${l} reads ${h.length===1?"it":"them"}.`:` This page can't tell whether this ${l} reads ${vr(R.map(Hr),"or")}.`;let A;return E===""?A=`This needs ${M}. Set ${h.length===1?"it":"them"} in the Givens section above.${P}`:M===""?A=`This needs ${E}, which this page can't set; open the source in a dashboard or notebook.`:A=`This needs ${M} (set ${h.length===1?"it":"them"} in the Givens section above) and ${E}, which this page can't set; open the source in a dashboard or notebook.${P}`,{kind:"blocked",reason:A,canRunAnyway:b}}const v=M=>M.length>0?`${M.length===1?"the default":"the defaults"} ${M.map(E=>wa(E)).join(", ")}`:"",k=[];x.length>0&&k.push(`Ran without a value for ${x.length===1?"the given":"the givens"} ${vr(x.map(Hr),"and")}, which this page can't tell this ${l} reads.`);const C=a.filter(M=>!x.includes(M)),S=C.filter(M=>!u(M)),T=v(S.filter(M=>!d(M)));T!==""&&k.push(`Ran with ${T}.`);const O=C.filter(u);if(O.length>0){const M=[O.filter(d).map(E=>wa(E,r?.[E.name])).join(", "),v(O.filter(E=>!d(E)))].filter(E=>E!=="").join(" and ");k.push(O.length===C.length?`This page can't tell which givens this ${l} reads. Where it reads one, it ran with ${M}.`:`This page can't tell whether this ${l} reads ${vr(O.map(Hr),"or")}. Where it does, it ran with ${M}.`)}return k.length>0?{kind:"noted",note:k.join(" ")}:{kind:"ok"}}const Um=400;function Gm({givens:e,unknown:n,inheritedFrom:r,values:o,onChange:i,onReset:l,environmentName:a,packageName:d,modelPath:u,versionId:h,declaredTypes:y}){const b=j.useMemo(()=>[...e],[e]),x=j.useMemo(()=>{const A=e.filter(H=>n?.has(H.name));if(A.length!==0)return A.length===e.length?"This page can't tell which of these givens this source reads, so a value set here may not apply to it.":`This page can't tell whether this source reads ${vr(A.map(H=>H.label??H.name),"or")}, so a value set for ${A.length===1?"it":"them"} may not apply.`},[e,n]),[v,k]=j.useState(()=>new Set),C=j.useCallback(A=>k(H=>H.has(A)?H:new Set([...H,A])),[]),S=c.useSettled(o,Um),T=j.useMemo(()=>({values:S,declaredTypes:y}),[S,y]),{options:O,isLoading:M,failed:E,truncated:R,search:P}=c.useSuggestOptions(a,d,u,b,h,T,void 0,v,!0);return t.jsxs(Ln,{label:"Givens",count:e.length,testId:"model-givens-section",children:[t.jsx(p.Box,{sx:{"& .MuiPaper-root":{borderColor:"divider"}},children:t.jsx(c.GivensPanel,{layout:"bar",givens:b,values:o,onChange:i,onReset:l,options:O,optionsLoading:M,optionsFailed:E,optionsTruncated:R,optionSearch:P,onControlOpen:C})}),x&&t.jsx(un,{"data-testid":"model-givens-unknown",sx:{mt:1},children:x}),r&&r.size>0&&t.jsx(un,{"data-testid":"model-givens-inherited",sx:{mt:1},children:[...r].map(([A,H])=>H.length===1?`${A} is inherited from ${H[0]}, which this model doesn't export.`:`${A} is inherited from ${H.slice(0,-1).join(", ")} and ${H.at(-1)}, none of which this model exports.`).join(" ")})]})}const Ym="A source is a queryable entry point into the model — pick one to browse its dimensions, measures, views and joins.";function Km(e,n=!1){return e===0?"No sources":`${e} ${n?"public ":""}source${e===1?"":"s"}`}const Qm=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),Zm=c.createSvgIcon(t.jsx("path",{d:"M6 6v2h8.59L5 17.59 6.41 19 16 9.41V18h2V6z"})),Xm=c.createSvgIcon(t.jsx("path",{d:"M4 9h4v11H4zm12 4h4v7h-4zm-6-9h4v16h-4z"})),Jm=c.createSvgIcon([t.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14z"},"0"),t.jsx("path",{d:"M6.25 7.72h5v1.5h-5zM13 15.75h5v1.5h-5zm0-2.5h5v1.5h-5zM8 18h1.5v-2h2v-1.5h-2v-2H8v2H6V16h2zm6.09-7.05 1.41-1.41 1.41 1.41 1.06-1.06-1.41-1.42 1.41-1.41L16.91 6 15.5 7.41 14.09 6l-1.06 1.06 1.41 1.41-1.41 1.42z"},"1")]),Rl=c.createSvgIcon(t.jsx("path",{d:"M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 18H4V10h16zm0-13H4V5h16z"})),ep=c.createSvgIcon(t.jsx("path",{d:"M17 20.41 18.41 19 15 15.59 13.59 17zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5z"})),tp=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"})),np=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),rp=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),sp=c.createSvgIcon(t.jsx("path",{d:"m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"})),op=c.createSvgIcon(t.jsx("path",{d:"M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5m0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5m0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5M7 19h14v-2H7zm0-6h14v-2H7zm0-8v2h14V5z"})),Nl=c.createSvgIcon(t.jsx("path",{d:"M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6z"})),ip=c.createSvgIcon(t.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2M9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9zm9 14H6V10h12zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2"})),ap=c.createSvgIcon(t.jsx("path",{d:"m20.5 10 .5-2h-4l1-4h-2l-1 4h-4l1-4h-2L9 8H5l-.5 2h4l-1 4h-4L3 16h4l-1 4h2l1-4h4l-1 4h2l1-4h4l.5-2h-4l1-4zm-7 4h-4l1-4h4z"})),Ll=c.createSvgIcon(t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8m.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"})),lp=c.createSvgIcon([t.jsx("path",{d:"m21.41 11.41-8.83-8.83c-.37-.37-.88-.58-1.41-.58H4c-1.1 0-2 .9-2 2v7.17c0 .53.21 1.04.59 1.41l8.83 8.83c.78.78 2.05.78 2.83 0l7.17-7.17c.78-.78.78-2.04-.01-2.83M12.83 20 4 11.17V4h7.17L20 12.83z"},"0"),t.jsx("circle",{cx:"6.5",cy:"6.5",r:"1.5"},"1")]),_l=c.createSvgIcon(t.jsx("path",{d:"M17 6H7c-3.31 0-6 2.69-6 6s2.69 6 6 6h10c3.31 0 6-2.69 6-6s-2.69-6-6-6m0 10H7c-2.21 0-4-1.79-4-4s1.79-4 4-4h10c2.21 0 4 1.79 4 4s-1.79 4-4 4m0-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"})),cp=c.createSvgIcon(t.jsx("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"})),Pl=c.createSvgIcon(t.jsx("path",{d:"M3 5v14h18V5zm5.33 12H5V7h3.33zm5.34 0h-3.33V7h3.33zM19 17h-3.33V7H19z"})),up=c.createSvgIcon(t.jsx("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22zm1 14h-2v2h2zm0-6h-2v4h2z"}));function st(e,n){const r=({size:o,...i})=>t.jsx(e,{...i,sx:{fontSize:o}});return r.displayName=n,r}const dp=st(Qm,"IconText"),Sa=st(Zm,"IconOpen"),zl=st(Xm,"IconResult"),hp=st(Jm,"IconCalculation"),fp=st(Rl,"IconDate"),mp=st(ep,"IconJoin"),pp=st(tp,"IconCode"),gp=st(np,"IconList"),yp=st(rp,"IconRecord"),xp=st(sp,"IconCollapse"),vp=st(c.ExpandMoreIcon,"IconExpand"),bp=st(op,"IconFields"),wp=st(Nl,"IconDropdown"),Sp=st(ip,"IconLock"),Wl=st(ap,"IconNumber"),kp=st(Ll,"IconTimestamp"),Cp=st(lp,"IconValues"),jp=st(_l,"IconBoolean"),Tp=st(cp,"IconGivens"),ql=st(Pl,"IconColumn");st(up,"IconWarning");const Or=j.createContext(void 0);function bo(){const[e,n]=j.useState(!1),r=j.useContext(Or),[o,i]=j.useState(r?.n);return r&&r.n!==o&&(i(r.n),n(r.open)),[e,n]}function Op({allOpen:e,onToggle:n,noun:r,disabledReason:o}){const i=e?t.jsx(xp,{size:16,"aria-hidden":!0}):t.jsx(vp,{size:16,"aria-hidden":!0});return t.jsx(p.Tooltip,{title:o??"",children:t.jsx("span",{children:t.jsxs(p.ButtonBase,{disabled:!!o,onClick:n,"aria-label":o??`${e?"Collapse":"Expand"} all ${r[1]}`,sx:{font:"inherit",color:"text.secondary",gap:.25,borderRadius:1,"&:hover":{color:"text.primary",textDecoration:"underline"},...Tr,"&.Mui-disabled":{opacity:.5}},children:[i,e?"Collapse all":"Expand all"]})})})}function ns({noun:e,disabledReason:n}){const[r,o]=j.useState(void 0),i=r?.open??!1;return{command:r,action:t.jsx(Op,{allOpen:i,onToggle:()=>o({open:!i,n:(r?.n??0)+1}),noun:e,disabledReason:n})}}let Fs;function Mp(e,n){if(Fs?.text===n)return Fs.parsed;const r=n.replace(/\r\n/g,`
16
+ `)){const a=o===0?/^source\s*:\s*`?([A-Za-z_]\w*)`?\s+is\b/.exec(l):null;a?(i(),r={name:a[1],lines:[l]}):o===0&&km.test(l)?i():r&&r.lines.push(l);for(const u of l)u==="{"?o+=1:u==="}"&&(o=Math.max(0,o-1))}return i(),n}function jm(e,n,r){const o=[];let i=!1;const l=d=>{d===null||d===n||(d!==void 0&&r.has(d)?o.push(d):i=!0)},a=new RegExp(`source\\s*:\\s*\`?${pn(n)}\`?\\s+is\\s+`).exec(e);a&&l(to(e.slice(a.index+a[0].length)));const u=/join_\w+\s*:\s*`?([A-Za-z_]\w*)`?(\s+is\s+)?/g;for(let d=u.exec(e);d;d=u.exec(e))l(d[2]?to(e.slice(d.index+d[0].length)):d[1]);return{sources:o,unresolved:i}}function to(e){const n=/^`?([A-Za-z_]\w*)`?/.exec(e);if(!n)return;const r=e.slice(n[0].length).trimStart();if(r.startsWith("."))return null;if(!r.startsWith("("))return n[1]}const Tr={"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},jl=j.createContext(void 0);function yo({layer:e,title:n,children:r,testId:o}){const i=j.useContext(jl);if(!i||!e||!i.layers.includes(e))return t.jsx(p.Tooltip,{title:n,children:t.jsx(p.Box,{component:"span",tabIndex:0,role:"img","aria-label":n,"data-testid":o,sx:{display:"inline-flex",borderRadius:1,...Tr},children:r})});const l=i.openLayer===e;return t.jsx(p.Tooltip,{title:n,children:t.jsx(p.Box,{component:"button",type:"button",onClick:()=>i.toggle(e),"aria-expanded":l,"aria-controls":i.cardId,"aria-label":`${n} ${l?"Hide":"Show"} details.`,"data-testid":o,"data-header-chip":e,sx:{appearance:"none",border:"none",background:"none",font:"inherit",p:0,cursor:"pointer",display:"inline-flex",alignItems:"center",borderRadius:1,"& [data-pill-tone]":{transition:"filter 120ms ease",...l?{filter:"brightness(0.9)"}:{}},"&:hover [data-pill-tone]":{filter:l?"brightness(0.9)":"brightness(0.94)"},...Tr},children:r})})}function Tm(e){try{const{data:n}=JSON.parse(e);return n?.kind==="array_cell"?n.array_value.length:n?.kind==="record_cell"?1:0}catch{return}}const Om={authorize:[],accessFilter:[]};function da(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim()!==""):[]}function Mm(e){const n=new Map,r=e?.sources;if(!Array.isArray(r))return n;for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(typeof i.name!="string"||!i.name)continue;const l=da(i.authorize),a=da(i.accessFilter);l.length===0&&a.length===0||n.set(i.name,{authorize:l,accessFilter:a})}return n}function Qr(e,n){return n&&e?.get(n)||Om}function Yt(e){return!!e&&e.authorize.some(n=>n.trim()!=="true")}function Jt(e){return!!e&&e.accessFilter.length>0}const ha=/^\(?\s*(?:'([^']*)'|"([^"]*)")\s+in\s+\$GROUPS\s*\)?$/;function Em(e){const n=e.trim();if(n==="false")return"no one";const r=ha.exec(n);if(r)return`members of ${r[1]??r[2]}`;for(const o of["or","and"]){const i=n.split(new RegExp(`\\s+${o}\\s+`));if(i.length<2)continue;const l=i.map(a=>ha.exec(a.trim()));if(l.every(a=>a)){const a=l.map(u=>u[1]??u[2]);return o==="or"?`members of ${a.slice(0,-1).join(", ")} or ${a[a.length-1]}`:`members of all of ${a.join(", ")}`}}}function Tl(e){const n=e.authorize.filter(o=>o.trim()!=="true").map(o=>Em(o)??"readers its access rule admits");return Array.from(new Set(n)).join(", and ")}const Ol="Only some readers can query this source",Ml="Each reader sees only the rows they're allowed to see";function Im(e,n){return e?Yt(n)?`You can't access ${e}. It is restricted to ${Tl(n)}; ask an administrator of this package for access.`:`You can't access ${e}. Ask an administrator of this package for access.`:"You don't have access to run this. Ask an administrator of this package for access."}function Dm(e,n){if(!(!Jt(e)||n===void 0))return Tm(n)===0?"Filtered to your rows: this source shows each reader only the rows they're allowed to see.":void 0}function El(e){return Yt(e)||Jt(e)}function $m(e,n){return`This join doesn't apply the ${Yt(n)&&Jt(n)?"access rule and row filter":Yt(n)?"access rule":"row filter"} on ${e}: its rows are read under this source's rules.`}function Fm({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(fa,{label:"Restricted",meaning:Ol}),Jt(e)&&t.jsx(fa,{label:"Row filtered",meaning:Ml})]})}function fa({label:e,meaning:n}){return t.jsx(yo,{layer:"access",title:`${e}: ${n}`,testId:`source-access-chip-${e==="Restricted"?"restricted":"row-filtered"}`,children:t.jsx($t,{tone:"neutral",size:"header",children:e})})}function Il({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(p.Tooltip,{title:`Restricted: ${Ol}`,children:t.jsx($t,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Restricted"})}),Jt(e)&&t.jsx(p.Tooltip,{title:`Row filtered: ${Ml}`,children:t.jsx($t,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Row filtered"})})]})}function Am(e){return[Yt(e)&&"restricted",Jt(e)&&"row filtered"].filter(Boolean).map(n=>`, ${n}`).join("")}function Rm({access:e,showRules:n}){const r=Yt(e),o=Jt(e);return!r&&!o?null:t.jsxs(p.Box,{"data-testid":"source-access-facts",sx:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline"},children:[r&&t.jsx(Ut,{label:"Restricted to",value:Tl(e)}),r&&n&&e.authorize.filter(i=>i.trim()!=="true").map((i,l)=>t.jsx(Ut,{label:"Access rule",value:i,mono:!0},`a${l}`)),o&&t.jsx(Ut,{label:"Rows",value:"Rows are filtered for each reader"}),o&&n&&e.accessFilter.map((i,l)=>t.jsx(Ut,{label:"Row filter",value:i,mono:!0},`f${l}`))]})}const ma="Private",Lm="index.malloy doesn't export this file, so only people who can edit the package see it.";function pa(){return t.jsx(yo,{title:`${ma}: ${Lm}`,testId:"model-viewer-off-surface",children:t.jsx($t,{tone:"warning",size:"header",children:ma})})}const ga="Public",_m="index.malloy exports this source, so everyone who can read the package can query it.";function Nm(){return t.jsx(yo,{title:`${ga}: ${_m}`,testId:"model-viewer-public-surface",children:t.jsx($t,{tone:"positive",size:"header",children:ga})})}function Pm(e){const n=j.useRef(e);return e!==void 0&&(n.current=e),n.current}function $s({title:e,titleAdornments:n,kindLabel:r,meta:o,doc:i,provenance:l,actions:a,status:u,headingLevel:d="h1",modelDoc:h,access:y,showRules:b=!1,isSource:x=!0,offSurface:v,publicSurface:k=!1}){const C=Yt(y)||Jt(y),S=C?["access"]:[],[T,O]=j.useState(void 0),M=T!==void 0&&S.includes(T)?T:void 0,E=Pm(M),R=j.useId(),P={openLayer:M,layers:S,toggle:_=>O(V=>V===_?void 0:_),cardId:R},F=C||v||k||!!u,B=q.usePublisherTheme().theme.ui.type.pageTitle,D=typeof B.fontSize=="number"?`${B.fontSize}px`:B.fontSize;return t.jsxs(p.Box,{children:[t.jsxs(p.Box,{"data-testid":"model-viewer-source-heading",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:eo,pb:.5},children:[t.jsx(p.Box,{component:d,sx:{m:0,fontSize:d==="h1"?D:`calc(${D} * 0.8)`,fontWeight:B.fontWeight??600,lineHeight:1.25,color:"text.primary",fontFamily:Dt,minWidth:0,overflowWrap:"anywhere"},children:e}),n,a&&t.jsx(p.Box,{sx:{ml:"auto",display:"flex",alignItems:"center",gap:1},children:a})]}),!x&&v&&t.jsx(p.Box,{sx:{display:"flex",alignItems:"center",pt:.5,pb:1},children:t.jsx(pa,{})}),x&&F&&t.jsx(jl.Provider,{value:P,children:t.jsxs(p.Box,{"data-testid":"model-viewer-status-row",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:.5,pb:1},children:[t.jsx(Fm,{access:y}),v&&t.jsx(pa,{}),k&&t.jsx(Nm,{}),u]})}),h&&t.jsx(ya,{doc:h,label:"model description",testId:"model-viewer-model-doc"},`model:${h}`),i&&t.jsx(ya,{doc:i},i),(r!==void 0||o!==void 0||l)&&t.jsxs(p.Box,{"data-testid":"model-viewer-source-meta",sx:{display:"flex",alignItems:"center",gap:.75,minWidth:0,pb:2,fontSize:wt.body,color:"text.secondary",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[r!==void 0&&t.jsx(p.Box,{component:"span","data-testid":"model-viewer-source-kind",children:r}),r!==void 0&&(o!==void 0||l)&&t.jsx(p.Box,{component:"span","aria-hidden":!0,children:"·"}),o!==void 0&&t.jsx(p.Box,{component:"span",children:o}),o!==void 0&&l&&t.jsx(p.Box,{component:"span","aria-hidden":!0,children:"·"}),l&&t.jsx(p.Box,{component:"span",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:l})]}),t.jsx(p.Collapse,{in:M!==void 0,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{id:R,"data-testid":"model-viewer-source-detail","data-layer":E??void 0,sx:{...Pn,p:jr,mb:2},children:E==="access"&&y&&t.jsx(Rm,{access:y,showRules:b})})})]})}const zm=2;function ya({doc:e,label:n="description",testId:r="model-viewer-source-doc"}){const[o,i]=j.useState(!1),[l,a]=j.useState(!1),u=j.useRef(null);return j.useEffect(()=>{const d=u.current;if(!d||o)return;const h=()=>a(d.scrollHeight>d.clientHeight+1);if(h(),typeof ResizeObserver>"u")return;const y=new ResizeObserver(h);return y.observe(d),()=>y.disconnect()},[o,e]),t.jsxs(p.Box,{"data-testid":r,sx:{pb:.5},children:[t.jsx(p.Box,{ref:u,sx:{fontSize:wt.body,lineHeight:1.5,color:"text.secondary",whiteSpace:"pre-line",...o?{}:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:zm,overflow:"hidden"}},children:Dl(e)}),(l||o)&&t.jsx(p.Box,{component:"button",type:"button",onClick:()=>i(!o),"aria-expanded":o,"aria-label":o?`Show less of the ${n}`:`Show the full ${n}`,sx:{all:"unset",cursor:"pointer",fontSize:wt.small,color:"text.secondary",textDecoration:"underline","&:hover":{color:"text.primary"},"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}},children:o?"Less":"More"})]})}function Dl(e){return e.split(/(`[^`\n]+`)/g).map((n,r)=>/^`[^`]+`$/.test(n)?t.jsx(p.Box,{component:"code",sx:{fontFamily:Dt,fontSize:"0.92em",color:"text.primary"},children:n.slice(1,-1)},r):n)}function cs(e){const n=e?.response?.status;return typeof n=="number"?n:void 0}function Wm(e){const n=cs(e);return n===403||n===404}function qm(e,n){if(!e?.modelPath||!e.sourceName)return{kind:"unknown"};const r=n.get(e.modelPath);return r?r.has(e.sourceName)?{kind:"link"}:{kind:"join-only"}:{kind:"unknown"}}const xo=j.createContext([]),ts="text.primary",ur=e=>({main:e,tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),Fn={steel:ur(q.PALETTE.cyan),sage:ur(q.PALETTE.lime),brown:ur(q.PALETTE.slate),olive:ur(q.PALETTE.violet),amber:ur(q.PALETTE.amber)};function xa(e){return e==="measure"?Fn.sage:e==="calculate"?Fn.amber:e==="view"?Fn.olive:Fn.steel}const va=["steel","brown","olive","sage"];function Bm(e){return va[e%va.length]}const $l={small:13,caption:12},Vm={fontFamily:Dt,fontSize:$l.small,fontWeight:500,color:ts},Fl={fontSize:$l.caption,color:"text.secondary"};function _n({label:e,count:n,level:r="h2",testId:o,action:i,children:l}){return n===0?null:r==="h3"?t.jsxs(p.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:2},children:[t.jsx(p.Box,{component:"h3",sx:{m:0,mb:1,fontSize:wt.bodyLarge,fontWeight:Js.strong,color:ts},children:e}),l]}):t.jsxs(p.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:3},children:[t.jsxs(p.Box,{sx:{mb:2},children:[t.jsx(p.Box,{component:"h2",sx:{m:0,fontSize:"1.25rem",fontWeight:Js.strong,color:ts},children:e}),i&&t.jsx(p.Box,{sx:{...Fl,mt:.25,display:"flex",alignItems:"center"},children:i})]}),l]})}function vr(e,n){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${n} ${e.at(-1)}`}function ba(e,n){return`${e.label??e.name}: ${c.describeGivenValue(e,n)}`}const Hr=e=>e.label??e.name;function Al(e,n,r=void 0,o=void 0,i=!1,l="source"){const a=e??[],u=M=>r?.[M.name]!==void 0,d=M=>o?.has(M.name)===!0,h=a.filter(M=>!u(M)&&M.default===void 0),y=n??[],b=y.length===0&&h.length>0&&h.every(M=>d(M)),x=i&&b?h:[];if(x.length===0&&(h.length>0||y.length>0)){const M=h.length>0?`a value for ${h.length===1?"the given":"the givens"} ${h.map(Hr).join(", ")}`:"",E=y.length>0?`${y.length===1?"the required filter":"the required filters"} ${y.join(", ")}`:"",R=h.filter(d),P=R.length===0?"":R.length===h.length?` This page can't tell whether this ${l} reads ${h.length===1?"it":"them"}.`:` This page can't tell whether this ${l} reads ${vr(R.map(Hr),"or")}.`;let F;return E===""?F=`This needs ${M}. Set ${h.length===1?"it":"them"} in the Givens section above.${P}`:M===""?F=`This needs ${E}, which this page can't set; open the source in a dashboard or notebook.`:F=`This needs ${M} (set ${h.length===1?"it":"them"} in the Givens section above) and ${E}, which this page can't set; open the source in a dashboard or notebook.${P}`,{kind:"blocked",reason:F,canRunAnyway:b}}const v=M=>M.length>0?`${M.length===1?"the default":"the defaults"} ${M.map(E=>ba(E)).join(", ")}`:"",k=[];x.length>0&&k.push(`Ran without a value for ${x.length===1?"the given":"the givens"} ${vr(x.map(Hr),"and")}, which this page can't tell this ${l} reads.`);const C=a.filter(M=>!x.includes(M)),S=C.filter(M=>!d(M)),T=v(S.filter(M=>!u(M)));T!==""&&k.push(`Ran with ${T}.`);const O=C.filter(d);if(O.length>0){const M=[O.filter(u).map(E=>ba(E,r?.[E.name])).join(", "),v(O.filter(E=>!u(E)))].filter(E=>E!=="").join(" and ");k.push(O.length===C.length?`This page can't tell which givens this ${l} reads. Where it reads one, it ran with ${M}.`:`This page can't tell whether this ${l} reads ${vr(O.map(Hr),"or")}. Where it does, it ran with ${M}.`)}return k.length>0?{kind:"noted",note:k.join(" ")}:{kind:"ok"}}const Hm=400;function Um({givens:e,unknown:n,inheritedFrom:r,values:o,onChange:i,onReset:l,environmentName:a,packageName:u,modelPath:d,versionId:h,declaredTypes:y}){const b=j.useMemo(()=>[...e],[e]),x=j.useMemo(()=>{const F=e.filter(B=>n?.has(B.name));if(F.length!==0)return F.length===e.length?"This page can't tell which of these givens this source reads, so a value set here may not apply to it.":`This page can't tell whether this source reads ${vr(F.map(B=>B.label??B.name),"or")}, so a value set for ${F.length===1?"it":"them"} may not apply.`},[e,n]),[v,k]=j.useState(()=>new Set),C=j.useCallback(F=>k(B=>B.has(F)?B:new Set([...B,F])),[]),S=c.useSettled(o,Hm),T=j.useMemo(()=>({values:S,declaredTypes:y}),[S,y]),{options:O,isLoading:M,failed:E,truncated:R,search:P}=c.useSuggestOptions(a,u,d,b,h,T,void 0,v,!0);return t.jsxs(_n,{label:"Givens",count:e.length,testId:"model-givens-section",children:[t.jsx(p.Box,{sx:{"& .MuiPaper-root":{borderColor:"divider"}},children:t.jsx(c.GivensPanel,{layout:"bar",givens:b,values:o,onChange:i,onReset:l,options:O,optionsLoading:M,optionsFailed:E,optionsTruncated:R,optionSearch:P,onControlOpen:C})}),x&&t.jsx(un,{"data-testid":"model-givens-unknown",sx:{mt:1},children:x}),r&&r.size>0&&t.jsx(un,{"data-testid":"model-givens-inherited",sx:{mt:1},children:[...r].map(([F,B])=>B.length===1?`${F} is inherited from ${B[0]}, which this model doesn't export.`:`${F} is inherited from ${B.slice(0,-1).join(", ")} and ${B.at(-1)}, none of which this model exports.`).join(" ")})]})}const Gm="A source is a queryable entry point into the model — pick one to browse its dimensions, measures, views and joins.";function Ym(e,n=!1){return e===0?"No sources":`${e} ${n?"public ":""}source${e===1?"":"s"}`}const Km=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),Qm=c.createSvgIcon(t.jsx("path",{d:"M6 6v2h8.59L5 17.59 6.41 19 16 9.41V18h2V6z"})),Zm=c.createSvgIcon(t.jsx("path",{d:"M4 9h4v11H4zm12 4h4v7h-4zm-6-9h4v16h-4z"})),Xm=c.createSvgIcon([t.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14z"},"0"),t.jsx("path",{d:"M6.25 7.72h5v1.5h-5zM13 15.75h5v1.5h-5zm0-2.5h5v1.5h-5zM8 18h1.5v-2h2v-1.5h-2v-2H8v2H6V16h2zm6.09-7.05 1.41-1.41 1.41 1.41 1.06-1.06-1.41-1.42 1.41-1.41L16.91 6 15.5 7.41 14.09 6l-1.06 1.06 1.41 1.41-1.41 1.42z"},"1")]),Rl=c.createSvgIcon(t.jsx("path",{d:"M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 18H4V10h16zm0-13H4V5h16z"})),Jm=c.createSvgIcon(t.jsx("path",{d:"M17 20.41 18.41 19 15 15.59 13.59 17zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5z"})),ep=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"})),tp=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),np=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),rp=c.createSvgIcon(t.jsx("path",{d:"m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"})),sp=c.createSvgIcon(t.jsx("path",{d:"M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5m0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5m0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5M7 19h14v-2H7zm0-6h14v-2H7zm0-8v2h14V5z"})),Ll=c.createSvgIcon(t.jsx("path",{d:"M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6z"})),op=c.createSvgIcon(t.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2M9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9zm9 14H6V10h12zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2"})),ip=c.createSvgIcon(t.jsx("path",{d:"m20.5 10 .5-2h-4l1-4h-2l-1 4h-4l1-4h-2L9 8H5l-.5 2h4l-1 4h-4L3 16h4l-1 4h2l1-4h4l-1 4h2l1-4h4l.5-2h-4l1-4zm-7 4h-4l1-4h4z"})),_l=c.createSvgIcon(t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8m.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"})),ap=c.createSvgIcon([t.jsx("path",{d:"m21.41 11.41-8.83-8.83c-.37-.37-.88-.58-1.41-.58H4c-1.1 0-2 .9-2 2v7.17c0 .53.21 1.04.59 1.41l8.83 8.83c.78.78 2.05.78 2.83 0l7.17-7.17c.78-.78.78-2.04-.01-2.83M12.83 20 4 11.17V4h7.17L20 12.83z"},"0"),t.jsx("circle",{cx:"6.5",cy:"6.5",r:"1.5"},"1")]),Nl=c.createSvgIcon(t.jsx("path",{d:"M17 6H7c-3.31 0-6 2.69-6 6s2.69 6 6 6h10c3.31 0 6-2.69 6-6s-2.69-6-6-6m0 10H7c-2.21 0-4-1.79-4-4s1.79-4 4-4h10c2.21 0 4 1.79 4 4s-1.79 4-4 4m0-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"})),lp=c.createSvgIcon(t.jsx("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"})),Pl=c.createSvgIcon(t.jsx("path",{d:"M3 5v14h18V5zm5.33 12H5V7h3.33zm5.34 0h-3.33V7h3.33zM19 17h-3.33V7H19z"})),cp=c.createSvgIcon(t.jsx("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22zm1 14h-2v2h2zm0-6h-2v4h2z"}));function rt(e,n){const r=({size:o,...i})=>t.jsx(e,{...i,sx:{fontSize:o}});return r.displayName=n,r}const up=rt(Km,"IconText"),wa=rt(Qm,"IconOpen"),zl=rt(Zm,"IconResult"),dp=rt(Xm,"IconCalculation"),hp=rt(Rl,"IconDate"),fp=rt(Jm,"IconJoin"),mp=rt(ep,"IconCode"),pp=rt(tp,"IconList"),gp=rt(np,"IconRecord"),yp=rt(rp,"IconCollapse"),xp=rt(c.ExpandMoreIcon,"IconExpand"),vp=rt(sp,"IconFields"),bp=rt(Ll,"IconDropdown"),wp=rt(op,"IconLock"),Wl=rt(ip,"IconNumber"),Sp=rt(_l,"IconTimestamp"),kp=rt(ap,"IconValues"),Cp=rt(Nl,"IconBoolean"),jp=rt(lp,"IconGivens"),ql=rt(Pl,"IconColumn");rt(cp,"IconWarning");const Or=j.createContext(void 0);function vo(){const[e,n]=j.useState(!1),r=j.useContext(Or),[o,i]=j.useState(r?.n);return r&&r.n!==o&&(i(r.n),n(r.open)),[e,n]}function Tp({allOpen:e,onToggle:n,noun:r,disabledReason:o}){const i=e?t.jsx(yp,{size:16,"aria-hidden":!0}):t.jsx(xp,{size:16,"aria-hidden":!0});return t.jsx(p.Tooltip,{title:o??"",children:t.jsx("span",{children:t.jsxs(p.ButtonBase,{disabled:!!o,onClick:n,"aria-label":o??`${e?"Collapse":"Expand"} all ${r[1]}`,sx:{font:"inherit",color:"text.secondary",gap:.25,borderRadius:1,"&:hover":{color:"text.primary",textDecoration:"underline"},...Tr,"&.Mui-disabled":{opacity:.5}},children:[i,e?"Collapse all":"Expand all"]})})})}function ns({noun:e,disabledReason:n}){const[r,o]=j.useState(void 0),i=r?.open??!1;return{command:r,action:t.jsx(Tp,{allOpen:i,onToggle:()=>o({open:!i,n:(r?.n??0)+1}),noun:e,disabledReason:n})}}let Fs;function Op(e,n){if(Fs?.text===n)return Fs.parsed;const r=n.replace(/\r\n/g,`
17
17
  `);let o;try{o={lines:r.split(`
18
- `),symbols:e.Malloy.parse({source:r}).symbols}}catch{o=void 0}return Fs={text:n,parsed:o},o}function ds(e,n){const{start:r,end:o}=n;return r.line===o.line?(e[r.line]??"").slice(r.character,o.character):[(e[r.line]??"").slice(r.character),...e.slice(r.line+1,o.line),(e[o.line]??"").slice(0,o.character)].join(`
19
- `)}let Bl,Ur;function Ep(){return Ur??=import("@malloydata/malloy").then(e=>{const n="Malloy"in e?e:e.default;return Bl=n,n}),Ur.catch(()=>{Ur=void 0}),Ur}function Vl(e,n=!0){const[r,o]=j.useState(Bl),[i,l]=j.useState(!1),a=!!e&&n;return j.useEffect(()=>{if(!a||r)return;let u=!0;return Ep().then(h=>u&&o(h),()=>u&&l(!0)),()=>{u=!1}},[a,r]),{parsed:j.useMemo(()=>a&&r&&e?Mp(r,e):void 0,[a,r,e]),pending:a&&!r&&!i}}function Ip(e,n){if(!e)return;const r=e.symbols.filter(o=>o.type==="query"&&o.name.replace(/^`(.*)`$/,"$1")===n);if(r.length===1)return`query: ${ds(e.lines,r[0].range).trimEnd()}`}function Hl(e){const n=e.replace(/^\n+/,"").split(`
18
+ `),symbols:e.Malloy.parse({source:r}).symbols}}catch{o=void 0}return Fs={text:n,parsed:o},o}function us(e,n){const{start:r,end:o}=n;return r.line===o.line?(e[r.line]??"").slice(r.character,o.character):[(e[r.line]??"").slice(r.character),...e.slice(r.line+1,o.line),(e[o.line]??"").slice(0,o.character)].join(`
19
+ `)}let Bl,Ur;function Mp(){return Ur??=import("@malloydata/malloy").then(e=>{const n="Malloy"in e?e:e.default;return Bl=n,n}),Ur.catch(()=>{Ur=void 0}),Ur}function Vl(e,n=!0){const[r,o]=j.useState(Bl),[i,l]=j.useState(!1),a=!!e&&n;return j.useEffect(()=>{if(!a||r)return;let d=!0;return Mp().then(h=>d&&o(h),()=>d&&l(!0)),()=>{d=!1}},[a,r]),{parsed:j.useMemo(()=>a&&r&&e?Op(r,e):void 0,[a,r,e]),pending:a&&!r&&!i}}function Ep(e,n){if(!e)return;const r=e.symbols.filter(o=>o.type==="query"&&o.name.replace(/^`(.*)`$/,"$1")===n);if(r.length===1)return`query: ${us(e.lines,r[0].range).trimEnd()}`}function Hl(e){const n=e.replace(/^\n+/,"").split(`
20
20
  `),r=[];let o=0;for(;o<n.length;){const i=n[o].trim();if(!i.startsWith("#"))break;!i.startsWith('#"')&&!i.startsWith("#(doc)")&&r.push(n[o]),o+=1}return[...r,...n.slice(o)].join(`
21
- `).trim()}function Dp(e,n){const r=Hl(n),o=pn(e),i=new RegExp(`^(?:(?:dimension|measure|view)\\s*:\\s*)?${o}\\s+is\\s+`),l=r.replace(i,"");if(l===r||!(l.startsWith("{")&&l.endsWith("}")))return r;const d=l.slice(1,-1).replace(/^\n/,"").replace(/\s+$/,"").split(`
22
- `),u=d.filter(b=>b.trim()).map(b=>b.match(/^[ \t]*/)[0].length),h=u.length?Math.min(...u):0;return d.map(b=>b.slice(h)).join(`
23
- `).trim()||r}function $p(e,n){const r=Hl(n),o=r.split(`
24
- `),i=o.findIndex(d=>!d.trim().startsWith("#"));if(i<0)return r;const l=o[i];if(/^\s*view\s*:/.test(l))return ka(o,i).join(`
25
- `);const a=pn(e);return new RegExp(`^\\s*${a}\\s+is\\b`).test(l)?(o[i]=l.replace(/^(\s*)/,"$1view: "),ka(o,i).join(`
26
- `)):r}function ka(e,n){const r=e.slice(n+1).filter(i=>i.trim()!=="");if(r.length===0)return e;const o=Math.min(...r.map(i=>i.length-i.trimStart().length));return o===0?e:e.map((i,l)=>l<=n?i:i.slice(Math.min(o,i.length-i.trimStart().length)))}function wo(e){return e.kind==="dimension"&&e.indexed===!0}function So(e){return!!e&&(e.loading||!!e.code||!!e.inheritedFrom||!!e.error)}function Ap(e,n){const r=[],o=[];for(const i of e){const l=n(i);(!!l&&!l.loading&&(!!l.code||!!l.error)||wo(i)?r:o).push(i)}return o.length===0||r.length===0?e:[...r,...o]}function Fp(e,n){return n.includes(`
27
- `)||e.scrollWidth>e.clientWidth}const Rp={dimension:ql,measure:Wl,calculate:hp,view:zl,join:mp};function Np(e){switch(e){case"dimension":case"measure":case"calculate":case"view":return va(e).main;case"column":return va("dimension").main;case"join":return An.brown.main}}function Lp(e){const n=e?.trim().toLowerCase()??"";if(!n)return;if(n.startsWith("array"))return gp;if(n.startsWith("record")||/\bfields?\b/.test(n))return yp;switch(n.split(/[\s·<]/)[0]){case"string":return dp;case"number":return Wl;case"date":return fp;case"timestamp":case"timestamptz":return kp;case"boolean":return jp;default:return}}const _p=16;function ko({kind:e,dataType:n}){const r=e==="dimension"||e==="measure"||e==="calculate"||e==="column"?Lp(n):void 0;return t.jsx(p.Box,{component:"span","aria-hidden":!0,"data-row-glyph":e,sx:{display:"inline-flex",alignSelf:"center",flexShrink:0,color:Np(e)},children:j.createElement(r??Rp[e==="column"?"dimension":e],{size:_p})})}function Co(e,n){return(n?e.givensBySource?.get(n):void 0)??e.givens}function Ul(e,n){if(!e.givenValues||!n)return e;const r=new Set(n.map(i=>i.name)),o=Object.entries(e.givenValues).filter(([i])=>r.has(i));return{...e,givenValues:o.length>0?Object.fromEntries(o):void 0}}function Pp({run:e,modelPath:n,query:r,enabled:o}){const{server:i,apiClients:l}=q.useServer(),a=yt.useQuery({...Gl({server:i,apiClients:l,run:e,modelPath:n,query:r}),enabled:o,refetchOnWindowFocus:!1,refetchOnReconnect:!1});return{result:a.data?.data.result,isSuccess:a.isSuccess,isLoading:a.isLoading,isFetching:a.isFetching,isError:a.isError,error:a.error,refetch:a.refetch}}function jo(e,n,r,o){return["model-viewer-run",e,n.projectName,n.packageName,r,n.versionId??"",o,yo(n.givenValues),...n.includeHiddenFilesAndSources?["off-surface"]:[]]}function Gl({server:e,apiClients:n,run:r,modelPath:o,query:i}){const l=yo(r.givenValues)===""?void 0:r.givenValues;return{queryKey:jo(e,r,o,i),queryFn:async({signal:a})=>{const d=performance.now(),u=()=>Math.round(performance.now()-d);try{const h=await n.models.executeQueryModel(r.projectName,r.packageName,o,{query:i,versionId:r.versionId,...l&&{givens:l},...r.queryMetadata&&{queryMetadata:{...r.queryMetadata}}},r.includeHiddenFilesAndSources?!0:void 0,void 0,{signal:a});return r.onQueryRun?.({outcome:"success",durationMs:u()}),h}catch(h){throw a?.aborted||r.onQueryRun?.({outcome:"error",durationMs:u()}),h}},staleTime:1/0,retry:!1}}const Rs=12,zp=5*6e4;function Wp(e){const n=us(e);return n===void 0?!1:n>=400&&n<500&&n!==401&&n!==408&&n!==429}function qp(e){if(!e)return[];const{data:n}=JSON.parse(e);return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>{if(r.kind!=="record_cell")return[];const o=r.record_value[0];if(!o)return[];switch(o.kind){case"string_cell":return[o.string_value];case"number_cell":return[String(o.number_value)];case"boolean_cell":return[String(o.boolean_value)];case"date_cell":return[o.date_value];case"timestamp_cell":return[o.timestamp_value];default:return[]}})}function Bp({run:e,modelPath:n,sourceName:r,field:o,fetchSamples:i,generation:l}){const{server:a,apiClients:d}=q.useServer(),u=o?.kind==="dimension"&&o.indexed===!0,h=Co(e,r),y=u&&!i?Fl(h,e.requiredFiltersBySource?.get(r),e.givenValues):void 0,b=y?.kind==="blocked"?y.reason:void 0,x=u&&!b?o.name:void 0,v=yt.useQuery({...Gl({server:a,apiClients:d,run:Ul(e,h),modelPath:n,query:c.sampleValuesQuery(r,x??"",Rs)}),enabled:!!x&&!i,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),k=yt.useQuery({queryKey:["model-viewer-samples",a,e.projectName,e.packageName,e.versionId??"",n,r,x,l??"host"],enabled:!!x&&!!i,staleTime:zp,retry:!1,refetchOnWindowFocus:!1,queryFn:async({signal:T})=>{try{const O=await i({modelPath:n,sourceName:r,fieldName:x,limit:Rs,signal:T}),M=Array.isArray(O)?{values:O}:O;return{...M,values:M.values.slice(0,Rs)}}catch(O){if(Wp(O))return{values:[]};throw O}}}),C=i?k:v,S=i?k.data:v.data&&{values:qp(v.data.data.result)};return{samples:S?.values??[],total:S?.total,unavailable:b??S?.unavailable,loading:!!x&&C.isPending,failed:C.isError}}function Vp({children:e}){return t.jsx(p.Box,{component:"span",sx:{fontFamily:Dt,fontSize:St.caption,color:"text.primary",bgcolor:rt.background.muted,border:"1px solid",borderColor:"divider",borderRadius:1,padding:"2px 8px"},children:e})}function Hp({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l}){const{samples:a,total:d,unavailable:u,loading:h,failed:y}=Bp({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l});return t.jsxs(p.Box,{"data-testid":"model-viewer-values",sx:{fontSize:St.small},children:[t.jsx(p.Box,{component:"div",sx:{color:ls,fontSize:St.caption,mb:"6px"},children:d!=null?`The most common of ${d.toLocaleString()} ${d===1?"value":"values"}`:"The most common values"}),h?t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}}):u?t.jsx(p.Box,{component:"span","data-testid":"model-viewer-values-unavailable",sx:{color:"text.secondary"},children:u}):y?t.jsx(p.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"Sample values couldn't be loaded."}):a.length===0?t.jsx(p.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"No values found."}):t.jsx(p.Box,{sx:{display:"flex",flexWrap:"wrap",gap:"6px"},children:a.map(b=>t.jsx(Vp,{children:b},b))})]})}const Ns={scopeName:"source.malloy",patterns:[{include:"#malloy-language"}],repository:{"malloy-language":{patterns:[{include:"#sql-string"},{include:"#comments"},{include:"#tags"},{include:"#strings"},{include:"#numbers"},{include:"#keywords"},{include:"#properties"},{include:"#functions"},{include:"#datetimes"},{include:"#identifiers-quoted"},{include:"#types"},{include:"#constants"},{include:"#timeframes"},{include:"#identifiers-unquoted"}]},"malloy-matched":{begin:"{",end:"}",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"malloy-in-sql":{begin:"%{",name:"source.malloy-in-sql",end:"}%?",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"sql-string":{patterns:[{begin:'(\\b[A-Za-z_][A-Za-z_0-9]*)(\\s*\\.\\s*)(sql)(\\s*\\(\\s*)(""")',end:'"""',beginCaptures:{1:{name:"variable.other"},3:{name:"keyword.control.sql"},5:{name:"punctuation.sql-block.open"}},endCaptures:{0:{name:"punctuation.sql-block.close"}},name:"source.sql",patterns:[{include:"#malloy-in-sql"},{include:"source.sql"}]}]},functions:{patterns:[{match:"(?i)\\b(count)(\\s*\\()(distinct)",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.function.modifier"}}},{match:"(?i)\\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE|UNGROUPED)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(!)(timestamp|number|string|boolean|date)?(\\s*\\()",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.type"}}}]},datetimes:{patterns:[{match:"(?i)@[0-9]{4}-[0-9]{2}-[0-9]{2}[ T][0-9]{2}:[0-9]{2}((:[0-9]{2})(([\\.,][0-9]+)(\\[[A-Za-z_/]+\\])?)?)?",name:"constant.numeric.timestamp"},{match:"(?i)@[0-9]{4}(-Q[1-4]|-[0-9]{2}(-[0-9]{2}(-WK)?)?)?",name:"constant.numeric.date"}]},"identifiers-quoted":{patterns:[{match:"`[^`]*`",name:"variable.other.quoted"}]},"identifiers-unquoted":{patterns:[{match:"(?i)\\b[A-Za-z_][A-Za-z_0-9]*\\b",name:"variable.other"}]},timeframes:{patterns:[{match:"(?i)\\b((year|quarter|month|week|day|hour|minute|second)s?)\\b",name:"keyword.other.timeframe"},{match:"(?i)\\b(day_of_year|day_of_month)\\b",name:"keyword.other.timeframe"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]},tags:{patterns:[{match:"##\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:'#"',end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{match:"#\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:"#\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"##\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"#",end:"\\n",beginCaptures:{0:{name:"string.quoted"}},name:"string.quoted"}],repository:{"tag-values":{name:"support.type.property-name.json",match:'(-)?((?:[^\\s=#]+)|(?:"[^#]+"))(?:\\s*(=)\\s*((?:[^\\s=#]+)|(?:"[^#]+")))?',captures:{1:{name:"keyword.control.negate"},2:{name:"support.type.property-name.json"},3:{name:"keyword.operator.comparison.ts"},4:{name:"string.quoted"}}}}},strings:{patterns:[{begin:"'",end:"'",beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.single",patterns:[{include:"#escapes"}]},{begin:'"',end:'"',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.double",patterns:[{include:"#escapes"}]},{begin:'"""',end:'"""',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.triple"},{begin:"(?i)[r|/]'",end:"'",name:"string.regexp",patterns:[{include:"#regex-escapes"}]}],repository:{escapes:{name:"constant.character.escape",match:"\\\\(u[A-Fa-f0-9]{4}|.)",captures:{0:{name:"constant.character.escape"}}},"regex-escapes":{name:"constant.character.escape",match:"\\\\.",captures:{0:{name:"constant.character.escape"}}}}},numbers:{match:"(?i)(\\b((0|[1-9][0-9]*)(E[+-]?[0-9]+|\\.[0-9]*)?)|\\.[0-9]+)",name:"constant.numeric"},constants:{patterns:[{match:"(?i)\\bnull\\b",name:"constant.language.null"},{match:"(?i)\\btrue\\b",name:"constant.language.true"},{match:"(?i)\\bfalse\\b",name:"constant.language.false"}]},types:{patterns:[{match:"(?i)\\bstring\\b",name:"entity.name.type.string"},{match:"(?i)\\bnumber\\b",name:"entity.name.type.number"},{match:"(?i)\\bdate\\b",name:"entity.name.type.date"},{match:"(?i)\\btimestamp\\b",name:"entity.name.type.timestamp"},{match:"(?i)\\bboolean\\b",name:"entity.name.type.boolean"}]},properties:{patterns:[{match:"(?i)\\baccept\\b",name:"keyword.control.accept"},{match:"(?i)\\bselect\\b",name:"keyword.control.select"},{match:"(?i)\\bconnection\\b",name:"keyword.control.connection"},{match:"(?i)\\brun\\b",name:"keyword.control.run"},{match:"(?i)\\bextend\\b",name:"keyword.control.extend"},{match:"(?i)\\brefine\\b",name:"keyword.control.refine"},{match:"(?i)\\baggregate\\b",name:"keyword.control.aggregate"},{match:"(?i)\\bsample\\b",name:"keyword.control.sample"},{match:"(?i)\\bcalculate\\b",name:"keyword.control.calculate"},{match:"(?i)\\btimezone\\b",name:"keyword.control.timezone"},{match:"(?i)\\bdimension\\b",name:"keyword.control.dimension"},{match:"(?i)\\bexcept\\b",name:"keyword.control.except"},{match:"(?i)\\bsource\\b",name:"keyword.control.source"},{match:"(?i)\\bgroup_by\\b",name:"keyword.control.group_by"},{match:"(?i)\\bhaving\\b",name:"keyword.control.having"},{match:"(?i)\\bindex\\b",name:"keyword.control.index"},{match:"(?i)\\bjoin_one\\b",name:"keyword.control.join_one"},{match:"(?i)\\bwith\\b",name:"keyword.control.with"},{match:"(?i)\\bjoin_many\\b",name:"keyword.control.join_many"},{match:"(?i)\\bjoin_cross\\b",name:"keyword.control.join_cross"},{match:"(?i)\\blimit\\b",name:"keyword.control.limit"},{match:"(?i)\\bmeasure\\b",name:"keyword.control.measure"},{match:"(?i)\\bnest\\b",name:"keyword.control.nest"},{match:"(?i)\\border_by\\b",name:"keyword.control.order_by"},{match:"(?i)\\bpartition_by\\b",name:"keyword.control.partition_by"},{match:"(?i)\\bprimary_key\\b",name:"keyword.control.primary_key"},{match:"(?i)\\bproject\\b",name:"keyword.control.project"},{match:"(?i)\\bquery\\b",name:"keyword.control.query"},{match:"(?i)\\brename\\b",name:"keyword.control.rename"},{match:"(?i)\\btop\\b",name:"keyword.control.top"},{match:"(?i)\\bview\\b",name:"keyword.control.view"},{match:"(?i)\\bwhere\\b",name:"keyword.control.where"},{match:"(?i)\\bdeclare\\b",name:"keyword.control.declare"}]},keywords:{patterns:[{match:"(?i)\\bis\\b",name:"keyword.control.is"},{match:"(?i)\\bon\\b",name:"keyword.control.on"},{match:"(?i)\\bnot\\b",name:"keyword.other.not"},{match:"(?i)\\bor\\b",name:"keyword.other.or"},{match:"(?i)\\bdesc\\b",name:"keyword.control.desc"},{match:"(?i)\\bby\\b",name:"keyword.control.by"},{match:"(?i)\\band\\b",name:"keyword.other.and"},{match:"(?i)\\basc\\b",name:"keyword.control.asc"},{match:"(?i)\\bfor\\b",name:"keyword.other.for"},{match:"(?i)\\belse\\b",name:"keyword.other.else"},{match:"(?i)\\bto\\b",name:"keyword.other.to"},{match:"(?i)\\bwhen\\b",name:"keyword.other.when"},{match:"(?i)\\bpick\\b",name:"keyword.other.pick"},{match:"(?i)\\bimport\\b",name:"keyword.control.import"}]}}},Up={...Ns,patterns:[...Ns.patterns,{include:"#docvar"}],repository:{...Ns.repository,docvar:{patterns:[{match:"\\<\\<[^(\\>\\>)]*\\>\\>",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"markup.italic.markdown"}]}}},Gp={name:"Malloy SQL",scopeName:"source.malloy-sql",patterns:[{include:"#malloysql-sql"}],repository:{"malloysql-sql":{beginCaptures:{0:{name:"entity.other.attribute.malloy-sql"},1:{name:"entity.other.attribute.malloy-sql"},3:{name:"comment.line.double-slash"}},name:"meta.embedded.block.malloysql.sql",patterns:[{include:"#comments"},{begin:"%{",end:"}%",beginCaptures:{0:{name:"punctuation.definition.malloy-sql"}},endCaptures:{0:{name:"punctuation.definition.malloy-sql"}},name:"meta.embedded.block.malloy",patterns:[{include:"source.malloy"}]},{include:"source.sql"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]}}},Yp="github-light",Kp="github-dark";let Ls;function Qp(){return Ls||(Ls=(async()=>{const[{createHighlighterCore:e},{createOnigurumaEngine:n},{default:r},{default:o},{default:i},{default:l},{default:a}]=await Promise.all([Promise.resolve().then(()=>require("./core-8NVBCLZh.cjs.js")),Promise.resolve().then(()=>require("./engine-oniguruma-BkproSVE.cjs.js")),Promise.resolve().then(()=>require("./sql-BqWZrLHB.cjs.js")),Promise.resolve().then(()=>require("./json-y-J1j5EW.cjs.js")),Promise.resolve().then(()=>require("./typescript-BqvpT6pB.cjs.js")),Promise.resolve().then(()=>require("./github-light-BFTOhCbz.cjs.js")),Promise.resolve().then(()=>require("./github-dark-BKL9xNgN.cjs.js"))]);return e({engine:n(Promise.resolve().then(()=>require("./wasm-Dw4u1m6u.cjs.js"))),themes:[l,a],langs:[r,o,i,{name:"malloy",scopeName:"source.malloy",embeddedLangs:["sql"],...Up},{name:"malloysql",scopeName:"source.malloy-sql",embeddedLangs:["sql"],...Gp}]})})()),Ls}async function To(e,n,r="light"){return(await Qp()).codeToHtml(e,{lang:n,theme:r==="dark"?Kp:Yp})}function Mr({code:e,testId:n,framed:r=!0}){const{mode:o}=q.usePublisherTheme(),[i,l]=j.useState(void 0);return j.useEffect(()=>{let a=!0;return To(e,"malloy",o).then(d=>a&&l(d)).catch(()=>a&&l(void 0)),()=>{a=!1}},[e,o]),t.jsx(p.Box,{"data-testid":n,sx:{fontFamily:Dt,fontSize:"0.75rem",overflowX:"auto","& pre":{m:0,background:"transparent !important"},...r&&{border:"1px solid",borderColor:"divider",borderRadius:1,px:1.5,py:1,bgcolor:"background.default"}},children:i?t.jsx("div",{dangerouslySetInnerHTML:{__html:i}}):t.jsx(p.Box,{component:"pre",sx:{whiteSpace:"pre"},children:e})})}function hs({message:e,onRetry:n,severity:r="error"}){return t.jsx(p.Alert,{severity:r,action:n&&t.jsx(p.Button,{color:"inherit",size:"small",onClick:n,children:"Retry"}),children:e})}function Yl(e){const n=e?.response?.data?.message;return typeof n=="string"&&n?n:void 0}function Kl(e,n){const r=Yl(n);return r?`${e}: ${r}`:`${e}.`}function Zp(e){const n=us(e);return!(n===400||n===401||n===403||n===404||n===422)}function Xp({query:e,error:n,onRetry:r,testId:o,forbiddenMessage:i}){const l=i!==void 0&&us(n)===403;return t.jsxs(p.Box,{"data-testid":o,sx:{display:"flex",flexDirection:"column",gap:1},children:[e&&t.jsx(Mr,{code:e,testId:"query-failure-code"}),t.jsx(hs,{message:l?i:Kl("Query failed",n),onRetry:r&&Zp(n)?r:void 0})]})}const Ca=j.forwardRef(function(n,r){return t.jsx(p.Button,{ref:r,variant:"contained",size:"small",disableElevation:!0,...n,sx:{textTransform:"none",...n.sx}})}),Jp=j.forwardRef(function(n,r){return t.jsx(p.Button,{ref:r,variant:"outlined",size:"small",color:"inherit",...n,sx:{textTransform:"none",borderRadius:999,borderColor:"divider",color:"text.secondary",...n.sx}})}),yr=10,eg="clamp(340px, 40%, 520px)";function tg({field:e,run:n,modelPath:r,sourceName:o,fieldCode:i,joined:l=!1}){const[a,d]=bo(),{fetchSamples:u,samplesGeneration:h,renderFieldStatus:y,renderFieldAction:b,renderFieldDetail:x}=cs(),v={modelPath:r,sourceName:o,field:e,joined:l},k=y?.(v),C=b?.(v),S=e.doc?void 0:i?.columnDoc,T=e.doc??S,O=So(i),M=j.useContext(vo),E=j.useMemo(()=>dn(i?.code,M),[i?.code,M]),R=wo(e)&&!l&&!!n,P=[...O?["code"]:[],...R?["values"]:[],...E.length>0?["givens"]:[]],A=$=>P.includes($),H=e.kind==="measure"?"measure":e.kind==="calculate"?"calculate":"dimension",D=P.length>0?t.jsxs(p.Box,{"data-testid":"model-viewer-field-card",sx:{...Pn,"& > * + *":{borderTop:1,borderColor:"divider"}},children:[A("code")&&(i?.loading?t.jsx(p.Box,{sx:{p:jr,display:"flex"},children:t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}})}):i?.code?t.jsx(Mr,{testId:"model-viewer-definition",code:Dp(e.name,i.code),framed:!1}):i?.inheritedFrom?t.jsx(Mr,{testId:"model-viewer-definition",code:`${i.inheritedFrom.fromTable?"// A column of the table this source reads, as it is":"// Passed through from the query this source is built on"}
28
- ${i.inheritedFrom.code}`,framed:!1}):t.jsx(p.Box,{sx:{p:1},children:t.jsx(hs,{message:"Couldn't load this model's code right now."})})),A("values")&&n&&t.jsx(p.Box,{sx:{p:jr},children:t.jsx(Hp,{run:n,fetchSamples:u,generation:h,modelPath:r,sourceName:o,field:e})}),A("givens")&&t.jsx(go,{givens:E,framed:!1})]}):void 0,L=x?x(v,D):D,U=L!=null&&L!==!1;return t.jsxs(p.Box,{"data-testid":"model-viewer-field-row","data-name":e.name,sx:a&&U?{pb:1.25}:void 0,children:[t.jsx(Oo,{glyph:t.jsx(ko,{kind:H,dataType:e.dataType}),name:e.name,typeLabel:e.dataType,typeTip:e.typeTip,typeAsChip:!0,stackPills:!0,doc:T,generatedDoc:!!S,open:a,expandable:U,onToggle:()=>d($=>!$),descriptors:t.jsx(wl,{givens:E}),pills:k,action:C}),U&&t.jsx(p.Collapse,{in:a,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{"data-testid":"model-viewer-field-detail",sx:{mx:`${yr}px`,mt:"2px",display:"flex",flexDirection:"column",gap:1.5},children:L})})]})}function Oo({glyph:e,name:n,typeLabel:r,typeAsChip:o=!1,stackPills:i=!1,typeTip:l,descriptors:a,pills:d,action:u,trailing:h,doc:y,generatedDoc:b=!1,open:x,expandable:v,onToggle:k}){const C=j.useId(),S=T=>{if(!v||T.target.closest("[data-row-action]"))return;const O=T.target.closest("button, a, [role='button']");O&&!O.hasAttribute("data-field-toggle")||k()};return t.jsxs(p.Box,{onClick:S,sx:{display:"flex",alignItems:x?"flex-start":"center",borderRadius:1.5,transition:"background 0.1s",cursor:v?"pointer":"default",...v?{"&:hover":{bgcolor:rt.background.muted},"&:hover [data-pill-tone='quiet']":{bgcolor:rt.background.strong}}:{}},children:[t.jsxs(p.Box,{sx:{display:"flex",flexDirection:i?"column":"row",alignItems:i?"stretch":"center",minWidth:0,flexShrink:0,width:{md:eg},overflow:{md:"hidden"}},children:[t.jsxs(p.Box,{component:v?"button":"div",type:v?"button":void 0,"aria-expanded":v?x:void 0,"aria-describedby":i?C:void 0,"data-field-toggle":v?"":void 0,sx:{appearance:"none",border:"none",background:"none",font:"inherit",color:"inherit",textAlign:"left",minWidth:0,px:`${yr}px`,py:"6px",borderRadius:1.5,...Tr,display:"flex",alignItems:"baseline",gap:"8px",flexWrap:i?"nowrap":"wrap",rowGap:"4px",cursor:v?"pointer":"default"},children:[e,t.jsxs(p.Box,{component:"span",sx:{display:"contents","& > *":{flexShrink:0},...i?{"& > *:first-of-type":{flexShrink:1,minWidth:0}}:{}},children:[t.jsx(p.Box,{component:"span",title:n,sx:{...Hm,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),r&&(o?t.jsx(p.Tooltip,{title:l?t.jsx(p.Box,{sx:{whiteSpace:"pre-line"},children:l}):"",children:t.jsx($t,{voice:"token",tone:"quiet",sx:{alignSelf:"center"},children:r})}):t.jsx(p.Box,{component:"span",sx:Al,children:r})),a]}),!i&&d]}),i?t.jsxs(p.Box,{id:C,sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",px:`${yr}px`,pb:"6px",mt:"-2px","&:empty":{display:"none"}},children:[d,u&&t.jsx(p.Box,{component:"span","data-row-action":"",sx:{display:"inline-flex"},children:u})]}):u&&t.jsx(p.Box,{component:"span","data-row-action":"",sx:{display:"inline-flex"},children:u})]}),y&&t.jsxs(p.Box,{component:"span","data-testid":"model-viewer-field-doc",onMouseEnter:T=>{const O=T.currentTarget;O.title=!x&&Fp(O,y)?y:""},sx:{flex:1,minWidth:0,ml:1,pr:`${yr}px`,py:x?"6px":0,fontSize:St.small,color:ls,...x?{whiteSpace:"pre-line"}:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}},children:[b&&t.jsx($t,{voice:"state",tone:"quiet","data-testid":"model-viewer-field-doc-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),x?y:y.split(`
29
- `)[0]]}),h&&t.jsx(p.Box,{sx:{ml:"auto",flexShrink:0,pl:1,pr:`${yr}px`,display:"inline-flex",alignItems:"center",height:32},children:h})]})}const ng=480;function rg({run:e,modelPath:n,query:r,sourceName:o,givens:i,givensUnknown:l,mode:a="result",renderCode:d,onShownChange:u}){const h=yo(e.givenValues),[y,b]=j.useState(a==="result"?h:null);a==="result"&&y===null&&b(h);const x=y!==null&&y!==h,v=o?e.requiredFiltersBySource?.get(o):void 0,[k,C]=j.useState(null),S=k===h,T=j.useMemo(()=>Fl(i??Co(e,o),v,e.givenValues,i?l:o?e.unknownGivensBySource?.get(o):void 0,S,i?"query":"source"),[e,o,i,l,v,S]),{result:O,isSuccess:M,isError:E,error:R,refetch:P}=Pp({run:e,modelPath:n,query:r,enabled:y===h&&T.kind!=="blocked"});y!==null&&y!==h&&O!==void 0&&b(h);const A=Qr(e.accessBySource,o),H=Dm(o,A),D=()=>x?b(h):void P(),[L,U]=j.useState(null);O!==void 0&&(L?.givensKey!==h||L.result!==O)&&U({result:O,givensKey:h});const $=T.kind==="blocked"?void 0:O!==void 0?{result:O,givensKey:h}:x&&L?{result:L.result,givensKey:L.givensKey}:void 0,W=$?.result,Q=j.useMemo(()=>$m(A,W),[A,W]),te=$?.givensKey??"";j.useEffect(()=>{if(u){if(W===void 0)return u(void 0);u({result:W,givensKey:te})}},[u,W,te]);const ee=a==="result"&&T.kind!=="blocked";return j.useEffect(()=>{ee&&c.warmMalloyRenderer()},[ee]),t.jsx(p.Box,{"data-testid":"model-viewer-run-result","data-mode":a,children:a==="code"?d?.():T.kind==="blocked"?t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1.5,flexWrap:"wrap"},children:[t.jsx(un,{"data-testid":"model-viewer-run-blocked",children:T.reason}),T.canRunAnyway&&t.jsx(Ca,{size:"small",onClick:()=>{C(h),b(h)},children:"Run anyway"})]}):E&&!x?t.jsx(Xp,{query:r,error:R,onRetry:()=>void P(),forbiddenMessage:H}):M&&!O&&!x?t.jsx(xr,{message:"The query returned no result."}):t.jsxs(p.Box,{"data-testid":"model-viewer-result-card",sx:{...Pn,p:jr,overflowX:"auto"},children:[x&&t.jsxs(p.Box,{"data-testid":"model-viewer-run-stale",sx:{display:"flex",alignItems:"center",gap:1.5,flexWrap:"wrap",mb:1},children:[t.jsx(un,{children:"The given values changed since this ran."}),t.jsx(Ca,{size:"small",onClick:D,"aria-label":"Run with these values",children:"Run"})]}),T.kind==="noted"&&W&&!x&&t.jsx(Cr,{"data-testid":"model-viewer-run-defaults",component:"div",sx:{mb:1},children:T.note}),!(x&&!W)&&(W===void 0?t.jsx(c.Loading,{text:c.LOADING_COPY.running}):t.jsx(c.ResultContainer,{result:W,maxHeight:ng,maxResultSize:e.maxResultSize})),Q&&t.jsx(Cr,{"data-testid":"model-viewer-run-filtered",component:"div",sx:{mt:1},children:Q})]})})}function sg(e){return{p:"3px",borderRadius:1,color:e?"text.primary":"text.secondary",bgcolor:e?rt.background.strong:"transparent","&:hover":{bgcolor:e?rt.background.strong:rt.background.muted,color:"text.primary"},"&.Mui-disabled":{color:"text.disabled"}}}function og({value:e,options:n,onChange:r,"aria-label":o}){return t.jsx(p.Box,{role:"group","aria-label":o,sx:{display:"inline-flex",gap:"2px"},children:n.map(i=>{const l=i.value===e,a=i.disabled===!0;return t.jsx(p.Tooltip,{title:a?i.disabledReason??i.label:i.label,children:t.jsx("span",{style:{display:"inline-flex"},children:t.jsx(p.IconButton,{size:"small",role:"button","aria-pressed":l,"aria-label":a?i.disabledReason??i.label:i.label,disabled:a,onClick:()=>r(i.value),sx:sg(l),children:i.icon})})},i.value)})})}const ig=["result","givens","fields","code","values","access"],ag={result:{icon:t.jsx(zl,{size:14}),label:"Result"},fields:{icon:t.jsx(bp,{size:14}),label:"Fields"},code:{icon:t.jsx(pp,{size:14}),label:"Code"},values:{icon:t.jsx(Cp,{size:14}),label:"Values"},givens:{icon:t.jsx(Tp,{size:14}),label:"Givens"},access:{icon:t.jsx(Sp,{size:14}),label:"Access"}};function Ql(e,n){const r=ig.filter(a=>e.includes(a)),[o,i]=j.useState(void 0),l=o!==void 0&&r.includes(o)?o:n!==void 0&&r.includes(n)?n:r[0];return{layers:r,layer:l,setLayer:i}}function Zl({layers:e,value:n,onChange:r,"aria-label":o,disabledReasons:i}){return e.length<2||n===void 0?null:t.jsx(og,{"aria-label":o,value:n,onChange:r,options:e.map(l=>{const a=i?.[l];return{value:l,...ag[l],...a?{disabled:!0,disabledReason:a}:{}}})})}function Xl({field:e,modelPath:n,sourceName:r,fieldCode:o,run:i,runQuery:l,runGivens:a,runGivensUnknown:d}){const u=l??c.viewRunQuery(r,e.name),h=a??(i&&Co(i,r)),y=j.useMemo(()=>i&&Ul(i,h),[i,h]),b=l?"query":"view",[x,v]=bo(),[k,C]=j.useState(void 0),S=So(o),T=j.useContext(vo),{renderRunActions:O}=cs(),{server:M}=q.useServer(),E=j.useMemo(()=>dn(o?.code,T),[o?.code,T]),{chartNames:R,tagsInFull:P}=j.useMemo(()=>{const W=e.tags??[],Q=Xf(W),te=Q.length>0?Q:W;return{chartNames:te,tagsInFull:W.join(" ")===te.join(" ")?void 0:W.map(ee=>`# ${ee}`).join(`
30
- `)}},[e.tags]),A=["result","code",...E.length>0?["givens"]:[]],{layers:H,layer:D,setLayer:L}=Ql(A,i?"result":"code"),U=D??"code",$=()=>U==="givens"?t.jsx(go,{givens:E}):o?.loading?t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}}):o?.code?t.jsx(Mr,{testId:"model-viewer-definition",code:l?o.code:$p(e.name,o.code)}):o?.error?t.jsx(hs,{message:"Couldn't load this model's code right now."}):t.jsx(xr,{message:`No Malloy code to show for this ${b}.`});return t.jsxs(p.Box,{"data-testid":"model-viewer-view-row","data-name":e.name,sx:x?{pb:1.5}:void 0,children:[t.jsx(Oo,{glyph:t.jsx(ko,{kind:"view"}),name:e.name,doc:e.doc,open:x,expandable:!0,onToggle:()=>v(W=>!W),trailing:x&&t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:"2px"},children:[t.jsx(Zl,{"aria-label":`Show for ${e.name}`,layers:H,value:U,onChange:L,disabledReasons:{result:i?void 0:`This ${b} can't be run here`,code:S?void 0:`No Malloy code to show for this ${b}`}}),y&&O?.({kind:l?"query":"view",modelPath:n,sourceName:l?"":r,name:e.name,query:u,givens:y.givenValues,queryKey:jo(M,y,n,u),shown:k})]}),descriptors:t.jsxs(t.Fragment,{children:[R.map(W=>{const Q=t.jsx($t,{voice:"token",tone:"quiet",sx:{alignSelf:"center"},children:W},W);return P?t.jsx(p.Tooltip,{title:P,slotProps:{tooltip:{sx:{whiteSpace:"pre-line",fontFamily:Dt}}},children:Q},W):Q}),t.jsx(wl,{givens:E})]})}),t.jsx(p.Collapse,{in:x,timeout:"auto",mountOnEnter:!0,children:t.jsx(p.Box,{"data-testid":"model-viewer-view-card",sx:{mx:"10px",mt:1,minWidth:0},children:t.jsx(p.Box,{sx:{minWidth:0,overflowX:"auto"},children:y?t.jsx(rg,{run:y,modelPath:n,query:u,sourceName:r||void 0,givens:a,givensUnknown:d,mode:U==="result"?"result":"code",renderCode:$,onShownChange:C}):$()})})})]})}function lg({queries:e,sourceText:n,modelPath:r,run:o}){const{parsed:i,pending:l}=Vl(n,e.length>0),a=j.useMemo(()=>e.map(u=>{const h=Ip(i,u.name),y=u.sourceName||!o?.givens||l?void 0:wm(h,o.givens,o.givensBySource,o.unknownGivensBySource);return{query:u,field:{name:u.name,kind:"view",doc:u.doc,tags:u.tags},code:{code:h,loading:l},runGivens:y?.givens,runGivensUnknown:y?.unknown}}),[e,i,l,o?.givens,o?.givensBySource,o?.unknownGivensBySource]),d=ns({noun:["query","queries"]});return t.jsx(Ln,{label:"Queries",count:e.length,testId:"model-viewer-queries",action:d.action,children:t.jsx(Or.Provider,{value:d.command,children:a.map(({query:u,field:h,code:y,runGivens:b,runGivensUnknown:x})=>t.jsx(Xl,{field:h,modelPath:r,sourceName:u.sourceName??"",fieldCode:y,run:o,runQuery:c.namedQueryRunQuery(u.name),runGivens:b,runGivensUnknown:x},u.name))})})}function Jl(e){const{entities:n,loading:r,error:o,columnDescriptions:i,declarations:l,declarationsLoading:a}=e;return d=>{const u=n?.get(d.name),h=l?.get(d.name);if(!u&&!r&&h&&h.kind===d.kind)return{code:h.code,loading:!1,error:!1,inherited:!1};if(!u&&!r&&!o&&a)return{loading:!0,error:!1,inherited:!1};const y=u?.fieldType==="column";return{code:y?void 0:u?.code??void 0,inheritedFrom:y&&u?.code?{code:u.code,fromTable:!!u.table||u.code!==d.name}:void 0,loading:!o&&r,error:o,inherited:y,columnDoc:y?i?.get(d.name):void 0}}}const ja=200;function br({label:e,noun:n,items:r,run:o,modelPath:i,sourceName:l,getFieldCode:a,level:d}){const{showField:u}=cs(),h=j.useMemo(()=>u?r.filter(O=>u({modelPath:i,sourceName:l,field:O,joined:d==="h3"})):r,[r,u,i,l,d]),[y,b]=j.useState(!1),x=h.some(O=>wo(O)&&d!=="h3"||So(a?.(O))),{command:v,action:k}=ns({noun:n,disabledReason:x?void 0:`None of these ${n[1]} has anything to show`}),C=d!=="h3"?k:void 0,S=j.useMemo(()=>a?Ap(h,a):h,[h,a]),T=y||S.length<=ja?S:S.slice(0,ja);return t.jsx(Ln,{label:e,count:h.length,level:d,action:C,children:t.jsx(Or.Provider,{value:v,children:t.jsxs(p.Box,{sx:{display:"flex",flexDirection:"column",gap:"3px"},children:[T.map(O=>t.jsx(tg,{field:O,run:o,modelPath:i,sourceName:l,fieldCode:a?.(O),joined:d==="h3"},O.name)),T.length<S.length&&t.jsxs(p.Button,{size:"small",onClick:()=>b(!0),sx:{alignSelf:"flex-start",textTransform:"none"},children:["Show all ",S.length.toLocaleString()," ",n[1]]})]})})})}function cg(e,n){const r=new Map;if(!e||!n)return r;const o=new Map;for(const l of e.symbols)l.type==="explore"&&o.set(Mo(l.name),l);const i=new Set;for(let l=n;l&&!i.has(l);){i.add(l);const a=o.get(l);if(!a)break;for(const[d,u]of dg(e.lines,a))r.has(d)||r.set(d,u);l=vg(ds(e.lines,a.range))}return r}const Ta=/^\s*(view|measure|dimension)\s*:\s*$/,ug=/^`?([A-Za-z_]\w*)`?\s+is\b/;function dg(e,n){const r=new Map;let o,i=n.range.start;for(const a of n.children){const d=ds(e,{start:i,end:a.range.start});o=gg(d)??o,i=a.range.end;const u=hg(a,o);if(!u)continue;const h=fg(e,a,u);if(!h)continue;const y=Mo(a.name);r.set(y,r.has(y)?null:h)}const l=new Map;for(const[a,d]of r)d&&l.set(a,d);return l}function hg(e,n){if(e.type==="query")return n==="view"?"view":void 0;if(e.type==="field"&&(n==="dimension"||n==="measure"))return n}function fg(e,n,r){const o=ds(e,n.range).split(`
31
- `),i=[];for(;o.length>1&&/^\s*(#|\/\/|--|$)/.test(o[0]);){const d=o.shift().trim();d.startsWith("#")&&i.push(d)}o[0]=o[0].trimStart();const l=o.join(`
32
- `).trimEnd(),a=ug.exec(l);if(!(!a||a[1]!==Mo(n.name)))return{kind:r,code:[...mg(e,n.range.start),...i,l].join(`
33
- `)}}function mg(e,n){const r=(e[n.line]??"").slice(0,n.character),o=r.trim()==="";if(!o&&!Ta.test(r))return[];const i=a=>{const d=[];let u=a;for(;u>=0&&e[u].trim().startsWith("#");)d.unshift(e[u--].trim());return{out:d,next:u}},l=i(n.line-1);return o&&l.next>=0&&Ta.test(e[l.next])?[...i(l.next-1).out,...l.out]:l.out}const pg=/(?<![\w:])([A-Za-z_]\w*)\s*:(?!:)/g;function gg(e){let n;for(const r of yg(e).matchAll(pg))n=r[1];return n}function yg(e){let n="";for(let r=0;r<e.length;r++){const o=e[r];if(e.startsWith('"""',r)){const i=e.indexOf('"""',r+3),l=i===-1?e.length:i+3;n+=" ".repeat(l-r),r=l-1}else if(o==='"'||o==="'"||o==="`"){const i=xg(e,r);n+=" ".repeat(i-r+1),r=i}else if(o==="#"||o==="/"&&e[r+1]==="/"||o==="-"&&e[r+1]==="-"){const i=e.indexOf(`
34
- `,r),l=i===-1?e.length:i;n+=" ".repeat(l-r),r=l-1}else n+=o}return n}function xg(e,n){const r=e[n];for(let o=n+1;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===r)return o;return e.length}function vg(e){return/^`?[A-Za-z_]\w*`?\s+is\s+`?([A-Za-z_]\w*)`?\s*(?:extend\b|$)/.exec(e)?.[1]}function Mo(e){return e.replace(/^`(.*)`$/,"$1")}const bg=["fields","code"],Oa={display:"inline-flex",alignItems:"center",color:"text.secondary",borderRadius:1,padding:"2px",flexShrink:0,"&:hover":{color:ts}};function wg({join:e,run:n,modelPath:r,sourceName:o,link:i,entitiesByName:l,entitiesLoading:a,entitiesError:d,code:u,target:h,showRules:y=!1}){const[b,x]=bo(),{layers:v,layer:k,setLayer:C}=Ql(bg),S=j.useMemo(()=>l?Jl({entities:l,loading:!!a,error:!!d}):void 0,[l,a,d]),T=e.dimensions.length+e.measures.length,O=t.jsxs(p.Box,{sx:{display:"inline-flex",alignItems:"center",gap:1},children:[b&&t.jsx(Zl,{"aria-label":`Show for ${e.name}`,layers:v,value:k,onChange:C,disabledReasons:{code:u?void 0:"No Malloy code to show for this join"}}),i?.kind==="link"&&i.href&&t.jsx(p.Link,{href:i.href,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:Oa,children:t.jsx(Sa,{size:14})}),i?.kind==="link"&&!i.href&&i.onOpen&&t.jsx(p.Link,{component:"button",type:"button",onClick:i.onOpen,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:Oa,children:t.jsx(Sa,{size:14})}),i?.kind==="join-only"&&t.jsx(p.Box,{component:"span",sx:{fontSize:St.micro,fontStyle:"italic",color:"text.secondary",flexShrink:0},children:"only accessible via join"})]});return t.jsxs(p.Box,{"data-testid":"model-viewer-join-row","data-name":e.name,sx:b?{pb:1.25}:void 0,children:[t.jsx(Oo,{glyph:t.jsx(ko,{kind:"join"}),name:e.name,typeLabel:`${T} ${T===1?"field":"fields"}`,stackPills:!0,descriptors:t.jsxs($t,{tone:"quiet",voice:"token",sx:{alignSelf:"center",flexShrink:0},children:["join_",e.relationship]}),doc:e.doc,open:b,expandable:!0,onToggle:()=>x(M=>!M),trailing:O,pills:h&&t.jsx(Il,{access:h.access})}),t.jsx(p.Collapse,{in:b,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{sx:{mx:"10px",mt:"2px"},children:k==="code"&&u?t.jsx(Mr,{testId:"model-viewer-join-code",code:u}):t.jsxs(p.Box,{"data-testid":"model-viewer-join-fields",sx:{...Pn,bgcolor:"transparent",p:1.5,pb:0},children:[h&&y&&t.jsx(Cr,{component:"div","data-testid":"model-viewer-join-gate-warning",sx:{mb:1},children:Am(h.sourceName,h.access)}),t.jsx(br,{label:"Measures",noun:["measure","measures"],level:"h3",items:e.measures,run:n,modelPath:r,sourceName:o,getFieldCode:S}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],level:"h3",items:e.dimensions,run:n,modelPath:r,sourceName:o,getFieldCode:S})]})})})]})}function Sg({source:e,modelPath:n,entitiesByName:r,entitiesLoading:o,entitiesError:i,modelText:l,joinLinks:a,joinEntities:d,joinCodes:u,joinAccess:h,showRules:y=!1,columnDescriptions:b,run:x,queries:v,givens:k}){const C={run:x,modelPath:n,sourceName:e.name},{showField:S}=cs(),T=j.useMemo(()=>S?e.views.filter(D=>S({modelPath:n,sourceName:e.name,field:D,joined:!1})):e.views,[S,e,n]),O=ns({noun:["view","views"]}),M=ns({noun:["join","joins"]}),E=j.useMemo(()=>!o&&[...e.views,...e.measures,...e.calculations,...e.dimensions].some(D=>!r?.get(D.name)),[o,r,e]),{parsed:R,pending:P}=Vl(l,E),A=j.useMemo(()=>cg(R,e.name),[R,e.name]),H=j.useMemo(()=>Jl({entities:r,loading:!!o,error:!!i,columnDescriptions:b,declarations:A,declarationsLoading:P}),[r,o,i,b,A,P]);return t.jsxs(p.Box,{sx:{paddingBottom:"24px"},children:[k,t.jsx(Ln,{label:"Views",count:T.length,action:O.action,children:t.jsx(Or.Provider,{value:O.command,children:T.map(D=>t.jsx(Xl,{field:D,modelPath:n,sourceName:e.name,fieldCode:H(D),run:x},D.name))})}),v,t.jsx(br,{label:"Measures",noun:["measure","measures"],items:e.measures,getFieldCode:H,...C}),t.jsx(br,{label:"Calculations",noun:["calculation","calculations"],items:e.calculations,getFieldCode:H,...C}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],items:e.dimensions,getFieldCode:H,...C}),t.jsx(Ln,{label:"Joins",count:e.joins.length,action:M.action,children:t.jsx(Or.Provider,{value:M.command,children:e.joins.map(D=>t.jsx(wg,{join:D,run:x,modelPath:n,sourceName:e.name,link:a?.get(D.name),entitiesByName:d?.get(D.name),code:u?.get(D.name),target:h?.get(D.name),showRules:y,entitiesLoading:o,entitiesError:i},D.name))})})]})}function ro(e){return{name:e.name,kind:e.kind,dataType:po(e.type),typeTip:tm(e.type),tags:nm(e.annotations),doc:Nn(e.annotations),indexed:e.kind==="dimension"?ym(e):void 0,preaggregate:e.kind==="measure"?em(e.annotations):void 0}}function kg(e){const n=[],r=[];for(const o of e.schema?.fields??[]){if(o.kind!=="dimension"&&o.kind!=="measure")continue;const i={...ro(o),indexed:!1,preaggregate:!1};o.kind==="dimension"?n.push(i):r.push(i)}return{name:e.name,relationship:e.relationship,doc:Nn(e.annotations),dimensions:n,measures:r}}function Cg(e,n){const r={name:e.name,doc:Nn(e.annotations),docParts:yl(e.annotations),accent:Vm(n),persist:Jf(e.annotations),dimensions:[],measures:[],calculations:[],views:[],joins:[]};for(const o of e.schema?.fields??[])switch(o.kind){case"dimension":case"measure":r[o.kind==="dimension"?"dimensions":"measures"].push(ro(o));break;case"calculate":r.calculations.push(ro(o));break;case"view":r.views.push({name:o.name,kind:"view",doc:Nn(o.annotations),tags:mo(o.annotations)});break;case"join":r.joins.push(kg(o));break}return r}function jg(e){const n=[];for(const r of e??[]){if(!r.name)continue;const o=(r.annotations??[]).map(i=>({value:i}));n.push({name:r.name,sourceName:r.sourceName||void 0,doc:Nn(o),tags:mo(o)})}return n}function ec(e){return e.dimensions.length+e.measures.length+e.calculations.length+e.views.length}function Tg(e,n){if(e.length===0)return null;const r=h=>h.toLowerCase().replace(/[-_]/g,""),o=n?r((n.split("/").pop()??n).replace(/\.malloy$/,"")):void 0,i=new Map(e.map(h=>[h.name,new Set(h.views.map(y=>y.name))])),l=h=>e.some(y=>{if(y.name===h.name||y.views.length===0)return!1;const b=i.get(h.name);return y.views.length<h.views.length&&[...i.get(y.name)].every(x=>b.has(x))}),a=e.filter(h=>!l(h)),d=a.length>0?a:e;let u=d[0];for(const h of d.slice(1)){if(h.views.length!==u.views.length){h.views.length>u.views.length&&(u=h);continue}o&&r(h.name)===o&&r(u.name)!==o&&(u=h)}return u}function Og(e,n,r){if(!e||!n)return;const i=new RegExp("source:\\s*`?"+pn(n)+"`?\\s+is\\s+`?([A-Za-z_]\\w*)`?\\s*(?:->|extend\\b)").exec(e);if(!i)return;const l=i[1];return r.has(l)?l:void 0}function _s(e,n){return`${e} ${e===1?n:`${n}s`}`}function Mg(e){const n=ec(e),r=[_s(e.views.length,"view"),_s(n,"field")];return e.joins.length>0&&r.push(_s(e.joins.length,"join")),r.join(" · ")}function Eg(e,n,r){if(r){const d=r.exportOrder,u=d.length>0&&e.some(h=>d.includes(h.name));return{sources:$g(e,h=>h.name,d),curated:!0,exportOrdered:u}}const o=e.map((d,u)=>({source:d,index:u})).filter(({source:d})=>d.name!==n?.name).sort((d,u)=>u.source.views.length-d.source.views.length||d.index-u.index).map(({source:d})=>d),i=n?[n,...o]:o,l=n?.views.length??0,a=n&&l>0&&e.every(d=>d.views.length<=l)?n.name:void 0;return{sources:i,curated:!1,exportOrdered:!1,mostViews:a}}function Ig(e){return/^`.*`$/.test(e)?e.slice(1,-1):e}function Dg(e){if(!e)return[];const n=Ir(e),r=[];for(const o of n.matchAll(/(?:^|[\s;])export\s*\{([^}]*)\}/gi))for(const i of o[1].split(",")){const l=Ig(i.trim());l&&!r.includes(l)&&r.push(l)}return r}function $g(e,n,r){if(r.length===0)return[...e];const o=i=>{const l=r.indexOf(n(i));return l===-1?r.length:l};return e.map((i,l)=>({item:i,index:l})).sort((i,l)=>o(i.item)-o(l.item)||i.index-l.index).map(({item:i})=>i)}function Ag(e,n){const r=e?.trim();if(r)return{text:r,generated:!1};const o=n?.trim();return o?{text:o,generated:!0}:void 0}const Fg="This package's curated sources, in the order its index.malloy exports them.",Rg="This package's public sources.";function Ng(e){return e.mostViews?", most views":""}function Lg({anchorEl:e,onClose:n,sources:r,currentName:o,onPickSource:i,curated:l=!1,exportOrdered:a=!1}){const d=!!e;return t.jsxs(p.Popover,{open:d,anchorEl:e,onClose:n,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},slotProps:{paper:{sx:{width:460,maxWidth:"calc(100vw - 32px)",maxHeight:"min(70vh, 560px)",display:"flex",flexDirection:"column",borderRadius:"10px"},"data-testid":"model-sources-dropdown"}},children:[t.jsxs(p.Box,{sx:{px:2,pt:1.5,pb:1,borderBottom:1,borderColor:"divider"},children:[t.jsx(p.Typography,{variant:"subtitle2",component:"h2",sx:{m:0},children:"Sources"}),t.jsx(Cr,{component:"p",sx:{m:0},children:l?a?Fg:Rg:Ym})]}),t.jsx(p.Box,{sx:{overflowY:"auto",py:.5},children:r.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{py:4,textAlign:"center"},children:"This model defines no sources."}):r.map(u=>{const h=u.name===o;return t.jsxs(p.ButtonBase,{"data-item-name":u.name,"aria-label":`Open source ${u.name}${Ng(u)}${Rm(u.access)}`,"aria-current":h||void 0,onClick:()=>{n(),i(u.name)},sx:{display:"flex",width:"100%",alignItems:"flex-start",justifyContent:"flex-start",textAlign:"left",gap:1.25,px:2,py:1,bgcolor:h?rt.background.muted:void 0,"&:hover":{bgcolor:h?rt.background.strong:rt.background.muted},...Tr},children:[t.jsx(p.Box,{component:"span","aria-hidden":!0,sx:{color:An.steel.main,display:"inline-flex",pt:"2px"},children:t.jsx(ql,{size:16})}),t.jsxs(p.Box,{component:"span",sx:{minWidth:0,flex:1},children:[t.jsxs(p.Box,{component:"span",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1},children:[t.jsx(p.Box,{component:"span",sx:{fontFamily:Dt,fontSize:St.body,fontWeight:500,color:"text.primary"},children:u.name}),u.mostViews&&t.jsx($t,{tone:"quiet",sx:{alignSelf:"center"},children:_g}),El(u.access)&&t.jsx(Il,{access:u.access}),u.status]}),(u.description||u.descriptionPending)&&t.jsxs(p.Box,{component:"span",sx:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",mt:.25,fontSize:St.small,color:"text.secondary",minHeight:u.description?void 0:"1.4em"},children:[u.description?.generated&&t.jsx($t,{tone:"quiet","data-testid":"model-sources-summary-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),u.description&&Dl(u.description.text)]}),t.jsx(Cr,{"data-testid":"model-sources-row-meta",sx:{display:"block",mt:.25},children:u.meta})]})]},`source:${u.name}`)})})]})}const _g="Most views";function Pg({sources:e,currentName:n,countLabel:r,onPickSource:o,curated:i=!1,exportOrdered:l=!1,onWarm:a}){const[d,u]=j.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Jp,{size:"small",variant:"outlined",onClick:h=>{a?.(),u(h.currentTarget)},endIcon:t.jsx(wp,{size:20}),"aria-label":`${r}. Showing ${n}, one of the ${r} in this model`,"aria-haspopup":"dialog","aria-expanded":!!d,onPointerEnter:a,onFocus:a,sx:{ml:1,transition:"none"},children:r}),t.jsx(Lg,{anchorEl:d,onClose:()=>u(null),sources:e,currentName:n,onPickSource:o,curated:i,exportOrdered:l})]})}const zg=[],Wg=[],qg=[],Bg=new Map;function Vg(e){const n=e.modelDef;if(typeof n!="string")return!1;try{const r=JSON.parse(n);return Array.isArray(r.imports)&&r.imports.length>0}catch{return!1}}function Hg(e,n){if(typeof e=="string")try{const o=da(JSON.parse(e).annotations);if(o)return o}catch{}if(!n)return;const r=n.split(`
35
- `).filter(o=>/^##(\(doc\)|")/.test(o.trim())).map(o=>({value:o}));return da(r)}async function Ug(e,n,r,o,i,l){const a=await e.models.getModel(n,r,o,i,l),d=Gg(a.data);return{sourceInfos:(a.data.sourceInfos??[]).map(u=>JSON.parse(u)),queries:a.data.queries??[],sourceText:d,givens:cm(o,a.data),access:Em(a.data),modelDoc:Hg(a.data.modelInfo,d),hasImports:Vg(a.data)}}function Gg(e){const n=e.sourceText;return typeof n=="string"?n:void 0}function tc(e,n,r,o,i=!1){return["model-viewer-sources",e,n,r,o??"",...i?["off-surface"]:[]]}function Yg(e,n,r,o,i,l=!1){return{queryKey:tc(n,r,o,i,l),queryFn:()=>Ug(e,n,r,o,i,l),...i&&i!=="latest"?{staleTime:1/0}:{}}}function Kg(e,n,r,o,i=!0,l=!1){const{apiClients:a}=q.useServer(),d=yt.useQuery({...Yg(a,e,n,r,o,l),enabled:i&&!!(e&&n&&r)});return{sources:d.data?.sourceInfos??zg,queries:d.data?.queries??Wg,sourceText:d.data?.sourceText,givens:d.data?.givens??qg,access:d.data?.access??Bg,modelDoc:d.data?.modelDoc,hasImports:d.data?.hasImports??!1,isLoading:d.isLoading,isError:d.isError,error:d.error,refetch:d.refetch}}const Qg=new Map;function Ma(e){return(e.split("/").pop()??e).replace(/\.malloy$/,"")}function Zg(e,n){const r=bm(e,n),o=n.filter(l=>!r.has(l.name)),i="Nothing on this page reads them.";return o.length===0?`Declared here for the models that import this file. ${i}`:o.length===n.length?`Imported from another file, for the models that import this one. ${i}`:`For the models that import this file. ${vr(o.map(l=>l.name),"and")} ${o.length===1?"comes":"come"} from a file this one imports; the rest are declared here. ${i}`}function nc({resourceUri:e,sourceName:n,onSourceChange:r,initialSourceName:o,includeHiddenFilesAndSources:i=!1,hostGivenNames:l,givens:a,onGivensChange:d,showAccessRules:u=!1,headingLevel:h="h1",headerActions:y,renderSourceStatus:b,entities:x,entitiesLoading:v=!1,entitiesError:k=!1,columnDescriptions:C,joinHref:S,queryMetadata:T,onQueryRun:O,maxResultSize:M,extensions:E}){const{environmentName:R,packageName:P,modelPath:A="",versionId:H}=c.parseResourceUri(e),D=q.usePublisherTheme().theme.ui.font.mono,{sources:L,queries:U,sourceText:$,givens:W,access:Q,modelDoc:te,hasImports:ee,isLoading:G,isError:Z,error:ae,refetch:z}=Kg(R,P,A,H,!0,i),re=j.useMemo(()=>new Set(l??[]),[l]),se=j.useMemo(()=>W.filter(ke=>!re.has(ke.name)),[W,re]),ne=j.useMemo(()=>L.map(Cg),[L]),Ie=j.useMemo(()=>jg(U),[U]),de=j.useMemo(()=>vm(ne),[ne]),pe=j.useMemo(()=>xm(L),[L]),De=j.useMemo(()=>um(se),[se]),Le=JSON.stringify(a??null),oe=j.useMemo(()=>a&&Object.fromEntries(Object.entries(a).filter(([ke])=>De.has(ke))),[Le,De]),K=!G&&!Z,le=j.useCallback(ke=>d?.(ke,Array.from(De.keys())),[d,De]),be=c.useGivensState({declaredTypes:De,params:oe,onParamsChange:K&&d?le:void 0,documentKey:`${R}/${P}@${H??""}/${A}`,autorun:!0}),ge=j.useMemo(()=>dm(be.applied,De),[be.applied,De]),{givensBySource:ue,unknownGivensBySource:ye}=j.useMemo(()=>{const ke=new Map,Ne=new Map;for(const Ee of ne){const Be=Sm($,Ee.name,se);ke.set(Ee.name,Be.givens),Be.unknown.size>0&&Ne.set(Ee.name,Be.unknown)}return{givensBySource:ke,unknownGivensBySource:Ne}},[ne,$,se]),$e=j.useMemo(()=>({projectName:R,packageName:P,versionId:H,givens:se,givensBySource:ue,unknownGivensBySource:ye,requiredFiltersBySource:pe,givenValues:ge,accessBySource:Q,includeHiddenFilesAndSources:i,queryMetadata:T,onQueryRun:O,maxResultSize:M}),[R,P,H,se,ue,ye,pe,ge,Q,i,T,O,M]),[ze,me]=j.useState(o),Y=n!==void 0,ie=Y?n:ze,Oe=j.useCallback(ke=>{Y||me(ke),r?.(ke)},[Y,r]),Fe=j.useMemo(()=>Tg(ne,A),[ne,A]),Me=ne.find(ke=>ke.name===ie)??(Y?void 0:Fe),lt=j.useMemo(()=>Me?ue.get(Me.name)??se:se,[Me,ue,se]),xt=j.useMemo(()=>Me?km($,Me.name,se,de):new Map,[Me,$,se,de]),vt=j.useMemo(()=>Og($,Me?.name,de),[$,Me?.name,de]),Ot=j.useMemo(()=>Me?Zf(Me,ne.find(ke=>ke.name===vt)):void 0,[Me,ne,vt]),pt=j.useMemo(()=>x?kl(x):Qg,[x]),Ke=Me?pt.get(Me.name):void 0,{joinLinks:he,joinEntities:Qe,joinCodes:qe,joinAccessRules:ct}=j.useMemo(()=>{const ke=new Map,Ne=new Map,Ee=new Map,Be=new Map,ht=new Map([[A,new Set(de)]]);for(const We of Ke?.values()??[]){if(We.fieldType!=="join")continue;We.code&&Ee.set(We.name,We.code);const nt=We.joinTarget;if(nt)if(nt.modelPath===A){const Mt=pt.get(nt.sourceName);Mt&&Ne.set(We.name,Mt);const kt=Qr(Q,nt.sourceName);El(kt)&&Be.set(We.name,{sourceName:nt.sourceName,access:kt});const At=Bm(nt,ht);ke.set(We.name,At.kind==="link"?{...At,onOpen:()=>Oe(nt.sourceName)}:At)}else{const Mt=S?.(nt);Mt&&ke.set(We.name,{kind:"link",href:Mt})}}return{joinLinks:ke,joinEntities:Ne,joinCodes:Ee,joinAccessRules:Be}},[Ke,pt,A,de,Q,Oe,S]),ut=A==="index.malloy"&&!i,Ze=j.useMemo(()=>Eg(ne,Fe,ut?{exportOrder:Dg($)}:void 0),[ne,Fe,ut,$]),fe=E?.describePickerSource,Ue=j.useMemo(()=>Ze.sources.map(ke=>{const Ne=fe?.({modelPath:A,sourceName:ke.name});return{name:ke.name,description:Ag(ke.doc,Ne?.summary),descriptionPending:!ke.doc?.trim()&&!Ne?.summary&&!!Ne?.summaryPending,meta:Mg(ke),mostViews:Ze.mostViews===ke.name,access:Qr(Q,ke.name),status:Ne?.status}}),[Ze,Q,fe,A]),bt=(()=>{if(G)return t.jsx(c.Loading,{text:"Fetching Model..."});if(Z)return qm(ae)?t.jsx(p.Box,{sx:{pt:to},children:t.jsx(xr,{message:Yl(ae)??`${P}/${A} doesn't exist, or you don't have access to it.`})}):t.jsx(hs,{message:Kl("Failed to load model",ae),onRetry:()=>void z()});const ke=Ie.length>0&&t.jsx(lg,{queries:Ie,sourceText:$,modelPath:A,run:$e});if(ne.length===0)return Ie.length===0?t.jsxs(t.Fragment,{children:[t.jsx(As,{headingLevel:h,title:Ma(A),meta:se.length>0?`${se.length} ${se.length===1?"given":"givens"}`:void 0,actions:y,isSource:!1,offSurface:i}),t.jsx(xr,{message:"This model defines no sources or queries.",secondary:ee&&t.jsxs(t.Fragment,{children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})}),t.jsxs(Ln,{label:"Givens",count:se.length,testId:"model-viewer-declared-givens",children:[t.jsx(un,{"data-testid":"model-viewer-declared-givens-where",sx:{mb:1},children:Zg($,se)}),t.jsx(go,{givens:se})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(As,{headingLevel:h,title:Ma(A),meta:`${Ie.length} ${Ie.length===1?"query":"queries"}`,actions:y,isSource:!1,offSurface:i}),ke]});if(!Me)return t.jsx(p.Box,{sx:{pt:to},children:t.jsx(xr,{message:`This model has no source named ${ie}.`,secondary:t.jsxs(p.Box,{component:"span","data-testid":"model-viewer-source-links",children:["Sources in this model: ",ne.map((We,nt)=>t.jsxs("span",{children:[nt>0&&", ",t.jsx(p.Link,{component:"button",type:"button",onClick:()=>Oe(We.name),sx:{fontFamily:Dt,verticalAlign:"baseline"},children:We.name})]},We.name))]})})});const Ne=ec(Me),Ee=vt?void 0:[...Ke?.values()??[]].find(We=>We.table)?.table,Be=vt?t.jsxs(t.Fragment,{children:["from ",t.jsx(p.Link,{component:"button",type:"button",onClick:()=>Oe(vt),sx:{fontFamily:Dt,color:ls,textDecorationColor:"inherit",verticalAlign:"baseline"},children:vt})]}):Ee?t.jsxs(t.Fragment,{children:["reads ",t.jsx(p.Box,{component:"span","data-testid":"model-viewer-source-table",sx:{fontFamily:Dt},children:[Ee.connectionName,Ee.catalogName,Ee.schemaName,Ee.tableName].filter(Boolean).join(".")})]}):void 0,ht=E?.renderSourceDetail?.({modelPath:A,sourceName:Me.name});return t.jsxs(t.Fragment,{children:[t.jsx(As,{headingLevel:h,title:Me.name,titleAdornments:ne.length>1&&t.jsx(Pg,{sources:Ue,currentName:Me.name,countLabel:Km(Ue.length,Ze.curated),onPickSource:Oe,curated:Ze.curated,exportOrdered:Ze.exportOrdered}),actions:y,status:b?.(Me.name),kindLabel:"Source",meta:`${Ne} ${Ne===1?"field":"fields"}`,doc:Ot,modelDoc:te,access:Qr(Q,Me.name),showRules:u,offSurface:i,publicSurface:ut,provenance:Be}),ht&&t.jsx(p.Box,{"data-testid":"model-viewer-source-detail",sx:{mt:1.5},children:ht}),t.jsx(vo.Provider,{value:se,children:t.jsx(Sg,{source:Me,modelPath:A,entitiesByName:Ke,entitiesLoading:v,entitiesError:k,columnDescriptions:C?.get(Me.name),modelText:$,joinLinks:he,joinAccess:ct,showRules:u,joinEntities:Qe,joinCodes:qe,run:$e,queries:ke,givens:t.jsx(Gm,{givens:lt,unknown:Me?ye.get(Me.name):void 0,inheritedFrom:xt,values:be.draft,onChange:be.setGiven,onReset:be.reset,environmentName:R,packageName:P,modelPath:A,versionId:H,declaredTypes:De})},Me.name)})]})})();return t.jsx(Sl.Provider,{value:E??{},children:t.jsx(p.Box,{"data-testid":"model-viewer",sx:{...om,pb:2,[vl]:D},children:t.jsx(p.Box,{sx:im,children:bt})})})}const Xg=c.createSvgIcon(t.jsx("path",{d:"M8 5v14l11-7z"}));function rc({open:e,onClose:n,result:r,title:o="Results",renderLogs:i,drill:l}){return t.jsx(c.AppDialog,{open:e,onClose:n,title:o,maxWidth:!1,showClose:!0,children:t.jsx(p.Box,{sx:{height:"70vh",overflow:"auto"},children:t.jsx(c.ResultContainer,{result:r,maxHeight:c.RESULTS_DIALOG_MAX_HEIGHT,maxResultSize:1e6,renderLogs:i,drill:l})})})}function Jg({queryName:e,annotations:n,resourceUri:r,runOnDemand:o=!1,maxResultSize:i=0}){const[l,a]=j.useState(),[d,u]=j.useState(!1),[h,y]=j.useState(!1),{packageName:b,environmentName:x,versionId:v,modelPath:k}=c.parseResourceUri(r),C=!o||h,S=c.useQueryResult({environmentName:x,packageName:b,modelPath:k,versionId:v,queryName:e},{enabled:C}),T=S.data,{mode:O}=q.usePublisherTheme();return j.useEffect(()=>{if(n&&n.length>0){const M=n.map(E=>`// ${E}`).join(`
36
- `);To(M,"typescript",O).then(E=>{a(E)})}},[n,O]),t.jsxs(p.Box,{children:[l&&t.jsx(p.Box,{sx:{marginBottom:"16px"},children:t.jsx(p.Typography,{fontSize:"12px",sx:{fontSize:"12px","& .line":{textWrap:"wrap"}},children:t.jsx("div",{className:"content",dangerouslySetInnerHTML:{__html:l}})})}),t.jsxs(p.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontSize:"15px",fontWeight:600,color:"text.primary",px:2,py:1,bgcolor:"action.hover",borderRadius:1.5,border:1,borderColor:"divider"},children:e}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>u(!0),children:t.jsx(c.SearchIcon,{})})]}),t.jsxs(q.CleanMetricCard,{sx:{position:"relative"},children:[o&&!h&&t.jsxs(p.Box,{sx:{padding:"40px 20px",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Click Run to execute the query"}),t.jsx(p.Button,{variant:"contained",startIcon:t.jsx(Xg,{}),onClick:()=>y(!0),children:"Run Query"})]}),C&&t.jsx(c.ResultPanel,{state:S,context:e,maxHeight:c.MODEL_CELL_MAX_HEIGHT,maxResultSize:i})]}),t.jsx(rc,{open:d,onClose:()=>u(!1),result:T?.data?.result||"",renderLogs:T?.data?.renderLogs,title:`Query: ${e}`})]})}function ey(e){return e!=null}function ty(e,n){const r=[],o=[];for(const l of e){if(l.name===void 0||ey(n.get(l.name)))continue;if(l.default==null){r.push(l.name);continue}const a=c.renderGivenDefault(l.type??"string",l.default);a&&o.push(`${l.name} = ${a}`)}const i={missing:r};return o.length>0&&(i.defaultsNote=o.length===1?`Ran with the default ${o[0]}`:`Ran with defaults ${o.join(", ")}`),i}function ny(e){return e.length===1?`This source may need a value for the given ${e[0]}. Set it in the parameters above.`:`This source may need values for the givens ${e.join(", ")}. Set them in the parameters above.`}function sc({sourceAndPaths:e,selectedSourceIndex:n,existingQuery:r,onQueryChange:o,onSourceChange:i,resourceUri:l,givens:a,gate:d}){return j.useEffect(()=>{i&&i(n)},[n,i]),t.jsx(q.StyledCardMedia,{children:t.jsxs(wr.Stack,{spacing:2,component:"section",children:[t.jsx(sy,{sourceAndPath:e[n],existingQuery:r,onChange:u=>{o&&o(u)},resourceUri:l,givens:a,gate:d}),t.jsx(wr.Box,{height:"5px"})]})})}function Ps(){return{query:void 0,malloyQuery:void 0,malloyResult:void 0}}function ry({sourceAndPath:e,onChange:n,existingQuery:r,explorerComponents:o,QueryBuilder:i,resourceUri:l,givens:a,gate:d}){const[u,h]=j.useState(r||Ps()),[y,b]=j.useState(void 0);j.useEffect(()=>{r&&h(r)},[r]);const[x,v]=j.useState([]),{MalloyExplorerProvider:k,QueryPanel:C,ResizableCollapsiblePanel:S,ResultPanel:T,SourcePanel:O}=o;j.useEffect(()=>{n&&n(u)},[n,u]);const{environmentName:M,packageName:E,versionId:R}=c.parseResourceUri(l),{apiClients:P}=q.useServer(),A=j.useRef(void 0),H=c.useMutationWithApiError({mutationFn:()=>{A.current=d,b({executionState:"running",query:u?.malloyQuery,queryResolutionStartMillis:Date.now(),onCancel:()=>{H.reset(),b(void 0)},response:{}});const $=typeof u?.malloyQuery=="string"?u.malloyQuery:new i.ASTQuery({source:e.sourceInfo,query:u?.malloyQuery}).toMalloy();return h({...u,query:$}),P.models.executeQueryModel(M,E,e.modelPath,{query:$,sourceName:void 0,queryName:void 0,versionId:R,...a&&Object.keys(a).length>0?{givens:a}:{}})},onSuccess:$=>{if($){const W=JSON.parse($.data.result);h({...u,malloyResult:W});const Q=A.current;b(te=>te?{...te,executionState:"finished",response:{result:W,...Q?.defaultsNote?{messages:[{severity:"INFO",title:Q.defaultsNote}]}:{}}}:void 0)}},onError:$=>{console.error("Query execution error:",$);const W=$?.data?.message??$?.message??"The query could not be run.",Q=[{severity:"ERROR",title:W}],te=A.current?.missing??[];($?.status===403||/Access denied for source/i.test(W))&&te.length>0&&Q.push({severity:"WARN",title:ny(te)}),b(G=>G?{...G,executionState:"finished",response:{messages:Q}}:void 0)}}),[D,L]=j.useState(e.sourceInfo.name);j.useEffect(()=>{D!==e.sourceInfo.name&&(L(e.sourceInfo.name),h(Ps()),b(void 0))},[e,D]);const U=j.useCallback($=>{h({...u,malloyQuery:$,malloyResult:void 0})},[u]);return D!==e.sourceInfo.name?t.jsx("div",{children:"Loading..."}):t.jsx(q.StyledExplorerContent,{sx:{border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},children:t.jsx(k,{source:e.sourceInfo,query:u?.malloyQuery,topValues:[],onFocusedNestViewPathChange:v,focusedNestViewPath:x,onQueryChange:U,children:t.jsxs("div",{style:{display:"flex",height:"100%",overflowY:"auto"},children:[t.jsx(S,{isInitiallyExpanded:!0,initialWidth:180,minWidth:180,icon:"database",title:e.sourceInfo.name,children:t.jsx(O,{onRefresh:()=>h(Ps())})}),t.jsx(S,{isInitiallyExpanded:!0,initialWidth:280,minWidth:280,icon:"filterSliders",title:"Query",children:t.jsx(C,{runQuery:()=>{console.log(`running query with: ${u?.malloyQuery}`);try{H.mutate()}catch($){console.error("Error running query:",$)}}})}),t.jsx(T,{source:e.sourceInfo,draftQuery:u?.malloyQuery,setDraftQuery:$=>h({...u,malloyQuery:$}),submittedQuery:y,options:{showRawQuery:!0}})]})})},e.sourceInfo.name)}function sy(e){const[n,r]=j.useState(null),[o,i]=j.useState(null),[l,a]=j.useState(!0);return j.useEffect(()=>{let d=!0;return Promise.all([import("@malloydata/malloy-explorer"),c.loadQueryBuilder()]).then(([u,h])=>{d&&(r(u),i(h),a(!1))}).catch(u=>{console.error("Failed to load Malloy components:",u),d&&a(!1)}),()=>{d=!1}},[]),l||!n||!o?t.jsx(q.StyledExplorerPage,{children:t.jsx(q.StyledExplorerContent,{children:t.jsx(wr.Box,{sx:{alignItems:"center",justifyContent:"center",height:"200px",color:"text.secondary"},children:"Loading explorer..."})})}):t.jsx(ry,{...e,explorerComponents:n,QueryBuilder:o,resourceUri:e.resourceUri})}function Eo(e,n=!0){const{modelPath:r,environmentName:o,packageName:i,versionId:l}=c.parseResourceUri(e),{apiClients:a}=q.useServer();return c.useQueryWithApiError({queryKey:["package",o,i,r,l],queryFn:async()=>(await a.models.getModel(o,i,r,l)).data,enabled:n})}function Io({data:e,onChange:n,existingQuery:r,initialSelectedSourceIndex:o=0,onSourceChange:i,resourceUri:l,givens:a,onGivensChange:d,startingGivens:u}){const[h,y]=j.useState(o);j.useEffect(()=>{y(o)},[o]);const{data:b,isError:x,isLoading:v,error:k}=Eo(l,!e),{environmentName:C,packageName:S,modelPath:T,versionId:O}=c.parseResourceUri(l),M=e||b,E=j.useMemo(()=>M?.givens??[],[M]),R=c.useDocumentControls({specs:E,loaded:!!M,params:a,onGivensChange:d,startingValues:u,documentKey:l,autorun:!0,environmentName:C??"",packageName:S??"",modelPath:T,versionId:O,documentName:T}),P=j.useMemo(()=>c.givensToRequest(R.applied,R.declaredTypes),[R.applied,R.declaredTypes]),A=j.useMemo(()=>ty(E,R.applied),[E,R.applied]);if(v&&!e)return t.jsx(c.Loading,{text:"Fetching Model..."});if(x&&!e)return console.log("error",k),t.jsx(c.ApiErrorDisplay,{error:k,context:`ModelExplorer > ${T}`});if(!M)return t.jsx(c.Loading,{text:c.LOADING_COPY.loading});const H=(M?.sourceInfos||[]).map((L,U)=>{try{return JSON.parse(L)?.name||`Source ${U+1}`}catch{return`Source ${U+1}`}}),D=H[h]||"";return t.jsxs(q.StyledCard,{variant:"outlined",children:[t.jsx(q.StyledCardContent,{children:t.jsx(p.Stack,{sx:{flexDirection:"row"},children:t.jsx(Qs,{size:"small",id:"size-small-standard",disablePortal:!0,options:H,value:D,onChange:(L,U)=>{if(!U)return;const $=H.indexOf(U);$>=0&&(y($),i?.($))},renderInput:L=>t.jsx(c.TextField,{...L}),style:{width:350,marginTop:"3px",marginLeft:"6px",marginBottom:"8px"}})})}),t.jsx(c.GivensPanel,{...R.panel}),t.jsx(q.StyledCardMedia,{children:t.jsxs(p.Stack,{spacing:2,component:"section",children:[Array.isArray(M.sourceInfos)&&M.sourceInfos.length>0&&t.jsx(sc,{sourceAndPaths:M.sourceInfos.map(L=>({sourceInfo:JSON.parse(L),modelPath:T})),selectedSourceIndex:h,existingQuery:r,onQueryChange:n,resourceUri:l,givens:P,gate:A}),t.jsx(p.Box,{height:"5px"})]})})]})}function Do({open:e,onClose:n,resourceUri:r,data:o,title:i="Data Sources",hasValidImport:l=!0,existingQuery:a,initialSelectedSourceIndex:d,onChange:u,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}){return t.jsxs(p.Dialog,{open:e,onClose:n,fullScreen:!0,children:[t.jsxs(p.DialogTitle,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i,t.jsx(p.IconButton,{onClick:n,sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{})})]}),t.jsx(p.DialogContent,{children:l?t.jsx(Io,{resourceUri:r,data:o,existingQuery:a,initialSelectedSourceIndex:d,onChange:u,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}):t.jsx("div",{children:"No valid import statement found in cell"})})]})}function oy({onChange:e,resourceUri:n,runOnDemand:r=!1,maxResultSize:o=0,givens:i,onGivensChange:l}){const{modelPath:a}=c.parseResourceUri(n),{data:d,isError:u,isLoading:h,error:y}=Eo(n),[b,x]=j.useState(!1),[v,k]=j.useState(),[C,S]=j.useState(0),[T,O]=j.useState(""),[M,E]=j.useState({}),R=i??M,P=l??($=>E($)),A=d?.modelDef,H=j.useMemo(()=>{if(!A)return!1;try{const $=JSON.parse(A);return Array.isArray($.imports)&&$.imports.length>0}catch{return!1}},[A]);if(h)return t.jsx(c.Loading,{text:"Fetching Model..."});if(u)return console.log("error",y),t.jsx(c.ApiErrorDisplay,{error:y,context:`Model > ${a}`});const D=$=>{k($),e&&e($)},L=$=>{S($)},U=()=>{const $=window.location.href;navigator.clipboard.writeText($).then(()=>O("URL copied to clipboard!")).catch(()=>O("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsxs(p.Box,{sx:{position:"relative",maxWidth:"1200px",margin:"0 auto",paddingTop:"24px"},children:[Array.isArray(d?.sourceInfos)&&d.sourceInfos.length>0&&t.jsxs(p.Stack,{spacing:2,component:"section",children:[t.jsxs(p.Box,{sx:{padding:"0 0 16px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx(p.Typography,{variant:"h1",sx:{fontSize:"28px",fontWeight:"600",color:"#1a1a1a",marginBottom:"8px",marginTop:"0",paddingLeft:"0"},children:"Sources"}),t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{size:"small","aria-label":"Copy link",onClick:U,sx:{color:"text.secondary"},children:t.jsx(fo,{fontSize:"small"})})})]}),t.jsx(Io,{data:d,onChange:D,onSourceChange:L,existingQuery:v,initialSelectedSourceIndex:C,resourceUri:n,givens:R,onGivensChange:P}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",sx:{position:"absolute",top:"90px",right:"4px",zIndex:2},onClick:()=>x(!0),children:t.jsx(c.SearchIcon,{})})]}),d?.queries?.length>0&&t.jsxs(p.Stack,{spacing:2,component:"section",sx:{marginTop:"24px"},children:[t.jsx(p.Box,{sx:{padding:"0 0 16px 0"},children:t.jsx(p.Typography,{variant:"h2",sx:{fontSize:"24px",fontWeight:"600",color:"#1a1a1a",marginBottom:"0",marginTop:"8px",paddingLeft:"0"},children:"Named Queries"})}),d.queries.map($=>t.jsx(Jg,{queryName:$.name,annotations:$.annotations,resourceUri:n,runOnDemand:r,maxResultSize:o},$.name))]}),(!Array.isArray(d?.sourceInfos)||d.sourceInfos.length===0)&&!(d?.queries&&d.queries.length>0)&&t.jsxs(p.Box,{sx:{textAlign:"center",py:6},children:[t.jsx(p.Typography,{variant:"body1",sx:{color:"text.secondary",marginBottom:"8px"},children:"This model exposes no sources or queries."}),H&&t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})]}),t.jsx(Do,{open:b,onClose:()=>x(!1),resourceUri:n,data:d,title:`Model: ${a.split("/").pop()}`,existingQuery:v,initialSelectedSourceIndex:C,onChange:D,onSourceChange:L,givens:R,onGivensChange:P})]}),t.jsx(p.Snackbar,{open:T!=="",autoHideDuration:6e3,onClose:()=>O(""),message:T})]})}function iy(){const[e,n]=j.useState(""),r=()=>{navigator.clipboard.writeText(window.location.href).then(()=>n("URL copied to clipboard!")).catch(()=>n("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{size:"small","aria-label":"Copy link",onClick:r,sx:{color:"text.secondary"},children:t.jsx(fo,{fontSize:"small"})})}),t.jsx(p.Snackbar,{open:e!=="",autoHideDuration:6e3,onClose:()=>n(""),message:e})]})}function ay(e){const{modelPage:n,isLoadingStatus:r}=q.useServer();if(r)return t.jsx(c.Loading,{text:"Fetching Model..."});if(n!=="viewer")return t.jsx(oy,{...e});const{onChange:o,runOnDemand:i,headerActions:l,...a}=e;return t.jsx(nc,{...a,headerActions:l??t.jsx(iy,{})})}const ly={"persist-source-refused":"persist-not-built","preaggregate-not-built":"rollup-not-built","preaggregate-join-one-key-repeated":"rollup-join-one-key-repeated","stored-native-schema-missing":"database-native-type-missing"};function cy(e){const n=(o,i)=>`${o}\0${i.subject??""}\0${i.message??""}`,r=new Set(e.map(o=>n(o.code,o)));return e.filter(o=>{const i=o.code!==void 0?ly[o.code]:void 0;return i===void 0||!r.has(n(i,o))})}function uy({warnings:e}){const[n,r]=j.useState(!1),o=cy(e??[]),i=o.filter(a=>a.severity==="error"),l=o.filter(a=>a.severity!=="error");return i.length===0&&l.length===0?null:t.jsxs(p.Stack,{sx:{gap:1,mb:4},children:[i.length>0&&t.jsxs(p.Alert,{severity:"warning",children:[t.jsx(p.AlertTitle,{children:i.length===1?"1 problem in this package":`${i.length} problems in this package`}),t.jsx(Ea,{findings:i})]}),l.length>0&&t.jsxs(p.Box,{children:[t.jsxs(p.Button,{size:"small","aria-expanded":n,onClick:()=>r(a=>!a),sx:{px:.5,color:"text.secondary"},children:[n?"Hide":"Show"," ",l.length," ",l.length===1?"note":"notes"]}),n&&t.jsx(p.Box,{sx:{pl:.5,pt:.5},children:t.jsx(Ea,{findings:l})})]})]})}function Ea({findings:e}){return t.jsx(p.Stack,{component:"ul",sx:{m:0,p:0,listStyle:"none",gap:.75},children:e.map((n,r)=>t.jsxs(p.Typography,{component:"li",variant:"body2",children:[n.model&&t.jsx(p.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.85em",mr:1},children:n.model}),n.message]},`${n.model??""}:${n.code??""}:${r}`))})}function oc({resourceUri:e,path:n,givens:r,onGivensChange:o,onNavigate:i,onLinkNavigate:l,height:a,maxResultSize:d,onEvent:u,chrome:h,manifestStaleTime:y,actions:b,rowsActions:x}){const v=c.parseResourceUri(e),{apiClients:k}=q.useServer(),C=v.environmentName??"",S=v.packageName??"",T=v.versionId,O=!!v.environmentName&&!!v.packageName,{data:M,isSuccess:E,isError:R,error:P}=c.useQueryWithApiError({...c.reportQueryOptions(k,{environmentName:C,packageName:S,path:n,versionId:T},y),enabled:O&&n!==""}),A=M?.layout,H=c.useReportEmitter({path:n,layout:A},u),D=`${e}|${n}`,L=j.useRef(void 0),U=j.useRef({key:D,at:c.now()});U.current.key!==D&&(U.current={key:D,at:c.now()}),j.useEffect(()=>{L.current!==D&&(O?R?(L.current=D,H.emit({type:"report.load_failed",surface:"view",category:c.failureCategory(P)})):M?.notebook?.format==="malloynb"?(L.current=D,H.emit({type:"report.load_failed",surface:"view",category:"unsupported"})):E&&M&&(L.current=D,H.emit({type:"report.opened",surface:"view",from:"package",tiles:M.tiles?.length??0,durationMs:c.now()-U.current.at})):(L.current=D,H.emit({type:"report.load_failed",surface:"view",category:"invalid"})))},[D,O,R,P,E,M,H]);const $=j.useCallback((te,ee)=>{const G=i?.(te,ee);G&&H.emit({type:"report.drill",to:"report",outcome:G})},[i,H]),W=i?$:void 0;if(!O)return t.jsxs(p.Alert,{severity:"error",children:["A report resource URI must name an environment and a package. Received: ",e]});if(R)return t.jsx(c.ApiErrorDisplay,{context:`${C} > ${S} > ${n}`,error:P});if(!E||!M)return t.jsx(c.Loading,{text:c.LOADING_COPY.opening("report")});if(M.notebook?.format==="malloynb")return t.jsxs(p.Alert,{severity:"info",children:[n," is a .malloynb notebook, which Report does not run: render it with Notebook."]});const Q=t.jsx(rs,{manifest:M,environmentName:C,packageName:S,versionId:T,documentName:n,givens:r,onGivensChange:o,onNavigate:W,...l?{onLinkNavigate:l}:{},height:a,maxResultSize:d,chrome:h,...b!==void 0?{actions:b}:{},...x!==void 0?{rowsActions:x}:{}});return t.jsx(c.ReportEventsContext.Provider,{value:H,children:Q})}function ic({open:e,layout:n,kind:r,allowLayoutChange:o,allowKindChange:i,environmentName:l,packageName:a,versionId:d,models:u,modelsLoading:h=!1,modelsError:y,onRetryModels:b,target:x,savedAs:v,onClose:k,onCreated:C,onEvent:S}){const T=n??(r?c.layoutOfKind(r):"linear"),O=o??i??!0,[M,E]=j.useState(T),[R,P]=j.useState(void 0),[A,H]=j.useState(""),[D,L]=j.useState(""),[U,$]=j.useState(""),W=j.useRef(null),[Q,te]=j.useState(""),[ee,G]=j.useState(!1),[Z,ae]=j.useState(!1),[z,re]=j.useState(!1),[se,ne]=j.useState(void 0),Ie=y!=null,{choices:de,isLoading:pe,isSuccess:De,failed:Le,retry:oe,canRetry:K}=c.useDocumentChoices({environmentName:l,packageName:a,...d!==void 0?{versionId:d}:{},models:u,enabled:e&&u.length>0}),le=j.useMemo(()=>de.get(A)??[],[de,A]),be=j.useMemo(()=>new Map([...de.entries()].flatMap(([fe,Ue])=>Ue.map(bt=>[zs(fe,bt.source,bt.view),{model:fe,source:bt.source,view:bt.view}]))),[de]),ge=j.useMemo(()=>{const fe=de.size>1;return[...de.entries()].flatMap(([Ue,bt])=>{const ke=new Map;for(const Ne of bt)ke.set(Ne.source,[...ke.get(Ne.source)??[],Ne]);return[...ke.entries()].map(([Ne,Ee])=>({key:`${Ue}::${Ne}`,label:Ne,ariaLabel:`${Ne} in ${Ue}`,...fe||Ee[0]?.sourceDescription?{detail:[fe?Ue:void 0,Ee[0]?.sourceDescription].filter(Boolean).join(" · ")}:{},entries:Ee.map(Be=>({key:zs(Ue,Be.source,Be.view),name:Be.view,title:Be.description??c.readableName(Be.view),...Be.chart?{chart:Be.chart}:{}}))}))})},[de]),ue=fe=>{const Ue=be.get(fe);Ue&&(H(Ue.model),L(`${Ue.source}::${Ue.view}`))},ye=le.find(fe=>`${fe.source}::${fe.view}`===D),$e=ye?zs(A,ye.source,ye.view):void 0,ze=dy(ye,250);j.useEffect(()=>{e&&E(T)},[e,T]),j.useEffect(()=>{if(!e)return;const fe=[...de.keys()];A===""&&fe.length>0&&H(fe[0])},[e,de,A]),j.useEffect(()=>{!e||le.length===0||D!==""||L(`${le[0].source}::${le[0].view}`)},[e,le,D]),j.useEffect(()=>{!e||ee||ye===void 0||te(c.readableName(ye.view))},[e,ee,ye]),j.useEffect(()=>{e||(H(""),L(""),$(""),te(""),G(!1),P(void 0),ae(!1),ne(void 0))},[e]);const me=j.useMemo(()=>{if(Q.trim()!=="")for(let fe=1;fe<=c.MAX_SLUG_ATTEMPTS;fe++){const Ue=c.reportPathForTitle(Q,fe);if(!x.existing?.includes(Ue))return Ue}},[Q,x]),Y=R?.trim(),ie=Y===void 0||Y===""?void 0:Y.endsWith(".malloy")?Y:`${Y}.malloy`,Oe=ie??me,Fe=ie===void 0?void 0:c.reportPathProblem(ie)??(x.existing?.includes(ie)?`${ie} already exists; choose another location.`:void 0),Me=(ye===void 0?void 0:c.newDocumentProblem({title:Q,modelPath:A,source:ye.source,view:ye.view}))??(Q.trim()!==""&&Oe===void 0?"No free file name for this title; choose another.":void 0),lt=Me!==void 0&&(Z||Q.trim()!==""),xt=h||pe,{theme:vt}=q.usePublisherTheme(),Ot=vt.ui,pt=c.edgeColor(vt.cardBorder),Ke=de.size===0&&(Ie||Le.length>0),he=xt?"Loading the model":Ke?"Couldn't read the model to start from":de.size===0?"Nothing in the model to start from yet":ye===void 0?"Pick what to start from":void 0,Qe="report",qe=z?`Creating ${Qe}…`:`Create ${Qe}`,ct=D!==""&&ye===void 0&&le.length>0,ut=async()=>{if(!(he!==void 0||ye===void 0||z)){if(Me!==void 0||Fe!==void 0){ae(!0);return}re(!0),ne(void 0);try{const fe=await c.createDocument({layout:M,...ie!==void 0?{path:ie}:{},document:{title:Q,modelPath:A,source:ye.source,view:ye.view},target:x,...S?{onEvent:S}:{}});C(fe)}catch(fe){const Ue=fe.response?.data?.message;ne(Ue??(fe instanceof Error?fe.message:String(fe)))}finally{re(!1)}}},Ze=fe=>t.jsx(p.Button,{color:"inherit",size:"small",onClick:fe,children:"Retry"});return t.jsx(c.AppDialog,{className:`${c.reportClasses.dialog} ${c.reportClasses.newReportDialog}`,maxWidth:"md",initialFocus:W,open:e,onClose:z?()=>{}:k,title:`New ${Qe}`,description:"A report is a Malloy file in the package that lays out text and queries. Pick what its first query shows; the rest is the builder.",actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{onClick:k,disabled:z,children:"Cancel"}),t.jsx(p.Tooltip,{title:z?"":he??"",children:t.jsx("span",{children:t.jsx(p.Button,{variant:"contained",disabled:z||he!==void 0,"aria-label":!z&&he!==void 0?`${qe}: ${he}`:qe,onClick:()=>void ut(),children:qe})})})]}),children:t.jsxs(p.Stack,{sx:{gap:1.5},children:[Ie?t.jsx(p.Alert,{severity:"error",action:b&&oo.canRetryRequest(y)?Ze(b):void 0,children:"Couldn't read this package's models, so no view is listed to start from."}):u.length===0?!h&&t.jsxs(p.Alert,{severity:"info",children:["This package has no models yet. Add a .malloy file that declares a source with a view, then create a ",Qe," from it."]}):Le.length>0?t.jsxs(p.Alert,{severity:"warning",action:K?Ze(oe):void 0,children:["Couldn't read ",Le.join(", "),", so nothing from"," ",Le.length===1?"it":"them"," is listed."]}):De&&de.size===0&&t.jsxs(p.Alert,{severity:"info",children:["A ",Qe," starts from a view of a source, and no model in this package declares one yet. Add a view to a source in a model file and this list fills in."]}),t.jsxs(p.Box,{sx:{mx:-3,mb:-1,borderTop:`1px solid ${pt}`,borderBottom:`1px solid ${pt}`,display:"grid",gridTemplateColumns:{xs:"1fr",md:"320px minmax(0, 1fr)"},height:{md:500}},children:[t.jsx(p.Box,{sx:{display:"flex",flexDirection:"column",minHeight:0,borderRight:{md:`1px solid ${pt}`},maxHeight:{xs:280,md:"none"}},children:t.jsx(c.ViewPicker,{groups:ge,query:U,onQuery:$,picked:$e,onPick:ue,onTake:fe=>{ue(fe)},searchRef:W,disabled:z,empty:t.jsx(p.Typography,{variant:"body2",sx:{color:"text.secondary",p:2},children:xt?"Reading the package's models…":"Nothing to start from."})})}),t.jsxs(p.Box,{sx:fe=>({p:2.5,display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto",bgcolor:`color-mix(in srgb, ${fe.palette.text.primary} 3%, ${fe.palette.background.paper})`}),children:[O&&t.jsxs(p.Box,{children:[t.jsx(Ia,{children:"Layout"}),t.jsx(p.Box,{role:"radiogroup","aria-label":"Layout",sx:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:1},children:["linear","grid"].map(fe=>t.jsx(my,{layout:fe,checked:M===fe,disabled:z,onPick:()=>E(fe)},fe))}),t.jsx(p.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"Switch it any time in the builder."})]}),t.jsxs(p.Box,{children:[t.jsx(Ia,{children:"First query"}),t.jsx(p.Box,{role:"region","aria-label":"Preview",sx:fe=>({height:200,display:"flex",position:"relative",overflow:"hidden",borderRadius:Ot.radius.tile,border:`1px solid ${pt}`,bgcolor:fe.palette.background.paper,"&::after":{content:'""',position:"absolute",left:0,right:0,bottom:0,height:40,pointerEvents:"none",background:`linear-gradient(to bottom, transparent, ${fe.palette.background.paper})`}}),children:ye&&ze?t.jsx(p.Box,{sx:{flex:1,minWidth:0,px:2,pt:1.5},children:t.jsx(c.DashboardTile,{environmentName:l,packageName:a,...d!==void 0?{versionId:d}:{},modelPath:A,tile:`${ze.source} -> ${ze.view}`,label:Q.trim()||c.readableName(ze.view),borderless:!0,givens:hy,declaredTypes:fy,height:180})}):t.jsx(p.Typography,{variant:"body2",sx:{color:"text.secondary",m:"auto"},children:ct?"What you picked is no longer in this model; pick something else.":"Pick what to start from."})}),t.jsx(p.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"More are added in the builder."})]}),t.jsx(p.TextField,{size:"small",label:"Title",value:Q,disabled:z,onChange:fe=>{G(!0),te(fe.target.value)},InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Report title"},error:lt,helperText:lt?Me:x.route==="package"?"Names the file too, unless you type a location.":v??`Saved as a new ${Qe} in the host's store, and opened in the builder.`}),t.jsx(p.TextField,{size:"small",label:"Location",value:R??me??"",placeholder:"report.malloy",disabled:z,onChange:fe=>P(fe.target.value),InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Location"},error:Fe!==void 0,helperText:Fe??(Oe?`Written as ${Oe} in the package, and opened in the builder.`:"A path in the package; the package root by default.")}),se&&t.jsx(p.Alert,{severity:"error",children:se})]})]})]})})}function dy(e,n){const[r,o]=j.useState(void 0);return j.useEffect(()=>{const i=window.setTimeout(()=>o(e),n);return()=>window.clearTimeout(i)},[e,n]),r}const zs=(e,n,r)=>`${e}::${n}::${r}`,hy=new Map,fy=new Map;function Ia({children:e}){const n=q.usePublisherTheme().theme.ui;return t.jsx(p.Typography,{component:"div",sx:{...n.type.label,color:"text.secondary",mb:.75},children:e})}function my({layout:e,checked:n,disabled:r,onPick:o}){const{theme:i}=q.usePublisherTheme(),l=i.ui,a=c.edgeColor(i.cardBorder),d=n?i.accent:"currentColor";return t.jsxs(p.ButtonBase,{role:"radio","aria-checked":n,"aria-label":e==="linear"?"Linear":"Grid",disabled:r,onClick:o,sx:u=>({justifyContent:"flex-start",gap:1.25,px:1.25,py:1,borderRadius:l.radius.tile,border:`1px solid ${n?i.accent:a}`,boxShadow:n?`0 0 0 1px ${i.accent}`:"none",bgcolor:n?`color-mix(in srgb, ${i.accent} 6%, ${u.palette.background.paper})`:u.palette.background.paper,color:u.palette.text.secondary,textAlign:"left"}),children:[t.jsx("svg",{width:"34",height:"26",viewBox:"0 0 34 26","aria-hidden":!0,children:e==="linear"?t.jsxs("g",{fill:"none",stroke:d,strokeWidth:"1.5",children:[t.jsx("rect",{x:"3",y:"2",width:"28",height:"7",rx:"1.5"}),t.jsx("rect",{x:"3",y:"12",width:"28",height:"5",rx:"1.5"}),t.jsx("path",{d:"M5 21.5h20",strokeLinecap:"round"})]}):t.jsxs("g",{fill:"none",stroke:d,strokeWidth:"1.5",children:[t.jsx("rect",{x:"2",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"18",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"2",y:"14",width:"30",height:"10",rx:"1.5"})]})}),t.jsxs(p.Box,{children:[t.jsx(p.Box,{sx:{...l.type.control,fontWeight:n?l.type.label.fontWeight:500,color:n?i.accent:"text.primary"},children:e==="linear"?"Linear":"Grid"}),t.jsx(p.Box,{sx:{...l.type.caption,color:"text.secondary"},children:e==="linear"?"Read top to bottom":"Tiles side by side"})]})]})}const py=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),gy=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),yy=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),xy=c.createSvgIcon(t.jsx("path",{d:"M20 10V8h-4V4h-2v4h-4V4H8v4H4v2h4v4H4v2h4v4h2v-4h4v4h2v-4h4v-2h-4v-4zm-6 4h-4v-4h4z"})),ac={dashboard:q.PALETTE.blue,report:q.PALETTE.violet,model:q.PALETTE.cyan,dataApp:q.PALETTE.pink,data:q.PALETTE.lime,materialization:q.PALETTE.amber,agent:q.PALETTE.red};function lc({type:e,size:n=18,sx:r,...o}){return t.jsx(c.SvgIcon,{...o,viewBox:"0 0 24 24",sx:{width:n,height:n,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",...r},children:vy[e]()})}const vy={report:by,model:wy,data:Sy,materialization:ky,dataApp:Ty,dashboard:Cy,agent:jy};function by(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M14 3 H6 a2 2 0 0 0 -2 2 v14 a2 2 0 0 0 2 2 h12 a2 2 0 0 0 2 -2 V9 z"}),t.jsx("path",{d:"M14 3 v4 a2 2 0 0 0 2 2 h4"}),t.jsx("path",{d:"M8 17 v-3"}),t.jsx("path",{d:"M12 17 v-6"}),t.jsx("path",{d:"M16 17 v-4"})]})}function wy(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L4 7 v10 l8 4 l8 -4 V7 z"}),t.jsx("path",{d:"M4 7 l8 4 l8 -4"}),t.jsx("path",{d:"M12 11 v10"})]})}function Sy(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M9.5 3.5 V20.5"})]})}function ky(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L21 7.5 L12 12 L3 7.5 Z"}),t.jsx("path",{d:"M3 12 L12 16.5 L21 12"}),t.jsx("path",{d:"M3 16.5 L12 21 L21 16.5"})]})}function Cy(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M12 9.5 V20.5"}),t.jsx("path",{d:"M12 15 H20.5"})]})}function jy(){return t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:"12",cy:"8",r:"3.5"}),t.jsx("path",{d:"M5 20 a7 7 0 0 1 14 0"})]})}function Ty(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M7 13.5 H17"}),t.jsx("path",{d:"M7 16.5 H13"})]})}function cc(e){return e>=1e9?`${(e/1e9).toFixed(1)} B rows`:e>=1e6?`${(e/1e6).toFixed(1)} M rows`:e>=1e3?`${(e/1e3).toFixed(1)} K rows`:`${e} rows`}const Oy=12;function My(e){const n=e?.trim().toLowerCase()??"";if(n.startsWith("array")||n.endsWith("[]"))return gy;if(n.startsWith("record")||n.startsWith("struct"))return yy;switch(n.split(/[\s(<]/)[0]){case"string":return py;case"number":return xy;case"date":return Rl;case"timestamp":case"timestamptz":return Ll;case"boolean":return _l;default:return Pl}}function Ey({column:e}){const n=My(e.type);return t.jsxs(p.Box,{component:"li",sx:r=>({display:"flex",alignItems:"center",gap:1.25,px:1,py:.625,borderRadius:1,transition:"background-color 0.1s","&:hover":{backgroundColor:r.palette.mode==="dark"?"rgba(255, 255, 255, 0.06)":r.palette.grey[100]}}),children:[t.jsx(n,{"aria-hidden":!0,sx:{fontSize:18,color:"primary.main",flexShrink:0}}),t.jsxs(p.Box,{sx:{display:"flex",alignItems:"baseline",gap:1,minWidth:0,flex:1},children:[t.jsx(p.Typography,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.8125rem",fontWeight:500,color:"text.primary",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.type&&t.jsx(p.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{flexShrink:0,maxWidth:"50%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.type})]})]})}function Iy({database:e,onClose:n}){const r=e!==null,[o,i]=j.useState(e);e!==null&&e!==o&&i(e);const[l,a]=j.useState(""),[d,u]=j.useState(o?.path);d!==o?.path&&(u(o?.path),a(""));const h=j.useId(),y=o?.path??"",b=y.split("/").pop()||y,x=y.slice(0,Math.max(0,y.length-b.length-1)),v=o?.info?.rowCount,k=[x,v===void 0?null:cc(v)].filter(Boolean).join(" · "),C=j.useMemo(()=>o?.info?.columns??[],[o]),S=l.trim().toLowerCase(),T=j.useMemo(()=>S?C.filter(O=>O.name?.toLowerCase().includes(S)||O.type?.toLowerCase().includes(S)):C,[C,S]);return t.jsxs(c.AppDialog,{open:r,onClose:n,showClose:!0,title:t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{minWidth:0},children:[t.jsx(p.Box,{"aria-hidden":!0,sx:{width:32,height:32,borderRadius:1,bgcolor:ac.data,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(lc,{type:"data",size:18})}),t.jsxs(p.Box,{sx:{minWidth:0},children:[t.jsx(p.Typography,{component:"span",noWrap:!0,title:y,sx:{display:"block",fontFamily:q.MONO_FONT_FAMILY,fontSize:"1rem",fontWeight:600,letterSpacing:0,lineHeight:1.4},children:b||"Columns"}),k&&t.jsx(p.Typography,{component:"span",variant:"caption",color:"text.secondary",noWrap:!0,sx:{display:"block",lineHeight:1.4},children:k})]})]}),children:[o?.error&&t.jsx(p.Alert,{severity:"error",variant:"outlined",children:o.error}),o&&!o.error&&t.jsxs(p.Box,{component:"section","aria-labelledby":h,sx:{display:"flex",flexDirection:"column",border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",mb:2},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{px:1.5,py:1,minHeight:44,borderBottom:"1px solid",borderColor:"divider"},children:[t.jsxs(p.Typography,{id:h,component:"h3",sx:{fontSize:"0.875rem",fontWeight:600},children:["Columns",t.jsxs(p.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{ml:.75,fontVariantNumeric:"tabular-nums"},children:["· ",S?`${T.length} of `:"",C.length]})]}),C.length>Oy&&t.jsx(p.InputBase,{value:l,onChange:O=>a(O.target.value),placeholder:"Filter columns",inputProps:{"aria-label":"Filter columns"},startAdornment:t.jsx(p.InputAdornment,{position:"start",children:t.jsx(c.SearchIcon,{sx:{fontSize:16,color:"text.secondary"}})}),sx:{ml:"auto !important",width:200,fontSize:"0.8125rem",px:1,py:.25,border:"1px solid",borderColor:"divider",borderRadius:1.5,"&.Mui-focused":{borderColor:"primary.main"}}})]}),t.jsx(p.Box,{sx:{overflowY:"auto",maxHeight:420,px:.75,py:.75},children:T.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic",px:1,py:1},children:S?"No columns match":"No columns"}):t.jsx(p.Box,{component:"ul","aria-labelledby":h,sx:{listStyle:"none",m:0,p:0},children:T.map((O,M)=>t.jsx(Ey,{column:O},`${O.name}-${M}`))})})]})]})}const $o=(e,n,r)=>["packageVersions",e,n,r];async function uc(e,n,r){try{return(await e.versions.listPackageVersions(n,r)).data}catch(o){const i=o?.response?.status;if(i===404||i===501)return[];throw o}}function dc(e,n,r={}){const{apiClients:o,server:i}=q.useServer(),l=(r.enabled??!0)&&e!==""&&n!=="",a=yt.useQuery({queryKey:$o(e,n,i),queryFn:()=>uc(o,e,n),enabled:l,staleTime:3e4,retry:!1}),{refetch:d}=a,u=j.useCallback(()=>void d(),[d]),h=a.data??[];return{versions:h,latest:h.find(y=>y.latest)?.id,isPending:l&&a.isPending,isError:l&&a.isError,refetch:u}}function Dy(e,n){const{apiClients:r,server:o}=q.useServer(),i=yt.useQueryClient();return j.useCallback(()=>i.fetchQuery({queryKey:$o(e,n,o),queryFn:()=>uc(r,e,n),staleTime:0,retry:!1}),[i,r,o,e,n])}function hc(e,n){const r=yt.useQueryClient();return j.useCallback(()=>r.invalidateQueries({predicate:o=>o.queryKey[1]===e&&o.queryKey[2]===n}),[r,e,n])}const $y=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.81.97H5.44zM5 19V8h14v11zm8.45-9h-2.9v3H8l4 4 4-4h-2.55z"})),Ay=c.createSvgIcon(t.jsx("path",{d:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"})),Fy=c.createSvgIcon(t.jsx("path",{d:"M14 4v5c0 1.12.37 2.16 1 3H9c.65-.86 1-1.9 1-3V4zm3-2H7c-.55 0-1 .45-1 1s.45 1 1 1h1v5c0 1.66-1.34 3-3 3v2h5.97v7l1 1 1-1v-7H19v-2c-1.66 0-3-1.34-3-3V4h1c.55 0 1-.45 1-1s-.45-1-1-1"})),Ry=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.83 1H5.42zM5 19V8h14v11zm3-5h2.55v3h2.9v-3H16l-4-4z"})),dr=e=>{const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error?e.message:"Unknown error"},Ny=e=>{const n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})},Fn=e=>e.archiveStatus==="archive",Ws="Tables built for this version alone (under scope: version) are dropped.";function Da(e,n){const r=!Fn(e)&&n.filter(i=>!Fn(i)).length<=1,o=n.length<=1;return{archive:e.latest?"The latest version can't be archived":r?"The last version in service can't be archived":void 0,delete:o?void 0:e.latest?"Pin another version as latest first":r?"The last version in service; delete the archived versions first":void 0}}function fc({environmentName:e,packageName:n,versions:r,selectedVersionId:o,onSelectVersion:i,onReplaceVersion:l,onPackageDeleted:a,canManage:d}){const{apiClients:u}=q.useServer(),h=yt.useQueryClient(),y=hc(e,n),b=Dy(e,n),[x,v]=j.useState(null),[k,C]=j.useState(null),[S,T]=j.useState(null),[O,M]=j.useState(null),[E,R]=j.useState(null),[P,A]=j.useState(null),H=j.useRef(null),D=j.useRef(null),L=j.useRef(null),U=j.useRef(new Map),$=r.find(K=>K.latest)?.id,W=o??$,Q=()=>Promise.all([y(),h.invalidateQueries({queryKey:["packages",e]})]),te=async(K,le)=>{const be=le??await b().catch(()=>{});if(be===void 0)return;const ge=be.find(ye=>ye.latest)?.id,ue=ge??be.find(ye=>ye.id!==K&&!Fn(ye))?.id;ue!==void 0&&(l?l(ue===ge?void 0:ue):i(ue))},ee=yt.useMutation({mutationFn:K=>u.versions.setPackageLatestVersion(e,n,{version:K}),onSuccess:async()=>{T(null),await Q()},onError:()=>void Q()}),G=yt.useMutation({mutationFn:({id:K,archiveStatus:le})=>u.versions.updatePackageVersion(e,n,K,{archiveStatus:le}),onSuccess:async(K,{id:le,archiveStatus:be})=>{M(null),be==="archive"&&le===W&&await te(le),await Q()},onError:(K,{id:le,archiveStatus:be})=>{be==="unarchive"&&A(`Couldn't unarchive v${le}: ${dr(K)}`),Q()}}),Z=G.isPending?G.variables?.id:void 0,ae=yt.useMutation({mutationFn:({id:K})=>u.versions.deletePackageVersion(e,n,K),onSuccess:async(K,{id:le,read:be})=>{R(null);const ue=await b().catch(()=>{})??be.filter(ye=>ye.id!==le);if(ue.length===0){await h.invalidateQueries({queryKey:["packages",e]}),a?.();return}le===W&&await te(le,ue),await Q()},onError:()=>void Q()}),z=()=>C(null),re=k?Da(k.version,r):{},se=k!==null&&!Fn(k.version)&&k.version.latest&&re.archive!==void 0&&re.delete!==void 0,ne=E!==null&&E.versions===void 0,Ie=E?.versions!==void 0&&E.versions.length<=1,de=E?.versions!==void 0?Da(E.version,E.versions).delete:void 0,pe=async K=>{z(),v(null),ae.reset(),R({version:K});const le=ue=>R(ye=>ye!==null&&ye.version.id===K.id&&ye.versions===void 0?ue:ye);let be;try{be=await b()}catch(ue){le(null),A(`Couldn't check v${K.id} before deleting it: ${dr(ue)}`);return}const ge=be.find(ue=>ue.id===K.id);if(ge===void 0){le(null),A(`v${K.id} is no longer a version of ${n}.`),Q();return}le({version:ge,versions:be})},De=(K,le)=>{!d||Z===K.id||C({version:K,anchor:U.current.get(K.id)??le})},Le=(K,le)=>{const be=K.key==="ArrowRight"||K.key==="ContextMenu"||K.key==="F10"&&K.shiftKey;!d||!be||(K.preventDefault(),K.stopPropagation(),De(le,K.currentTarget))},oe=k&&t.jsxs(p.MenuItem,{disabled:re.delete!==void 0,onClick:()=>void pe(k.version),children:[t.jsx(p.ListItemIcon,{children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Delete version",secondary:re.delete})]},"delete");return t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{size:"small",variant:"outlined",endIcon:t.jsx(Nl,{}),"aria-label":W?`Version v${W}, change version`:"Select a version","aria-haspopup":"menu",onClick:K=>v(K.currentTarget),sx:{borderRadius:999,textTransform:"none",fontWeight:500,px:1.5,minWidth:0,whiteSpace:"nowrap"},children:W?`v${W}`:"Select a version"}),t.jsx(p.Menu,{anchorEl:x,open:x!==null,onClose:()=>v(null),slotProps:{paper:{sx:{minWidth:320,maxWidth:400,mt:1,borderRadius:3}},list:{"aria-label":`Versions of ${n}`,disabledItemsFocusable:!0}},children:r.map(K=>{const le=K.id===W,be=Fn(K),ge=[be?"Archived":void 0,Ny(K.createdAt),K.gitCommitSha?K.gitCommitSha.slice(0,7):void 0].filter(Boolean).join(" · ");return t.jsxs(p.MenuItem,{"aria-current":le?"true":void 0,"aria-disabled":be&&!d?"true":void 0,"aria-haspopup":d?"menu":void 0,"data-testid":"version-row",onKeyDown:ue=>Le(ue,K),onClick:ue=>{if(be){De(K,ue.currentTarget);return}le||(v(null),i(K.id,ue))},sx:ue=>({gap:1,borderLeft:"3px solid",borderLeftColor:le?ue.palette.primary.main:"transparent",backgroundColor:le?p.alpha(ue.palette.primary.main,.04):void 0,cursor:le||be&&!d?"default":"pointer"}),children:[t.jsx(p.ListItemText,{primary:K.id,secondary:ge,sx:{opacity:be?.6:1},slotProps:{primary:{sx:{fontWeight:le?600:400}}}}),K.latest&&t.jsx(p.Chip,{size:"small",label:"Latest",color:"info",variant:"outlined",sx:{height:20,fontSize:11,fontWeight:600}}),d&&t.jsx(p.Tooltip,{title:Z===K.id?"Updating this version…":"",children:t.jsx("span",{children:t.jsx(p.IconButton,{ref:ue=>{ue?U.current.set(K.id,ue):U.current.delete(K.id)},size:"small","aria-label":`More actions for version ${K.id}`,"aria-haspopup":"menu",disabled:Z===K.id,onClick:ue=>{ue.stopPropagation(),C({version:K,anchor:ue.currentTarget})},children:t.jsx(Ay,{fontSize:"small"})})})})]},K.id)})}),t.jsx(p.Menu,{anchorEl:k?.anchor??null,open:k!==null,onClose:z,slotProps:{list:{"aria-label":k?`Actions for version ${k.version.id}`:void 0,disabledItemsFocusable:!0,autoFocus:se}},children:k&&Fn(k.version)?[t.jsxs(p.MenuItem,{onClick:()=>{const{id:K}=k.version;z(),G.mutate({id:K,archiveStatus:"unarchive"})},children:[t.jsx(p.ListItemIcon,{children:t.jsx(Ry,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Unarchive"})]},"unarchive"),t.jsx(p.Divider,{},"divider"),oe]:k&&[t.jsxs(p.MenuItem,{disabled:k.version.latest,onClick:()=>{T(k.version),ee.reset(),z(),v(null)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(Fy,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Pin as latest",secondary:k.version.latest?"Already the latest version":void 0})]},"pin-latest"),t.jsxs(p.MenuItem,{disabled:re.archive!==void 0,onClick:()=>{M(k.version),G.reset(),z(),v(null)},children:[t.jsx(p.ListItemIcon,{children:t.jsx($y,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Archive",secondary:re.archive})]},"archive"),t.jsx(p.Divider,{},"divider"),oe]}),t.jsx(c.AppDialog,{open:S!==null,onClose:()=>{ee.isPending||T(null)},title:S?`Pin v${S.id} as latest`:"",description:S?`Requests that name no version will be served from v${S.id}.`:void 0,initialFocus:H,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:H,disabled:ee.isPending,onClick:()=>T(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:ee.isPending,onClick:()=>S&&ee.mutate(S.id),children:"Pin as latest"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[$&&S&&$!==S.id&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:`The latest version is v${$} now. Links and requests that name a version keep answering as before.`}),ee.isError&&S&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't pin v${S.id} as latest: ${dr(ee.error)}`})]})}),t.jsx(c.AppDialog,{open:O!==null,onClose:()=>{G.isPending||M(null)},title:O?`Archive v${O.id}`:"",description:O?`v${O.id} stops being served and is unloaded. Its files stay, so it can be unarchived.`:void 0,initialFocus:D,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:D,disabled:G.isPending,onClick:()=>M(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:G.isPending,onClick:()=>O&&G.mutate({id:O.id,archiveStatus:"archive"}),children:"Archive"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:`${Ws} Its scheduled builds stop, and once unarchived it serves live until it is built again.`}),G.isError&&O&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't archive v${O.id}: ${dr(G.error)}`})]})}),t.jsx(c.AppDialog,{open:E!==null,onClose:()=>{ae.isPending||R(null)},title:E?`Delete v${E.version.id}`:"",initialFocus:L,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:L,disabled:ae.isPending,onClick:()=>R(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",color:"error",loading:ae.isPending,disabled:ne||de!==void 0,onClick:()=>E?.versions&&ae.mutate({id:E.version.id,read:E.versions}),children:Ie?"Delete package":"Delete version"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[ne&&E&&t.jsx(p.Typography,{variant:"body2",children:`Checking ${n}'s versions before deleting v${E.version.id}…`}),E&&!ne&&t.jsx(p.Typography,{variant:"body2",children:Ie?`v${E.version.id} is the only version of ${n}, so deleting it deletes the package. ${Ws} This cannot be undone.`:`v${E.version.id} stops being served and its files are removed. ${Ws} Links that name it stop working, and this cannot be undone.`}),de!==void 0&&E&&t.jsx(p.Alert,{severity:"warning",role:"alert",children:`v${E.version.id} can't be deleted now: ${de}.`}),ae.isError&&E&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't delete v${E.version.id}: ${dr(ae.error)}`})]})}),t.jsx(p.Snackbar,{open:P!==null,autoHideDuration:8e3,onClose:()=>A(null),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:t.jsx(p.Box,{children:t.jsx(p.Alert,{severity:"error",variant:"filled",onClose:()=>A(null),children:P})})})]})}const Ly="README.malloynb",_y=e=>!!e&&!e.includes("/")&&c.documentSlug(e)?.toLowerCase()==="readme";function Py({onClickPackageFile:e,onOpenDocument:n,resourceUri:r,onEvent:o,onSelectVersion:i,onReplaceVersion:l}){const{apiClients:a,server:d,mutable:u}=q.useServer(),h=yt.useQueryClient(),y=e??(Y=>{window.location.href=Y}),{environmentName:b,packageName:x,versionId:v}=c.parseResourceUri(r),k=dc(b,x),{versions:C}=k,S=C.length>0,T=!S&&!k.isPending&&!k.isError,O=i??((Y,ie)=>y(`/${encodeURIComponent(b)}/${encodeURIComponent(x)}/${encodeURIComponent(Y)}`,ie)),M=n??((Y,ie)=>{const Oe=Y.mode==="edit"?c.reportEditRoute(b,x,Y.path):c.reportRoute(b,x,Y.path);ie?y(Oe,ie):y(Oe)}),[E,R]=j.useState(null),[P,A]=j.useState(!1),H=Fa(),D=c.useOptionalDocumentStorage()?.documentStorage,[L,U]=j.useState([]),[$,W]=j.useState({state:D?"pending":"ready"}),Q=j.useCallback(async()=>{if(!D)return;let Y;try{Y=await D.listWorkspaces(!1)}catch{W({state:"failed"});return}W({state:"ready",chosen:c.chooseWorkspace(Y)});const ie=[],Oe=c.draftKey(b,x,"");for(const Fe of Y.filter(at=>at.writeable))for(const at of await D.listDocuments(Fe))at.path.startsWith(Oe)&&ie.push({locator:at,where:Fe.description});U(ie)},[D,b,x]);j.useEffect(()=>{Q()},[Q]);const te=Y=>Y.path.slice(c.draftKey(b,x,"").length),ee=c.useQueryWithApiError({queryKey:["package",b,x,v],queryFn:()=>a.packages.getPackage(b,x,v,!1)}),G=c.useQueryWithApiError({queryKey:["package-agents",b,x,v],queryFn:()=>a.agents.listAgents(b,x,v)}),Z=c.useReportListing(b,x,v),ae=c.useQueryWithApiError({queryKey:["models",b,x,v],queryFn:()=>a.models.listModels(b,x,v)}),z=c.useQueryWithApiError({queryKey:["databases",b,x,v],queryFn:()=>a.databases.listDatabases(b,x,v)}),se=c.useQueryWithApiError({queryKey:["data-apps",b,x,v],queryFn:async()=>{try{return await a.dataApps.listDataApps(b,x,v)}catch(Y){const ie=Y?.response?.status;if(ie===404||ie===void 0)return{data:[]};throw Y}}}).data?.data??[],ne=Z.reports.filter(Y=>!!Y.path),Ie=Wy(ne),de=new Set(ne.map(Y=>Y.path).filter(Y=>Y!==void 0)),pe=(ae.data?.data??[]).slice().filter(Y=>!de.has(Y.path)).sort((Y,ie)=>Y.path.localeCompare(ie.path)),De=(z.data?.data??[]).slice().sort((Y,ie)=>Y.path.localeCompare(ie.path)),Le=$.state==="ready"?c.createRoute({authoritative:$.chosen?.authoritative===!0,mutable:u&&T,canStore:$.chosen?.writeable===!0,...v===void 0?{}:{versionId:v}}):void 0,oe=Z.settled&&(ae.isSuccess||ae.isError),K=Le!==void 0&&oe,le=K&&!H,be=j.useMemo(()=>{if(!K)return;const Y=[...Z.reports.flatMap(ie=>ie.path?[ie.path]:[]),...(ae.data?.data??[]).flatMap(ie=>ie.path?[ie.path]:[])];if(Le==="storage"&&D&&$.state==="ready")return $.chosen?{route:Le,storage:D,workspace:$.chosen,environmentName:b,packageName:x,existing:Y}:void 0;if(Le==="package")return{route:Le,existing:Y,write:async(ie,Oe)=>{await a.models.updateModelSource(b,x,ie,{source:Oe})}}},[K,Le,D,$,b,x,a,Z.reports,ae.data]),ge=ee.data?.data?.description??"",ue=G.data?.data??[],ye=(ne.find(Y=>Y.path===Ly)??ne.find(Y=>_y(Y.path)))?.path,$e=!Z.settled,ze=S?t.jsx(fc,{environmentName:b,packageName:x,versions:C,...v!==void 0?{selectedVersionId:v}:{},onSelectVersion:O,...l?{onReplaceVersion:l}:{},onPackageDeleted:()=>y(`/${encodeURIComponent(b)}`),canManage:u}):null,me=t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{mb:.5},children:[t.jsx(p.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),ze]});if(ee.isError){const Y=t.jsx(c.ApiErrorDisplay,{error:ee.error,context:`${b} > ${x}`});return ze?t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsx(p.Box,{sx:{mb:4},children:me}),Y]}):Y}return t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(p.Box,{sx:{mb:4},children:[me,ge&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:ge})]}),t.jsx(uy,{warnings:ee.data?.data?.warnings}),k.isError&&t.jsx(p.Box,{sx:{mb:4},children:t.jsx(p.Alert,{severity:"warning",action:t.jsx(p.Button,{color:"inherit",size:"small",onClick:k.refetch,children:"Retry"}),children:"Could not read this package's versions, so nothing that changes it is offered until they load."})}),$e&&t.jsx(c.Loading,{text:"Loading package..."}),be&&t.jsx(ic,{open:P,layout:"linear",environmentName:b,packageName:x,...v!==void 0?{versionId:v}:{},models:pe.map(Y=>Y.path).filter(Y=>typeof Y=="string"&&Y.endsWith(".malloy")&&!de.has(Y)),modelsLoading:ae.isPending,...ae.isError?{modelsError:ae.error}:{},onRetryModels:()=>void ae.refetch(),target:be,...o?{onEvent:o}:{},onClose:()=>A(!1),onCreated:Y=>{A(!1),c.invalidateReportQueries(h,b,x),h.invalidateQueries({queryKey:["models"]}),M({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"edit"})}}),!$e&&t.jsxs(t.Fragment,{children:[Z.isError&&t.jsx(p.Box,{sx:{mb:4},children:t.jsx(p.Alert,{severity:"warning",action:t.jsx(p.Button,{color:"inherit",size:"small",onClick:()=>void Z.refetch(),children:"Retry"}),children:"Could not list this package's reports, so any it has are missing from this page."})}),(Ie.length>0||K)&&t.jsxs(_t,{title:"Reports",count:Ie.length,...le?{action:t.jsx(c.AddButton,{label:"Report",onClick:()=>A(!0)})}:{},children:[Ie.length===0&&t.jsx(qs,{label:"No reports yet",...le?{action:{label:"Add report",onClick:()=>A(!0)}}:{}}),Ie.map(Y=>t.jsx(Dn,{type:Y.layout==="grid"?"dashboard":"report",label:Y.label,rightLabel:Y.layout,...Y.secondary===void 0?{}:{description:Y.secondary},onClick:ie=>Y.path.endsWith(".malloynb")?y(`/${b}/${x}/${Y.path}`,ie):M({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"view"},ie)},Y.path))]}),T&&L.length>0&&t.jsx(_t,{title:"Drafts",count:L.length,children:L.map(({locator:Y,where:ie})=>t.jsx(Dn,{type:Y.type==="grid"?"dashboard":"report",label:te(Y),rightLabel:ie,onClick:Oe=>M({path:te(Y),layout:Y.type,slug:c.documentSlug(te(Y))??"",mode:"edit"},Oe),trailingAction:t.jsx(p.Tooltip,{title:"Delete this draft",children:t.jsx(p.IconButton,{size:"small","aria-label":`Delete draft ${te(Y)}`,onClick:Oe=>{Oe.stopPropagation(),D?.deleteDocument(Y).then(Q)},children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})})})},`${Y.workspace}:${Y.path}`))}),se.length>0&&t.jsx(_t,{title:"Apps",count:se.length,children:se.map(Y=>{const ie=!!Y.title&&Y.title!==Y.path,Oe=`${Ka(d)}${Y.resource}`;return t.jsx(Dn,{type:"dataApp",label:ie?Y.title:Y.path,rightLabel:ie?Y.path:void 0,onClick:Fe=>{e?e(`/${b}/${x}/data-apps/${Y.path}`,Fe):Fe&&(Fe.metaKey||Fe.ctrlKey)?window.open(Oe,"_blank"):window.location.href=Oe},trailingAction:t.jsx(p.Tooltip,{title:"Open standalone in new tab",children:t.jsx(p.IconButton,{size:"small",href:Oe,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",onClick:Fe=>Fe.stopPropagation(),sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})},Y.path)})}),t.jsxs(_t,{title:"Models",count:pe.length,children:[pe.map(Y=>t.jsx(Dn,{type:"model",label:Y.path,onClick:ie=>y(`/${b}/${x}/${Y.path}`,ie)},Y.path)),pe.length===0&&t.jsx(qs,{label:"No models"})]}),ue.length>0&&t.jsx(_t,{title:"Agents",count:ue.length,description:"Declared in publisher.json. Name one in an agent session to work as it. Schedules are listed only; nothing runs them yet.",children:ue.map(Y=>t.jsx(zy,{agent:Y},Y.name))}),t.jsxs(_t,{title:"Data",count:De.length,children:[De.map(Y=>t.jsx(Dn,{type:"data",label:Y.path,rightLabel:Y.info?cc(Y.info.rowCount):"Unreadable",onClick:()=>R(Y)},Y.path)),De.length===0&&t.jsx(qs,{label:"No data files"})]}),t.jsx(gl,{resourceUri:r,versioned:!T}),ye&&t.jsx(p.Box,{sx:{mt:6},children:t.jsx(oc,{resourceUri:c.encodeResourceUri({environmentName:b,packageName:x,versionId:v}),path:ye,onLinkNavigate:y})})]}),t.jsx(Iy,{database:E,onClose:()=>R(null)})]})}function Dn({type:e,label:n,description:r,rightLabel:o,onClick:i,trailingAction:l}){return t.jsx(ss,{icon:t.jsx(lc,{type:e}),tint:ac[e],label:n,mono:!0,...r===void 0?{}:{description:r},...o===void 0?{}:{rightLabel:o},...i===void 0?{}:{onClick:i},...l===void 0?{}:{trailingAction:l}})}function zy({agent:e}){return t.jsxs(t.Fragment,{children:[t.jsx(Dn,{type:"agent",label:e.name??"",...e.description?{description:e.description}:{},...e.model&&e.model!=="inherit"?{rightLabel:e.model}:{}}),(e.schedules??[]).map(n=>{const r=ho(n.cron??"");return t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",sx:{display:"block",ml:6,mb:.5},children:[r.valid?r.description:n.cron," (UTC), task"," ",n.task,". Not run yet."]},`${n.cron}|${n.task}`)})]})}function Wy(e){const n=e.map(o=>({path:o.path??"",layout:c.listedLayout(o),slug:c.documentSlug(o.path)??o.path??"",title:o.title})),r=new Map;for(const o of n)r.set(o.slug,(r.get(o.slug)??0)+1);return n.map(({title:o,...i})=>{const l=!!o&&o!==i.slug&&o!==i.path,a=(r.get(i.slug)??0)>1,d=l?o:i.path.endsWith(".malloynb")?i.path:i.slug;return{...i,label:d,secondary:d!==i.path&&(l||a||i.path.includes("/"))?i.path:void 0}}).sort((o,i)=>o.label.localeCompare(i.label)||o.path.localeCompare(i.path))}function qs({label:e,action:n}){return t.jsxs(p.Stack,{direction:"row",sx:{alignItems:"center",gap:1,py:1},children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:e}),n&&t.jsx(p.Button,{size:"small",onClick:n.onClick,children:n.label})]})}const $a=/^publisher:document:(dashboard|notebook):(.+)$/;function qy(e,n){const r=[];for(let o=0;o<e.length;o++){const i=e.key(o);i!==null&&$a.test(i)&&r.push(i)}for(const o of r){const[,i,l]=$a.exec(o),a=e.getItem(o);a!==null&&n(l,c.layoutOfKind(i),a)&&e.removeItem(o)}}const Bs={name:"Local",description:"Stored in this browser only",writeable:!0},so="publisher:report:",cn=e=>`${so}${e}`;function hr(e){const n=localStorage.getItem(e);if(n!==null)try{const r=JSON.parse(n);if(typeof r.content=="string"&&(r.type==="grid"||r.type==="linear"))return{type:r.type,content:r.content}}catch{}}const Vs=(e,n)=>localStorage.setItem(cn(e),JSON.stringify(n));class By{migrated=!1;migrate(){this.migrated||(this.migrated=!0,qy(localStorage,(n,r,o)=>hr(cn(n))!==void 0?!1:(Vs(n,{type:r,content:o}),!0)))}async listWorkspaces(n){return[Bs]}async listDocuments(n,r){if(n.name!==Bs.name)return[];this.migrate();const o=[];for(let i=0;i<localStorage.length;i++){const l=localStorage.key(i);if(l===null||!l.startsWith(so))continue;const a=hr(l);a&&(r===void 0||a.type===r)&&o.push({workspace:Bs.name,type:a.type,path:l.slice(so.length)})}return o}async getDocument(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Hs(n);return r.content}async getDocumentType(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Hs(n);return r.type}async saveDocument(n,r){this.migrate(),Vs(n.path,{type:n.type,content:r})}async deleteDocument(n){if(this.migrate(),hr(cn(n.path))===void 0)throw Hs(n);localStorage.removeItem(cn(n.path))}async moveDocument(n,r){const o=await this.getDocument(n);Vs(r.path,{type:r.type,content:o}),r.path!==n.path&&localStorage.removeItem(cn(n.path))}}function Hs(e){return new c.DocumentNotFoundError(`No report at ${e.workspace}/${e.path}`)}async function Vy(e,n,r,o){const i=c.chooseWorkspace(await e.listWorkspaces(!1));if(!i)return;const l=c.draftKey(n,r,o);if(e.getDocumentType)try{return await e.getDocumentType({workspace:i.name,path:l})}catch(a){if(c.isDocumentNotFound(a))return;throw a}return(await e.listDocuments(i)).find(a=>a.path===l)?.type}function Hy(e,n,r,o=!0){const i=c.useOptionalDocumentStorage()?.documentStorage,l=o&&i!==void 0,[a,d]=j.useState(),u=c.draftKey(e,n,r);return j.useEffect(()=>{if(!l||!i)return;let h=!1;return Vy(i,e,n,r).catch(()=>{}).then(y=>{h||d({key:u,layout:y})}),()=>{h=!0}},[l,i,e,n,r,u]),l?a?.key===u?{layout:a.layout,settled:!0}:{layout:void 0,settled:!1}:{layout:void 0,settled:!0}}function mc(e){const{environmentName:n,packageName:r}=c.parseResourceUri(e.resourceUri);if(!n||!r)throw new Error("Environment and Package name must be provided for query embedding.");return JSON.stringify({...e})}function Uy({embeddedQueryResult:e}){const{query:n,sourceName:r,queryName:o,resourceUri:i,height:l}=JSON.parse(e),{modelPath:a}=c.parseResourceUri(i);if(!a||!n&&(!o||!r)||typeof a!="string")throw new Error("Invalid embedded query result: "+e);return t.jsx(pc,{query:n,sourceName:r,queryName:o,resourceUri:i,height:l})}function pc({query:e,sourceName:n,queryName:r,resourceUri:o,height:i=400}){const{modelPath:l,environmentName:a,packageName:d,versionId:u}=c.parseResourceUri(o);if(!a||!d)throw new Error("No environment or package name provided. A resource URI must be provided.");const h=c.useQueryResult({environmentName:a,packageName:d,modelPath:l,versionId:u,query:e,sourceName:n,queryName:r});return t.jsx(c.ResultPanel,{state:h,context:`${a} > ${d} > ${l}`,maxHeight:i})}function Gy({resourceUri:e,dashboard:n,givens:r,onGivensChange:o,onNavigate:i,height:l,maxResultSize:a,onEvent:d,chrome:u}){const h=c.parseResourceUri(e),{apiClients:y}=q.useServer(),b=h.environmentName??"",x=h.packageName??"",v=h.versionId,k=!!h.environmentName&&!!h.packageName,{data:C,isSuccess:S,isError:T,error:O}=c.useQueryWithApiError({queryKey:["dashboard",b,x,v,n],queryFn:()=>y.dashboards.getDashboard(b,x,n,v),enabled:k}),M=C?.data,E=c.useReportEmitter({path:M?.path??n,layout:"grid"},d);return k?T?t.jsx(c.ApiErrorDisplay,{context:`${b} > ${x} > ${n}`,error:O}):!S||!M?t.jsx(c.Loading,{text:c.LOADING_COPY.opening("report")}):t.jsx(c.ReportEventsContext.Provider,{value:E,children:t.jsx(rs,{manifest:M,environmentName:b,packageName:x,versionId:v,documentName:n,givens:r,onGivensChange:o,onNavigate:i,height:l,maxResultSize:a,chrome:u})}):t.jsxs(p.Alert,{severity:"error",children:["A dashboard resource URI must name an environment and a package. Received: ",e]})}function gc(e){return j.useMemo(()=>{if(!e?.sources?.length)return[];const n=new Map;for(const r of e.sources)if(r.givens?.length)for(const o of r.givens)o.name&&!n.has(o.name)&&n.set(o.name,o);return Array.from(n.values())},[e])}function Yy(e){return e.type==="code"}function Ky(e){return(e.text??"").split(`
21
+ `).trim()}function Ip(e,n){const r=Hl(n),o=pn(e),i=new RegExp(`^(?:(?:dimension|measure|view)\\s*:\\s*)?${o}\\s+is\\s+`),l=r.replace(i,"");if(l===r||!(l.startsWith("{")&&l.endsWith("}")))return r;const u=l.slice(1,-1).replace(/^\n/,"").replace(/\s+$/,"").split(`
22
+ `),d=u.filter(b=>b.trim()).map(b=>b.match(/^[ \t]*/)[0].length),h=d.length?Math.min(...d):0;return u.map(b=>b.slice(h)).join(`
23
+ `).trim()||r}function Dp(e,n){const r=Hl(n),o=r.split(`
24
+ `),i=o.findIndex(u=>!u.trim().startsWith("#"));if(i<0)return r;const l=o[i];if(/^\s*view\s*:/.test(l))return Sa(o,i).join(`
25
+ `);const a=pn(e);return new RegExp(`^\\s*${a}\\s+is\\b`).test(l)?(o[i]=l.replace(/^(\s*)/,"$1view: "),Sa(o,i).join(`
26
+ `)):r}function Sa(e,n){const r=e.slice(n+1).filter(i=>i.trim()!=="");if(r.length===0)return e;const o=Math.min(...r.map(i=>i.length-i.trimStart().length));return o===0?e:e.map((i,l)=>l<=n?i:i.slice(Math.min(o,i.length-i.trimStart().length)))}function bo(e){return e.kind==="dimension"&&e.indexed===!0}function wo(e){return!!e&&(e.loading||!!e.code||!!e.inheritedFrom||!!e.error)}function $p(e,n){const r=[],o=[];for(const i of e){const l=n(i);(!!l&&!l.loading&&(!!l.code||!!l.error)||bo(i)?r:o).push(i)}return o.length===0||r.length===0?e:[...r,...o]}function Fp(e,n){return n.includes(`
27
+ `)||e.scrollWidth>e.clientWidth}const Ap={dimension:ql,measure:Wl,calculate:dp,view:zl,join:fp};function Rp(e){switch(e){case"dimension":case"measure":case"calculate":case"view":return xa(e).main;case"column":return xa("dimension").main;case"join":return Fn.brown.main}}function Lp(e){const n=e?.trim().toLowerCase()??"";if(!n)return;if(n.startsWith("array"))return pp;if(n.startsWith("record")||/\bfields?\b/.test(n))return gp;switch(n.split(/[\s·<]/)[0]){case"string":return up;case"number":return Wl;case"date":return hp;case"timestamp":case"timestamptz":return Sp;case"boolean":return Cp;default:return}}const _p=16;function So({kind:e,dataType:n}){const r=e==="dimension"||e==="measure"||e==="calculate"||e==="column"?Lp(n):void 0;return t.jsx(p.Box,{component:"span","aria-hidden":!0,"data-row-glyph":e,sx:{display:"inline-flex",alignSelf:"center",flexShrink:0,color:Rp(e)},children:j.createElement(r??Ap[e==="column"?"dimension":e],{size:_p})})}function ko(e,n){return(n?e.givensBySource?.get(n):void 0)??e.givens}function Ul(e,n){if(!e.givenValues||!n)return e;const r=new Set(n.map(i=>i.name)),o=Object.entries(e.givenValues).filter(([i])=>r.has(i));return{...e,givenValues:o.length>0?Object.fromEntries(o):void 0}}function Np({run:e,modelPath:n,query:r,enabled:o}){const{server:i,apiClients:l}=q.useServer(),a=mt.useQuery({...Gl({server:i,apiClients:l,run:e,modelPath:n,query:r}),enabled:o,refetchOnWindowFocus:!1,refetchOnReconnect:!1});return{result:a.data?.data.result,isSuccess:a.isSuccess,isLoading:a.isLoading,isFetching:a.isFetching,isError:a.isError,error:a.error,refetch:a.refetch}}function Co(e,n,r,o){return["model-viewer-run",e,n.projectName,n.packageName,r,n.versionId??"",o,go(n.givenValues),...n.includeHiddenFilesAndSources?["off-surface"]:[]]}function Gl({server:e,apiClients:n,run:r,modelPath:o,query:i}){const l=go(r.givenValues)===""?void 0:r.givenValues;return{queryKey:Co(e,r,o,i),queryFn:async({signal:a})=>{const u=performance.now(),d=()=>Math.round(performance.now()-u);try{const h=await n.models.executeQueryModel(r.projectName,r.packageName,o,{query:i,versionId:r.versionId,...l&&{givens:l},...r.queryMetadata&&{queryMetadata:{...r.queryMetadata}}},r.includeHiddenFilesAndSources?!0:void 0,void 0,{signal:a});return r.onQueryRun?.({outcome:"success",durationMs:d()}),h}catch(h){throw a?.aborted||r.onQueryRun?.({outcome:"error",durationMs:d()}),h}},staleTime:1/0,retry:!1}}const As=12,Pp=5*6e4;function zp(e){const n=cs(e);return n===void 0?!1:n>=400&&n<500&&n!==401&&n!==408&&n!==429}function Wp(e){if(!e)return[];const{data:n}=JSON.parse(e);return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>{if(r.kind!=="record_cell")return[];const o=r.record_value[0];if(!o)return[];switch(o.kind){case"string_cell":return[o.string_value];case"number_cell":return[String(o.number_value)];case"boolean_cell":return[String(o.boolean_value)];case"date_cell":return[o.date_value];case"timestamp_cell":return[o.timestamp_value];default:return[]}})}function qp({run:e,modelPath:n,sourceName:r,field:o,fetchSamples:i,generation:l}){const{server:a,apiClients:u}=q.useServer(),d=o?.kind==="dimension"&&o.indexed===!0,h=ko(e,r),y=d&&!i?Al(h,e.requiredFiltersBySource?.get(r),e.givenValues):void 0,b=y?.kind==="blocked"?y.reason:void 0,x=d&&!b?o.name:void 0,v=mt.useQuery({...Gl({server:a,apiClients:u,run:Ul(e,h),modelPath:n,query:c.sampleValuesQuery(r,x??"",As)}),enabled:!!x&&!i,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),k=mt.useQuery({queryKey:["model-viewer-samples",a,e.projectName,e.packageName,e.versionId??"",n,r,x,l??"host"],enabled:!!x&&!!i,staleTime:Pp,retry:!1,refetchOnWindowFocus:!1,queryFn:async({signal:T})=>{try{const O=await i({modelPath:n,sourceName:r,fieldName:x,limit:As,signal:T}),M=Array.isArray(O)?{values:O}:O;return{...M,values:M.values.slice(0,As)}}catch(O){if(zp(O))return{values:[]};throw O}}}),C=i?k:v,S=i?k.data:v.data&&{values:Wp(v.data.data.result)};return{samples:S?.values??[],total:S?.total,unavailable:b??S?.unavailable,loading:!!x&&C.isPending,failed:C.isError}}function Bp({children:e}){return t.jsx(p.Box,{component:"span",sx:{fontFamily:Dt,fontSize:wt.caption,color:"text.primary",bgcolor:nt.background.muted,border:"1px solid",borderColor:"divider",borderRadius:1,padding:"2px 8px"},children:e})}function Vp({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l}){const{samples:a,total:u,unavailable:d,loading:h,failed:y}=qp({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l});return t.jsxs(p.Box,{"data-testid":"model-viewer-values",sx:{fontSize:wt.small},children:[t.jsx(p.Box,{component:"div",sx:{color:as,fontSize:wt.caption,mb:"6px"},children:u!=null?`The most common of ${u.toLocaleString()} ${u===1?"value":"values"}`:"The most common values"}),h?t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}}):d?t.jsx(p.Box,{component:"span","data-testid":"model-viewer-values-unavailable",sx:{color:"text.secondary"},children:d}):y?t.jsx(p.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"Sample values couldn't be loaded."}):a.length===0?t.jsx(p.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"No values found."}):t.jsx(p.Box,{sx:{display:"flex",flexWrap:"wrap",gap:"6px"},children:a.map(b=>t.jsx(Bp,{children:b},b))})]})}const Rs={scopeName:"source.malloy",patterns:[{include:"#malloy-language"}],repository:{"malloy-language":{patterns:[{include:"#sql-string"},{include:"#comments"},{include:"#tags"},{include:"#strings"},{include:"#numbers"},{include:"#keywords"},{include:"#properties"},{include:"#functions"},{include:"#datetimes"},{include:"#identifiers-quoted"},{include:"#types"},{include:"#constants"},{include:"#timeframes"},{include:"#identifiers-unquoted"}]},"malloy-matched":{begin:"{",end:"}",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"malloy-in-sql":{begin:"%{",name:"source.malloy-in-sql",end:"}%?",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"sql-string":{patterns:[{begin:'(\\b[A-Za-z_][A-Za-z_0-9]*)(\\s*\\.\\s*)(sql)(\\s*\\(\\s*)(""")',end:'"""',beginCaptures:{1:{name:"variable.other"},3:{name:"keyword.control.sql"},5:{name:"punctuation.sql-block.open"}},endCaptures:{0:{name:"punctuation.sql-block.close"}},name:"source.sql",patterns:[{include:"#malloy-in-sql"},{include:"source.sql"}]}]},functions:{patterns:[{match:"(?i)\\b(count)(\\s*\\()(distinct)",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.function.modifier"}}},{match:"(?i)\\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE|UNGROUPED)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(!)(timestamp|number|string|boolean|date)?(\\s*\\()",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.type"}}}]},datetimes:{patterns:[{match:"(?i)@[0-9]{4}-[0-9]{2}-[0-9]{2}[ T][0-9]{2}:[0-9]{2}((:[0-9]{2})(([\\.,][0-9]+)(\\[[A-Za-z_/]+\\])?)?)?",name:"constant.numeric.timestamp"},{match:"(?i)@[0-9]{4}(-Q[1-4]|-[0-9]{2}(-[0-9]{2}(-WK)?)?)?",name:"constant.numeric.date"}]},"identifiers-quoted":{patterns:[{match:"`[^`]*`",name:"variable.other.quoted"}]},"identifiers-unquoted":{patterns:[{match:"(?i)\\b[A-Za-z_][A-Za-z_0-9]*\\b",name:"variable.other"}]},timeframes:{patterns:[{match:"(?i)\\b((year|quarter|month|week|day|hour|minute|second)s?)\\b",name:"keyword.other.timeframe"},{match:"(?i)\\b(day_of_year|day_of_month)\\b",name:"keyword.other.timeframe"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]},tags:{patterns:[{match:"##\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:'#"',end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{match:"#\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:"#\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"##\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"#",end:"\\n",beginCaptures:{0:{name:"string.quoted"}},name:"string.quoted"}],repository:{"tag-values":{name:"support.type.property-name.json",match:'(-)?((?:[^\\s=#]+)|(?:"[^#]+"))(?:\\s*(=)\\s*((?:[^\\s=#]+)|(?:"[^#]+")))?',captures:{1:{name:"keyword.control.negate"},2:{name:"support.type.property-name.json"},3:{name:"keyword.operator.comparison.ts"},4:{name:"string.quoted"}}}}},strings:{patterns:[{begin:"'",end:"'",beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.single",patterns:[{include:"#escapes"}]},{begin:'"',end:'"',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.double",patterns:[{include:"#escapes"}]},{begin:'"""',end:'"""',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.triple"},{begin:"(?i)[r|/]'",end:"'",name:"string.regexp",patterns:[{include:"#regex-escapes"}]}],repository:{escapes:{name:"constant.character.escape",match:"\\\\(u[A-Fa-f0-9]{4}|.)",captures:{0:{name:"constant.character.escape"}}},"regex-escapes":{name:"constant.character.escape",match:"\\\\.",captures:{0:{name:"constant.character.escape"}}}}},numbers:{match:"(?i)(\\b((0|[1-9][0-9]*)(E[+-]?[0-9]+|\\.[0-9]*)?)|\\.[0-9]+)",name:"constant.numeric"},constants:{patterns:[{match:"(?i)\\bnull\\b",name:"constant.language.null"},{match:"(?i)\\btrue\\b",name:"constant.language.true"},{match:"(?i)\\bfalse\\b",name:"constant.language.false"}]},types:{patterns:[{match:"(?i)\\bstring\\b",name:"entity.name.type.string"},{match:"(?i)\\bnumber\\b",name:"entity.name.type.number"},{match:"(?i)\\bdate\\b",name:"entity.name.type.date"},{match:"(?i)\\btimestamp\\b",name:"entity.name.type.timestamp"},{match:"(?i)\\bboolean\\b",name:"entity.name.type.boolean"}]},properties:{patterns:[{match:"(?i)\\baccept\\b",name:"keyword.control.accept"},{match:"(?i)\\bselect\\b",name:"keyword.control.select"},{match:"(?i)\\bconnection\\b",name:"keyword.control.connection"},{match:"(?i)\\brun\\b",name:"keyword.control.run"},{match:"(?i)\\bextend\\b",name:"keyword.control.extend"},{match:"(?i)\\brefine\\b",name:"keyword.control.refine"},{match:"(?i)\\baggregate\\b",name:"keyword.control.aggregate"},{match:"(?i)\\bsample\\b",name:"keyword.control.sample"},{match:"(?i)\\bcalculate\\b",name:"keyword.control.calculate"},{match:"(?i)\\btimezone\\b",name:"keyword.control.timezone"},{match:"(?i)\\bdimension\\b",name:"keyword.control.dimension"},{match:"(?i)\\bexcept\\b",name:"keyword.control.except"},{match:"(?i)\\bsource\\b",name:"keyword.control.source"},{match:"(?i)\\bgroup_by\\b",name:"keyword.control.group_by"},{match:"(?i)\\bhaving\\b",name:"keyword.control.having"},{match:"(?i)\\bindex\\b",name:"keyword.control.index"},{match:"(?i)\\bjoin_one\\b",name:"keyword.control.join_one"},{match:"(?i)\\bwith\\b",name:"keyword.control.with"},{match:"(?i)\\bjoin_many\\b",name:"keyword.control.join_many"},{match:"(?i)\\bjoin_cross\\b",name:"keyword.control.join_cross"},{match:"(?i)\\blimit\\b",name:"keyword.control.limit"},{match:"(?i)\\bmeasure\\b",name:"keyword.control.measure"},{match:"(?i)\\bnest\\b",name:"keyword.control.nest"},{match:"(?i)\\border_by\\b",name:"keyword.control.order_by"},{match:"(?i)\\bpartition_by\\b",name:"keyword.control.partition_by"},{match:"(?i)\\bprimary_key\\b",name:"keyword.control.primary_key"},{match:"(?i)\\bproject\\b",name:"keyword.control.project"},{match:"(?i)\\bquery\\b",name:"keyword.control.query"},{match:"(?i)\\brename\\b",name:"keyword.control.rename"},{match:"(?i)\\btop\\b",name:"keyword.control.top"},{match:"(?i)\\bview\\b",name:"keyword.control.view"},{match:"(?i)\\bwhere\\b",name:"keyword.control.where"},{match:"(?i)\\bdeclare\\b",name:"keyword.control.declare"}]},keywords:{patterns:[{match:"(?i)\\bis\\b",name:"keyword.control.is"},{match:"(?i)\\bon\\b",name:"keyword.control.on"},{match:"(?i)\\bnot\\b",name:"keyword.other.not"},{match:"(?i)\\bor\\b",name:"keyword.other.or"},{match:"(?i)\\bdesc\\b",name:"keyword.control.desc"},{match:"(?i)\\bby\\b",name:"keyword.control.by"},{match:"(?i)\\band\\b",name:"keyword.other.and"},{match:"(?i)\\basc\\b",name:"keyword.control.asc"},{match:"(?i)\\bfor\\b",name:"keyword.other.for"},{match:"(?i)\\belse\\b",name:"keyword.other.else"},{match:"(?i)\\bto\\b",name:"keyword.other.to"},{match:"(?i)\\bwhen\\b",name:"keyword.other.when"},{match:"(?i)\\bpick\\b",name:"keyword.other.pick"},{match:"(?i)\\bimport\\b",name:"keyword.control.import"}]}}},Hp={...Rs,patterns:[...Rs.patterns,{include:"#docvar"}],repository:{...Rs.repository,docvar:{patterns:[{match:"\\<\\<[^(\\>\\>)]*\\>\\>",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"markup.italic.markdown"}]}}},Up={name:"Malloy SQL",scopeName:"source.malloy-sql",patterns:[{include:"#malloysql-sql"}],repository:{"malloysql-sql":{beginCaptures:{0:{name:"entity.other.attribute.malloy-sql"},1:{name:"entity.other.attribute.malloy-sql"},3:{name:"comment.line.double-slash"}},name:"meta.embedded.block.malloysql.sql",patterns:[{include:"#comments"},{begin:"%{",end:"}%",beginCaptures:{0:{name:"punctuation.definition.malloy-sql"}},endCaptures:{0:{name:"punctuation.definition.malloy-sql"}},name:"meta.embedded.block.malloy",patterns:[{include:"source.malloy"}]},{include:"source.sql"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]}}},Gp="github-light",Yp="github-dark";let Ls;function Kp(){return Ls||(Ls=(async()=>{const[{createHighlighterCore:e},{createOnigurumaEngine:n},{default:r},{default:o},{default:i},{default:l},{default:a}]=await Promise.all([Promise.resolve().then(()=>require("./core-8NVBCLZh.cjs.js")),Promise.resolve().then(()=>require("./engine-oniguruma-BkproSVE.cjs.js")),Promise.resolve().then(()=>require("./sql-BqWZrLHB.cjs.js")),Promise.resolve().then(()=>require("./json-y-J1j5EW.cjs.js")),Promise.resolve().then(()=>require("./typescript-BqvpT6pB.cjs.js")),Promise.resolve().then(()=>require("./github-light-BFTOhCbz.cjs.js")),Promise.resolve().then(()=>require("./github-dark-BKL9xNgN.cjs.js"))]);return e({engine:n(Promise.resolve().then(()=>require("./wasm-Dw4u1m6u.cjs.js"))),themes:[l,a],langs:[r,o,i,{name:"malloy",scopeName:"source.malloy",embeddedLangs:["sql"],...Hp},{name:"malloysql",scopeName:"source.malloy-sql",embeddedLangs:["sql"],...Up}]})})()),Ls}async function jo(e,n,r="light"){return(await Kp()).codeToHtml(e,{lang:n,theme:r==="dark"?Yp:Gp})}function Mr({code:e,testId:n,framed:r=!0}){const{mode:o}=q.usePublisherTheme(),[i,l]=j.useState(void 0);return j.useEffect(()=>{let a=!0;return jo(e,"malloy",o).then(u=>a&&l(u)).catch(()=>a&&l(void 0)),()=>{a=!1}},[e,o]),t.jsx(p.Box,{"data-testid":n,sx:{fontFamily:Dt,fontSize:"0.75rem",overflowX:"auto","& pre":{m:0,background:"transparent !important"},...r&&{border:"1px solid",borderColor:"divider",borderRadius:1,px:1.5,py:1,bgcolor:"background.default"}},children:i?t.jsx("div",{dangerouslySetInnerHTML:{__html:i}}):t.jsx(p.Box,{component:"pre",sx:{whiteSpace:"pre"},children:e})})}function ds({message:e,onRetry:n,severity:r="error"}){return t.jsx(p.Alert,{severity:r,action:n&&t.jsx(p.Button,{color:"inherit",size:"small",onClick:n,children:"Retry"}),children:e})}function Yl(e){const n=e?.response?.data?.message;return typeof n=="string"&&n?n:void 0}function Kl(e,n){const r=Yl(n);return r?`${e}: ${r}`:`${e}.`}function Qp(e){const n=cs(e);return!(n===400||n===401||n===403||n===404||n===422)}function Zp({query:e,error:n,onRetry:r,testId:o,forbiddenMessage:i}){const l=i!==void 0&&cs(n)===403;return t.jsxs(p.Box,{"data-testid":o,sx:{display:"flex",flexDirection:"column",gap:1},children:[e&&t.jsx(Mr,{code:e,testId:"query-failure-code"}),t.jsx(ds,{message:l?i:Kl("Query failed",n),onRetry:r&&Qp(n)?r:void 0})]})}const ka=j.forwardRef(function(n,r){return t.jsx(p.Button,{ref:r,variant:"contained",size:"small",disableElevation:!0,...n,sx:{textTransform:"none",...n.sx}})}),Xp=j.forwardRef(function(n,r){return t.jsx(p.Button,{ref:r,variant:"outlined",size:"small",color:"inherit",...n,sx:{textTransform:"none",borderRadius:999,borderColor:"divider",color:"text.secondary",...n.sx}})}),yr=10,Jp="clamp(340px, 40%, 520px)";function eg({field:e,run:n,modelPath:r,sourceName:o,fieldCode:i,joined:l=!1}){const[a,u]=vo(),{fetchSamples:d,samplesGeneration:h,renderFieldStatus:y,renderFieldAction:b,renderFieldDetail:x}=ls(),v={modelPath:r,sourceName:o,field:e,joined:l},k=y?.(v),C=b?.(v),S=e.doc?void 0:i?.columnDoc,T=e.doc??S,O=wo(i),M=j.useContext(xo),E=j.useMemo(()=>dn(i?.code,M),[i?.code,M]),R=bo(e)&&!l&&!!n,P=[...O?["code"]:[],...R?["values"]:[],...E.length>0?["givens"]:[]],F=$=>P.includes($),B=e.kind==="measure"?"measure":e.kind==="calculate"?"calculate":"dimension",D=P.length>0?t.jsxs(p.Box,{"data-testid":"model-viewer-field-card",sx:{...Pn,"& > * + *":{borderTop:1,borderColor:"divider"}},children:[F("code")&&(i?.loading?t.jsx(p.Box,{sx:{p:jr,display:"flex"},children:t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}})}):i?.code?t.jsx(Mr,{testId:"model-viewer-definition",code:Ip(e.name,i.code),framed:!1}):i?.inheritedFrom?t.jsx(Mr,{testId:"model-viewer-definition",code:`${i.inheritedFrom.fromTable?"// A column of the table this source reads, as it is":"// Passed through from the query this source is built on"}
28
+ ${i.inheritedFrom.code}`,framed:!1}):t.jsx(p.Box,{sx:{p:1},children:t.jsx(ds,{message:"Couldn't load this model's code right now."})})),F("values")&&n&&t.jsx(p.Box,{sx:{p:jr},children:t.jsx(Vp,{run:n,fetchSamples:d,generation:h,modelPath:r,sourceName:o,field:e})}),F("givens")&&t.jsx(po,{givens:E,framed:!1})]}):void 0,_=x?x(v,D):D,V=_!=null&&_!==!1;return t.jsxs(p.Box,{"data-testid":"model-viewer-field-row","data-name":e.name,sx:a&&V?{pb:1.25}:void 0,children:[t.jsx(To,{glyph:t.jsx(So,{kind:B,dataType:e.dataType}),name:e.name,typeLabel:e.dataType,typeTip:e.typeTip,typeAsChip:!0,stackPills:!0,doc:T,generatedDoc:!!S,open:a,expandable:V,onToggle:()=>u($=>!$),descriptors:t.jsx(wl,{givens:E}),pills:k,action:C}),V&&t.jsx(p.Collapse,{in:a,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{"data-testid":"model-viewer-field-detail",sx:{mx:`${yr}px`,mt:"2px",display:"flex",flexDirection:"column",gap:1.5},children:_})})]})}function To({glyph:e,name:n,typeLabel:r,typeAsChip:o=!1,stackPills:i=!1,typeTip:l,descriptors:a,pills:u,action:d,trailing:h,doc:y,generatedDoc:b=!1,open:x,expandable:v,onToggle:k}){const C=j.useId(),S=T=>{if(!v||T.target.closest("[data-row-action]"))return;const O=T.target.closest("button, a, [role='button']");O&&!O.hasAttribute("data-field-toggle")||k()};return t.jsxs(p.Box,{onClick:S,sx:{display:"flex",alignItems:x?"flex-start":"center",borderRadius:1.5,transition:"background 0.1s",cursor:v?"pointer":"default",...v?{"&:hover":{bgcolor:nt.background.muted},"&:hover [data-pill-tone='quiet']":{bgcolor:nt.background.strong}}:{}},children:[t.jsxs(p.Box,{sx:{display:"flex",flexDirection:i?"column":"row",alignItems:i?"stretch":"center",minWidth:0,flexShrink:0,width:{md:Jp},overflow:{md:"hidden"}},children:[t.jsxs(p.Box,{component:v?"button":"div",type:v?"button":void 0,"aria-expanded":v?x:void 0,"aria-describedby":i?C:void 0,"data-field-toggle":v?"":void 0,sx:{appearance:"none",border:"none",background:"none",font:"inherit",color:"inherit",textAlign:"left",minWidth:0,px:`${yr}px`,py:"6px",borderRadius:1.5,...Tr,display:"flex",alignItems:"baseline",gap:"8px",flexWrap:i?"nowrap":"wrap",rowGap:"4px",cursor:v?"pointer":"default"},children:[e,t.jsxs(p.Box,{component:"span",sx:{display:"contents","& > *":{flexShrink:0},...i?{"& > *:first-of-type":{flexShrink:1,minWidth:0}}:{}},children:[t.jsx(p.Box,{component:"span",title:n,sx:{...Vm,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),r&&(o?t.jsx(p.Tooltip,{title:l?t.jsx(p.Box,{sx:{whiteSpace:"pre-line"},children:l}):"",children:t.jsx($t,{voice:"token",tone:"quiet",sx:{alignSelf:"center"},children:r})}):t.jsx(p.Box,{component:"span",sx:Fl,children:r})),a]}),!i&&u]}),i?t.jsxs(p.Box,{id:C,sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",px:`${yr}px`,pb:"6px",mt:"-2px","&:empty":{display:"none"}},children:[u,d&&t.jsx(p.Box,{component:"span","data-row-action":"",sx:{display:"inline-flex"},children:d})]}):d&&t.jsx(p.Box,{component:"span","data-row-action":"",sx:{display:"inline-flex"},children:d})]}),y&&t.jsxs(p.Box,{component:"span","data-testid":"model-viewer-field-doc",onMouseEnter:T=>{const O=T.currentTarget;O.title=!x&&Fp(O,y)?y:""},sx:{flex:1,minWidth:0,ml:1,pr:`${yr}px`,py:x?"6px":0,fontSize:wt.small,color:as,...x?{whiteSpace:"pre-line"}:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}},children:[b&&t.jsx($t,{voice:"state",tone:"quiet","data-testid":"model-viewer-field-doc-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),x?y:y.split(`
29
+ `)[0]]}),h&&t.jsx(p.Box,{sx:{ml:"auto",flexShrink:0,pl:1,pr:`${yr}px`,display:"inline-flex",alignItems:"center",height:32},children:h})]})}const tg=480;function ng({run:e,modelPath:n,query:r,sourceName:o,givens:i,givensUnknown:l,mode:a="result",renderCode:u,onShownChange:d}){const h=go(e.givenValues),[y,b]=j.useState(a==="result"?h:null);a==="result"&&y===null&&b(h);const x=y!==null&&y!==h,v=o?e.requiredFiltersBySource?.get(o):void 0,[k,C]=j.useState(null),S=k===h,T=j.useMemo(()=>Al(i??ko(e,o),v,e.givenValues,i?l:o?e.unknownGivensBySource?.get(o):void 0,S,i?"query":"source"),[e,o,i,l,v,S]),{result:O,isSuccess:M,isError:E,error:R,refetch:P}=Np({run:e,modelPath:n,query:r,enabled:y===h&&T.kind!=="blocked"});y!==null&&y!==h&&O!==void 0&&b(h);const F=Qr(e.accessBySource,o),B=Im(o,F),D=()=>x?b(h):void P(),[_,V]=j.useState(null);O!==void 0&&(_?.givensKey!==h||_.result!==O)&&V({result:O,givensKey:h});const $=T.kind==="blocked"?void 0:O!==void 0?{result:O,givensKey:h}:x&&_?{result:_.result,givensKey:_.givensKey}:void 0,W=$?.result,Z=j.useMemo(()=>Dm(F,W),[F,W]),ne=$?.givensKey??"";j.useEffect(()=>{if(d){if(W===void 0)return d(void 0);d({result:W,givensKey:ne})}},[d,W,ne]);const J=a==="result"&&T.kind!=="blocked";return j.useEffect(()=>{J&&c.warmMalloyRenderer()},[J]),t.jsx(p.Box,{"data-testid":"model-viewer-run-result","data-mode":a,children:a==="code"?u?.():T.kind==="blocked"?t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1.5,flexWrap:"wrap"},children:[t.jsx(un,{"data-testid":"model-viewer-run-blocked",children:T.reason}),T.canRunAnyway&&t.jsx(ka,{size:"small",onClick:()=>{C(h),b(h)},children:"Run anyway"})]}):E&&!x?t.jsx(Zp,{query:r,error:R,onRetry:()=>void P(),forbiddenMessage:B}):M&&!O&&!x?t.jsx(xr,{message:"The query returned no result."}):t.jsxs(p.Box,{"data-testid":"model-viewer-result-card",sx:{...Pn,p:jr,overflowX:"auto"},children:[x&&t.jsxs(p.Box,{"data-testid":"model-viewer-run-stale",sx:{display:"flex",alignItems:"center",gap:1.5,flexWrap:"wrap",mb:1},children:[t.jsx(un,{children:"The given values changed since this ran."}),t.jsx(ka,{size:"small",onClick:D,"aria-label":"Run with these values",children:"Run"})]}),T.kind==="noted"&&W&&!x&&t.jsx(Cr,{"data-testid":"model-viewer-run-defaults",component:"div",sx:{mb:1},children:T.note}),!(x&&!W)&&(W===void 0?t.jsx(c.Loading,{text:c.LOADING_COPY.running}):t.jsx(c.ResultContainer,{result:W,maxHeight:tg,maxResultSize:e.maxResultSize})),Z&&t.jsx(Cr,{"data-testid":"model-viewer-run-filtered",component:"div",sx:{mt:1},children:Z})]})})}function rg(e){return{p:"3px",borderRadius:1,color:e?"text.primary":"text.secondary",bgcolor:e?nt.background.strong:"transparent","&:hover":{bgcolor:e?nt.background.strong:nt.background.muted,color:"text.primary"},"&.Mui-disabled":{color:"text.disabled"}}}function sg({value:e,options:n,onChange:r,"aria-label":o}){return t.jsx(p.Box,{role:"group","aria-label":o,sx:{display:"inline-flex",gap:"2px"},children:n.map(i=>{const l=i.value===e,a=i.disabled===!0;return t.jsx(p.Tooltip,{title:a?i.disabledReason??i.label:i.label,children:t.jsx("span",{style:{display:"inline-flex"},children:t.jsx(p.IconButton,{size:"small",role:"button","aria-pressed":l,"aria-label":a?i.disabledReason??i.label:i.label,disabled:a,onClick:()=>r(i.value),sx:rg(l),children:i.icon})})},i.value)})})}const og=["result","givens","fields","code","values","access"],ig={result:{icon:t.jsx(zl,{size:14}),label:"Result"},fields:{icon:t.jsx(vp,{size:14}),label:"Fields"},code:{icon:t.jsx(mp,{size:14}),label:"Code"},values:{icon:t.jsx(kp,{size:14}),label:"Values"},givens:{icon:t.jsx(jp,{size:14}),label:"Givens"},access:{icon:t.jsx(wp,{size:14}),label:"Access"}};function Ql(e,n){const r=og.filter(a=>e.includes(a)),[o,i]=j.useState(void 0),l=o!==void 0&&r.includes(o)?o:n!==void 0&&r.includes(n)?n:r[0];return{layers:r,layer:l,setLayer:i}}function Zl({layers:e,value:n,onChange:r,"aria-label":o,disabledReasons:i}){return e.length<2||n===void 0?null:t.jsx(sg,{"aria-label":o,value:n,onChange:r,options:e.map(l=>{const a=i?.[l];return{value:l,...ig[l],...a?{disabled:!0,disabledReason:a}:{}}})})}function Xl({field:e,modelPath:n,sourceName:r,fieldCode:o,run:i,runQuery:l,runGivens:a,runGivensUnknown:u}){const d=l??c.viewRunQuery(r,e.name),h=a??(i&&ko(i,r)),y=j.useMemo(()=>i&&Ul(i,h),[i,h]),b=l?"query":"view",[x,v]=vo(),[k,C]=j.useState(void 0),S=wo(o),T=j.useContext(xo),{renderRunActions:O}=ls(),{server:M}=q.useServer(),E=j.useMemo(()=>dn(o?.code,T),[o?.code,T]),{chartNames:R,tagsInFull:P}=j.useMemo(()=>{const W=e.tags??[],Z=Zf(W),ne=Z.length>0?Z:W;return{chartNames:ne,tagsInFull:W.join(" ")===ne.join(" ")?void 0:W.map(J=>`# ${J}`).join(`
30
+ `)}},[e.tags]),F=["result","code",...E.length>0?["givens"]:[]],{layers:B,layer:D,setLayer:_}=Ql(F,i?"result":"code"),V=D??"code",$=()=>V==="givens"?t.jsx(po,{givens:E}):o?.loading?t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}}):o?.code?t.jsx(Mr,{testId:"model-viewer-definition",code:l?o.code:Dp(e.name,o.code)}):o?.error?t.jsx(ds,{message:"Couldn't load this model's code right now."}):t.jsx(xr,{message:`No Malloy code to show for this ${b}.`});return t.jsxs(p.Box,{"data-testid":"model-viewer-view-row","data-name":e.name,sx:x?{pb:1.5}:void 0,children:[t.jsx(To,{glyph:t.jsx(So,{kind:"view"}),name:e.name,doc:e.doc,open:x,expandable:!0,onToggle:()=>v(W=>!W),trailing:x&&t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:"2px"},children:[t.jsx(Zl,{"aria-label":`Show for ${e.name}`,layers:B,value:V,onChange:_,disabledReasons:{result:i?void 0:`This ${b} can't be run here`,code:S?void 0:`No Malloy code to show for this ${b}`}}),y&&O?.({kind:l?"query":"view",modelPath:n,sourceName:l?"":r,name:e.name,query:d,givens:y.givenValues,queryKey:Co(M,y,n,d),shown:k})]}),descriptors:t.jsxs(t.Fragment,{children:[R.map(W=>{const Z=t.jsx($t,{voice:"token",tone:"quiet",sx:{alignSelf:"center"},children:W},W);return P?t.jsx(p.Tooltip,{title:P,slotProps:{tooltip:{sx:{whiteSpace:"pre-line",fontFamily:Dt}}},children:Z},W):Z}),t.jsx(wl,{givens:E})]})}),t.jsx(p.Collapse,{in:x,timeout:"auto",mountOnEnter:!0,children:t.jsx(p.Box,{"data-testid":"model-viewer-view-card",sx:{mx:"10px",mt:1,minWidth:0},children:t.jsx(p.Box,{sx:{minWidth:0,overflowX:"auto"},children:y?t.jsx(ng,{run:y,modelPath:n,query:d,sourceName:r||void 0,givens:a,givensUnknown:u,mode:V==="result"?"result":"code",renderCode:$,onShownChange:C}):$()})})})]})}function ag({queries:e,sourceText:n,modelPath:r,run:o}){const{parsed:i,pending:l}=Vl(n,e.length>0),a=j.useMemo(()=>e.map(d=>{const h=Ep(i,d.name),y=d.sourceName||!o?.givens||l?void 0:bm(h,o.givens,o.givensBySource,o.unknownGivensBySource);return{query:d,field:{name:d.name,kind:"view",doc:d.doc,tags:d.tags},code:{code:h,loading:l},runGivens:y?.givens,runGivensUnknown:y?.unknown}}),[e,i,l,o?.givens,o?.givensBySource,o?.unknownGivensBySource]),u=ns({noun:["query","queries"]});return t.jsx(_n,{label:"Queries",count:e.length,testId:"model-viewer-queries",action:u.action,children:t.jsx(Or.Provider,{value:u.command,children:a.map(({query:d,field:h,code:y,runGivens:b,runGivensUnknown:x})=>t.jsx(Xl,{field:h,modelPath:r,sourceName:d.sourceName??"",fieldCode:y,run:o,runQuery:c.namedQueryRunQuery(d.name),runGivens:b,runGivensUnknown:x},d.name))})})}function Jl(e){const{entities:n,loading:r,error:o,columnDescriptions:i,declarations:l,declarationsLoading:a}=e;return u=>{const d=n?.get(u.name),h=l?.get(u.name);if(!d&&!r&&h&&h.kind===u.kind)return{code:h.code,loading:!1,error:!1,inherited:!1};if(!d&&!r&&!o&&a)return{loading:!0,error:!1,inherited:!1};const y=d?.fieldType==="column";return{code:y?void 0:d?.code??void 0,inheritedFrom:y&&d?.code?{code:d.code,fromTable:!!d.table||d.code!==u.name}:void 0,loading:!o&&r,error:o,inherited:y,columnDoc:y?i?.get(u.name):void 0}}}const Ca=200;function br({label:e,noun:n,items:r,run:o,modelPath:i,sourceName:l,getFieldCode:a,level:u}){const{showField:d}=ls(),h=j.useMemo(()=>d?r.filter(O=>d({modelPath:i,sourceName:l,field:O,joined:u==="h3"})):r,[r,d,i,l,u]),[y,b]=j.useState(!1),x=h.some(O=>bo(O)&&u!=="h3"||wo(a?.(O))),{command:v,action:k}=ns({noun:n,disabledReason:x?void 0:`None of these ${n[1]} has anything to show`}),C=u!=="h3"?k:void 0,S=j.useMemo(()=>a?$p(h,a):h,[h,a]),T=y||S.length<=Ca?S:S.slice(0,Ca);return t.jsx(_n,{label:e,count:h.length,level:u,action:C,children:t.jsx(Or.Provider,{value:v,children:t.jsxs(p.Box,{sx:{display:"flex",flexDirection:"column",gap:"3px"},children:[T.map(O=>t.jsx(eg,{field:O,run:o,modelPath:i,sourceName:l,fieldCode:a?.(O),joined:u==="h3"},O.name)),T.length<S.length&&t.jsxs(p.Button,{size:"small",onClick:()=>b(!0),sx:{alignSelf:"flex-start",textTransform:"none"},children:["Show all ",S.length.toLocaleString()," ",n[1]]})]})})})}function lg(e,n){const r=new Map;if(!e||!n)return r;const o=new Map;for(const l of e.symbols)l.type==="explore"&&o.set(Oo(l.name),l);const i=new Set;for(let l=n;l&&!i.has(l);){i.add(l);const a=o.get(l);if(!a)break;for(const[u,d]of ug(e.lines,a))r.has(u)||r.set(u,d);l=xg(us(e.lines,a.range))}return r}const ja=/^\s*(view|measure|dimension)\s*:\s*$/,cg=/^`?([A-Za-z_]\w*)`?\s+is\b/;function ug(e,n){const r=new Map;let o,i=n.range.start;for(const a of n.children){const u=us(e,{start:i,end:a.range.start});o=pg(u)??o,i=a.range.end;const d=dg(a,o);if(!d)continue;const h=hg(e,a,d);if(!h)continue;const y=Oo(a.name);r.set(y,r.has(y)?null:h)}const l=new Map;for(const[a,u]of r)u&&l.set(a,u);return l}function dg(e,n){if(e.type==="query")return n==="view"?"view":void 0;if(e.type==="field"&&(n==="dimension"||n==="measure"))return n}function hg(e,n,r){const o=us(e,n.range).split(`
31
+ `),i=[];for(;o.length>1&&/^\s*(#|\/\/|--|$)/.test(o[0]);){const u=o.shift().trim();u.startsWith("#")&&i.push(u)}o[0]=o[0].trimStart();const l=o.join(`
32
+ `).trimEnd(),a=cg.exec(l);if(!(!a||a[1]!==Oo(n.name)))return{kind:r,code:[...fg(e,n.range.start),...i,l].join(`
33
+ `)}}function fg(e,n){const r=(e[n.line]??"").slice(0,n.character),o=r.trim()==="";if(!o&&!ja.test(r))return[];const i=a=>{const u=[];let d=a;for(;d>=0&&e[d].trim().startsWith("#");)u.unshift(e[d--].trim());return{out:u,next:d}},l=i(n.line-1);return o&&l.next>=0&&ja.test(e[l.next])?[...i(l.next-1).out,...l.out]:l.out}const mg=/(?<![\w:])([A-Za-z_]\w*)\s*:(?!:)/g;function pg(e){let n;for(const r of gg(e).matchAll(mg))n=r[1];return n}function gg(e){let n="";for(let r=0;r<e.length;r++){const o=e[r];if(e.startsWith('"""',r)){const i=e.indexOf('"""',r+3),l=i===-1?e.length:i+3;n+=" ".repeat(l-r),r=l-1}else if(o==='"'||o==="'"||o==="`"){const i=yg(e,r);n+=" ".repeat(i-r+1),r=i}else if(o==="#"||o==="/"&&e[r+1]==="/"||o==="-"&&e[r+1]==="-"){const i=e.indexOf(`
34
+ `,r),l=i===-1?e.length:i;n+=" ".repeat(l-r),r=l-1}else n+=o}return n}function yg(e,n){const r=e[n];for(let o=n+1;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===r)return o;return e.length}function xg(e){return/^`?[A-Za-z_]\w*`?\s+is\s+`?([A-Za-z_]\w*)`?\s*(?:extend\b|$)/.exec(e)?.[1]}function Oo(e){return e.replace(/^`(.*)`$/,"$1")}const vg=["fields","code"],Ta={display:"inline-flex",alignItems:"center",color:"text.secondary",borderRadius:1,padding:"2px",flexShrink:0,"&:hover":{color:ts}};function bg({join:e,run:n,modelPath:r,sourceName:o,link:i,entitiesByName:l,entitiesLoading:a,entitiesError:u,code:d,target:h,showRules:y=!1}){const[b,x]=vo(),{layers:v,layer:k,setLayer:C}=Ql(vg),S=j.useMemo(()=>l?Jl({entities:l,loading:!!a,error:!!u}):void 0,[l,a,u]),T=e.dimensions.length+e.measures.length,O=t.jsxs(p.Box,{sx:{display:"inline-flex",alignItems:"center",gap:1},children:[b&&t.jsx(Zl,{"aria-label":`Show for ${e.name}`,layers:v,value:k,onChange:C,disabledReasons:{code:d?void 0:"No Malloy code to show for this join"}}),i?.kind==="link"&&i.href&&t.jsx(p.Link,{href:i.href,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:Ta,children:t.jsx(wa,{size:14})}),i?.kind==="link"&&!i.href&&i.onOpen&&t.jsx(p.Link,{component:"button",type:"button",onClick:i.onOpen,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:Ta,children:t.jsx(wa,{size:14})}),i?.kind==="join-only"&&t.jsx(p.Box,{component:"span",sx:{fontSize:wt.micro,fontStyle:"italic",color:"text.secondary",flexShrink:0},children:"only accessible via join"})]});return t.jsxs(p.Box,{"data-testid":"model-viewer-join-row","data-name":e.name,sx:b?{pb:1.25}:void 0,children:[t.jsx(To,{glyph:t.jsx(So,{kind:"join"}),name:e.name,typeLabel:`${T} ${T===1?"field":"fields"}`,stackPills:!0,descriptors:t.jsxs($t,{tone:"quiet",voice:"token",sx:{alignSelf:"center",flexShrink:0},children:["join_",e.relationship]}),doc:e.doc,open:b,expandable:!0,onToggle:()=>x(M=>!M),trailing:O,pills:h&&t.jsx(Il,{access:h.access})}),t.jsx(p.Collapse,{in:b,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{sx:{mx:"10px",mt:"2px"},children:k==="code"&&d?t.jsx(Mr,{testId:"model-viewer-join-code",code:d}):t.jsxs(p.Box,{"data-testid":"model-viewer-join-fields",sx:{...Pn,bgcolor:"transparent",p:1.5,pb:0},children:[h&&y&&t.jsx(Cr,{component:"div","data-testid":"model-viewer-join-gate-warning",sx:{mb:1},children:$m(h.sourceName,h.access)}),t.jsx(br,{label:"Measures",noun:["measure","measures"],level:"h3",items:e.measures,run:n,modelPath:r,sourceName:o,getFieldCode:S}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],level:"h3",items:e.dimensions,run:n,modelPath:r,sourceName:o,getFieldCode:S})]})})})]})}function wg({source:e,modelPath:n,entitiesByName:r,entitiesLoading:o,entitiesError:i,modelText:l,joinLinks:a,joinEntities:u,joinCodes:d,joinAccess:h,showRules:y=!1,columnDescriptions:b,run:x,queries:v,givens:k}){const C={run:x,modelPath:n,sourceName:e.name},{showField:S}=ls(),T=j.useMemo(()=>S?e.views.filter(D=>S({modelPath:n,sourceName:e.name,field:D,joined:!1})):e.views,[S,e,n]),O=ns({noun:["view","views"]}),M=ns({noun:["join","joins"]}),E=j.useMemo(()=>!o&&[...e.views,...e.measures,...e.calculations,...e.dimensions].some(D=>!r?.get(D.name)),[o,r,e]),{parsed:R,pending:P}=Vl(l,E),F=j.useMemo(()=>lg(R,e.name),[R,e.name]),B=j.useMemo(()=>Jl({entities:r,loading:!!o,error:!!i,columnDescriptions:b,declarations:F,declarationsLoading:P}),[r,o,i,b,F,P]);return t.jsxs(p.Box,{sx:{paddingBottom:"24px"},children:[k,t.jsx(_n,{label:"Views",count:T.length,action:O.action,children:t.jsx(Or.Provider,{value:O.command,children:T.map(D=>t.jsx(Xl,{field:D,modelPath:n,sourceName:e.name,fieldCode:B(D),run:x},D.name))})}),v,t.jsx(br,{label:"Measures",noun:["measure","measures"],items:e.measures,getFieldCode:B,...C}),t.jsx(br,{label:"Calculations",noun:["calculation","calculations"],items:e.calculations,getFieldCode:B,...C}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],items:e.dimensions,getFieldCode:B,...C}),t.jsx(_n,{label:"Joins",count:e.joins.length,action:M.action,children:t.jsx(Or.Provider,{value:M.command,children:e.joins.map(D=>t.jsx(bg,{join:D,run:x,modelPath:n,sourceName:e.name,link:a?.get(D.name),entitiesByName:u?.get(D.name),code:d?.get(D.name),target:h?.get(D.name),showRules:y,entitiesLoading:o,entitiesError:i},D.name))})})]})}function no(e){return{name:e.name,kind:e.kind,dataType:mo(e.type),typeTip:em(e.type),tags:tm(e.annotations),doc:Ln(e.annotations),indexed:e.kind==="dimension"?gm(e):void 0,preaggregate:e.kind==="measure"?Jf(e.annotations):void 0}}function Sg(e){const n=[],r=[];for(const o of e.schema?.fields??[]){if(o.kind!=="dimension"&&o.kind!=="measure")continue;const i={...no(o),indexed:!1,preaggregate:!1};o.kind==="dimension"?n.push(i):r.push(i)}return{name:e.name,relationship:e.relationship,doc:Ln(e.annotations),dimensions:n,measures:r}}function kg(e,n){const r={name:e.name,doc:Ln(e.annotations),docParts:yl(e.annotations),accent:Bm(n),persist:Xf(e.annotations),dimensions:[],measures:[],calculations:[],views:[],joins:[]};for(const o of e.schema?.fields??[])switch(o.kind){case"dimension":case"measure":r[o.kind==="dimension"?"dimensions":"measures"].push(no(o));break;case"calculate":r.calculations.push(no(o));break;case"view":r.views.push({name:o.name,kind:"view",doc:Ln(o.annotations),tags:fo(o.annotations)});break;case"join":r.joins.push(Sg(o));break}return r}function Cg(e){const n=[];for(const r of e??[]){if(!r.name)continue;const o=(r.annotations??[]).map(i=>({value:i}));n.push({name:r.name,sourceName:r.sourceName||void 0,doc:Ln(o),tags:fo(o)})}return n}function ec(e){return e.dimensions.length+e.measures.length+e.calculations.length+e.views.length}function jg(e,n){if(e.length===0)return null;const r=h=>h.toLowerCase().replace(/[-_]/g,""),o=n?r((n.split("/").pop()??n).replace(/\.malloy$/,"")):void 0,i=new Map(e.map(h=>[h.name,new Set(h.views.map(y=>y.name))])),l=h=>e.some(y=>{if(y.name===h.name||y.views.length===0)return!1;const b=i.get(h.name);return y.views.length<h.views.length&&[...i.get(y.name)].every(x=>b.has(x))}),a=e.filter(h=>!l(h)),u=a.length>0?a:e;let d=u[0];for(const h of u.slice(1)){if(h.views.length!==d.views.length){h.views.length>d.views.length&&(d=h);continue}o&&r(h.name)===o&&r(d.name)!==o&&(d=h)}return d}function Tg(e,n,r){if(!e||!n)return;const i=new RegExp("source:\\s*`?"+pn(n)+"`?\\s+is\\s+`?([A-Za-z_]\\w*)`?\\s*(?:->|extend\\b)").exec(e);if(!i)return;const l=i[1];return r.has(l)?l:void 0}function _s(e,n){return`${e} ${e===1?n:`${n}s`}`}function Og(e){const n=ec(e),r=[_s(e.views.length,"view"),_s(n,"field")];return e.joins.length>0&&r.push(_s(e.joins.length,"join")),r.join(" · ")}function Mg(e,n,r){if(r){const u=r.exportOrder,d=u.length>0&&e.some(h=>u.includes(h.name));return{sources:Dg(e,h=>h.name,u),curated:!0,exportOrdered:d}}const o=e.map((u,d)=>({source:u,index:d})).filter(({source:u})=>u.name!==n?.name).sort((u,d)=>d.source.views.length-u.source.views.length||u.index-d.index).map(({source:u})=>u),i=n?[n,...o]:o,l=n?.views.length??0,a=n&&l>0&&e.every(u=>u.views.length<=l)?n.name:void 0;return{sources:i,curated:!1,exportOrdered:!1,mostViews:a}}function Eg(e){return/^`.*`$/.test(e)?e.slice(1,-1):e}function Ig(e){if(!e)return[];const n=Ir(e),r=[];for(const o of n.matchAll(/(?:^|[\s;])export\s*\{([^}]*)\}/gi))for(const i of o[1].split(",")){const l=Eg(i.trim());l&&!r.includes(l)&&r.push(l)}return r}function Dg(e,n,r){if(r.length===0)return[...e];const o=i=>{const l=r.indexOf(n(i));return l===-1?r.length:l};return e.map((i,l)=>({item:i,index:l})).sort((i,l)=>o(i.item)-o(l.item)||i.index-l.index).map(({item:i})=>i)}function $g(e,n){const r=e?.trim();if(r)return{text:r,generated:!1};const o=n?.trim();return o?{text:o,generated:!0}:void 0}const Fg="This package's curated sources, in the order its index.malloy exports them.",Ag="This package's public sources.";function Rg(e){return e.mostViews?", most views":""}function Lg({anchorEl:e,onClose:n,sources:r,currentName:o,onPickSource:i,curated:l=!1,exportOrdered:a=!1}){const u=!!e;return t.jsxs(p.Popover,{open:u,anchorEl:e,onClose:n,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},slotProps:{paper:{sx:{width:460,maxWidth:"calc(100vw - 32px)",maxHeight:"min(70vh, 560px)",display:"flex",flexDirection:"column",borderRadius:"10px"},"data-testid":"model-sources-dropdown"}},children:[t.jsxs(p.Box,{sx:{px:2,pt:1.5,pb:1,borderBottom:1,borderColor:"divider"},children:[t.jsx(p.Typography,{variant:"subtitle2",component:"h2",sx:{m:0},children:"Sources"}),t.jsx(Cr,{component:"p",sx:{m:0},children:l?a?Fg:Ag:Gm})]}),t.jsx(p.Box,{sx:{overflowY:"auto",py:.5},children:r.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{py:4,textAlign:"center"},children:"This model defines no sources."}):r.map(d=>{const h=d.name===o;return t.jsxs(p.ButtonBase,{"data-item-name":d.name,"aria-label":`Open source ${d.name}${Rg(d)}${Am(d.access)}`,"aria-current":h||void 0,onClick:()=>{n(),i(d.name)},sx:{display:"flex",width:"100%",alignItems:"flex-start",justifyContent:"flex-start",textAlign:"left",gap:1.25,px:2,py:1,bgcolor:h?nt.background.muted:void 0,"&:hover":{bgcolor:h?nt.background.strong:nt.background.muted},...Tr},children:[t.jsx(p.Box,{component:"span","aria-hidden":!0,sx:{color:Fn.steel.main,display:"inline-flex",pt:"2px"},children:t.jsx(ql,{size:16})}),t.jsxs(p.Box,{component:"span",sx:{minWidth:0,flex:1},children:[t.jsxs(p.Box,{component:"span",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1},children:[t.jsx(p.Box,{component:"span",sx:{fontFamily:Dt,fontSize:wt.body,fontWeight:500,color:"text.primary"},children:d.name}),d.mostViews&&t.jsx($t,{tone:"quiet",sx:{alignSelf:"center"},children:_g}),El(d.access)&&t.jsx(Il,{access:d.access}),d.status]}),(d.description||d.descriptionPending)&&t.jsxs(p.Box,{component:"span",sx:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",mt:.25,fontSize:wt.small,color:"text.secondary",minHeight:d.description?void 0:"1.4em"},children:[d.description?.generated&&t.jsx($t,{tone:"quiet","data-testid":"model-sources-summary-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),d.description&&Dl(d.description.text)]}),t.jsx(Cr,{"data-testid":"model-sources-row-meta",sx:{display:"block",mt:.25},children:d.meta})]})]},`source:${d.name}`)})})]})}const _g="Most views";function Ng({sources:e,currentName:n,countLabel:r,onPickSource:o,curated:i=!1,exportOrdered:l=!1,onWarm:a}){const[u,d]=j.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Xp,{size:"small",variant:"outlined",onClick:h=>{a?.(),d(h.currentTarget)},endIcon:t.jsx(bp,{size:20}),"aria-label":`${r}. Showing ${n}, one of the ${r} in this model`,"aria-haspopup":"dialog","aria-expanded":!!u,onPointerEnter:a,onFocus:a,sx:{ml:1,transition:"none"},children:r}),t.jsx(Lg,{anchorEl:u,onClose:()=>d(null),sources:e,currentName:n,onPickSource:o,curated:i,exportOrdered:l})]})}const Pg=[],zg=[],Wg=[],qg=new Map;function Bg(e){const n=e.modelDef;if(typeof n!="string")return!1;try{const r=JSON.parse(n);return Array.isArray(r.imports)&&r.imports.length>0}catch{return!1}}function Vg(e,n){if(typeof e=="string")try{const o=ua(JSON.parse(e).annotations);if(o)return o}catch{}if(!n)return;const r=n.split(`
35
+ `).filter(o=>/^##(\(doc\)|")/.test(o.trim())).map(o=>({value:o}));return ua(r)}async function Hg(e,n,r,o,i,l){const a=await e.models.getModel(n,r,o,i,l),u=Ug(a.data);return{sourceInfos:(a.data.sourceInfos??[]).map(d=>JSON.parse(d)),queries:a.data.queries??[],sourceText:u,givens:lm(o,a.data),access:Mm(a.data),modelDoc:Vg(a.data.modelInfo,u),hasImports:Bg(a.data)}}function Ug(e){const n=e.sourceText;return typeof n=="string"?n:void 0}function tc(e,n,r,o,i=!1){return["model-viewer-sources",e,n,r,o??"",...i?["off-surface"]:[]]}function Gg(e,n,r,o,i,l=!1){return{queryKey:tc(n,r,o,i,l),queryFn:()=>Hg(e,n,r,o,i,l),...i&&i!=="latest"?{staleTime:1/0}:{}}}function Yg(e,n,r,o,i=!0,l=!1){const{apiClients:a}=q.useServer(),u=mt.useQuery({...Gg(a,e,n,r,o,l),enabled:i&&!!(e&&n&&r)});return{sources:u.data?.sourceInfos??Pg,queries:u.data?.queries??zg,sourceText:u.data?.sourceText,givens:u.data?.givens??Wg,access:u.data?.access??qg,modelDoc:u.data?.modelDoc,hasImports:u.data?.hasImports??!1,isLoading:u.isLoading,isError:u.isError,error:u.error,refetch:u.refetch}}const Kg=new Map;function Oa(e){return(e.split("/").pop()??e).replace(/\.malloy$/,"")}function Qg(e,n){const r=vm(e,n),o=n.filter(l=>!r.has(l.name)),i="Nothing on this page reads them.";return o.length===0?`Declared here for the models that import this file. ${i}`:o.length===n.length?`Imported from another file, for the models that import this one. ${i}`:`For the models that import this file. ${vr(o.map(l=>l.name),"and")} ${o.length===1?"comes":"come"} from a file this one imports; the rest are declared here. ${i}`}function nc({resourceUri:e,sourceName:n,onSourceChange:r,initialSourceName:o,includeHiddenFilesAndSources:i=!1,hostGivenNames:l,givens:a,onGivensChange:u,showAccessRules:d=!1,headingLevel:h="h1",headerActions:y,renderSourceStatus:b,entities:x,entitiesLoading:v=!1,entitiesError:k=!1,columnDescriptions:C,joinHref:S,queryMetadata:T,onQueryRun:O,maxResultSize:M,extensions:E}){const{environmentName:R,packageName:P,modelPath:F="",versionId:B}=c.parseResourceUri(e),D=q.usePublisherTheme().theme.ui.font.mono,{sources:_,queries:V,sourceText:$,givens:W,access:Z,modelDoc:ne,hasImports:J,isLoading:H,isError:Q,error:re,refetch:z}=Yg(R,P,F,B,!0,i),oe=j.useMemo(()=>new Set(l??[]),[l]),se=j.useMemo(()=>W.filter(Ce=>!oe.has(Ce.name)),[W,oe]),ie=j.useMemo(()=>_.map(kg),[_]),De=j.useMemo(()=>Cg(V),[V]),de=j.useMemo(()=>xm(ie),[ie]),ue=j.useMemo(()=>ym(_),[_]),be=j.useMemo(()=>cm(se),[se]),Me=JSON.stringify(a??null),te=j.useMemo(()=>a&&Object.fromEntries(Object.entries(a).filter(([Ce])=>be.has(Ce))),[Me,be]),K=!H&&!Q,he=j.useCallback(Ce=>u?.(Ce,Array.from(be.keys())),[u,be]),we=c.useGivensState({declaredTypes:be,params:te,onParamsChange:K&&u?he:void 0,documentKey:`${R}/${P}@${B??""}/${F}`,autorun:!0}),ge=j.useMemo(()=>um(we.applied,be),[we.applied,be]),{givensBySource:pe,unknownGivensBySource:ye}=j.useMemo(()=>{const Ce=new Map,Re=new Map;for(const Ie of ie){const We=wm($,Ie.name,se);Ce.set(Ie.name,We.givens),We.unknown.size>0&&Re.set(Ie.name,We.unknown)}return{givensBySource:Ce,unknownGivensBySource:Re}},[ie,$,se]),Le=j.useMemo(()=>({projectName:R,packageName:P,versionId:B,givens:se,givensBySource:pe,unknownGivensBySource:ye,requiredFiltersBySource:ue,givenValues:ge,accessBySource:Z,includeHiddenFilesAndSources:i,queryMetadata:T,onQueryRun:O,maxResultSize:M}),[R,P,B,se,pe,ye,ue,ge,Z,i,T,O,M]),[st,ce]=j.useState(o),Y=n!==void 0,ae=Y?n:st,Fe=j.useCallback(Ce=>{Y||ce(Ce),r?.(Ce)},[Y,r]),Ve=j.useMemo(()=>jg(ie,F),[ie,F]),Ee=ie.find(Ce=>Ce.name===ae)??(Y?void 0:Ve),at=j.useMemo(()=>Ee?pe.get(Ee.name)??se:se,[Ee,pe,se]),yt=j.useMemo(()=>Ee?Sm($,Ee.name,se,de):new Map,[Ee,$,se,de]),xt=j.useMemo(()=>Tg($,Ee?.name,de),[$,Ee?.name,de]),Ot=j.useMemo(()=>Ee?Qf(Ee,ie.find(Ce=>Ce.name===xt)):void 0,[Ee,ie,xt]),pt=j.useMemo(()=>x?kl(x):Kg,[x]),Ye=Ee?pt.get(Ee.name):void 0,{joinLinks:fe,joinEntities:Ke,joinCodes:ze,joinAccessRules:lt}=j.useMemo(()=>{const Ce=new Map,Re=new Map,Ie=new Map,We=new Map,dt=new Map([[F,new Set(de)]]);for(const Pe of Ye?.values()??[]){if(Pe.fieldType!=="join")continue;Pe.code&&Ie.set(Pe.name,Pe.code);const tt=Pe.joinTarget;if(tt)if(tt.modelPath===F){const Mt=pt.get(tt.sourceName);Mt&&Re.set(Pe.name,Mt);const kt=Qr(Z,tt.sourceName);El(kt)&&We.set(Pe.name,{sourceName:tt.sourceName,access:kt});const Ft=qm(tt,dt);Ce.set(Pe.name,Ft.kind==="link"?{...Ft,onOpen:()=>Fe(tt.sourceName)}:Ft)}else{const Mt=S?.(tt);Mt&&Ce.set(Pe.name,{kind:"link",href:Mt})}}return{joinLinks:Ce,joinEntities:Re,joinCodes:Ie,joinAccessRules:We}},[Ye,pt,F,de,Z,Fe,S]),ct=F==="index.malloy"&&!i,Qe=j.useMemo(()=>Mg(ie,Ve,ct?{exportOrder:Ig($)}:void 0),[ie,Ve,ct,$]),me=E?.describePickerSource,He=j.useMemo(()=>Qe.sources.map(Ce=>{const Re=me?.({modelPath:F,sourceName:Ce.name});return{name:Ce.name,description:$g(Ce.doc,Re?.summary),descriptionPending:!Ce.doc?.trim()&&!Re?.summary&&!!Re?.summaryPending,meta:Og(Ce),mostViews:Qe.mostViews===Ce.name,access:Qr(Z,Ce.name),status:Re?.status}}),[Qe,Z,me,F]),vt=(()=>{if(H)return t.jsx(c.Loading,{text:"Fetching Model..."});if(Q)return Wm(re)?t.jsx(p.Box,{sx:{pt:eo},children:t.jsx(xr,{message:Yl(re)??`${P}/${F} doesn't exist, or you don't have access to it.`})}):t.jsx(ds,{message:Kl("Failed to load model",re),onRetry:()=>void z()});const Ce=De.length>0&&t.jsx(ag,{queries:De,sourceText:$,modelPath:F,run:Le});if(ie.length===0)return De.length===0?t.jsxs(t.Fragment,{children:[t.jsx($s,{headingLevel:h,title:Oa(F),meta:se.length>0?`${se.length} ${se.length===1?"given":"givens"}`:void 0,actions:y,isSource:!1,offSurface:i}),t.jsx(xr,{message:"This model defines no sources or queries.",secondary:J&&t.jsxs(t.Fragment,{children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})}),t.jsxs(_n,{label:"Givens",count:se.length,testId:"model-viewer-declared-givens",children:[t.jsx(un,{"data-testid":"model-viewer-declared-givens-where",sx:{mb:1},children:Qg($,se)}),t.jsx(po,{givens:se})]})]}):t.jsxs(t.Fragment,{children:[t.jsx($s,{headingLevel:h,title:Oa(F),meta:`${De.length} ${De.length===1?"query":"queries"}`,actions:y,isSource:!1,offSurface:i}),Ce]});if(!Ee)return t.jsx(p.Box,{sx:{pt:eo},children:t.jsx(xr,{message:`This model has no source named ${ae}.`,secondary:t.jsxs(p.Box,{component:"span","data-testid":"model-viewer-source-links",children:["Sources in this model: ",ie.map((Pe,tt)=>t.jsxs("span",{children:[tt>0&&", ",t.jsx(p.Link,{component:"button",type:"button",onClick:()=>Fe(Pe.name),sx:{fontFamily:Dt,verticalAlign:"baseline"},children:Pe.name})]},Pe.name))]})})});const Re=ec(Ee),Ie=xt?void 0:[...Ye?.values()??[]].find(Pe=>Pe.table)?.table,We=xt?t.jsxs(t.Fragment,{children:["from ",t.jsx(p.Link,{component:"button",type:"button",onClick:()=>Fe(xt),sx:{fontFamily:Dt,color:as,textDecorationColor:"inherit",verticalAlign:"baseline"},children:xt})]}):Ie?t.jsxs(t.Fragment,{children:["reads ",t.jsx(p.Box,{component:"span","data-testid":"model-viewer-source-table",sx:{fontFamily:Dt},children:[Ie.connectionName,Ie.catalogName,Ie.schemaName,Ie.tableName].filter(Boolean).join(".")})]}):void 0,dt=E?.renderSourceDetail?.({modelPath:F,sourceName:Ee.name});return t.jsxs(t.Fragment,{children:[t.jsx($s,{headingLevel:h,title:Ee.name,titleAdornments:ie.length>1&&t.jsx(Ng,{sources:He,currentName:Ee.name,countLabel:Ym(He.length,Qe.curated),onPickSource:Fe,curated:Qe.curated,exportOrdered:Qe.exportOrdered}),actions:y,status:b?.(Ee.name),kindLabel:"Source",meta:`${Re} ${Re===1?"field":"fields"}`,doc:Ot,modelDoc:ne,access:Qr(Z,Ee.name),showRules:d,offSurface:i,publicSurface:ct,provenance:We}),dt&&t.jsx(p.Box,{"data-testid":"model-viewer-source-detail",sx:{mt:1.5},children:dt}),t.jsx(xo.Provider,{value:se,children:t.jsx(wg,{source:Ee,modelPath:F,entitiesByName:Ye,entitiesLoading:v,entitiesError:k,columnDescriptions:C?.get(Ee.name),modelText:$,joinLinks:fe,joinAccess:lt,showRules:d,joinEntities:Ke,joinCodes:ze,run:Le,queries:Ce,givens:t.jsx(Um,{givens:at,unknown:Ee?ye.get(Ee.name):void 0,inheritedFrom:yt,values:we.draft,onChange:we.setGiven,onReset:we.reset,environmentName:R,packageName:P,modelPath:F,versionId:B,declaredTypes:be})},Ee.name)})]})})();return t.jsx(Sl.Provider,{value:E??{},children:t.jsx(p.Box,{"data-testid":"model-viewer",sx:{...sm,pb:2,[vl]:D},children:t.jsx(p.Box,{sx:om,children:vt})})})}const Zg=c.createSvgIcon(t.jsx("path",{d:"M8 5v14l11-7z"}));function rc({open:e,onClose:n,result:r,title:o="Results",renderLogs:i,drill:l}){return t.jsx(c.AppDialog,{open:e,onClose:n,title:o,maxWidth:!1,showClose:!0,children:t.jsx(p.Box,{sx:{height:"70vh",overflow:"auto"},children:t.jsx(c.ResultContainer,{result:r,maxHeight:c.RESULTS_DIALOG_MAX_HEIGHT,maxResultSize:1e6,renderLogs:i,drill:l})})})}function Xg({queryName:e,annotations:n,resourceUri:r,runOnDemand:o=!1,maxResultSize:i=0}){const[l,a]=j.useState(),[u,d]=j.useState(!1),[h,y]=j.useState(!1),{packageName:b,environmentName:x,versionId:v,modelPath:k}=c.parseResourceUri(r),C=!o||h,S=c.useQueryResult({environmentName:x,packageName:b,modelPath:k,versionId:v,queryName:e},{enabled:C}),T=S.data,{mode:O}=q.usePublisherTheme();return j.useEffect(()=>{if(n&&n.length>0){const M=n.map(E=>`// ${E}`).join(`
36
+ `);jo(M,"typescript",O).then(E=>{a(E)})}},[n,O]),t.jsxs(p.Box,{children:[l&&t.jsx(p.Box,{sx:{marginBottom:"16px"},children:t.jsx(p.Typography,{fontSize:"12px",sx:{fontSize:"12px","& .line":{textWrap:"wrap"}},children:t.jsx("div",{className:"content",dangerouslySetInnerHTML:{__html:l}})})}),t.jsxs(p.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontSize:"15px",fontWeight:600,color:"text.primary",px:2,py:1,bgcolor:"action.hover",borderRadius:1.5,border:1,borderColor:"divider"},children:e}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>d(!0),children:t.jsx(c.SearchIcon,{})})]}),t.jsxs(q.CleanMetricCard,{sx:{position:"relative"},children:[o&&!h&&t.jsxs(p.Box,{sx:{padding:"40px 20px",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Click Run to execute the query"}),t.jsx(p.Button,{variant:"contained",startIcon:t.jsx(Zg,{}),onClick:()=>y(!0),children:"Run Query"})]}),C&&t.jsx(c.ResultPanel,{state:S,context:e,maxHeight:c.MODEL_CELL_MAX_HEIGHT,maxResultSize:i})]}),t.jsx(rc,{open:u,onClose:()=>d(!1),result:T?.data?.result||"",renderLogs:T?.data?.renderLogs,title:`Query: ${e}`})]})}function Jg(e){return e!=null}function ey(e,n){const r=[],o=[];for(const l of e){if(l.name===void 0||Jg(n.get(l.name)))continue;if(l.default==null){r.push(l.name);continue}const a=c.renderGivenDefault(l.type??"string",l.default);a&&o.push(`${l.name} = ${a}`)}const i={missing:r};return o.length>0&&(i.defaultsNote=o.length===1?`Ran with the default ${o[0]}`:`Ran with defaults ${o.join(", ")}`),i}function ty(e){return e.length===1?`This source may need a value for the given ${e[0]}. Set it in the parameters above.`:`This source may need values for the givens ${e.join(", ")}. Set them in the parameters above.`}function sc({sourceAndPaths:e,selectedSourceIndex:n,existingQuery:r,onQueryChange:o,onSourceChange:i,resourceUri:l,givens:a,gate:u}){return j.useEffect(()=>{i&&i(n)},[n,i]),t.jsx(q.StyledCardMedia,{children:t.jsxs(wr.Stack,{spacing:2,component:"section",children:[t.jsx(ry,{sourceAndPath:e[n],existingQuery:r,onChange:d=>{o&&o(d)},resourceUri:l,givens:a,gate:u}),t.jsx(wr.Box,{height:"5px"})]})})}function Ns(){return{query:void 0,malloyQuery:void 0,malloyResult:void 0}}function ny({sourceAndPath:e,onChange:n,existingQuery:r,explorerComponents:o,QueryBuilder:i,resourceUri:l,givens:a,gate:u}){const[d,h]=j.useState(r||Ns()),[y,b]=j.useState(void 0);j.useEffect(()=>{r&&h(r)},[r]);const[x,v]=j.useState([]),{MalloyExplorerProvider:k,QueryPanel:C,ResizableCollapsiblePanel:S,ResultPanel:T,SourcePanel:O}=o;j.useEffect(()=>{n&&n(d)},[n,d]);const{environmentName:M,packageName:E,versionId:R}=c.parseResourceUri(l),{apiClients:P}=q.useServer(),F=j.useRef(void 0),B=c.useMutationWithApiError({mutationFn:()=>{F.current=u,b({executionState:"running",query:d?.malloyQuery,queryResolutionStartMillis:Date.now(),onCancel:()=>{B.reset(),b(void 0)},response:{}});const $=typeof d?.malloyQuery=="string"?d.malloyQuery:new i.ASTQuery({source:e.sourceInfo,query:d?.malloyQuery}).toMalloy();return h({...d,query:$}),P.models.executeQueryModel(M,E,e.modelPath,{query:$,sourceName:void 0,queryName:void 0,versionId:R,...a&&Object.keys(a).length>0?{givens:a}:{}})},onSuccess:$=>{if($){const W=JSON.parse($.data.result);h({...d,malloyResult:W});const Z=F.current;b(ne=>ne?{...ne,executionState:"finished",response:{result:W,...Z?.defaultsNote?{messages:[{severity:"INFO",title:Z.defaultsNote}]}:{}}}:void 0)}},onError:$=>{console.error("Query execution error:",$);const W=$?.data?.message??$?.message??"The query could not be run.",Z=[{severity:"ERROR",title:W}],ne=F.current?.missing??[];($?.status===403||/Access denied for source/i.test(W))&&ne.length>0&&Z.push({severity:"WARN",title:ty(ne)}),b(H=>H?{...H,executionState:"finished",response:{messages:Z}}:void 0)}}),[D,_]=j.useState(e.sourceInfo.name);j.useEffect(()=>{D!==e.sourceInfo.name&&(_(e.sourceInfo.name),h(Ns()),b(void 0))},[e,D]);const V=j.useCallback($=>{h({...d,malloyQuery:$,malloyResult:void 0})},[d]);return D!==e.sourceInfo.name?t.jsx("div",{children:"Loading..."}):t.jsx(q.StyledExplorerContent,{sx:{border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},children:t.jsx(k,{source:e.sourceInfo,query:d?.malloyQuery,topValues:[],onFocusedNestViewPathChange:v,focusedNestViewPath:x,onQueryChange:V,children:t.jsxs("div",{style:{display:"flex",height:"100%",overflowY:"auto"},children:[t.jsx(S,{isInitiallyExpanded:!0,initialWidth:180,minWidth:180,icon:"database",title:e.sourceInfo.name,children:t.jsx(O,{onRefresh:()=>h(Ns())})}),t.jsx(S,{isInitiallyExpanded:!0,initialWidth:280,minWidth:280,icon:"filterSliders",title:"Query",children:t.jsx(C,{runQuery:()=>{console.log(`running query with: ${d?.malloyQuery}`);try{B.mutate()}catch($){console.error("Error running query:",$)}}})}),t.jsx(T,{source:e.sourceInfo,draftQuery:d?.malloyQuery,setDraftQuery:$=>h({...d,malloyQuery:$}),submittedQuery:y,options:{showRawQuery:!0}})]})})},e.sourceInfo.name)}function ry(e){const[n,r]=j.useState(null),[o,i]=j.useState(null),[l,a]=j.useState(!0);return j.useEffect(()=>{let u=!0;return Promise.all([import("@malloydata/malloy-explorer"),c.loadQueryBuilder()]).then(([d,h])=>{u&&(r(d),i(h),a(!1))}).catch(d=>{console.error("Failed to load Malloy components:",d),u&&a(!1)}),()=>{u=!1}},[]),l||!n||!o?t.jsx(q.StyledExplorerPage,{children:t.jsx(q.StyledExplorerContent,{children:t.jsx(wr.Box,{sx:{alignItems:"center",justifyContent:"center",height:"200px",color:"text.secondary"},children:"Loading explorer..."})})}):t.jsx(ny,{...e,explorerComponents:n,QueryBuilder:o,resourceUri:e.resourceUri})}function Mo(e,n=!0){const{modelPath:r,environmentName:o,packageName:i,versionId:l}=c.parseResourceUri(e),{apiClients:a}=q.useServer();return c.useQueryWithApiError({queryKey:["package",o,i,r,l],queryFn:async()=>(await a.models.getModel(o,i,r,l)).data,enabled:n})}function Eo({data:e,onChange:n,existingQuery:r,initialSelectedSourceIndex:o=0,onSourceChange:i,resourceUri:l,givens:a,onGivensChange:u,startingGivens:d}){const[h,y]=j.useState(o);j.useEffect(()=>{y(o)},[o]);const{data:b,isError:x,isLoading:v,error:k}=Mo(l,!e),{environmentName:C,packageName:S,modelPath:T,versionId:O}=c.parseResourceUri(l),M=e||b,E=j.useMemo(()=>M?.givens??[],[M]),R=c.useDocumentControls({specs:E,loaded:!!M,params:a,onGivensChange:u,startingValues:d,documentKey:l,autorun:!0,environmentName:C??"",packageName:S??"",modelPath:T,versionId:O,documentName:T}),P=j.useMemo(()=>c.givensToRequest(R.applied,R.declaredTypes),[R.applied,R.declaredTypes]),F=j.useMemo(()=>ey(E,R.applied),[E,R.applied]);if(v&&!e)return t.jsx(c.Loading,{text:"Fetching Model..."});if(x&&!e)return console.log("error",k),t.jsx(c.ApiErrorDisplay,{error:k,context:`ModelExplorer > ${T}`});if(!M)return t.jsx(c.Loading,{text:c.LOADING_COPY.loading});const B=(M?.sourceInfos||[]).map((_,V)=>{try{return JSON.parse(_)?.name||`Source ${V+1}`}catch{return`Source ${V+1}`}}),D=B[h]||"";return t.jsxs(q.StyledCard,{variant:"outlined",children:[t.jsx(q.StyledCardContent,{children:t.jsx(p.Stack,{sx:{flexDirection:"row"},children:t.jsx(Ks,{size:"small",id:"size-small-standard",disablePortal:!0,options:B,value:D,onChange:(_,V)=>{if(!V)return;const $=B.indexOf(V);$>=0&&(y($),i?.($))},renderInput:_=>t.jsx(c.TextField,{..._}),style:{width:350,marginTop:"3px",marginLeft:"6px",marginBottom:"8px"}})})}),t.jsx(c.GivensPanel,{...R.panel}),t.jsx(q.StyledCardMedia,{children:t.jsxs(p.Stack,{spacing:2,component:"section",children:[Array.isArray(M.sourceInfos)&&M.sourceInfos.length>0&&t.jsx(sc,{sourceAndPaths:M.sourceInfos.map(_=>({sourceInfo:JSON.parse(_),modelPath:T})),selectedSourceIndex:h,existingQuery:r,onQueryChange:n,resourceUri:l,givens:P,gate:F}),t.jsx(p.Box,{height:"5px"})]})})]})}function Io({open:e,onClose:n,resourceUri:r,data:o,title:i="Data Sources",hasValidImport:l=!0,existingQuery:a,initialSelectedSourceIndex:u,onChange:d,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}){return t.jsxs(p.Dialog,{open:e,onClose:n,fullScreen:!0,children:[t.jsxs(p.DialogTitle,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i,t.jsx(p.IconButton,{onClick:n,sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{})})]}),t.jsx(p.DialogContent,{children:l?t.jsx(Eo,{resourceUri:r,data:o,existingQuery:a,initialSelectedSourceIndex:u,onChange:d,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}):t.jsx("div",{children:"No valid import statement found in cell"})})]})}function sy({onChange:e,resourceUri:n,runOnDemand:r=!1,maxResultSize:o=0,givens:i,onGivensChange:l}){const{modelPath:a}=c.parseResourceUri(n),{data:u,isError:d,isLoading:h,error:y}=Mo(n),[b,x]=j.useState(!1),[v,k]=j.useState(),[C,S]=j.useState(0),[T,O]=j.useState(""),[M,E]=j.useState({}),R=i??M,P=l??($=>E($)),F=u?.modelDef,B=j.useMemo(()=>{if(!F)return!1;try{const $=JSON.parse(F);return Array.isArray($.imports)&&$.imports.length>0}catch{return!1}},[F]);if(h)return t.jsx(c.Loading,{text:"Fetching Model..."});if(d)return console.log("error",y),t.jsx(c.ApiErrorDisplay,{error:y,context:`Model > ${a}`});const D=$=>{k($),e&&e($)},_=$=>{S($)},V=()=>{const $=window.location.href;navigator.clipboard.writeText($).then(()=>O("URL copied to clipboard!")).catch(()=>O("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsxs(p.Box,{sx:{position:"relative",maxWidth:"1200px",margin:"0 auto",paddingTop:"24px"},children:[Array.isArray(u?.sourceInfos)&&u.sourceInfos.length>0&&t.jsxs(p.Stack,{spacing:2,component:"section",children:[t.jsxs(p.Box,{sx:{padding:"0 0 16px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx(p.Typography,{variant:"h1",sx:{fontSize:"28px",fontWeight:"600",color:"#1a1a1a",marginBottom:"8px",marginTop:"0",paddingLeft:"0"},children:"Sources"}),t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{size:"small","aria-label":"Copy link",onClick:V,sx:{color:"text.secondary"},children:t.jsx(ho,{fontSize:"small"})})})]}),t.jsx(Eo,{data:u,onChange:D,onSourceChange:_,existingQuery:v,initialSelectedSourceIndex:C,resourceUri:n,givens:R,onGivensChange:P}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",sx:{position:"absolute",top:"90px",right:"4px",zIndex:2},onClick:()=>x(!0),children:t.jsx(c.SearchIcon,{})})]}),u?.queries?.length>0&&t.jsxs(p.Stack,{spacing:2,component:"section",sx:{marginTop:"24px"},children:[t.jsx(p.Box,{sx:{padding:"0 0 16px 0"},children:t.jsx(p.Typography,{variant:"h2",sx:{fontSize:"24px",fontWeight:"600",color:"#1a1a1a",marginBottom:"0",marginTop:"8px",paddingLeft:"0"},children:"Named Queries"})}),u.queries.map($=>t.jsx(Xg,{queryName:$.name,annotations:$.annotations,resourceUri:n,runOnDemand:r,maxResultSize:o},$.name))]}),(!Array.isArray(u?.sourceInfos)||u.sourceInfos.length===0)&&!(u?.queries&&u.queries.length>0)&&t.jsxs(p.Box,{sx:{textAlign:"center",py:6},children:[t.jsx(p.Typography,{variant:"body1",sx:{color:"text.secondary",marginBottom:"8px"},children:"This model exposes no sources or queries."}),B&&t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})]}),t.jsx(Io,{open:b,onClose:()=>x(!1),resourceUri:n,data:u,title:`Model: ${a.split("/").pop()}`,existingQuery:v,initialSelectedSourceIndex:C,onChange:D,onSourceChange:_,givens:R,onGivensChange:P})]}),t.jsx(p.Snackbar,{open:T!=="",autoHideDuration:6e3,onClose:()=>O(""),message:T})]})}function oy(){const[e,n]=j.useState(""),r=()=>{navigator.clipboard.writeText(window.location.href).then(()=>n("URL copied to clipboard!")).catch(()=>n("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{size:"small","aria-label":"Copy link",onClick:r,sx:{color:"text.secondary"},children:t.jsx(ho,{fontSize:"small"})})}),t.jsx(p.Snackbar,{open:e!=="",autoHideDuration:6e3,onClose:()=>n(""),message:e})]})}function iy(e){const{modelPage:n,isLoadingStatus:r}=q.useServer();if(r)return t.jsx(c.Loading,{text:"Fetching Model..."});if(n!=="viewer")return t.jsx(sy,{...e});const{onChange:o,runOnDemand:i,headerActions:l,...a}=e;return t.jsx(nc,{...a,headerActions:l??t.jsx(oy,{})})}const ay={"persist-source-refused":"persist-not-built","preaggregate-not-built":"rollup-not-built","preaggregate-join-one-key-repeated":"rollup-join-one-key-repeated","stored-native-schema-missing":"database-native-type-missing"};function ly(e){const n=(o,i)=>`${o}\0${i.subject??""}\0${i.message??""}`,r=new Set(e.map(o=>n(o.code,o)));return e.filter(o=>{const i=o.code!==void 0?ay[o.code]:void 0;return i===void 0||!r.has(n(i,o))})}function cy({warnings:e}){const[n,r]=j.useState(!1),o=ly(e??[]),i=o.filter(a=>a.severity==="error"),l=o.filter(a=>a.severity!=="error");return i.length===0&&l.length===0?null:t.jsxs(p.Stack,{sx:{gap:1,mb:4},children:[i.length>0&&t.jsxs(p.Alert,{severity:"warning",children:[t.jsx(p.AlertTitle,{children:i.length===1?"1 problem in this package":`${i.length} problems in this package`}),t.jsx(Ma,{findings:i})]}),l.length>0&&t.jsxs(p.Box,{children:[t.jsxs(p.Button,{size:"small","aria-expanded":n,onClick:()=>r(a=>!a),sx:{px:.5,color:"text.secondary"},children:[n?"Hide":"Show"," ",l.length," ",l.length===1?"note":"notes"]}),n&&t.jsx(p.Box,{sx:{pl:.5,pt:.5},children:t.jsx(Ma,{findings:l})})]})]})}function Ma({findings:e}){return t.jsx(p.Stack,{component:"ul",sx:{m:0,p:0,listStyle:"none",gap:.75},children:e.map((n,r)=>t.jsxs(p.Typography,{component:"li",variant:"body2",children:[n.model&&t.jsx(p.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.85em",mr:1},children:n.model}),n.message]},`${n.model??""}:${n.code??""}:${r}`))})}function oc(e){return j.useMemo(()=>{if(!e?.sources?.length)return[];const n=new Map;for(const r of e.sources)if(r.givens?.length)for(const o of r.givens)o.name&&!n.has(o.name)&&n.set(o.name,o);return Array.from(n.values())},[e])}function uy(e){return e.type==="code"}function dy(e){return(e.text??"").split(`
37
37
  `).filter(n=>!n.trimStart().startsWith("##")).join(`
38
- `)}const Qy=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"}));function Zy({cell:e,resourceUri:n,showCopyLink:r,maxResultSize:o,isExecuting:i,pendingRerun:l,onNavigate:a,onDrillSelf:d,canDrillSelf:u,onDrillNavigate:h,givens:y,givenSpecs:b}){const[x,v]=j.useState(!1),[k,C]=j.useState(!1),[S,T]=j.useState(),[O,M]=j.useState(!1),{modelPage:E,isLoadingStatus:R}=q.useServer(),P=!R&&E!=="viewer",[A,H]=j.useState(""),{environmentName:D,packageName:L,modelPath:U}=c.parseResourceUri(n),$={environmentName:D,packageName:L,sourcePath:U,onNavigate:a},{drill:W,drillMenu:Q}=io({onNavigate:h,onSelf:d,canSelf:u}),te=/import\s*\{([^}]+)\}\s*from\s*['"`][^'"`]+['"`]/,ee=/import\s*(?:\{[^}]*\}\s*from\s*)?['"`]([^'"`]+)['"`]/,G=!!e.text&&(te.test(e.text)||ee.test(e.text)),Z=()=>{if(!e.newSources||e.newSources.length===0)return 0;let ne=[],Ie="";if(e.text){const de=e.text.match(te);de&&(ne=de[1].split(",").map(De=>De.trim()));const pe=e.text.match(ee);pe&&(Ie=pe[1].trim())}for(let de=0;de<e.newSources.length;de++)try{const pe=JSON.parse(e.newSources[de]);if(ne.length>0&&ne.includes(pe.name)||Ie&&Ie===pe.path)return de}catch{continue}return 0},ae=j.useMemo(()=>e.newSources&&e.newSources.length>0?{sourceInfos:e.newSources,resource:n,givens:b}:void 0,[e.newSources,n,b]),{mode:z}=q.usePublisherTheme();j.useEffect(()=>{e.type==="code"&&To(Ky(e),"malloy",z).then(ne=>{T(ne)})},[e,z]);const re=()=>{const ne=window.location.href;navigator.clipboard.writeText(ne).then(()=>H("URL copied to clipboard!")).catch(()=>H("Failed to copy URL"))},se=t.jsx(c.AppDialog,{open:x,onClose:()=>v(!1),title:"Malloy code",maxWidth:"lg",showClose:!0,children:t.jsx(p.Box,{sx:ne=>({border:`1px solid ${ne.palette.divider}`,borderRadius:"8px",padding:"16px",fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",lineHeight:"1.5",overflow:"auto",maxHeight:"70vh",backgroundColor:ne.palette.background.paper,color:ne.palette.text.primary}),children:t.jsx("pre",{className:"code-display",style:{margin:0},dangerouslySetInnerHTML:{__html:S}})})});return e.type==="markdown"&&t.jsx(p.Box,{children:t.jsxs(c.TextTileFrame,{children:[r?t.jsxs(p.Stack,{direction:"row",alignItems:"flex-start",justifyContent:"space-between",children:[t.jsx(c.Prose,{variant:"document",links:$,children:e.text}),t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{"aria-label":"Copy link",onClick:re,sx:{color:"text.secondary",mt:"18px"},children:t.jsx(fo,{sx:{fontSize:"24px"}})})})]}):t.jsx(c.Prose,{variant:"document",links:$,children:e.text}),t.jsx(p.Snackbar,{open:A!=="",autoHideDuration:6e3,onClose:()=>H(""),message:A})]})})||e.type==="code"&&t.jsxs(p.Box,{children:[e.newSources&&e.newSources.length>0&&t.jsx(p.Stack,{sx:{flexDirection:"column",gap:"8px",marginBottom:"2px"},children:t.jsx(q.CleanMetricCard,{sx:{position:"relative",padding:"0"},children:t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingLeft:"24px",paddingRight:"8px"},children:[S&&t.jsx("span",{dangerouslySetInnerHTML:{__html:S},style:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",flex:1,marginRight:"8px"}}),G&&P&&t.jsx(c.FloatingIconButton,{"aria-label":"Data sources",sx:{flexShrink:0},onClick:()=>M(!0),children:t.jsx(c.SearchIcon,{})})]})})}),t.jsx(Do,{open:O&&P,onClose:()=>M(!1),title:"Data Sources",hasValidImport:G,resourceUri:n,data:ae,initialSelectedSourceIndex:Z(),startingGivens:y}),se,t.jsx(rc,{open:k,onClose:()=>C(!1),result:e.result||"",title:"Results",drill:W}),i&&!e.result&&!e.error&&!G&&!(e.newSources&&e.newSources.length>0)&&t.jsx(c.TileCard,{children:t.jsx(p.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:200},children:t.jsx(p.CircularProgress,{size:32})})}),!e.result&&e.error&&t.jsx(c.ErrorDetailAlert,{summary:"This cell could not be run.",detail:e.error}),e.result&&l&&t.jsx(p.LinearProgress,{"aria-label":"Re-run pending",sx:{mb:1,height:2,borderRadius:1}}),e.result&&t.jsxs(c.TileCard,{children:[t.jsx(c.TileHeading,{title:"",action:t.jsxs(p.Stack,{direction:"row",sx:{gap:.5,mt:"-4px"},children:[t.jsx(c.FloatingIconButton,{"aria-label":"Malloy code",onClick:ne=>{ne.stopPropagation(),v(!0)},children:t.jsx(Qy,{})}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>C(!0),children:t.jsx(c.SearchIcon,{})})]})}),t.jsx(c.ResultContainer,{result:e.result,maxHeight:c.NOTEBOOK_CELL_MAX_HEIGHT,maxResultSize:o,drill:W}),Q]})]})}function Xy({ready:e,lastRunKey:n,pendingKey:r,runKey:o,documentKey:i}){if(!e)return{cancelPending:r!==void 0,dispatch:"none"};const l=r!==void 0&&r!==o;if(n===o)return{cancelPending:l,dispatch:"none"};if(r===o)return{cancelPending:l,dispatch:"none"};const a=n===null||!n.startsWith(`${i}|`);return{cancelPending:l,dispatch:a?"now":"settle"}}const Jy=4;function ex(e){const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error&&e.message!==""?e.message:"The server did not say why."}function tx({resourceUri:e,title:n,description:r,maxResultSize:o=0,givens:i,onGivensChange:l,onNavigate:a,onDrillNavigate:d,notebook:u,error:h,runCell:y}){const{environmentName:b,packageName:x,versionId:v,modelPath:k}=c.parseResourceUri(e),C=u!==void 0,S=!C&&!!h,[T,O]=j.useState([]),[M,E]=j.useState(!1),[R,P]=j.useState(!1),A=j.useRef(void 0),[H,D]=j.useState(null),L=gc(u),U=u?.autorun!==!1,$=c.useReportEvents(),W=c.useDocumentControls({specs:L,loaded:C,startingValues:u?.startingGivens,params:i,onGivensChange:l,documentKey:e,autorun:U,environmentName:b,packageName:x,modelPath:k,versionId:v,documentName:k}),{applied:Q,declaredTypes:te,canSelf:ee,onSelf:G}=W,Z=j.useCallback(K=>{const le=c.givensToRequest(K,te);return Object.keys(le).length>0?JSON.stringify(le):void 0},[te]),ae=j.useMemo(()=>c.givensToParams(Q,te),[Q,te]),z=j.useRef(0),re=j.useRef(null),se=j.useRef(null),ne=j.useRef(void 0);j.useEffect(()=>()=>{re.current?.abort(),se.current=null,clearTimeout(ne.current?.timer),ne.current=void 0},[]);const Ie=j.useCallback(async(K=new Map)=>{if(!C||!u?.notebookCells)return;const le=++z.current;re.current?.abort();const be=new AbortController;re.current=be,O(u.notebookCells.map(ge=>({...ge}))),E(!0),D(null);try{const ge=[];for(let ye=0;ye<u.notebookCells.length;ye++){const $e=u.notebookCells[ye];if(!Yy($e))continue;const ze=ye,me=async()=>{try{const Y=await y({cell:$e,index:ze,givens:K,declaredTypes:te,signal:be.signal});if(z.current!==le)return;const ie=Y.result,Oe=$e.newSources||Y.newSources;O(Fe=>{const at=[...Fe];return at[ze]||(at[ze]={...$e}),at[ze]={...at[ze],result:ie,newSources:Oe},at})}catch(Y){if(be.signal.aborted||z.current!==le)return;$.emit({type:"report.query_failed",tile:ze,category:c.failureCategory(Y)}),$.listening||console.error(`Error executing cell ${ze}:`,Y);const ie=ex(Y);O(Oe=>{const Fe=[...Oe];return Fe[ze]||(Fe[ze]={...$e}),Fe[ze]={...Fe[ze],error:ie},Fe})}};ge.push(me)}const ue=[];for(const ye of ge){const $e=ye().then(()=>{ue.splice(ue.indexOf($e),1)});ue.push($e),ue.length>=Jy&&await Promise.race(ue)}await Promise.all(ue)}catch(ge){if(be.signal.aborted||z.current!==le)return;$.emit({type:"report.query_failed",category:c.failureCategory(ge)}),$.listening||console.error("Error executing notebook cells:",ge),D(ge)}finally{z.current===le&&(E(!1),re.current=null)}},[C,u,te,y,$]),de=j.useRef(0),pe=j.useRef(void 0);pe.current!==u&&(pe.current=u,de.current+=1);const De=de.current;j.useEffect(()=>{const K=`${e}|${De}`,le=`${K}|${Z(Q)??""}`;A.current!==void 0&&A.current!==K&&(re.current?.abort(),re.current=null),A.current=K;const be=Xy({ready:C&&!!u?.notebookCells,lastRunKey:se.current,pendingKey:ne.current?.key,runKey:le,documentKey:K});if(be.cancelPending&&(clearTimeout(ne.current?.timer),ne.current=void 0,P(!1)),be.dispatch==="none")return;const ge=()=>{ne.current=void 0,P(!1),se.current=le,Ie(Q)};if(be.dispatch==="now"){ge();return}P(!0),ne.current={key:le,timer:setTimeout(ge,c.GIVEN_SETTLE_MS)}},[C,u,De,e,Q,Z,Ie]);const Le=T.length>0?T:u?.notebookCells||[],oe=0;return t.jsxs(c.ReportPage,{layout:"linear",header:n||r?t.jsx(c.ReportHeader,{title:n??"",description:r?t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",children:r})}):void 0}):null,controls:W.panel.givens.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...W.panel,layout:"bar"})}):void 0,children:[!C&&!S&&t.jsx(c.Loading,{text:c.LOADING_COPY.opening("report")}),C&&Le.map((K,le)=>t.jsx(Zy,{cell:K,showCopyLink:le===oe,resourceUri:e,maxResultSize:o,isExecuting:M,givens:ae,givenSpecs:L,pendingRerun:R,onNavigate:a,onDrillNavigate:d,onDrillSelf:L.length>0?G:void 0,canDrillSelf:ee},le)),S&&h?.status===404&&t.jsxs(p.Typography,{variant:"body2",sx:{color:"text.secondary"},children:[t.jsx("code",{children:`${b} > ${x} > ${k}`})," ","not found."]}),S&&h?.status!==404&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${b} > ${x} > ${k}`}),H&&t.jsx(c.ApiErrorDisplay,{error:{message:H.message,status:500,name:"ExecutionError"},context:"Notebook Execution"})]})}function yc(e){const{apiClients:n}=q.useServer(),{environmentName:r,packageName:o,versionId:i,modelPath:l}=c.parseResourceUri(e);return c.useQueryWithApiError({queryKey:[e],queryFn:async()=>(await n.notebooks.getNotebook(r,o,l,i)).data})}function nx(e){const{apiClients:n}=q.useServer(),{environmentName:r,packageName:o,versionId:i,modelPath:l}=c.parseResourceUri(e.resourceUri),a=yc(e.resourceUri),d=j.useCallback(async({index:u,givens:h,declaredTypes:y,signal:b})=>{const x=c.givensToRequest(h,y);return(await n.notebooks.executeNotebookCell(r,o,l,u,i,void 0,void 0,Object.keys(x).length>0?JSON.stringify(x):void 0,{signal:b})).data},[n.notebooks,r,o,l,i]);return t.jsx(tx,{...e,notebook:a.isSuccess?a.data:void 0,error:a.isError?a.error:void 0,runCell:d})}function rx(e){const{data:n}=yc(e.resourceUri);if(n?.dashboard){const{environmentName:r,packageName:o,versionId:i,modelPath:l}=c.parseResourceUri(e.resourceUri);return t.jsx(rs,{manifest:{...n.dashboard,layout:"linear"},environmentName:r,packageName:o,versionId:i,documentName:l,givens:e.givens,onGivensChange:e.onGivensChange,onNavigate:e.onDrillNavigate,...e.onNavigate?{onLinkNavigate:e.onNavigate}:{},maxResultSize:e.maxResultSize})}return t.jsx(nx,{...e})}function xc(e,n,r="grid"){const o=n.filter(l=>!!l.path).filter(l=>c.documentSlug(l.path)===e),i=o.filter(l=>c.listedLayout(l)===r);return i.length===1?{found:c.locatedReport(i[0])}:o.length===1?{found:c.locatedReport(o[0])}:o.length===0?{missing:!0}:{ambiguous:o.map(l=>l.path).sort()}}const sx=/^(dashboards|notebooks)\/([^/]+)$/;function ox(e){const n=sx.exec(e);if(n)return{name:n[2],prefer:n[1]==="dashboards"?"grid":"linear"}}const ix=(e,n,r,o)=>`/${e}/${n}/${r}s/${encodeURIComponent(o)}`;function ax({kind:e,slug:n,reports:r}){const o=xc(n,r,c.layoutOfKind(e));return"found"in o?o.found:void 0}function lx(e,n){return`${e}:${n}`}function hn(e){return lx(e.source,e.filterName??e.dimensionName)}function cx(e){const n=new Map;for(const r of e){const o=`${r.source}|${r.model}`,i=n.get(o)||[];i.push(r),n.set(o,i)}return n}function ux(e,n,r,o){const i=n.filter(h=>(h.filterType==="Star"||h.filterType==="MinMax"||h.filterType==="DateMinMax")&&!h.values);if(i.length===0)return"";const a=[...new Set(i.map(h=>h.dimensionName))].map(h=>`\`${h}\``).join(", "),d=o?.filter(h=>h.source===e)||[],u=d.length>0?d.map(h=>is(`\`${h.dimensionName}\``,h)).filter(h=>h.length>0).join(" and "):"";return`
38
+ `)}const hy=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"}));function fy({cell:e,resourceUri:n,showCopyLink:r,maxResultSize:o,isExecuting:i,pendingRerun:l,onNavigate:a,onDrillSelf:u,canDrillSelf:d,onDrillNavigate:h,givens:y,givenSpecs:b}){const[x,v]=j.useState(!1),[k,C]=j.useState(!1),[S,T]=j.useState(),[O,M]=j.useState(!1),{modelPage:E,isLoadingStatus:R}=q.useServer(),P=!R&&E!=="viewer",[F,B]=j.useState(""),{environmentName:D,packageName:_,modelPath:V}=c.parseResourceUri(n),$={environmentName:D,packageName:_,sourcePath:V,onNavigate:a},{drill:W,drillMenu:Z}=oo({onNavigate:h,onSelf:u,canSelf:d}),ne=/import\s*\{([^}]+)\}\s*from\s*['"`][^'"`]+['"`]/,J=/import\s*(?:\{[^}]*\}\s*from\s*)?['"`]([^'"`]+)['"`]/,H=!!e.text&&(ne.test(e.text)||J.test(e.text)),Q=()=>{if(!e.newSources||e.newSources.length===0)return 0;let ie=[],De="";if(e.text){const de=e.text.match(ne);de&&(ie=de[1].split(",").map(be=>be.trim()));const ue=e.text.match(J);ue&&(De=ue[1].trim())}for(let de=0;de<e.newSources.length;de++)try{const ue=JSON.parse(e.newSources[de]);if(ie.length>0&&ie.includes(ue.name)||De&&De===ue.path)return de}catch{continue}return 0},re=j.useMemo(()=>e.newSources&&e.newSources.length>0?{sourceInfos:e.newSources,resource:n,givens:b}:void 0,[e.newSources,n,b]),{mode:z}=q.usePublisherTheme();j.useEffect(()=>{e.type==="code"&&jo(dy(e),"malloy",z).then(ie=>{T(ie)})},[e,z]);const oe=()=>{const ie=window.location.href;navigator.clipboard.writeText(ie).then(()=>B("URL copied to clipboard!")).catch(()=>B("Failed to copy URL"))},se=t.jsx(c.AppDialog,{open:x,onClose:()=>v(!1),title:"Malloy code",maxWidth:"lg",showClose:!0,children:t.jsx(p.Box,{sx:ie=>({border:`1px solid ${ie.palette.divider}`,borderRadius:"8px",padding:"16px",fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",lineHeight:"1.5",overflow:"auto",maxHeight:"70vh",backgroundColor:ie.palette.background.paper,color:ie.palette.text.primary}),children:t.jsx("pre",{className:"code-display",style:{margin:0},dangerouslySetInnerHTML:{__html:S}})})});return e.type==="markdown"&&t.jsx(p.Box,{children:t.jsxs(c.TextTileFrame,{children:[r?t.jsxs(p.Stack,{direction:"row",alignItems:"flex-start",justifyContent:"space-between",children:[t.jsx(c.Prose,{variant:"document",links:$,children:e.text}),t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{"aria-label":"Copy link",onClick:oe,sx:{color:"text.secondary",mt:"18px"},children:t.jsx(ho,{sx:{fontSize:"24px"}})})})]}):t.jsx(c.Prose,{variant:"document",links:$,children:e.text}),t.jsx(p.Snackbar,{open:F!=="",autoHideDuration:6e3,onClose:()=>B(""),message:F})]})})||e.type==="code"&&t.jsxs(p.Box,{children:[e.newSources&&e.newSources.length>0&&t.jsx(p.Stack,{sx:{flexDirection:"column",gap:"8px",marginBottom:"2px"},children:t.jsx(q.CleanMetricCard,{sx:{position:"relative",padding:"0"},children:t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingLeft:"24px",paddingRight:"8px"},children:[S&&t.jsx("span",{dangerouslySetInnerHTML:{__html:S},style:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",flex:1,marginRight:"8px"}}),H&&P&&t.jsx(c.FloatingIconButton,{"aria-label":"Data sources",sx:{flexShrink:0},onClick:()=>M(!0),children:t.jsx(c.SearchIcon,{})})]})})}),t.jsx(Io,{open:O&&P,onClose:()=>M(!1),title:"Data Sources",hasValidImport:H,resourceUri:n,data:re,initialSelectedSourceIndex:Q(),startingGivens:y}),se,t.jsx(rc,{open:k,onClose:()=>C(!1),result:e.result||"",title:"Results",drill:W}),i&&!e.result&&!e.error&&!H&&!(e.newSources&&e.newSources.length>0)&&t.jsx(c.TileCard,{children:t.jsx(p.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:200},children:t.jsx(p.CircularProgress,{size:32})})}),!e.result&&e.error&&t.jsx(c.ErrorDetailAlert,{summary:"This cell could not be run.",detail:e.error}),e.result&&l&&t.jsx(p.LinearProgress,{"aria-label":"Re-run pending",sx:{mb:1,height:2,borderRadius:1}}),e.result&&t.jsxs(c.TileCard,{children:[t.jsx(c.TileHeading,{title:"",action:t.jsxs(p.Stack,{direction:"row",sx:{gap:.5,mt:"-4px"},children:[t.jsx(c.FloatingIconButton,{"aria-label":"Malloy code",onClick:ie=>{ie.stopPropagation(),v(!0)},children:t.jsx(hy,{})}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>C(!0),children:t.jsx(c.SearchIcon,{})})]})}),t.jsx(c.ResultContainer,{result:e.result,maxHeight:c.NOTEBOOK_CELL_MAX_HEIGHT,maxResultSize:o,drill:W}),Z]})]})}function my({ready:e,lastRunKey:n,pendingKey:r,runKey:o,documentKey:i}){if(!e)return{cancelPending:r!==void 0,dispatch:"none"};const l=r!==void 0&&r!==o;if(n===o)return{cancelPending:l,dispatch:"none"};if(r===o)return{cancelPending:l,dispatch:"none"};const a=n===null||!n.startsWith(`${i}|`);return{cancelPending:l,dispatch:a?"now":"settle"}}const py=4;function gy(e){const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error&&e.message!==""?e.message:"The server did not say why."}function yy({resourceUri:e,maxResultSize:n=0,givens:r,onGivensChange:o,onNavigate:i,onDrillNavigate:l,actions:a,notebook:u,runCell:d}){const{environmentName:h,packageName:y,versionId:b,modelPath:x}=c.parseResourceUri(e),[v,k]=j.useState([]),[C,S]=j.useState(!1),[T,O]=j.useState(!1),M=j.useRef(void 0),[E,R]=j.useState(null),P=oc(u),F=u.autorun!==!1,B=c.useReportEvents(),D=c.useDocumentControls({specs:P,loaded:!0,startingValues:u.startingGivens,params:r,onGivensChange:o,documentKey:e,autorun:F,environmentName:h,packageName:y,modelPath:x,versionId:b,documentName:x}),{applied:_,declaredTypes:V,canSelf:$,onSelf:W}=D,Z=j.useCallback(ue=>{const be=c.givensToRequest(ue,V);return Object.keys(be).length>0?JSON.stringify(be):void 0},[V]),ne=j.useMemo(()=>c.givensToParams(_,V),[_,V]),J=j.useRef(0),H=j.useRef(null),Q=j.useRef(null),re=j.useRef(void 0);j.useEffect(()=>()=>{H.current?.abort(),Q.current=null,clearTimeout(re.current?.timer),re.current=void 0},[]);const z=j.useCallback(async(ue=new Map)=>{if(!u.notebookCells)return;const be=++J.current;H.current?.abort();const Me=new AbortController;H.current=Me,k(u.notebookCells.map(te=>({...te}))),S(!0),R(null);try{const te=[];for(let he=0;he<u.notebookCells.length;he++){const we=u.notebookCells[he];if(!uy(we))continue;const ge=he,pe=async()=>{try{const ye=await d({cell:we,givens:ue,declaredTypes:V,signal:Me.signal});if(J.current!==be)return;const Le=ye.result;k(st=>{const ce=[...st];return ce[ge]||(ce[ge]={...we}),ce[ge]={...ce[ge],result:Le},ce})}catch(ye){if(Me.signal.aborted||J.current!==be)return;B.emit({type:"report.query_failed",tile:ge,category:c.failureCategory(ye)}),B.listening||console.error(`Error executing cell ${ge}:`,ye);const Le=gy(ye);k(st=>{const ce=[...st];return ce[ge]||(ce[ge]={...we}),ce[ge]={...ce[ge],error:Le},ce})}};te.push(pe)}const K=[];for(const he of te){const we=he().then(()=>{K.splice(K.indexOf(we),1)});K.push(we),K.length>=py&&await Promise.race(K)}await Promise.all(K)}catch(te){if(Me.signal.aborted||J.current!==be)return;B.emit({type:"report.query_failed",category:c.failureCategory(te)}),B.listening||console.error("Error executing notebook cells:",te),R(te)}finally{J.current===be&&(S(!1),H.current=null)}},[u,V,d,B]),oe=j.useRef(0),se=j.useRef(void 0);se.current!==u&&(se.current=u,oe.current+=1);const ie=oe.current;j.useEffect(()=>{const ue=`${e}|${ie}`,be=`${ue}|${Z(_)??""}`;M.current!==void 0&&M.current!==ue&&(H.current?.abort(),H.current=null),M.current=ue;const Me=my({ready:!!u.notebookCells,lastRunKey:Q.current,pendingKey:re.current?.key,runKey:be,documentKey:ue});if(Me.cancelPending&&(clearTimeout(re.current?.timer),re.current=void 0,O(!1)),Me.dispatch==="none")return;const te=()=>{re.current=void 0,O(!1),Q.current=be,z(_)};if(Me.dispatch==="now"){te();return}O(!0),re.current={key:be,timer:setTimeout(te,c.GIVEN_SETTLE_MS)}},[u,ie,e,_,Z,z]);const De=v.length>0?v:u.notebookCells||[],de=0;return t.jsxs(c.ReportPage,{layout:"linear",header:a?t.jsx(p.Stack,{direction:"row",sx:{justifyContent:"flex-end"},children:a}):null,controls:D.panel.givens.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...D.panel,layout:"bar"})}):void 0,children:[De.map((ue,be)=>t.jsx(fy,{cell:ue,showCopyLink:be===de,resourceUri:e,maxResultSize:n,isExecuting:C,givens:ne,givenSpecs:P,pendingRerun:T,onNavigate:i,onDrillNavigate:l,onDrillSelf:P.length>0?W:void 0,canDrillSelf:$},be)),E&&t.jsx(c.ApiErrorDisplay,{error:{message:E.message,status:500,name:"ExecutionError"},context:"Notebook Execution"})]})}function xy({environmentName:e,packageName:n,versionId:r,path:o,notebook:i,...l}){const{apiClients:a,server:u}=q.useServer(),d=j.useCallback(async({cell:h,givens:y,declaredTypes:b,signal:x})=>{const v=h.runQuery;if(v===void 0)return{};x.throwIfAborted();const k=c.givensToRequest(y,b),C={environmentName:e,packageName:n,versionId:r,modelPath:o,query:v,givens:Object.keys(k).length>0?k:void 0},S=[...c.queryResultKey(C),u],T=()=>q.globalQueryClient.fetchQuery({queryKey:S,queryFn:({signal:M})=>c.requestQueryResult(a,C,M),...q.CHART_RESULT_QUERY_OPTIONS}),O=()=>void q.globalQueryClient.cancelQueries({queryKey:S,exact:!0});x.addEventListener("abort",O,{once:!0});try{let M;try{M=await T()}catch(E){if(!mt.isCancelledError(E)||x.aborted)throw E;M=await T()}return{result:M.data.result}}finally{x.removeEventListener("abort",O)}},[a,u,e,n,o,r]);return t.jsx(yy,{...l,resourceUri:c.encodeResourceUri({environmentName:e,packageName:n,modelPath:o,versionId:r}),notebook:i,runCell:d})}function ic({resourceUri:e,path:n,givens:r,onGivensChange:o,onNavigate:i,onLinkNavigate:l,height:a,maxResultSize:u,onEvent:d,chrome:h,manifestStaleTime:y,actions:b,rowsActions:x}){const v=c.parseResourceUri(e),{apiClients:k}=q.useServer(),C=v.environmentName??"",S=v.packageName??"",T=v.versionId,O=!!v.environmentName&&!!v.packageName,{data:M,isSuccess:E,isError:R,error:P}=c.useQueryWithApiError({...c.reportQueryOptions(k,{environmentName:C,packageName:S,path:n,versionId:T},y),enabled:O&&n!==""}),F=M?.layout,B=c.useReportEmitter({path:n,layout:F},d),D=`${e}|${n}`,_=j.useRef(void 0),V=j.useRef({key:D,at:c.now()});V.current.key!==D&&(V.current={key:D,at:c.now()}),j.useEffect(()=>{_.current!==D&&(O?R?(_.current=D,B.emit({type:"report.load_failed",surface:"view",category:c.failureCategory(P)})):E&&M&&(_.current=D,B.emit({type:"report.opened",surface:"view",from:"package",tiles:M.tiles?.length??M.notebook?.notebookCells?.filter(ne=>ne.type==="code"&&ne.runQuery!==void 0).length??0,durationMs:c.now()-V.current.at})):(_.current=D,B.emit({type:"report.load_failed",surface:"view",category:"invalid"})))},[D,O,R,P,E,M,B]);const $=j.useCallback((ne,J)=>{const H=i?.(ne,J);H&&B.emit({type:"report.drill",to:"report",outcome:H})},[i,B]),W=i?$:void 0;if(!O)return t.jsxs(p.Alert,{severity:"error",children:["A report resource URI must name an environment and a package. Received: ",e]});if(R)return t.jsx(c.ApiErrorDisplay,{context:`${C} > ${S} > ${n}`,error:P});if(!E||!M)return t.jsx(c.Loading,{text:c.LOADING_COPY.opening("report")});const Z=M.notebook?.format==="malloynb"?t.jsx(xy,{environmentName:C,packageName:S,versionId:T,path:n,notebook:M.notebook,givens:r,onGivensChange:o,onNavigate:l,onDrillNavigate:W,maxResultSize:u,...b!==void 0?{actions:b}:{}}):t.jsx(Ga,{manifest:M,environmentName:C,packageName:S,versionId:T,documentName:n,givens:r,onGivensChange:o,onNavigate:W,...l?{onLinkNavigate:l}:{},height:a,maxResultSize:u,chrome:h,...b!==void 0?{actions:b}:{},...x!==void 0?{rowsActions:x}:{}});return t.jsx(c.ReportEventsContext.Provider,{value:B,children:Z})}function ac({open:e,layout:n,kind:r,allowLayoutChange:o,allowKindChange:i,environmentName:l,packageName:a,versionId:u,models:d,modelsLoading:h=!1,modelsError:y,onRetryModels:b,target:x,savedAs:v,onClose:k,onCreated:C,onEvent:S}){const T=n??(r?c.layoutOfKind(r):"linear"),O=o??i??!0,[M,E]=j.useState(T),[R,P]=j.useState(void 0),[F,B]=j.useState(""),[D,_]=j.useState(""),[V,$]=j.useState(""),W=j.useRef(null),[Z,ne]=j.useState(""),[J,H]=j.useState(!1),[Q,re]=j.useState(!1),[z,oe]=j.useState(!1),[se,ie]=j.useState(void 0),De=y!=null,{choices:de,isLoading:ue,isSuccess:be,failed:Me,retry:te,canRetry:K}=c.useDocumentChoices({environmentName:l,packageName:a,...u!==void 0?{versionId:u}:{},models:d,enabled:e&&d.length>0}),he=j.useMemo(()=>de.get(F)??[],[de,F]),we=j.useMemo(()=>new Map([...de.entries()].flatMap(([me,He])=>He.map(vt=>[Ps(me,vt.source,vt.view),{model:me,source:vt.source,view:vt.view}]))),[de]),ge=j.useMemo(()=>{const me=de.size>1;return[...de.entries()].flatMap(([He,vt])=>{const Ce=new Map;for(const Re of vt)Ce.set(Re.source,[...Ce.get(Re.source)??[],Re]);return[...Ce.entries()].map(([Re,Ie])=>({key:`${He}::${Re}`,label:Re,ariaLabel:`${Re} in ${He}`,...me||Ie[0]?.sourceDescription?{detail:[me?He:void 0,Ie[0]?.sourceDescription].filter(Boolean).join(" · ")}:{},entries:Ie.map(We=>({key:Ps(He,We.source,We.view),name:We.view,title:We.description??c.readableName(We.view),...We.chart?{chart:We.chart}:{}}))}))})},[de]),pe=me=>{const He=we.get(me);He&&(B(He.model),_(`${He.source}::${He.view}`))},ye=he.find(me=>`${me.source}::${me.view}`===D),Le=ye?Ps(F,ye.source,ye.view):void 0,st=vy(ye,250);j.useEffect(()=>{e&&E(T)},[e,T]),j.useEffect(()=>{if(!e)return;const me=[...de.keys()];F===""&&me.length>0&&B(me[0])},[e,de,F]),j.useEffect(()=>{!e||he.length===0||D!==""||_(`${he[0].source}::${he[0].view}`)},[e,he,D]),j.useEffect(()=>{!e||J||ye===void 0||ne(c.readableName(ye.view))},[e,J,ye]),j.useEffect(()=>{e||(B(""),_(""),$(""),ne(""),H(!1),P(void 0),re(!1),ie(void 0))},[e]);const ce=j.useMemo(()=>{if(Z.trim()!=="")for(let me=1;me<=c.MAX_SLUG_ATTEMPTS;me++){const He=c.reportPathForTitle(Z,me);if(!x.existing?.includes(He))return He}},[Z,x]),Y=R?.trim(),ae=Y===void 0||Y===""?void 0:Y.endsWith(".malloy")?Y:`${Y}.malloy`,Fe=ae??ce,Ve=ae===void 0?void 0:c.reportPathProblem(ae)??(x.existing?.includes(ae)?`${ae} already exists; choose another location.`:void 0),Ee=(ye===void 0?void 0:c.newDocumentProblem({title:Z,modelPath:F,source:ye.source,view:ye.view}))??(Z.trim()!==""&&Fe===void 0?"No free file name for this title; choose another.":void 0),at=Ee!==void 0&&(Q||Z.trim()!==""),yt=h||ue,{theme:xt}=q.usePublisherTheme(),Ot=xt.ui,pt=c.edgeColor(xt.cardBorder),Ye=de.size===0&&(De||Me.length>0),fe=yt?"Loading the model":Ye?"Couldn't read the model to start from":de.size===0?"Nothing in the model to start from yet":ye===void 0?"Pick what to start from":void 0,Ke="report",ze=z?`Creating ${Ke}…`:`Create ${Ke}`,lt=D!==""&&ye===void 0&&he.length>0,ct=async()=>{if(!(fe!==void 0||ye===void 0||z)){if(Ee!==void 0||Ve!==void 0){re(!0);return}oe(!0),ie(void 0);try{const me=await c.createDocument({layout:M,...ae!==void 0?{path:ae}:{},document:{title:Z,modelPath:F,source:ye.source,view:ye.view},target:x,...S?{onEvent:S}:{}});C(me)}catch(me){const He=me.response?.data?.message;ie(He??(me instanceof Error?me.message:String(me)))}finally{oe(!1)}}},Qe=me=>t.jsx(p.Button,{color:"inherit",size:"small",onClick:me,children:"Retry"});return t.jsx(c.AppDialog,{className:`${c.reportClasses.dialog} ${c.reportClasses.newReportDialog}`,maxWidth:"md",initialFocus:W,open:e,onClose:z?()=>{}:k,title:`New ${Ke}`,description:"A report is a Malloy file in the package that lays out text and queries. Pick what its first query shows; the rest is the builder.",actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{onClick:k,disabled:z,children:"Cancel"}),t.jsx(p.Tooltip,{title:z?"":fe??"",children:t.jsx("span",{children:t.jsx(p.Button,{variant:"contained",disabled:z||fe!==void 0,"aria-label":!z&&fe!==void 0?`${ze}: ${fe}`:ze,onClick:()=>void ct(),children:ze})})})]}),children:t.jsxs(p.Stack,{sx:{gap:1.5},children:[De?t.jsx(p.Alert,{severity:"error",action:b&&so.canRetryRequest(y)?Qe(b):void 0,children:"Couldn't read this package's models, so no view is listed to start from."}):d.length===0?!h&&t.jsxs(p.Alert,{severity:"info",children:["This package has no models yet. Add a .malloy file that declares a source with a view, then create a ",Ke," from it."]}):Me.length>0?t.jsxs(p.Alert,{severity:"warning",action:K?Qe(te):void 0,children:["Couldn't read ",Me.join(", "),", so nothing from"," ",Me.length===1?"it":"them"," is listed."]}):be&&de.size===0&&t.jsxs(p.Alert,{severity:"info",children:["A ",Ke," starts from a view of a source, and no model in this package declares one yet. Add a view to a source in a model file and this list fills in."]}),t.jsxs(p.Box,{sx:{mx:-3,mb:-1,borderTop:`1px solid ${pt}`,borderBottom:`1px solid ${pt}`,display:"grid",gridTemplateColumns:{xs:"1fr",md:"320px minmax(0, 1fr)"},height:{md:500}},children:[t.jsx(p.Box,{sx:{display:"flex",flexDirection:"column",minHeight:0,borderRight:{md:`1px solid ${pt}`},maxHeight:{xs:280,md:"none"}},children:t.jsx(c.ViewPicker,{groups:ge,query:V,onQuery:$,picked:Le,onPick:pe,onTake:me=>{pe(me)},searchRef:W,disabled:z,empty:t.jsx(p.Typography,{variant:"body2",sx:{color:"text.secondary",p:2},children:yt?"Reading the package's models…":"Nothing to start from."})})}),t.jsxs(p.Box,{sx:me=>({p:2.5,display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto",bgcolor:`color-mix(in srgb, ${me.palette.text.primary} 3%, ${me.palette.background.paper})`}),children:[O&&t.jsxs(p.Box,{children:[t.jsx(Ea,{children:"Layout"}),t.jsx(p.Box,{role:"radiogroup","aria-label":"Layout",sx:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:1},children:["linear","grid"].map(me=>t.jsx(Sy,{layout:me,checked:M===me,disabled:z,onPick:()=>E(me)},me))}),t.jsx(p.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"Switch it any time in the builder."})]}),t.jsxs(p.Box,{children:[t.jsx(Ea,{children:"First query"}),t.jsx(p.Box,{role:"region","aria-label":"Preview",sx:me=>({height:200,display:"flex",position:"relative",overflow:"hidden",borderRadius:Ot.radius.tile,border:`1px solid ${pt}`,bgcolor:me.palette.background.paper,"&::after":{content:'""',position:"absolute",left:0,right:0,bottom:0,height:40,pointerEvents:"none",background:`linear-gradient(to bottom, transparent, ${me.palette.background.paper})`}}),children:ye&&st?t.jsx(p.Box,{sx:{flex:1,minWidth:0,px:2,pt:1.5},children:t.jsx(c.DashboardTile,{environmentName:l,packageName:a,...u!==void 0?{versionId:u}:{},modelPath:F,tile:`${st.source} -> ${st.view}`,label:Z.trim()||c.readableName(st.view),borderless:!0,givens:by,declaredTypes:wy,height:180})}):t.jsx(p.Typography,{variant:"body2",sx:{color:"text.secondary",m:"auto"},children:lt?"What you picked is no longer in this model; pick something else.":"Pick what to start from."})}),t.jsx(p.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"More are added in the builder."})]}),t.jsx(p.TextField,{size:"small",label:"Title",value:Z,disabled:z,onChange:me=>{H(!0),ne(me.target.value)},InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Report title"},error:at,helperText:at?Ee:x.route==="package"?"Names the file too, unless you type a location.":v??`Saved as a new ${Ke} in the host's store, and opened in the builder.`}),t.jsx(p.TextField,{size:"small",label:"Location",value:R??ce??"",placeholder:"report.malloy",disabled:z,onChange:me=>P(me.target.value),InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Location"},error:Ve!==void 0,helperText:Ve??(Fe?`Written as ${Fe} in the package, and opened in the builder.`:"A path in the package; the package root by default.")}),se&&t.jsx(p.Alert,{severity:"error",children:se})]})]})]})})}function vy(e,n){const[r,o]=j.useState(void 0);return j.useEffect(()=>{const i=window.setTimeout(()=>o(e),n);return()=>window.clearTimeout(i)},[e,n]),r}const Ps=(e,n,r)=>`${e}::${n}::${r}`,by=new Map,wy=new Map;function Ea({children:e}){const n=q.usePublisherTheme().theme.ui;return t.jsx(p.Typography,{component:"div",sx:{...n.type.label,color:"text.secondary",mb:.75},children:e})}function Sy({layout:e,checked:n,disabled:r,onPick:o}){const{theme:i}=q.usePublisherTheme(),l=i.ui,a=c.edgeColor(i.cardBorder),u=n?i.accent:"currentColor";return t.jsxs(p.ButtonBase,{role:"radio","aria-checked":n,"aria-label":e==="linear"?"Linear":"Grid",disabled:r,onClick:o,sx:d=>({justifyContent:"flex-start",gap:1.25,px:1.25,py:1,borderRadius:l.radius.tile,border:`1px solid ${n?i.accent:a}`,boxShadow:n?`0 0 0 1px ${i.accent}`:"none",bgcolor:n?`color-mix(in srgb, ${i.accent} 6%, ${d.palette.background.paper})`:d.palette.background.paper,color:d.palette.text.secondary,textAlign:"left"}),children:[t.jsx("svg",{width:"34",height:"26",viewBox:"0 0 34 26","aria-hidden":!0,children:e==="linear"?t.jsxs("g",{fill:"none",stroke:u,strokeWidth:"1.5",children:[t.jsx("rect",{x:"3",y:"2",width:"28",height:"7",rx:"1.5"}),t.jsx("rect",{x:"3",y:"12",width:"28",height:"5",rx:"1.5"}),t.jsx("path",{d:"M5 21.5h20",strokeLinecap:"round"})]}):t.jsxs("g",{fill:"none",stroke:u,strokeWidth:"1.5",children:[t.jsx("rect",{x:"2",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"18",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"2",y:"14",width:"30",height:"10",rx:"1.5"})]})}),t.jsxs(p.Box,{children:[t.jsx(p.Box,{sx:{...l.type.control,fontWeight:n?l.type.label.fontWeight:500,color:n?i.accent:"text.primary"},children:e==="linear"?"Linear":"Grid"}),t.jsx(p.Box,{sx:{...l.type.caption,color:"text.secondary"},children:e==="linear"?"Read top to bottom":"Tiles side by side"})]})]})}const ky=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),Cy=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),jy=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),Ty=c.createSvgIcon(t.jsx("path",{d:"M20 10V8h-4V4h-2v4h-4V4H8v4H4v2h4v4H4v2h4v4h2v-4h4v4h2v-4h4v-2h-4v-4zm-6 4h-4v-4h4z"})),lc={dashboard:q.PALETTE.blue,report:q.PALETTE.violet,model:q.PALETTE.cyan,dataApp:q.PALETTE.pink,data:q.PALETTE.lime,materialization:q.PALETTE.amber,agent:q.PALETTE.red};function cc({type:e,size:n=18,sx:r,...o}){return t.jsx(c.SvgIcon,{...o,viewBox:"0 0 24 24",sx:{width:n,height:n,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",...r},children:Oy[e]()})}const Oy={report:My,model:Ey,data:Iy,materialization:Dy,dataApp:Ay,dashboard:$y,agent:Fy};function My(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M14 3 H6 a2 2 0 0 0 -2 2 v14 a2 2 0 0 0 2 2 h12 a2 2 0 0 0 2 -2 V9 z"}),t.jsx("path",{d:"M14 3 v4 a2 2 0 0 0 2 2 h4"}),t.jsx("path",{d:"M8 17 v-3"}),t.jsx("path",{d:"M12 17 v-6"}),t.jsx("path",{d:"M16 17 v-4"})]})}function Ey(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L4 7 v10 l8 4 l8 -4 V7 z"}),t.jsx("path",{d:"M4 7 l8 4 l8 -4"}),t.jsx("path",{d:"M12 11 v10"})]})}function Iy(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M9.5 3.5 V20.5"})]})}function Dy(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L21 7.5 L12 12 L3 7.5 Z"}),t.jsx("path",{d:"M3 12 L12 16.5 L21 12"}),t.jsx("path",{d:"M3 16.5 L12 21 L21 16.5"})]})}function $y(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M12 9.5 V20.5"}),t.jsx("path",{d:"M12 15 H20.5"})]})}function Fy(){return t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:"12",cy:"8",r:"3.5"}),t.jsx("path",{d:"M5 20 a7 7 0 0 1 14 0"})]})}function Ay(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M7 13.5 H17"}),t.jsx("path",{d:"M7 16.5 H13"})]})}function uc(e){return e>=1e9?`${(e/1e9).toFixed(1)} B rows`:e>=1e6?`${(e/1e6).toFixed(1)} M rows`:e>=1e3?`${(e/1e3).toFixed(1)} K rows`:`${e} rows`}const Ry=12;function Ly(e){const n=e?.trim().toLowerCase()??"";if(n.startsWith("array")||n.endsWith("[]"))return Cy;if(n.startsWith("record")||n.startsWith("struct"))return jy;switch(n.split(/[\s(<]/)[0]){case"string":return ky;case"number":return Ty;case"date":return Rl;case"timestamp":case"timestamptz":return _l;case"boolean":return Nl;default:return Pl}}function _y({column:e}){const n=Ly(e.type);return t.jsxs(p.Box,{component:"li",sx:r=>({display:"flex",alignItems:"center",gap:1.25,px:1,py:.625,borderRadius:1,transition:"background-color 0.1s","&:hover":{backgroundColor:r.palette.mode==="dark"?"rgba(255, 255, 255, 0.06)":r.palette.grey[100]}}),children:[t.jsx(n,{"aria-hidden":!0,sx:{fontSize:18,color:"primary.main",flexShrink:0}}),t.jsxs(p.Box,{sx:{display:"flex",alignItems:"baseline",gap:1,minWidth:0,flex:1},children:[t.jsx(p.Typography,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.8125rem",fontWeight:500,color:"text.primary",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.type&&t.jsx(p.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{flexShrink:0,maxWidth:"50%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.type})]})]})}function Ny({database:e,onClose:n}){const r=e!==null,[o,i]=j.useState(e);e!==null&&e!==o&&i(e);const[l,a]=j.useState(""),[u,d]=j.useState(o?.path);u!==o?.path&&(d(o?.path),a(""));const h=j.useId(),y=o?.path??"",b=y.split("/").pop()||y,x=y.slice(0,Math.max(0,y.length-b.length-1)),v=o?.info?.rowCount,k=[x,v===void 0?null:uc(v)].filter(Boolean).join(" · "),C=j.useMemo(()=>o?.info?.columns??[],[o]),S=l.trim().toLowerCase(),T=j.useMemo(()=>S?C.filter(O=>O.name?.toLowerCase().includes(S)||O.type?.toLowerCase().includes(S)):C,[C,S]);return t.jsxs(c.AppDialog,{open:r,onClose:n,showClose:!0,title:t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{minWidth:0},children:[t.jsx(p.Box,{"aria-hidden":!0,sx:{width:32,height:32,borderRadius:1,bgcolor:lc.data,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(cc,{type:"data",size:18})}),t.jsxs(p.Box,{sx:{minWidth:0},children:[t.jsx(p.Typography,{component:"span",noWrap:!0,title:y,sx:{display:"block",fontFamily:q.MONO_FONT_FAMILY,fontSize:"1rem",fontWeight:600,letterSpacing:0,lineHeight:1.4},children:b||"Columns"}),k&&t.jsx(p.Typography,{component:"span",variant:"caption",color:"text.secondary",noWrap:!0,sx:{display:"block",lineHeight:1.4},children:k})]})]}),children:[o?.error&&t.jsx(p.Alert,{severity:"error",variant:"outlined",children:o.error}),o&&!o.error&&t.jsxs(p.Box,{component:"section","aria-labelledby":h,sx:{display:"flex",flexDirection:"column",border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",mb:2},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{px:1.5,py:1,minHeight:44,borderBottom:"1px solid",borderColor:"divider"},children:[t.jsxs(p.Typography,{id:h,component:"h3",sx:{fontSize:"0.875rem",fontWeight:600},children:["Columns",t.jsxs(p.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{ml:.75,fontVariantNumeric:"tabular-nums"},children:["· ",S?`${T.length} of `:"",C.length]})]}),C.length>Ry&&t.jsx(p.InputBase,{value:l,onChange:O=>a(O.target.value),placeholder:"Filter columns",inputProps:{"aria-label":"Filter columns"},startAdornment:t.jsx(p.InputAdornment,{position:"start",children:t.jsx(c.SearchIcon,{sx:{fontSize:16,color:"text.secondary"}})}),sx:{ml:"auto !important",width:200,fontSize:"0.8125rem",px:1,py:.25,border:"1px solid",borderColor:"divider",borderRadius:1.5,"&.Mui-focused":{borderColor:"primary.main"}}})]}),t.jsx(p.Box,{sx:{overflowY:"auto",maxHeight:420,px:.75,py:.75},children:T.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic",px:1,py:1},children:S?"No columns match":"No columns"}):t.jsx(p.Box,{component:"ul","aria-labelledby":h,sx:{listStyle:"none",m:0,p:0},children:T.map((O,M)=>t.jsx(_y,{column:O},`${O.name}-${M}`))})})]})]})}const Do=(e,n,r)=>["packageVersions",e,n,r];async function dc(e,n,r){try{return(await e.versions.listPackageVersions(n,r)).data}catch(o){const i=o?.response?.status;if(i===404||i===501)return[];throw o}}function hc(e,n,r={}){const{apiClients:o,server:i}=q.useServer(),l=(r.enabled??!0)&&e!==""&&n!=="",a=mt.useQuery({queryKey:Do(e,n,i),queryFn:()=>dc(o,e,n),enabled:l,staleTime:3e4,retry:!1}),{refetch:u}=a,d=j.useCallback(()=>void u(),[u]),h=a.data??[];return{versions:h,latest:h.find(y=>y.latest)?.id,isPending:l&&a.isPending,isError:l&&a.isError,refetch:d}}function Py(e,n){const{apiClients:r,server:o}=q.useServer(),i=mt.useQueryClient();return j.useCallback(()=>i.fetchQuery({queryKey:Do(e,n,o),queryFn:()=>dc(r,e,n),staleTime:0,retry:!1}),[i,r,o,e,n])}function fc(e,n){const r=mt.useQueryClient();return j.useCallback(()=>r.invalidateQueries({predicate:o=>o.queryKey[1]===e&&o.queryKey[2]===n}),[r,e,n])}const zy=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.81.97H5.44zM5 19V8h14v11zm8.45-9h-2.9v3H8l4 4 4-4h-2.55z"})),Wy=c.createSvgIcon(t.jsx("path",{d:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"})),qy=c.createSvgIcon(t.jsx("path",{d:"M14 4v5c0 1.12.37 2.16 1 3H9c.65-.86 1-1.9 1-3V4zm3-2H7c-.55 0-1 .45-1 1s.45 1 1 1h1v5c0 1.66-1.34 3-3 3v2h5.97v7l1 1 1-1v-7H19v-2c-1.66 0-3-1.34-3-3V4h1c.55 0 1-.45 1-1s-.45-1-1-1"})),By=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.83 1H5.42zM5 19V8h14v11zm3-5h2.55v3h2.9v-3H16l-4-4z"})),dr=e=>{const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error?e.message:"Unknown error"},Vy=e=>{const n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})},An=e=>e.archiveStatus==="archive",zs="Tables built for this version alone (under scope: version) are dropped.";function Ia(e,n){const r=!An(e)&&n.filter(i=>!An(i)).length<=1,o=n.length<=1;return{archive:e.latest?"The latest version can't be archived":r?"The last version in service can't be archived":void 0,delete:o?void 0:e.latest?"Pin another version as latest first":r?"The last version in service; delete the archived versions first":void 0}}function mc({environmentName:e,packageName:n,versions:r,selectedVersionId:o,onSelectVersion:i,onReplaceVersion:l,onPackageDeleted:a,canManage:u}){const{apiClients:d}=q.useServer(),h=mt.useQueryClient(),y=fc(e,n),b=Py(e,n),[x,v]=j.useState(null),[k,C]=j.useState(null),[S,T]=j.useState(null),[O,M]=j.useState(null),[E,R]=j.useState(null),[P,F]=j.useState(null),B=j.useRef(null),D=j.useRef(null),_=j.useRef(null),V=j.useRef(new Map),$=r.find(K=>K.latest)?.id,W=o??$,Z=()=>Promise.all([y(),h.invalidateQueries({queryKey:["packages",e]})]),ne=async(K,he)=>{const we=he??await b().catch(()=>{});if(we===void 0)return;const ge=we.find(ye=>ye.latest)?.id,pe=ge??we.find(ye=>ye.id!==K&&!An(ye))?.id;pe!==void 0&&(l?l(pe===ge?void 0:pe):i(pe))},J=mt.useMutation({mutationFn:K=>d.versions.setPackageLatestVersion(e,n,{version:K}),onSuccess:async()=>{T(null),await Z()},onError:()=>void Z()}),H=mt.useMutation({mutationFn:({id:K,archiveStatus:he})=>d.versions.updatePackageVersion(e,n,K,{archiveStatus:he}),onSuccess:async(K,{id:he,archiveStatus:we})=>{M(null),we==="archive"&&he===W&&await ne(he),await Z()},onError:(K,{id:he,archiveStatus:we})=>{we==="unarchive"&&F(`Couldn't unarchive v${he}: ${dr(K)}`),Z()}}),Q=H.isPending?H.variables?.id:void 0,re=mt.useMutation({mutationFn:({id:K})=>d.versions.deletePackageVersion(e,n,K),onSuccess:async(K,{id:he,read:we})=>{R(null);const pe=await b().catch(()=>{})??we.filter(ye=>ye.id!==he);if(pe.length===0){await h.invalidateQueries({queryKey:["packages",e]}),a?.();return}he===W&&await ne(he,pe),await Z()},onError:()=>void Z()}),z=()=>C(null),oe=k?Ia(k.version,r):{},se=k!==null&&!An(k.version)&&k.version.latest&&oe.archive!==void 0&&oe.delete!==void 0,ie=E!==null&&E.versions===void 0,De=E?.versions!==void 0&&E.versions.length<=1,de=E?.versions!==void 0?Ia(E.version,E.versions).delete:void 0,ue=async K=>{z(),v(null),re.reset(),R({version:K});const he=pe=>R(ye=>ye!==null&&ye.version.id===K.id&&ye.versions===void 0?pe:ye);let we;try{we=await b()}catch(pe){he(null),F(`Couldn't check v${K.id} before deleting it: ${dr(pe)}`);return}const ge=we.find(pe=>pe.id===K.id);if(ge===void 0){he(null),F(`v${K.id} is no longer a version of ${n}.`),Z();return}he({version:ge,versions:we})},be=(K,he)=>{!u||Q===K.id||C({version:K,anchor:V.current.get(K.id)??he})},Me=(K,he)=>{const we=K.key==="ArrowRight"||K.key==="ContextMenu"||K.key==="F10"&&K.shiftKey;!u||!we||(K.preventDefault(),K.stopPropagation(),be(he,K.currentTarget))},te=k&&t.jsxs(p.MenuItem,{disabled:oe.delete!==void 0,onClick:()=>void ue(k.version),children:[t.jsx(p.ListItemIcon,{children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Delete version",secondary:oe.delete})]},"delete");return t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{size:"small",variant:"outlined",endIcon:t.jsx(Ll,{}),"aria-label":W?`Version v${W}, change version`:"Select a version","aria-haspopup":"menu",onClick:K=>v(K.currentTarget),sx:{borderRadius:999,textTransform:"none",fontWeight:500,px:1.5,minWidth:0,whiteSpace:"nowrap"},children:W?`v${W}`:"Select a version"}),t.jsx(p.Menu,{anchorEl:x,open:x!==null,onClose:()=>v(null),slotProps:{paper:{sx:{minWidth:320,maxWidth:400,mt:1,borderRadius:3}},list:{"aria-label":`Versions of ${n}`,disabledItemsFocusable:!0}},children:r.map(K=>{const he=K.id===W,we=An(K),ge=[we?"Archived":void 0,Vy(K.createdAt),K.gitCommitSha?K.gitCommitSha.slice(0,7):void 0].filter(Boolean).join(" · ");return t.jsxs(p.MenuItem,{"aria-current":he?"true":void 0,"aria-disabled":we&&!u?"true":void 0,"aria-haspopup":u?"menu":void 0,"data-testid":"version-row",onKeyDown:pe=>Me(pe,K),onClick:pe=>{if(we){be(K,pe.currentTarget);return}he||(v(null),i(K.id,pe))},sx:pe=>({gap:1,borderLeft:"3px solid",borderLeftColor:he?pe.palette.primary.main:"transparent",backgroundColor:he?p.alpha(pe.palette.primary.main,.04):void 0,cursor:he||we&&!u?"default":"pointer"}),children:[t.jsx(p.ListItemText,{primary:K.id,secondary:ge,sx:{opacity:we?.6:1},slotProps:{primary:{sx:{fontWeight:he?600:400}}}}),K.latest&&t.jsx(p.Chip,{size:"small",label:"Latest",color:"info",variant:"outlined",sx:{height:20,fontSize:11,fontWeight:600}}),u&&t.jsx(p.Tooltip,{title:Q===K.id?"Updating this version…":"",children:t.jsx("span",{children:t.jsx(p.IconButton,{ref:pe=>{pe?V.current.set(K.id,pe):V.current.delete(K.id)},size:"small","aria-label":`More actions for version ${K.id}`,"aria-haspopup":"menu",disabled:Q===K.id,onClick:pe=>{pe.stopPropagation(),C({version:K,anchor:pe.currentTarget})},children:t.jsx(Wy,{fontSize:"small"})})})})]},K.id)})}),t.jsx(p.Menu,{anchorEl:k?.anchor??null,open:k!==null,onClose:z,slotProps:{list:{"aria-label":k?`Actions for version ${k.version.id}`:void 0,disabledItemsFocusable:!0,autoFocus:se}},children:k&&An(k.version)?[t.jsxs(p.MenuItem,{onClick:()=>{const{id:K}=k.version;z(),H.mutate({id:K,archiveStatus:"unarchive"})},children:[t.jsx(p.ListItemIcon,{children:t.jsx(By,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Unarchive"})]},"unarchive"),t.jsx(p.Divider,{},"divider"),te]:k&&[t.jsxs(p.MenuItem,{disabled:k.version.latest,onClick:()=>{T(k.version),J.reset(),z(),v(null)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(qy,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Pin as latest",secondary:k.version.latest?"Already the latest version":void 0})]},"pin-latest"),t.jsxs(p.MenuItem,{disabled:oe.archive!==void 0,onClick:()=>{M(k.version),H.reset(),z(),v(null)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(zy,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Archive",secondary:oe.archive})]},"archive"),t.jsx(p.Divider,{},"divider"),te]}),t.jsx(c.AppDialog,{open:S!==null,onClose:()=>{J.isPending||T(null)},title:S?`Pin v${S.id} as latest`:"",description:S?`Requests that name no version will be served from v${S.id}.`:void 0,initialFocus:B,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:B,disabled:J.isPending,onClick:()=>T(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:J.isPending,onClick:()=>S&&J.mutate(S.id),children:"Pin as latest"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[$&&S&&$!==S.id&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:`The latest version is v${$} now. Links and requests that name a version keep answering as before.`}),J.isError&&S&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't pin v${S.id} as latest: ${dr(J.error)}`})]})}),t.jsx(c.AppDialog,{open:O!==null,onClose:()=>{H.isPending||M(null)},title:O?`Archive v${O.id}`:"",description:O?`v${O.id} stops being served and is unloaded. Its files stay, so it can be unarchived.`:void 0,initialFocus:D,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:D,disabled:H.isPending,onClick:()=>M(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:H.isPending,onClick:()=>O&&H.mutate({id:O.id,archiveStatus:"archive"}),children:"Archive"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:`${zs} Its scheduled builds stop, and once unarchived it serves live until it is built again.`}),H.isError&&O&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't archive v${O.id}: ${dr(H.error)}`})]})}),t.jsx(c.AppDialog,{open:E!==null,onClose:()=>{re.isPending||R(null)},title:E?`Delete v${E.version.id}`:"",initialFocus:_,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:_,disabled:re.isPending,onClick:()=>R(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",color:"error",loading:re.isPending,disabled:ie||de!==void 0,onClick:()=>E?.versions&&re.mutate({id:E.version.id,read:E.versions}),children:De?"Delete package":"Delete version"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[ie&&E&&t.jsx(p.Typography,{variant:"body2",children:`Checking ${n}'s versions before deleting v${E.version.id}…`}),E&&!ie&&t.jsx(p.Typography,{variant:"body2",children:De?`v${E.version.id} is the only version of ${n}, so deleting it deletes the package. ${zs} This cannot be undone.`:`v${E.version.id} stops being served and its files are removed. ${zs} Links that name it stop working, and this cannot be undone.`}),de!==void 0&&E&&t.jsx(p.Alert,{severity:"warning",role:"alert",children:`v${E.version.id} can't be deleted now: ${de}.`}),re.isError&&E&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't delete v${E.version.id}: ${dr(re.error)}`})]})}),t.jsx(p.Snackbar,{open:P!==null,autoHideDuration:8e3,onClose:()=>F(null),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:t.jsx(p.Box,{children:t.jsx(p.Alert,{severity:"error",variant:"filled",onClose:()=>F(null),children:P})})})]})}const Hy="README.malloynb",Uy=e=>!!e&&!e.includes("/")&&c.documentSlug(e)?.toLowerCase()==="readme";function Gy({onClickPackageFile:e,onOpenDocument:n,resourceUri:r,onEvent:o,onSelectVersion:i,onReplaceVersion:l}){const{apiClients:a,server:u,mutable:d}=q.useServer(),h=mt.useQueryClient(),y=e??(Y=>{window.location.href=Y}),{environmentName:b,packageName:x,versionId:v}=c.parseResourceUri(r),k=hc(b,x),{versions:C}=k,S=C.length>0,T=!S&&!k.isPending&&!k.isError,O=i??((Y,ae)=>y(`/${encodeURIComponent(b)}/${encodeURIComponent(x)}/${encodeURIComponent(Y)}`,ae)),M=n??((Y,ae)=>{const Fe=Y.mode==="edit"?c.reportEditRoute(b,x,Y.path):c.reportRoute(b,x,Y.path);ae?y(Fe,ae):y(Fe)}),[E,R]=j.useState(null),[P,F]=j.useState(!1),B=Fa(),D=c.useOptionalDocumentStorage()?.documentStorage,[_,V]=j.useState([]),[$,W]=j.useState({state:D?"pending":"ready"}),Z=j.useCallback(async()=>{if(!D)return;let Y;try{Y=await D.listWorkspaces(!1)}catch{W({state:"failed"});return}W({state:"ready",chosen:c.chooseWorkspace(Y)});const ae=[],Fe=c.draftKey(b,x,"");for(const Ve of Y.filter(St=>St.writeable))for(const St of await D.listDocuments(Ve))St.path.startsWith(Fe)&&ae.push({locator:St,where:Ve.description});V(ae)},[D,b,x]);j.useEffect(()=>{Z()},[Z]);const ne=Y=>Y.path.slice(c.draftKey(b,x,"").length),J=c.useQueryWithApiError({queryKey:["package",b,x,v],queryFn:()=>a.packages.getPackage(b,x,v,!1)}),H=c.useQueryWithApiError({queryKey:["package-agents",b,x,v],queryFn:()=>a.agents.listAgents(b,x,v)}),Q=c.useReportListing(b,x,v),re=c.useQueryWithApiError({queryKey:["models",b,x,v],queryFn:()=>a.models.listModels(b,x,v)}),z=c.useQueryWithApiError({queryKey:["databases",b,x,v],queryFn:()=>a.databases.listDatabases(b,x,v)}),se=c.useQueryWithApiError({queryKey:["data-apps",b,x,v],queryFn:async()=>{try{return await a.dataApps.listDataApps(b,x,v)}catch(Y){const ae=Y?.response?.status;if(ae===404||ae===void 0)return{data:[]};throw Y}}}).data?.data??[],ie=Q.reports.filter(Y=>!!Y.path),De=Ky(ie),de=new Set(ie.map(Y=>Y.path).filter(Y=>Y!==void 0)),ue=(re.data?.data??[]).slice().filter(Y=>!de.has(Y.path)).sort((Y,ae)=>Y.path.localeCompare(ae.path)),be=(z.data?.data??[]).slice().sort((Y,ae)=>Y.path.localeCompare(ae.path)),Me=$.state==="ready"?c.createRoute({authoritative:$.chosen?.authoritative===!0,mutable:d&&T,canStore:$.chosen?.writeable===!0,...v===void 0?{}:{versionId:v}}):void 0,te=Q.settled&&(re.isSuccess||re.isError),K=Me!==void 0&&te,he=K&&!B,we=j.useMemo(()=>{if(!K)return;const Y=[...Q.reports.flatMap(ae=>ae.path?[ae.path]:[]),...(re.data?.data??[]).flatMap(ae=>ae.path?[ae.path]:[])];if(Me==="storage"&&D&&$.state==="ready")return $.chosen?{route:Me,storage:D,workspace:$.chosen,environmentName:b,packageName:x,existing:Y}:void 0;if(Me==="package")return{route:Me,existing:Y,write:async(ae,Fe)=>{await a.models.updateModelSource(b,x,ae,{source:Fe})}}},[K,Me,D,$,b,x,a,Q.reports,re.data]),ge=J.data?.data?.description??"",pe=H.data?.data??[],ye=(ie.find(Y=>Y.path===Hy)??ie.find(Y=>Uy(Y.path)))?.path,Le=!Q.settled,st=S?t.jsx(mc,{environmentName:b,packageName:x,versions:C,...v!==void 0?{selectedVersionId:v}:{},onSelectVersion:O,...l?{onReplaceVersion:l}:{},onPackageDeleted:()=>y(`/${encodeURIComponent(b)}`),canManage:d}):null,ce=t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{mb:.5},children:[t.jsx(p.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),st]});if(J.isError){const Y=t.jsx(c.ApiErrorDisplay,{error:J.error,context:`${b} > ${x}`});return st?t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsx(p.Box,{sx:{mb:4},children:ce}),Y]}):Y}return t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(p.Box,{sx:{mb:4},children:[ce,ge&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:ge})]}),t.jsx(cy,{warnings:J.data?.data?.warnings}),k.isError&&t.jsx(p.Box,{sx:{mb:4},children:t.jsx(p.Alert,{severity:"warning",action:t.jsx(p.Button,{color:"inherit",size:"small",onClick:k.refetch,children:"Retry"}),children:"Could not read this package's versions, so nothing that changes it is offered until they load."})}),Le&&t.jsx(c.Loading,{text:"Loading package..."}),we&&t.jsx(ac,{open:P,layout:"linear",environmentName:b,packageName:x,...v!==void 0?{versionId:v}:{},models:ue.map(Y=>Y.path).filter(Y=>typeof Y=="string"&&Y.endsWith(".malloy")&&!de.has(Y)),modelsLoading:re.isPending,...re.isError?{modelsError:re.error}:{},onRetryModels:()=>void re.refetch(),target:we,...o?{onEvent:o}:{},onClose:()=>F(!1),onCreated:Y=>{F(!1),c.invalidateReportQueries(h),h.invalidateQueries({queryKey:["models"]}),M({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"edit"})}}),!Le&&t.jsxs(t.Fragment,{children:[Q.isError&&t.jsx(p.Box,{sx:{mb:4},children:t.jsx(p.Alert,{severity:"warning",action:t.jsx(p.Button,{color:"inherit",size:"small",onClick:()=>void Q.refetch(),children:"Retry"}),children:"Could not list this package's reports, so any it has are missing from this page."})}),(De.length>0||K)&&t.jsxs(Nt,{title:"Reports",count:De.length,...he?{action:t.jsx(c.AddButton,{label:"Report",onClick:()=>F(!0)})}:{},children:[De.length===0&&t.jsx(Ws,{label:"No reports yet",...he?{action:{label:"Add report",onClick:()=>F(!0)}}:{}}),De.map(Y=>t.jsx(Dn,{type:Y.layout==="grid"?"dashboard":"report",label:Y.label,rightLabel:Y.layout,...Y.secondary===void 0?{}:{description:Y.secondary},onClick:ae=>Y.path.endsWith(".malloynb")?y(`/${b}/${x}/${Y.path}`,ae):M({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"view"},ae)},Y.path))]}),T&&_.length>0&&t.jsx(Nt,{title:"Drafts",count:_.length,children:_.map(({locator:Y,where:ae})=>t.jsx(Dn,{type:Y.type==="grid"?"dashboard":"report",label:ne(Y),rightLabel:ae,onClick:Fe=>M({path:ne(Y),layout:Y.type,slug:c.documentSlug(ne(Y))??"",mode:"edit"},Fe),trailingAction:t.jsx(p.Tooltip,{title:"Delete this draft",children:t.jsx(p.IconButton,{size:"small","aria-label":`Delete draft ${ne(Y)}`,onClick:Fe=>{Fe.stopPropagation(),D?.deleteDocument(Y).then(Z)},children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})})})},`${Y.workspace}:${Y.path}`))}),se.length>0&&t.jsx(Nt,{title:"Apps",count:se.length,children:se.map(Y=>{const ae=!!Y.title&&Y.title!==Y.path,Fe=`${Ka(u)}${Y.resource}`;return t.jsx(Dn,{type:"dataApp",label:ae?Y.title:Y.path,rightLabel:ae?Y.path:void 0,onClick:Ve=>{e?e(`/${b}/${x}/data-apps/${Y.path}`,Ve):Ve&&(Ve.metaKey||Ve.ctrlKey)?window.open(Fe,"_blank"):window.location.href=Fe},trailingAction:t.jsx(p.Tooltip,{title:"Open standalone in new tab",children:t.jsx(p.IconButton,{size:"small",href:Fe,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",onClick:Ve=>Ve.stopPropagation(),sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})},Y.path)})}),t.jsxs(Nt,{title:"Models",count:ue.length,children:[ue.map(Y=>t.jsx(Dn,{type:"model",label:Y.path,onClick:ae=>y(`/${b}/${x}/${Y.path}`,ae)},Y.path)),ue.length===0&&t.jsx(Ws,{label:"No models"})]}),pe.length>0&&t.jsx(Nt,{title:"Agents",count:pe.length,description:"Declared in publisher.json. Name one in an agent session to work as it. Schedules are listed only; nothing runs them yet.",children:pe.map(Y=>t.jsx(Yy,{agent:Y},Y.name))}),t.jsxs(Nt,{title:"Data",count:be.length,children:[be.map(Y=>t.jsx(Dn,{type:"data",label:Y.path,rightLabel:Y.info?uc(Y.info.rowCount):"Unreadable",onClick:()=>R(Y)},Y.path)),be.length===0&&t.jsx(Ws,{label:"No data files"})]}),t.jsx(gl,{resourceUri:r,versioned:!T}),ye&&t.jsx(p.Box,{sx:{mt:6},children:t.jsx(ic,{resourceUri:c.encodeResourceUri({environmentName:b,packageName:x,versionId:v}),path:ye,onLinkNavigate:y})})]}),t.jsx(Ny,{database:E,onClose:()=>R(null)})]})}function Dn({type:e,label:n,description:r,rightLabel:o,onClick:i,trailingAction:l}){return t.jsx(rs,{icon:t.jsx(cc,{type:e}),tint:lc[e],label:n,mono:!0,...r===void 0?{}:{description:r},...o===void 0?{}:{rightLabel:o},...i===void 0?{}:{onClick:i},...l===void 0?{}:{trailingAction:l}})}function Yy({agent:e}){return t.jsxs(t.Fragment,{children:[t.jsx(Dn,{type:"agent",label:e.name??"",...e.description?{description:e.description}:{},...e.model&&e.model!=="inherit"?{rightLabel:e.model}:{}}),(e.schedules??[]).map(n=>{const r=uo(n.cron??"");return t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",sx:{display:"block",ml:6,mb:.5},children:[r.valid?r.description:n.cron," (UTC), task"," ",n.task,". Not run yet."]},`${n.cron}|${n.task}`)})]})}function Ky(e){const n=e.map(o=>({path:o.path??"",layout:c.listedLayout(o),slug:c.documentSlug(o.path)??o.path??"",title:o.title})),r=new Map;for(const o of n)r.set(o.slug,(r.get(o.slug)??0)+1);return n.map(({title:o,...i})=>{const l=!!o&&o!==i.slug&&o!==i.path,a=(r.get(i.slug)??0)>1,u=l?o:i.path.endsWith(".malloynb")?i.path:i.slug;return{...i,label:u,secondary:u!==i.path&&(l||a||i.path.includes("/"))?i.path:void 0}}).sort((o,i)=>o.label.localeCompare(i.label)||o.path.localeCompare(i.path))}function Ws({label:e,action:n}){return t.jsxs(p.Stack,{direction:"row",sx:{alignItems:"center",gap:1,py:1},children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:e}),n&&t.jsx(p.Button,{size:"small",onClick:n.onClick,children:n.label})]})}const Da=/^publisher:document:(dashboard|notebook):(.+)$/;function Qy(e,n){const r=[];for(let o=0;o<e.length;o++){const i=e.key(o);i!==null&&Da.test(i)&&r.push(i)}for(const o of r){const[,i,l]=Da.exec(o),a=e.getItem(o);a!==null&&n(l,c.layoutOfKind(i),a)&&e.removeItem(o)}}const qs={name:"Local",description:"Stored in this browser only",writeable:!0},ro="publisher:report:",cn=e=>`${ro}${e}`;function hr(e){const n=localStorage.getItem(e);if(n!==null)try{const r=JSON.parse(n);if(typeof r.content=="string"&&(r.type==="grid"||r.type==="linear"))return{type:r.type,content:r.content}}catch{}}const Bs=(e,n)=>localStorage.setItem(cn(e),JSON.stringify(n));class Zy{migrated=!1;migrate(){this.migrated||(this.migrated=!0,Qy(localStorage,(n,r,o)=>hr(cn(n))!==void 0?!1:(Bs(n,{type:r,content:o}),!0)))}async listWorkspaces(n){return[qs]}async listDocuments(n,r){if(n.name!==qs.name)return[];this.migrate();const o=[];for(let i=0;i<localStorage.length;i++){const l=localStorage.key(i);if(l===null||!l.startsWith(ro))continue;const a=hr(l);a&&(r===void 0||a.type===r)&&o.push({workspace:qs.name,type:a.type,path:l.slice(ro.length)})}return o}async getDocument(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Vs(n);return r.content}async getDocumentType(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Vs(n);return r.type}async saveDocument(n,r){this.migrate(),Bs(n.path,{type:n.type,content:r})}async deleteDocument(n){if(this.migrate(),hr(cn(n.path))===void 0)throw Vs(n);localStorage.removeItem(cn(n.path))}async moveDocument(n,r){const o=await this.getDocument(n);Bs(r.path,{type:r.type,content:o}),r.path!==n.path&&localStorage.removeItem(cn(n.path))}}function Vs(e){return new c.DocumentNotFoundError(`No report at ${e.workspace}/${e.path}`)}async function Xy(e,n,r,o){const i=c.chooseWorkspace(await e.listWorkspaces(!1));if(!i)return;const l=c.draftKey(n,r,o);if(e.getDocumentType)try{return await e.getDocumentType({workspace:i.name,path:l})}catch(a){if(c.isDocumentNotFound(a))return;throw a}return(await e.listDocuments(i)).find(a=>a.path===l)?.type}function Jy(e,n,r,o=!0){const i=c.useOptionalDocumentStorage()?.documentStorage,l=o&&i!==void 0,[a,u]=j.useState(),d=c.draftKey(e,n,r);return j.useEffect(()=>{if(!l||!i)return;let h=!1;return Xy(i,e,n,r).catch(()=>{}).then(y=>{h||u({key:d,layout:y})}),()=>{h=!0}},[l,i,e,n,r,d]),l?a?.key===d?{layout:a.layout,settled:!0}:{layout:void 0,settled:!1}:{layout:void 0,settled:!0}}function pc(e){const{environmentName:n,packageName:r}=c.parseResourceUri(e.resourceUri);if(!n||!r)throw new Error("Environment and Package name must be provided for query embedding.");return JSON.stringify({...e})}function ex({embeddedQueryResult:e}){const{query:n,sourceName:r,queryName:o,resourceUri:i,height:l}=JSON.parse(e),{modelPath:a}=c.parseResourceUri(i);if(!a||!n&&(!o||!r)||typeof a!="string")throw new Error("Invalid embedded query result: "+e);return t.jsx(gc,{query:n,sourceName:r,queryName:o,resourceUri:i,height:l})}function gc({query:e,sourceName:n,queryName:r,resourceUri:o,height:i=400}){const{modelPath:l,environmentName:a,packageName:u,versionId:d}=c.parseResourceUri(o);if(!a||!u)throw new Error("No environment or package name provided. A resource URI must be provided.");const h=c.useQueryResult({environmentName:a,packageName:u,modelPath:l,versionId:d,query:e,sourceName:n,queryName:r});return t.jsx(c.ResultPanel,{state:h,context:`${a} > ${u} > ${l}`,maxHeight:i})}function yc(e,n,r="grid"){const o=n.filter(l=>!!l.path).filter(l=>c.documentSlug(l.path)===e),i=o.filter(l=>c.listedLayout(l)===r);return i.length===1?{found:c.locatedReport(i[0])}:o.length===1?{found:c.locatedReport(o[0])}:o.length===0?{missing:!0}:{ambiguous:o.map(l=>l.path).sort()}}const tx=/^(dashboards|notebooks)\/([^/]+)$/;function nx(e){const n=tx.exec(e);if(n)return{name:n[2],prefer:n[1]==="dashboards"?"grid":"linear"}}const rx=(e,n,r,o)=>`/${e}/${n}/${r}s/${encodeURIComponent(o)}`;function sx({kind:e,slug:n,reports:r}){const o=yc(n,r,c.layoutOfKind(e));return"found"in o?o.found:void 0}function ox(e,n){return`${e}:${n}`}function hn(e){return ox(e.source,e.filterName??e.dimensionName)}function ix(e){const n=new Map;for(const r of e){const o=`${r.source}|${r.model}`,i=n.get(o)||[];i.push(r),n.set(o,i)}return n}function ax(e,n,r,o){const i=n.filter(h=>(h.filterType==="Star"||h.filterType==="MinMax"||h.filterType==="DateMinMax")&&!h.values);if(i.length===0)return"";const a=[...new Set(i.map(h=>h.dimensionName))].map(h=>`\`${h}\``).join(", "),u=o?.filter(h=>h.source===e)||[],d=u.length>0?u.map(h=>os(`\`${h.dimensionName}\``,h)).filter(h=>h.length>0).join(" and "):"";return`
39
39
  run: ${e} -> {
40
- ${u?`where: ${u}`:""}
40
+ ${d?`where: ${d}`:""}
41
41
  index: ${a}
42
42
  } -> {
43
43
  select: *
@@ -45,7 +45,7 @@ ${i.inheritedFrom.code}`,framed:!1}):t.jsx(p.Box,{sx:{p:1},children:t.jsx(hs,{me
45
45
 
46
46
  limit: ${r}
47
47
  }
48
- `}function dx(e,n){const r=new Map;for(const y of n){const b=hn(y);r.set(b,[])}const o=JSON.parse(e),i=o.schema.fields,l=new Map;i.forEach((y,b)=>{l.set(y.name,b)});const a=y=>{if(!y)return null;switch(y.kind){case"string_cell":return y.string_value??null;case"number_cell":return y.number_value??null;case"boolean_cell":return y.boolean_value??null;case"null_cell":return null;default:return console.log("Unknown cell kind: "+y.kind),null}},u=(o.data?.array_value||[]).map(y=>{const b={};return y.kind==="record_cell"&&y.record_value&&y.record_value.forEach((x,v)=>{const k=i[v]?.name;if(k){const C=a(x);k==="fieldName"&&typeof C=="string"?b.fieldName=C:k==="fieldPath"&&typeof C=="string"?b.fieldPath=C:k==="fieldType"&&typeof C=="string"?b.fieldType=C:k==="fieldValue"&&typeof C=="string"?b.fieldValue=C:k==="weight"&&typeof C=="number"&&(b.weight=C)}}),b}),h=u.length===0||u.every(y=>!y.fieldName);for(const y of n){if(y.filterType==="NONE"||y.filterType==="Retrieval")continue;const b=u.filter(v=>{const k=v.fieldName||"",C=v.fieldPath||"";if(k===y.dimensionName||C===y.dimensionName||k.toLowerCase()===y.dimensionName.toLowerCase()||C.toLowerCase()===y.dimensionName.toLowerCase())return!0;const S=C.split(".").pop()||"";return S===y.dimensionName||S.toLowerCase()===y.dimensionName.toLowerCase()});if(b.length===0)continue;const x=hn(y);if(y.filterType==="Star"){const v=b.filter(k=>k.fieldType==="string").map(k=>({value:k.fieldValue??"",count:k.weight})).sort((k,C)=>(C.count??0)-(k.count??0));r.set(x,v)}else if(y.filterType==="MinMax"){console.log("MinMax dimensionEntries: "+JSON.stringify(b,null,2)),console.log("All MinMax dimension entries fieldTypes:",b.map(k=>k.fieldType));const v=b.find(k=>k.fieldType==="number");if(console.log("numericEntry: "+JSON.stringify(v,null,2)),v?.fieldValue){const k=v.fieldValue,C=k.split(" to ");if(console.log("rangeParts: "+C),C.length===2){const S=[{value:parseFloat(C[0])},{value:parseFloat(C[1])}];r.set(x,S)}else console.warn(`Could not parse numeric range for ${y.dimensionName}: ${k}`)}else console.warn(`No numeric entry found for ${y.dimensionName}. Available entries:`,b)}else if(y.filterType==="DateMinMax"){const v=b.find(k=>k.fieldType==="date"||k.fieldType==="timestamp"||k.fieldType==="string");if(console.log("dateEntry: "+JSON.stringify(v,null,2)),console.log("All date dimension entries fieldTypes:",b.map(k=>k.fieldType)),v?.fieldValue){const k=v.fieldValue,C=k.split(" to ");if(console.log("date rangeParts: "+C),C.length===2){const S=[{value:new Date(C[0].trim())},{value:new Date(C[1].trim())}];r.set(x,S)}else console.warn(`Could not parse date range for ${y.dimensionName}: ${k}`)}else console.warn(`No date entry found for ${y.dimensionName}. Available entries:`,b)}}return{values:r,noRowsMatchedFilter:h}}function vc(e){const{environment:n,package:r,dimensionSpecs:o,versionId:i,enabled:l=!0,indexLimit:a=1e4,activeFilters:d=[]}=e,u=j.useMemo(()=>cx(o),[o]),h=j.useMemo(()=>{const C=[];for(const[S,T]of u){const[O,M]=S.split("|"),E=ux(O,T,a,d);E?C.push({key:S,source:O,model:M,query:E,specs:T}):console.log("No query for source: ",O,"model: ",M)}return C},[u,a,d]),y=j.useMemo(()=>l&&h.length>0&&o.some(C=>C.filterType==="Star"||C.filterType==="MinMax"||C.filterType==="DateMinMax"),[l,h,o]),{apiClients:b}=q.useServer(),x=c.useQueryWithApiError({queryKey:["dimensionalFilter",n,r,o,i,d],queryFn:async({signal:C})=>{if(!y){const M=new Map;for(const E of o){const R=hn(E);M.set(R,[])}return{values:M,noRowsMatchedFilter:!1}}const S=await Promise.all(h.map(async M=>{const E=await b.models.executeQueryModel(n,r,M.model,{query:M.query,versionId:i,bypassFilters:!0},void 0,void 0,{signal:C});return{config:M,result:dx(E.data.result,M.specs)}})),T=new Map;let O=!1;for(const{result:M}of S){for(const[E,R]of M.values)T.set(E,R);M.noRowsMatchedFilter&&(O=!0)}return{values:T,noRowsMatchedFilter:O}},enabled:y,staleTime:300*1e3,placeholderData:C=>C}),v=x.data?.values;return{data:j.useMemo(()=>{const C=new Map;for(const S of o){const T=hn(S);S.values?C.set(T,S.values.map(O=>({value:O}))):C.set(T,[])}if(v)for(const[S,T]of v)T.length>0&&C.set(S,T);return C},[o,v]),noRowsMatchedFilter:x.data?.noRowsMatchedFilter??!1,isLoading:y?x.isPending:!1,isError:y?x.isError:!1,error:y?x.error:null,refetch:x.refetch}}function hx(e){return is(`\`${e.dimensionName}\``,e)}function bc(e){const{dimensionSpecs:n}=e,[r,o]=j.useState(()=>{const h=new Map;return n.forEach(y=>{const b=hn(y);h.set(b,{spec:y,selection:null})}),h});j.useEffect(()=>{o(h=>{const y=new Map;return n.forEach(b=>{const x=hn(b),v=h.get(x);y.set(x,{spec:b,selection:v?.selection??null})}),y})},[n]);const i=j.useCallback((h,y)=>{o(b=>{const x=new Map(b),v=x.get(h);return v&&x.set(h,{...v,selection:y}),x})},[]),l=j.useCallback(h=>{i(h,null)},[i]),a=j.useCallback(()=>{o(h=>{const y=new Map(h);return y.forEach((b,x)=>{y.set(x,{...b,selection:null})}),y})},[]),d=j.useCallback(()=>{const h=[];return r.forEach(y=>{y.selection&&h.push(y.selection)}),h},[r]),u=j.useCallback(()=>{const h=d();if(h.length===0)return"";const y=h.map(b=>hx(b)).filter(b=>b.length>0);return y.length===0?"":`where ${y.join(" and ")}`},[d]);return{filterStates:r,updateFilter:i,clearFilter:l,clearAllFilters:a,getActiveFilters:d,generateWhereClause:u}}function fx(e){return is(`\`${e.dimensionName}\``,e)}function mx(e){if(e.length===0)return"";const n=e.map(r=>fx(r)).filter(r=>r.length>0);return n.length===0?"":n.join(" and ")}function px(e,n,r,o=1e3){const i=mx(n),a=r&&r.length>0?`group_by: ${r.map(d=>`\`${d}\``).join(", ")}`:"select: *";return i?`
48
+ `}function lx(e,n){const r=new Map;for(const y of n){const b=hn(y);r.set(b,[])}const o=JSON.parse(e),i=o.schema.fields,l=new Map;i.forEach((y,b)=>{l.set(y.name,b)});const a=y=>{if(!y)return null;switch(y.kind){case"string_cell":return y.string_value??null;case"number_cell":return y.number_value??null;case"boolean_cell":return y.boolean_value??null;case"null_cell":return null;default:return console.log("Unknown cell kind: "+y.kind),null}},d=(o.data?.array_value||[]).map(y=>{const b={};return y.kind==="record_cell"&&y.record_value&&y.record_value.forEach((x,v)=>{const k=i[v]?.name;if(k){const C=a(x);k==="fieldName"&&typeof C=="string"?b.fieldName=C:k==="fieldPath"&&typeof C=="string"?b.fieldPath=C:k==="fieldType"&&typeof C=="string"?b.fieldType=C:k==="fieldValue"&&typeof C=="string"?b.fieldValue=C:k==="weight"&&typeof C=="number"&&(b.weight=C)}}),b}),h=d.length===0||d.every(y=>!y.fieldName);for(const y of n){if(y.filterType==="NONE"||y.filterType==="Retrieval")continue;const b=d.filter(v=>{const k=v.fieldName||"",C=v.fieldPath||"";if(k===y.dimensionName||C===y.dimensionName||k.toLowerCase()===y.dimensionName.toLowerCase()||C.toLowerCase()===y.dimensionName.toLowerCase())return!0;const S=C.split(".").pop()||"";return S===y.dimensionName||S.toLowerCase()===y.dimensionName.toLowerCase()});if(b.length===0)continue;const x=hn(y);if(y.filterType==="Star"){const v=b.filter(k=>k.fieldType==="string").map(k=>({value:k.fieldValue??"",count:k.weight})).sort((k,C)=>(C.count??0)-(k.count??0));r.set(x,v)}else if(y.filterType==="MinMax"){console.log("MinMax dimensionEntries: "+JSON.stringify(b,null,2)),console.log("All MinMax dimension entries fieldTypes:",b.map(k=>k.fieldType));const v=b.find(k=>k.fieldType==="number");if(console.log("numericEntry: "+JSON.stringify(v,null,2)),v?.fieldValue){const k=v.fieldValue,C=k.split(" to ");if(console.log("rangeParts: "+C),C.length===2){const S=[{value:parseFloat(C[0])},{value:parseFloat(C[1])}];r.set(x,S)}else console.warn(`Could not parse numeric range for ${y.dimensionName}: ${k}`)}else console.warn(`No numeric entry found for ${y.dimensionName}. Available entries:`,b)}else if(y.filterType==="DateMinMax"){const v=b.find(k=>k.fieldType==="date"||k.fieldType==="timestamp"||k.fieldType==="string");if(console.log("dateEntry: "+JSON.stringify(v,null,2)),console.log("All date dimension entries fieldTypes:",b.map(k=>k.fieldType)),v?.fieldValue){const k=v.fieldValue,C=k.split(" to ");if(console.log("date rangeParts: "+C),C.length===2){const S=[{value:new Date(C[0].trim())},{value:new Date(C[1].trim())}];r.set(x,S)}else console.warn(`Could not parse date range for ${y.dimensionName}: ${k}`)}else console.warn(`No date entry found for ${y.dimensionName}. Available entries:`,b)}}return{values:r,noRowsMatchedFilter:h}}function xc(e){const{environment:n,package:r,dimensionSpecs:o,versionId:i,enabled:l=!0,indexLimit:a=1e4,activeFilters:u=[]}=e,d=j.useMemo(()=>ix(o),[o]),h=j.useMemo(()=>{const C=[];for(const[S,T]of d){const[O,M]=S.split("|"),E=ax(O,T,a,u);E?C.push({key:S,source:O,model:M,query:E,specs:T}):console.log("No query for source: ",O,"model: ",M)}return C},[d,a,u]),y=j.useMemo(()=>l&&h.length>0&&o.some(C=>C.filterType==="Star"||C.filterType==="MinMax"||C.filterType==="DateMinMax"),[l,h,o]),{apiClients:b}=q.useServer(),x=c.useQueryWithApiError({queryKey:["dimensionalFilter",n,r,o,i,u],queryFn:async({signal:C})=>{if(!y){const M=new Map;for(const E of o){const R=hn(E);M.set(R,[])}return{values:M,noRowsMatchedFilter:!1}}const S=await Promise.all(h.map(async M=>{const E=await b.models.executeQueryModel(n,r,M.model,{query:M.query,versionId:i,bypassFilters:!0},void 0,void 0,{signal:C});return{config:M,result:lx(E.data.result,M.specs)}})),T=new Map;let O=!1;for(const{result:M}of S){for(const[E,R]of M.values)T.set(E,R);M.noRowsMatchedFilter&&(O=!0)}return{values:T,noRowsMatchedFilter:O}},enabled:y,staleTime:300*1e3,placeholderData:C=>C}),v=x.data?.values;return{data:j.useMemo(()=>{const C=new Map;for(const S of o){const T=hn(S);S.values?C.set(T,S.values.map(O=>({value:O}))):C.set(T,[])}if(v)for(const[S,T]of v)T.length>0&&C.set(S,T);return C},[o,v]),noRowsMatchedFilter:x.data?.noRowsMatchedFilter??!1,isLoading:y?x.isPending:!1,isError:y?x.isError:!1,error:y?x.error:null,refetch:x.refetch}}function cx(e){return os(`\`${e.dimensionName}\``,e)}function vc(e){const{dimensionSpecs:n}=e,[r,o]=j.useState(()=>{const h=new Map;return n.forEach(y=>{const b=hn(y);h.set(b,{spec:y,selection:null})}),h});j.useEffect(()=>{o(h=>{const y=new Map;return n.forEach(b=>{const x=hn(b),v=h.get(x);y.set(x,{spec:b,selection:v?.selection??null})}),y})},[n]);const i=j.useCallback((h,y)=>{o(b=>{const x=new Map(b),v=x.get(h);return v&&x.set(h,{...v,selection:y}),x})},[]),l=j.useCallback(h=>{i(h,null)},[i]),a=j.useCallback(()=>{o(h=>{const y=new Map(h);return y.forEach((b,x)=>{y.set(x,{...b,selection:null})}),y})},[]),u=j.useCallback(()=>{const h=[];return r.forEach(y=>{y.selection&&h.push(y.selection)}),h},[r]),d=j.useCallback(()=>{const h=u();if(h.length===0)return"";const y=h.map(b=>cx(b)).filter(b=>b.length>0);return y.length===0?"":`where ${y.join(" and ")}`},[u]);return{filterStates:r,updateFilter:i,clearFilter:l,clearAllFilters:a,getActiveFilters:u,generateWhereClause:d}}function ux(e){return os(`\`${e.dimensionName}\``,e)}function dx(e){if(e.length===0)return"";const n=e.map(r=>ux(r)).filter(r=>r.length>0);return n.length===0?"":n.join(" and ")}function hx(e,n,r,o=1e3){const i=dx(n),a=r&&r.length>0?`group_by: ${r.map(u=>`\`${u}\``).join(", ")}`:"select: *";return i?`
49
49
  run: ${e} -> {
50
50
  where: ${i}
51
51
  ${a}
@@ -56,4 +56,4 @@ ${i.inheritedFrom.code}`,framed:!1}):t.jsx(p.Box,{sx:{p:1},children:t.jsx(hs,{me
56
56
  ${a}
57
57
  limit: ${o}
58
58
  }
59
- `}function wc(e){const{environment:n,package:r,model:o,source:i,filterSelections:l,fields:a,limit:d=1e3,versionId:u}=e,[h,y]=j.useState(null),b=j.useMemo(()=>px(i,l,a,d),[i,l,a,d]),x=j.useMemo(()=>c.encodeResourceUri({environmentName:n,packageName:r,modelPath:o,versionId:u}),[n,r,o,u]),v=l.length>0,k=j.useCallback(()=>{if(!v){y(null);return}const C=mc({resourceUri:x,query:b});y(C)},[v,x,b]);return{embeddedQueryResult:h,queryString:b,resourceUri:x,executeQuery:k,canExecute:v}}function gx(e,n=5e3){const r=e.dimensionSpecs[0]?.source??"",o=e.dimensionSpecs[0]?.model??"",{filterStates:i,updateFilter:l,clearAllFilters:a,getActiveFilters:d}=bc({dimensionSpecs:e.dimensionSpecs}),u=j.useMemo(()=>d(),[i,d]),{data:h,noRowsMatchedFilter:y,isLoading:b,isError:x,error:v,refetch:k}=vc({environment:e.environment,package:e.package,indexLimit:e.indexLimit,dimensionSpecs:e.dimensionSpecs,versionId:e.versionId,activeFilters:u}),C=b&&!h,{embeddedQueryResult:S,queryString:T,executeQuery:O,canExecute:M}=wc({environment:e.environment,package:e.package,model:o,source:r,filterSelections:u,limit:n,fields:e.selectFields,versionId:e.versionId});return{filterStates:i,updateFilter:l,clearAllFilters:a,activeFilters:u,data:h,noRowsMatchedFilter:y,isLoading:b,isInitialLoading:C,isError:x,error:v,refetch:k,embeddedQueryResult:S,queryString:T,executeQuery:O,canExecute:M}}function yx({modelPath:e,query:n,sourceName:r,queryName:o,enabled:i=!0,resourceUri:l}){const{environmentName:a,packageName:d,versionId:u}=c.parseResourceUri(l),{apiClients:h}=q.useServer(),{data:y,isSuccess:b,isError:x,error:v,isLoading:k}=c.useQueryWithApiError({queryKey:["rawQueryData",a,d,e,u,n,r,o],queryFn:({signal:S})=>h.models.executeQueryModel(a,d,e,{query:n,sourceName:r,queryName:o,versionId:u},void 0,void 0,{signal:S}),enabled:i});return{data:b&&y?.data?.result?(()=>{try{return JSON.parse(y.data.result).data?.array_value||[]}catch(S){return console.error("Failed to parse query result:",S),[]}})():[],isSuccess:b,isError:x,error:v,isLoading:k}}exports.AddButton=c.AddButton;exports.ApiErrorDisplay=c.ApiErrorDisplay;exports.AppDialog=c.AppDialog;exports.DRILL_SELF=c.DRILL_SELF;exports.DashboardTile=c.DashboardTile;exports.DocumentNotFoundError=c.DocumentNotFoundError;exports.DocumentStorageProvider=c.DocumentStorageProvider;exports.GivenInput=c.GivenInput;exports.GivensPanel=c.GivensPanel;exports.INITIAL_RENDER_HEIGHT=c.INITIAL_RENDER_HEIGHT;exports.LOADING_COPY=c.LOADING_COPY;exports.Loading=c.Loading;exports.MODEL_CELL_MAX_HEIGHT=c.MODEL_CELL_MAX_HEIGHT;exports.MOTION_FAST=c.MOTION_FAST;exports.NOTEBOOK_CELL_MAX_HEIGHT=c.NOTEBOOK_CELL_MAX_HEIGHT;exports.Prose=c.Prose;exports.REPORT_EDIT_PARAM=c.REPORT_EDIT_PARAM;exports.RESTRICTED_NOTICE=c.RESTRICTED_NOTICE;exports.RESULTS_DIALOG_MAX_HEIGHT=c.RESULTS_DIALOG_MAX_HEIGHT;exports.ResultContainer=c.ResultContainer;exports.ResultPanel=c.ResultPanel;exports.STICKY_CONTROLS_Z=c.STICKY_CONTROLS_Z;exports.STICKY_TOP_VAR=c.STICKY_TOP_VAR;exports.SecondaryButton=c.SecondaryButton;exports.TILE_MAX_HEIGHT=c.TILE_MAX_HEIGHT;exports.TILE_MIN_HEIGHT=c.TILE_MIN_HEIGHT;exports.TileCard=c.TileCard;exports.TileFilterTag=c.TileFilterTag;exports.TileHeading=c.TileHeading;exports.UNCAPPED_CONTAINER_HEIGHT=c.UNCAPPED_CONTAINER_HEIGHT;exports.UnsavedChangesDialog=c.UnsavedChangesDialog;exports.buildTableCssVars=c.buildTableCssVars;exports.clearReportDraft=c.clearReportDraft;exports.contentNodeDepth=c.contentNodeDepth;exports.dangerTextColor=c.dangerTextColor;exports.documentPreamble=c.documentPreamble;exports.documentSlug=c.documentSlug;exports.draftStorageAvailable=c.draftStorageAvailable;exports.drillDestinations=c.drillDestinations;exports.drillValueToFilter=c.drillValueToFilter;exports.encodeDrillValue=c.encodeDrillValue;exports.encodeResourceUri=c.encodeResourceUri;exports.humanizeSlug=c.humanizeSlug;exports.initialResultHeight=c.initialResultHeight;exports.isDocumentNotFound=c.isDocumentNotFound;exports.isDrillTargetPath=c.isDrillTargetPath;exports.localGivenSpec=c.localGivenSpec;exports.locateReport=c.locateReport;exports.malloyIdentifier=c.malloyIdentifier;exports.malloyLiteral=c.malloyLiteral;exports.measureContentHeight=c.measureContentHeight;exports.parseResourceUri=c.parseResourceUri;exports.queryResultKey=c.queryResultKey;exports.reducedMotionSx=c.reducedMotionSx;exports.remeasuresAfterReady=c.remeasuresAfterReady;exports.reportClasses=c.reportClasses;exports.reportDraftKey=c.reportDraftKey;exports.reportEditRoute=c.reportEditRoute;exports.reportRoute=c.reportRoute;exports.reportRoutePath=c.reportRoutePath;exports.resolveDrill=c.resolveDrill;exports.resolveDrillTarget=c.resolveDrillTarget;exports.resolveResultHeight=c.resolveResultHeight;exports.resultSizing=c.resultSizing;exports.scrollBehavior=c.scrollBehavior;exports.tileIgnoredFilterLabels=c.tileIgnoredFilterLabels;exports.useCompiledDocument=c.useCompiledDocument;exports.useDocumentControls=c.useDocumentControls;exports.useDocumentLocation=c.useDocumentLocation;exports.useDocumentStorage=c.useDocumentStorage;exports.useDrillSelf=c.useDrillSelf;exports.useGivensState=c.useGivensState;exports.useOptionalDocumentStorage=c.useOptionalDocumentStorage;exports.useQueryResult=c.useQueryResult;exports.useReportListing=c.useReportListing;exports.useSuggestOptions=c.useSuggestOptions;exports.visibleWithoutHoverSx=c.visibleWithoutHoverSx;exports.withPreamble=c.withPreamble;exports.DEFAULT_THEME=q.DEFAULT_THEME;exports.DEFAULT_UI=q.DEFAULT_UI;exports.MONO_FONT_FAMILY=q.MONO_FONT_FAMILY;exports.PALETTE=q.PALETTE;exports.SURFACE_TINT=q.SURFACE_TINT;exports.ServerProvider=q.ServerProvider;exports.ThemeProvider=q.ThemeProvider;exports.accentFor=q.accentFor;exports.contrastRatio=q.contrastRatio;exports.mergeUi=q.mergeUi;exports.resolveMode=q.resolveMode;exports.resolveTheme=q.resolveTheme;exports.usePublisherTheme=q.usePublisherTheme;exports.useServer=q.useServer;exports.canRetryRequest=oo.canRetryRequest;exports.DRILL_CELL_CLASS=fn.DRILL_CELL_CLASS;exports.RenderedResult=fn.RenderedResult;exports.buildMalloyExplicitTheme=fn.buildMalloyExplicitTheme;exports.buildVegaThemeOverride=fn.buildVegaThemeOverride;exports.drillableFieldNames=fn.drillableFieldNames;exports.markDrillableCells=fn.markDrillableCells;exports.readChartAnnotations=fn.readChartAnnotations;exports.BackLink=rd;exports.BrowserDocumentStorage=By;exports.ConnectionExplorer=tl;exports.DOC_LINKS=Vt;exports.Dashboard=Gy;exports.DashboardView=rs;exports.DataAppViewer=$d;exports.DimensionFilter=Qh;exports.DownloadRowsCsv=Ua;exports.EmbeddedQueryResult=Uy;exports.Environment=Th;exports.Home=df;exports.Materializations=gl;exports.Model=ay;exports.ModelExplorer=Io;exports.ModelExplorerDialog=Do;exports.ModelViewer=nc;exports.NarrowEditGate=sd;exports.NewDocumentDialog=ic;exports.Notebook=rx;exports.Package=Py;exports.Packages=nl;exports.QueryResult=pc;exports.Report=oc;exports.SourcesExplorer=sc;exports.VersionSwitch=fc;exports.createEmbeddedQueryResult=mc;exports.documentRoute=ix;exports.extractDimensionSpecs=tf;exports.extractSourceFromQuery=rf;exports.generateFilterClause=nf;exports.getDimensionKey=hn;exports.getJoinedSources=Zh;exports.groupEntitiesBySource=kl;exports.injectWhereClause=sf;exports.isNarrowScreen=Ra;exports.legacyAliasOf=ox;exports.locateDocument=ax;exports.locateReportByName=xc;exports.modelQueryKey=tc;exports.packageFileUrl=Qa;exports.packageVersionsQueryKey=$o;exports.parseAllSourceInfos=ef;exports.parseDimensionFilterAnnotation=rl;exports.parseNotebookFilterAnnotation=Xh;exports.runQueryKey=jo;exports.setConsoleEventHandler=Gd;exports.useDimensionFilters=bc;exports.useDimensionFiltersFromSpec=gx;exports.useDimensionFiltersQuery=wc;exports.useDimensionalFilterRangeData=vc;exports.useDraftLayout=Hy;exports.useDrill=io;exports.useGivenUrlParams=fd;exports.useInvalidatePackage=hc;exports.useModelData=Eo;exports.useModelGivens=gc;exports.useNarrowScreen=Fa;exports.usePackageVersions=dc;exports.useRawQueryData=yx;exports.useRouterClickHandler=od;
59
+ `}function bc(e){const{environment:n,package:r,model:o,source:i,filterSelections:l,fields:a,limit:u=1e3,versionId:d}=e,[h,y]=j.useState(null),b=j.useMemo(()=>hx(i,l,a,u),[i,l,a,u]),x=j.useMemo(()=>c.encodeResourceUri({environmentName:n,packageName:r,modelPath:o,versionId:d}),[n,r,o,d]),v=l.length>0,k=j.useCallback(()=>{if(!v){y(null);return}const C=pc({resourceUri:x,query:b});y(C)},[v,x,b]);return{embeddedQueryResult:h,queryString:b,resourceUri:x,executeQuery:k,canExecute:v}}function fx(e,n=5e3){const r=e.dimensionSpecs[0]?.source??"",o=e.dimensionSpecs[0]?.model??"",{filterStates:i,updateFilter:l,clearAllFilters:a,getActiveFilters:u}=vc({dimensionSpecs:e.dimensionSpecs}),d=j.useMemo(()=>u(),[i,u]),{data:h,noRowsMatchedFilter:y,isLoading:b,isError:x,error:v,refetch:k}=xc({environment:e.environment,package:e.package,indexLimit:e.indexLimit,dimensionSpecs:e.dimensionSpecs,versionId:e.versionId,activeFilters:d}),C=b&&!h,{embeddedQueryResult:S,queryString:T,executeQuery:O,canExecute:M}=bc({environment:e.environment,package:e.package,model:o,source:r,filterSelections:d,limit:n,fields:e.selectFields,versionId:e.versionId});return{filterStates:i,updateFilter:l,clearAllFilters:a,activeFilters:d,data:h,noRowsMatchedFilter:y,isLoading:b,isInitialLoading:C,isError:x,error:v,refetch:k,embeddedQueryResult:S,queryString:T,executeQuery:O,canExecute:M}}function mx({modelPath:e,query:n,sourceName:r,queryName:o,enabled:i=!0,resourceUri:l}){const{environmentName:a,packageName:u,versionId:d}=c.parseResourceUri(l),{apiClients:h}=q.useServer(),{data:y,isSuccess:b,isError:x,error:v,isLoading:k}=c.useQueryWithApiError({queryKey:["rawQueryData",a,u,e,d,n,r,o],queryFn:({signal:S})=>h.models.executeQueryModel(a,u,e,{query:n,sourceName:r,queryName:o,versionId:d},void 0,void 0,{signal:S}),enabled:i});return{data:b&&y?.data?.result?(()=>{try{return JSON.parse(y.data.result).data?.array_value||[]}catch(S){return console.error("Failed to parse query result:",S),[]}})():[],isSuccess:b,isError:x,error:v,isLoading:k}}exports.AddButton=c.AddButton;exports.ApiErrorDisplay=c.ApiErrorDisplay;exports.AppDialog=c.AppDialog;exports.DRILL_SELF=c.DRILL_SELF;exports.DashboardTile=c.DashboardTile;exports.DocumentNotFoundError=c.DocumentNotFoundError;exports.DocumentStorageProvider=c.DocumentStorageProvider;exports.GivenInput=c.GivenInput;exports.GivensPanel=c.GivensPanel;exports.INITIAL_RENDER_HEIGHT=c.INITIAL_RENDER_HEIGHT;exports.LOADING_COPY=c.LOADING_COPY;exports.Loading=c.Loading;exports.MODEL_CELL_MAX_HEIGHT=c.MODEL_CELL_MAX_HEIGHT;exports.MOTION_FAST=c.MOTION_FAST;exports.NOTEBOOK_CELL_MAX_HEIGHT=c.NOTEBOOK_CELL_MAX_HEIGHT;exports.Prose=c.Prose;exports.REPORT_EDIT_PARAM=c.REPORT_EDIT_PARAM;exports.RESTRICTED_NOTICE=c.RESTRICTED_NOTICE;exports.RESULTS_DIALOG_MAX_HEIGHT=c.RESULTS_DIALOG_MAX_HEIGHT;exports.ResultContainer=c.ResultContainer;exports.ResultPanel=c.ResultPanel;exports.STICKY_CONTROLS_Z=c.STICKY_CONTROLS_Z;exports.STICKY_TOP_VAR=c.STICKY_TOP_VAR;exports.SecondaryButton=c.SecondaryButton;exports.TILE_MAX_HEIGHT=c.TILE_MAX_HEIGHT;exports.TILE_MIN_HEIGHT=c.TILE_MIN_HEIGHT;exports.TileCard=c.TileCard;exports.TileFilterTag=c.TileFilterTag;exports.TileHeading=c.TileHeading;exports.UNCAPPED_CONTAINER_HEIGHT=c.UNCAPPED_CONTAINER_HEIGHT;exports.UnsavedChangesDialog=c.UnsavedChangesDialog;exports.buildTableCssVars=c.buildTableCssVars;exports.clearReportDraft=c.clearReportDraft;exports.contentNodeDepth=c.contentNodeDepth;exports.dangerTextColor=c.dangerTextColor;exports.documentPreamble=c.documentPreamble;exports.documentSlug=c.documentSlug;exports.draftStorageAvailable=c.draftStorageAvailable;exports.drillDestinations=c.drillDestinations;exports.drillValueToFilter=c.drillValueToFilter;exports.encodeDrillValue=c.encodeDrillValue;exports.encodeResourceUri=c.encodeResourceUri;exports.humanizeSlug=c.humanizeSlug;exports.initialResultHeight=c.initialResultHeight;exports.isDocumentNotFound=c.isDocumentNotFound;exports.isDrillTargetPath=c.isDrillTargetPath;exports.localGivenSpec=c.localGivenSpec;exports.locateReport=c.locateReport;exports.malloyIdentifier=c.malloyIdentifier;exports.malloyLiteral=c.malloyLiteral;exports.measureContentHeight=c.measureContentHeight;exports.parseResourceUri=c.parseResourceUri;exports.queryResultKey=c.queryResultKey;exports.reducedMotionSx=c.reducedMotionSx;exports.remeasuresAfterReady=c.remeasuresAfterReady;exports.reportClasses=c.reportClasses;exports.reportDraftKey=c.reportDraftKey;exports.reportEditRoute=c.reportEditRoute;exports.reportRoute=c.reportRoute;exports.reportRoutePath=c.reportRoutePath;exports.resolveDrill=c.resolveDrill;exports.resolveDrillTarget=c.resolveDrillTarget;exports.resolveResultHeight=c.resolveResultHeight;exports.resultSizing=c.resultSizing;exports.scrollBehavior=c.scrollBehavior;exports.tileIgnoredFilterLabels=c.tileIgnoredFilterLabels;exports.useCompiledDocument=c.useCompiledDocument;exports.useDocumentControls=c.useDocumentControls;exports.useDocumentLocation=c.useDocumentLocation;exports.useDocumentStorage=c.useDocumentStorage;exports.useDrillSelf=c.useDrillSelf;exports.useGivensState=c.useGivensState;exports.useOptionalDocumentStorage=c.useOptionalDocumentStorage;exports.useQueryResult=c.useQueryResult;exports.useReportListing=c.useReportListing;exports.useSuggestOptions=c.useSuggestOptions;exports.visibleWithoutHoverSx=c.visibleWithoutHoverSx;exports.withPreamble=c.withPreamble;exports.DEFAULT_THEME=q.DEFAULT_THEME;exports.DEFAULT_UI=q.DEFAULT_UI;exports.MONO_FONT_FAMILY=q.MONO_FONT_FAMILY;exports.PALETTE=q.PALETTE;exports.SURFACE_TINT=q.SURFACE_TINT;exports.ServerProvider=q.ServerProvider;exports.ThemeProvider=q.ThemeProvider;exports.accentFor=q.accentFor;exports.contrastRatio=q.contrastRatio;exports.mergeUi=q.mergeUi;exports.resolveMode=q.resolveMode;exports.resolveTheme=q.resolveTheme;exports.usePublisherTheme=q.usePublisherTheme;exports.useServer=q.useServer;exports.canRetryRequest=so.canRetryRequest;exports.DRILL_CELL_CLASS=fn.DRILL_CELL_CLASS;exports.RenderedResult=fn.RenderedResult;exports.buildMalloyExplicitTheme=fn.buildMalloyExplicitTheme;exports.buildVegaThemeOverride=fn.buildVegaThemeOverride;exports.drillableFieldNames=fn.drillableFieldNames;exports.markDrillableCells=fn.markDrillableCells;exports.readChartAnnotations=fn.readChartAnnotations;exports.BackLink=nd;exports.BrowserDocumentStorage=Zy;exports.ConnectionExplorer=tl;exports.DOC_LINKS=Vt;exports.DashboardView=Ga;exports.DataAppViewer=Dd;exports.DimensionFilter=Kh;exports.DownloadRowsCsv=Ha;exports.EmbeddedQueryResult=ex;exports.Environment=jh;exports.Home=uf;exports.Materializations=gl;exports.Model=iy;exports.ModelExplorer=Eo;exports.ModelExplorerDialog=Io;exports.ModelViewer=nc;exports.NarrowEditGate=rd;exports.NewDocumentDialog=ac;exports.Package=Gy;exports.Packages=nl;exports.QueryResult=gc;exports.Report=ic;exports.SourcesExplorer=sc;exports.VersionSwitch=mc;exports.createEmbeddedQueryResult=pc;exports.documentRoute=rx;exports.extractDimensionSpecs=ef;exports.extractSourceFromQuery=nf;exports.generateFilterClause=tf;exports.getDimensionKey=hn;exports.getJoinedSources=Qh;exports.groupEntitiesBySource=kl;exports.injectWhereClause=rf;exports.isNarrowScreen=Aa;exports.legacyAliasOf=nx;exports.locateDocument=sx;exports.locateReportByName=yc;exports.modelQueryKey=tc;exports.packageFileUrl=Qa;exports.packageVersionsQueryKey=Do;exports.parseAllSourceInfos=Jh;exports.parseDimensionFilterAnnotation=rl;exports.parseNotebookFilterAnnotation=Zh;exports.runQueryKey=Co;exports.setConsoleEventHandler=Ud;exports.useDimensionFilters=vc;exports.useDimensionFiltersFromSpec=fx;exports.useDimensionFiltersQuery=bc;exports.useDimensionalFilterRangeData=xc;exports.useDraftLayout=Jy;exports.useDrill=oo;exports.useGivenUrlParams=hd;exports.useInvalidatePackage=fc;exports.useModelData=Mo;exports.useModelGivens=oc;exports.useNarrowScreen=Fa;exports.usePackageVersions=hc;exports.useRawQueryData=mx;exports.useRouterClickHandler=sd;