react-semaphor 0.1.487 → 0.1.489

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 (77) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +1 -1
  3. package/dist/brand-studio/index.cjs +1 -1
  4. package/dist/brand-studio/index.js +3 -3
  5. package/dist/briefings/index.cjs +1 -1
  6. package/dist/briefings/index.js +3 -3
  7. package/dist/chunks/{calculated-field-identity-CQb7MOl2.js → calculated-field-identity-CSabKrXt.js} +2 -2
  8. package/dist/chunks/{calculated-field-identity-Dwl8yGej.cjs → calculated-field-identity-D4VOHjBJ.cjs} +1 -1
  9. package/dist/chunks/{constants-DCOEfAqV.cjs → constants-BMfm1XgO.cjs} +1 -1
  10. package/dist/chunks/{constants-CHyHJrbM.js → constants-D47EhfJR.js} +3 -3
  11. package/dist/chunks/{dashboard-briefing-launcher-CEFTQ1Bo.js → dashboard-briefing-launcher-BkYSN0Em.js} +1177 -1161
  12. package/dist/chunks/dashboard-briefing-launcher-TwquBRrW.cjs +21 -0
  13. package/dist/chunks/{dashboard-controls-B8sB1B3b.js → dashboard-controls-AmaFS8Kl.js} +10 -10
  14. package/dist/chunks/{dashboard-controls-DJrGf3ZB.cjs → dashboard-controls-Mj_mqC8u.cjs} +1 -1
  15. package/dist/chunks/{dashboard-json-B4KiEU0Q.js → dashboard-json-CdVpJZPY.js} +6 -6
  16. package/dist/chunks/{dashboard-json-BlcAA_hB.cjs → dashboard-json-X6uhUYk3.cjs} +1 -1
  17. package/dist/chunks/{edit-dashboard-visual-CoWjnH66.js → edit-dashboard-visual-DOBFMhus.js} +1967 -1969
  18. package/dist/chunks/{edit-dashboard-visual-Dy3g1mEH.cjs → edit-dashboard-visual-ehgeS2ss.cjs} +10 -10
  19. package/dist/chunks/{editor-action-buttons-CMlgLbyo.js → editor-action-buttons-BeiN-K5d.js} +5 -5
  20. package/dist/chunks/{editor-action-buttons-CCm0eEz_.cjs → editor-action-buttons-CRrxjkAi.cjs} +1 -1
  21. package/dist/chunks/{field-aggregations-4O27uCsl.js → field-aggregations-J7de9KZm.js} +2 -2
  22. package/dist/chunks/{field-aggregations-D9ZfvxOG.cjs → field-aggregations-hx8odlTh.cjs} +1 -1
  23. package/dist/chunks/{index-BJwEDK3K.cjs → index-9g7-nCDB.cjs} +230 -229
  24. package/dist/chunks/{index-DOBJv70o.js → index-BDtC8et3.js} +5 -5
  25. package/dist/chunks/{index-DmwnCmOH.js → index-CnZ0x05b.js} +25070 -25029
  26. package/dist/chunks/{index-BhsHg66K.cjs → index-Df4YBtX5.cjs} +1 -1
  27. package/dist/chunks/{matrix-card-CoQiV9pN.js → matrix-card-5R39CCdj.js} +1 -1
  28. package/dist/chunks/{matrix-card-JYMYSX0x.cjs → matrix-card-DzkJRoM4.cjs} +1 -1
  29. package/dist/chunks/{matrix-control-sources-C5yR-8Os.cjs → matrix-control-sources-BWbqiGmN.cjs} +1 -1
  30. package/dist/chunks/{matrix-control-sources-CVKluUf_.js → matrix-control-sources-DxjWV8ry.js} +4 -4
  31. package/dist/chunks/{matrix-formatter-C3cZwlyH.cjs → matrix-formatter-3QR1mqhn.cjs} +1 -1
  32. package/dist/chunks/{matrix-formatter-PvfZAZMO.js → matrix-formatter-youWVghC.js} +2 -2
  33. package/dist/chunks/matrix-operation-contract-BiUMcd6G.cjs +1 -0
  34. package/dist/chunks/{matrix-operation-contract-DITvltmL.js → matrix-operation-contract-D5I-t3i7.js} +2 -0
  35. package/dist/chunks/{pivot-header-presentation-BNk7eOw5.js → pivot-header-presentation-BslEo_4O.js} +2 -2
  36. package/dist/chunks/{pivot-header-presentation-D07xrP9g.cjs → pivot-header-presentation-Dcd4IBM5.cjs} +1 -1
  37. package/dist/chunks/{pivot-result-lifecycle-CmTnVy3z.js → pivot-result-lifecycle-BCoOFUiU.js} +1 -1
  38. package/dist/chunks/{pivot-result-lifecycle-lfXjvoZD.cjs → pivot-result-lifecycle-H_pntnd9.cjs} +1 -1
  39. package/dist/chunks/{report-preferences-dialog-BxS10Skt.cjs → report-preferences-dialog-BkhwOcF7.cjs} +1 -1
  40. package/dist/chunks/{report-preferences-dialog-CK7Yst5x.js → report-preferences-dialog-CcyeSXxN.js} +4 -4
  41. package/dist/chunks/{semantic-format-BOzelQDB.cjs → semantic-format-CMPIcb8l.cjs} +1 -1
  42. package/dist/chunks/{semantic-format-C_bee0be.js → semantic-format-UvUAyZS-.js} +1 -1
  43. package/dist/chunks/{switch-BiQDKn8o.js → switch-BPhOmWZm.js} +6 -6
  44. package/dist/chunks/{switch-DAO_vHPc.cjs → switch-BabZv_0t.cjs} +1 -1
  45. package/dist/chunks/{update-policy-C291nphu.cjs → update-policy-BP_2uCgs.cjs} +1 -1
  46. package/dist/chunks/{update-policy-kjd-Z5jD.js → update-policy-D3I1J2kl.js} +1 -1
  47. package/dist/dashboard/index.cjs +1 -1
  48. package/dist/dashboard/index.js +1 -1
  49. package/dist/dashboard-authoring/index.cjs +1 -1
  50. package/dist/dashboard-authoring/index.js +7 -7
  51. package/dist/data-app-builder/index.cjs +1 -1
  52. package/dist/data-app-builder/index.js +2 -2
  53. package/dist/data-app-codegen/index.cjs +1 -1
  54. package/dist/data-app-codegen/index.js +2 -2
  55. package/dist/data-app-codegen-node/index.cjs +1 -1
  56. package/dist/data-app-codegen-node/index.js +3 -3
  57. package/dist/data-app-sdk/index.cjs +1 -1
  58. package/dist/data-app-sdk/index.js +2 -2
  59. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  60. package/dist/data-app-sdk-adapters/index.js +1 -1
  61. package/dist/data-app-sdk-validation/index.cjs +1 -1
  62. package/dist/data-app-sdk-validation/index.js +2 -2
  63. package/dist/format-utils/index.cjs +1 -1
  64. package/dist/format-utils/index.js +8 -8
  65. package/dist/index.cjs +1 -1
  66. package/dist/index.js +11 -11
  67. package/dist/style.css +1 -1
  68. package/dist/surfboard/index.cjs +1 -1
  69. package/dist/surfboard/index.js +2 -2
  70. package/dist/types/analytics-protocol.d.ts +60 -0
  71. package/dist/types/dashboard-assistant.d.ts +10 -0
  72. package/dist/types/data-app-sdk-validation.d.ts +10 -0
  73. package/dist/types/data-app-sdk.d.ts +36 -0
  74. package/dist/types/main.d.ts +45 -6
  75. package/package.json +1 -1
  76. package/dist/chunks/dashboard-briefing-launcher-DuUM-xZw.cjs +0 -26
  77. package/dist/chunks/matrix-operation-contract-CCfuWtro.cjs +0 -1
@@ -1,26 +0,0 @@
1
- "use strict";const e=require("react/jsx-runtime"),m=require("react"),r=require("./switch-DAO_vHPc.cjs"),s=require("./index-BJwEDK3K.cjs"),ye=require("./layout-grid-xm8pqtx0.cjs"),K=require("./x-B6ghREd2.cjs"),R=require("./editor-action-buttons-CCm0eEz_.cjs"),Ce=require("./constants-DCOEfAqV.cjs");require("./validators-4dRtYUI1.cjs");require("./matrix-operation-contract-CCfuWtro.cjs");require("../value-format-preferences/index.cjs");const Oe=require("./search-BqqhaMx9.cjs"),_e=require("./mouse-pointer-2-DX4A_XZw.cjs"),Se=require("./matrix-formatter-C3cZwlyH.cjs");require("./appearance-runtime-provider-Ca8rxO86.cjs");require("./appearance-context-tNjvTJj3.cjs");require("./index-C8XCKzB6.cjs");require("./field-aggregations-D9ZfvxOG.cjs");require("zod");require("./matrix-continuation-6nhDy-lF.cjs");require("./color-CyB5o13F.cjs");require("react-dom");const X=require("./index-BhsHg66K.cjs");/**
2
- * @license lucide-react v0.453.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const ze=K.createLucideIcon("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/**
7
- * @license lucide-react v0.453.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const $e=K.createLucideIcon("CalendarRange",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M17 14h-6",key:"bkmgh3"}],["path",{d:"M13 18H7",key:"bb0bb7"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 18h.01",key:"1bdyru"}]]);/**
12
- * @license lucide-react v0.453.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const qe=K.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
17
- * @license lucide-react v0.453.0 - ISC
18
- *
19
- * This source code is licensed under the ISC license.
20
- * See the LICENSE file in the root directory of this source tree.
21
- */const De=K.createLucideIcon("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/**
22
- * @license lucide-react v0.453.0 - ISC
23
- *
24
- * This source code is licensed under the ISC license.
25
- * See the LICENSE file in the root directory of this source tree.
26
- */const He=K.createLucideIcon("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);function We(){return e.jsx("div",{className:"space-y-1.5 py-1",children:[...Array(5)].map((t,n)=>e.jsxs("div",{className:"flex animate-pulse items-start gap-3 rounded-xl border border-transparent px-2.5 py-2.5",children:[e.jsx("div",{className:"mt-0.5 h-4 w-4 flex-shrink-0 rounded bg-muted/60"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/5 rounded bg-muted/60"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted/40"})]})]},n))})}function Ge({open:t,onOpenChange:n,onSubmit:l,isCreating:a}){const c=s.useSurfaceAppearance("interactive"),[o,u]=m.useState(""),[p,d]=m.useState("");m.useEffect(()=>{t||(u(""),d(""))},[t]);const f=()=>{o.trim()&&l({title:o,description:p})},i=x=>{n(x)};return e.jsx(s.Dialog,{open:t,onOpenChange:i,children:e.jsxs(s.DialogContent,{showCloseButton:!1,className:"flex max-w-lg grid-cols-none flex-col gap-0 overflow-hidden rounded-card border-border/60 p-0 shadow-lg sm:rounded-card",style:c.dialogStyle,children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ye.LayoutGrid,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx(s.DialogTitle,{className:"truncate text-[13px] font-medium leading-none tracking-normal",children:"New library visual"}),e.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase leading-none tracking-[0.08em] text-muted-foreground",children:"Visual"})]})]}),e.jsx(r.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>i(!1),"aria-label":"Close",disabled:a,children:e.jsx(K.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"space-y-3 px-4 py-3",children:[e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create a saved visual that can be reused across dashboards."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(r.Label,{htmlFor:"visual-title",className:"text-[12px]",children:"Name"}),e.jsx(r.Input,{id:"visual-title",size:"sm",placeholder:"Untitled visual",value:o,onChange:x=>u(x.target.value),disabled:a,onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),f())}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(r.Label,{htmlFor:"visual-description",className:"text-[12px]",children:"Description"}),e.jsx(r.Input,{id:"visual-description",size:"sm",placeholder:"Optional",value:p,onChange:x=>d(x.target.value),disabled:a})]})]}),e.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t border-border/60 px-4 py-2.5",children:[e.jsx(r.Button,{size:"xs",variant:"outline",onClick:()=>i(!1),disabled:a,children:"Cancel"}),e.jsx(r.Button,{size:"xs",onClick:f,disabled:!o.trim()||a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Creating..."]}):"Create library visual"})]})]})})}function Ae(t){return t?new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Unknown"}function Be(t,n){var a;const l=(a=t.ownership.createdBy)==null?void 0:a.type;return l==="tenant"||l==="organization"&&n}function we(t,n){var l,a;return Be(t,n)?((l=t.ownership.createdBy)==null?void 0:l.name)||((a=t.createdByTenantUserRel)==null?void 0:a.name)||t.lastModifiedBy||"Unknown":"Organization"}function Xe(t,n){return we(t,n).split(/\s+/).filter(Boolean).slice(0,2).map(a=>a.charAt(0).toUpperCase()).join("")||"?"}function Ke(t){const n=(t||"").toLowerCase();return n.includes("table")?r.Table2:n.includes("pie")||n.includes("donut")?s.ChartPie:n.includes("line")?s.ChartLine:n.includes("bar")?r.ChartColumn:ye.LayoutGrid}function Qe({visual:t}){const n=t.ownership.status==="public"?"Public":t.ownership.status==="shared"||t.ownership.sharedCount>0?"Shared":"Private";return e.jsx("span",{className:"inline-flex items-center rounded-[4px] border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground",children:n})}function Ye({open:t,onOpenChange:n}){const l=s.useSurfaceAppearance("interactive"),[a,c]=m.useState(""),[o,u]=m.useState(new Set),[p,d]=m.useState(!1),[f,i]=m.useState(null),[x,h]=m.useState(null),[g,v]=m.useState(!1),[y,S]=m.useState(null),[B,D]=m.useState(null),w=()=>{u(new Set),i(null),h(null),v(!1),S(null)},k=()=>{n(!1),w()},{selectVisual:A}=s.useManagementActions(),{handleAddLibraryVisual:T,handleEditLibraryVisual:b}=R.useVisualUtils(),{isConsoleMode:j}=s.useDashboardPreferences(),{resources:L,isLoading:I,isError:$,createResource:E,updateResource:M,deleteResourceAsync:_,duplicateResource:oe,isCreating:Q,isDeleting:J}=s.useVisualManagement(void 0,C=>{d(!1),C&&(A(C),b(C),k())}),{startUpdating:he,stopUpdating:xe,isUpdating:ee}=s.useResourceUpdateState(),z=L,W=m.useMemo(()=>{const C=a.trim().toLowerCase();return C?z.filter(F=>{var V,Y,se;return((V=F.title)==null?void 0:V.toLowerCase().includes(C))||((Y=F.description)==null?void 0:Y.toLowerCase().includes(C))||((se=F.kind)==null?void 0:se.toLowerCase().includes(C))}):z},[a,z]),te=m.useMemo(()=>z.filter(C=>o.has(C.id)),[o,z]),G=te.filter(C=>C.permissions.canDelete),me=te.filter(C=>C.permissions.canShare),ie=W.length>0&&W.every(C=>o.has(C.id)),re=W.some(C=>o.has(C.id)),ne=C=>{const F=new Set(o);C(F),u(F)},H=C=>{ne(F=>{F.has(C)?F.delete(C):F.add(C)})},le=()=>{u(C=>{const F=new Set(C);return ie?W.forEach(V=>F.delete(V.id)):W.forEach(V=>F.add(V.id)),F})},U=async C=>{(await T(C)).success&&k()},O=async()=>{const C=te;if(C.length===0)return;let F=!1;for(const V of C)if(!(await T(V)).success){F=!0;break}F||k()},Z=C=>{b(C),k()},ae=C=>{D(C),oe(C,{onSettled:()=>D(null)})},pe=()=>{if(G.length===0){r.ue.error("Select a visual you can delete");return}S(null),v(!0)},ve=async()=>{const C=y?[y]:G;try{for(const F of C)await _(F.id);u(F=>{const V=new Set(F);return C.forEach(Y=>V.delete(Y.id)),V}),v(!1),S(null)}catch{}},ce=()=>{if(te.length!==1){r.ue.error("Select one visual to share");return}const[C]=te;if(!C.permissions.canShare){r.ue.error("You do not have permission to share this visual");return}i(C)},de=({title:C,description:F})=>{if(!x)return;const V={};if(C!==x.title&&(V.title=C),(x.description||"")!==F&&(V.description=F),Object.keys(V).length===0){h(null);return}const Y=Object.keys(V),se=Y.length===1?Y[0]:void 0;he(x.id,se),M({resourceId:x.id,data:V},{onSuccess:()=>{xe(x.id,se),h(null)},onError:()=>{xe(x.id,se)}})},q=C=>{n(C),C||w()},ue=y?1:G.length;return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:q,children:e.jsxs(s.DialogContent,{showCloseButton:!1,className:"flex max-h-[80vh] w-[min(72rem,calc(100vw-2rem))] max-w-none grid-cols-none flex-col gap-0 overflow-hidden rounded-card border-border/60 p-0 shadow-lg sm:rounded-card",style:l.dialogStyle,children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(r.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx(s.DialogTitle,{className:"truncate text-[13px] font-medium leading-none tracking-normal",children:"Visuals library"}),e.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase leading-none tracking-[0.08em] text-muted-foreground",children:"Add to dashboard"})]})]}),e.jsx(r.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>q(!1),"aria-label":"Close visuals library",children:"×"})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 px-3 py-2",children:[e.jsxs("div",{className:"relative min-w-[12rem] flex-1 md:max-w-md",children:[e.jsx(Oe.Search,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx("input",{autoFocus:!0,value:a,onChange:C=>c(C.target.value),placeholder:"Search visuals...",className:"h-7 w-full rounded-control border border-input bg-background pl-7 pr-2 text-[12px] text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none","aria-label":"Search visuals"})]}),e.jsxs(r.Button,{size:"xs",variant:"outline",className:"ml-auto",onClick:()=>d(!0),children:[e.jsx(s.Plus,{className:"h-3.5 w-3.5"}),"New library visual"]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:I?e.jsx("div",{className:"p-3",children:e.jsx(We,{})}):$?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:e.jsx("p",{className:"text-[13px] text-destructive",children:"Failed to load visuals"})}):W.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:[e.jsx(ye.LayoutGrid,{className:"h-5 w-5 text-muted-foreground/60"}),e.jsx("p",{className:"text-[13px] font-medium",children:a?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:a?"Try a different search.":"Create a saved visual to add it here."})]}):e.jsx(Ze,{visuals:W,selectedIds:o,allFilteredSelected:ie,someFilteredSelected:re,onSelectAll:le,onToggleSelection:H,onAddVisual:U,onOpenVisual:Z,onEditDetails:h,onShareVisual:i,onDeleteVisual:C=>{S(C),v(!0)},onDuplicateVisual:ae,duplicatingId:B,isDeleting:J,isConsoleMode:j})}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border/60 px-3 py-2",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:o.size>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-[12px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium tabular-nums text-foreground",children:o.size})," ","selected"]}),e.jsx(r.Button,{size:"xs",variant:"ghost",onClick:()=>u(new Set),children:"Clear"}),e.jsxs(r.Button,{size:"xs",variant:"outline",onClick:ce,disabled:te.length!==1||me.length!==1,children:[e.jsx(s.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),e.jsxs(r.Button,{size:"xs",variant:"outline",className:"text-destructive hover:text-destructive",onClick:pe,disabled:G.length===0,children:[e.jsx(s.Trash2,{className:"h-3.5 w-3.5"}),"Delete ",G.length||o.size]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.Button,{size:"xs",variant:"outline",onClick:()=>q(!1),children:"Close"}),e.jsxs(r.Button,{size:"xs",onClick:O,disabled:o.size===0,children:[e.jsx(r.Check,{className:"h-3.5 w-3.5"}),o.size===0?"Add to dashboard":`Add ${o.size} visual${o.size===1?"":"s"}`]})]})]})]})}),e.jsx(Ge,{open:p,onOpenChange:d,onSubmit:E,isCreating:Q}),f&&e.jsx(s.ShareDialog,{resource:f,resourceType:s.ResourceType.VISUAL,onClose:()=>i(null)}),x&&e.jsx(s.ResourceEditDialog,{open:!!x,resourceLabel:"Visual",initialTitle:x.title||"",initialDescription:x.description||"",onClose:()=>h(null),onSave:de,isSaving:ee(x.id)}),e.jsx(s.AlertDialog,{open:g,onOpenChange:C=>{!C&&J||(v(C),C||S(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsxs(s.AlertDialogTitle,{children:["Delete ",ue," visual",ue===1?"":"s","?"]}),e.jsx(s.AlertDialogDescription,{children:"This cannot be undone. Visuals already added to dashboards may need to be removed from those dashboards separately."})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:J,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:C=>{C.preventDefault(),ve()},disabled:J||ue===0,children:[J?e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"h-3.5 w-3.5"}),J?"Deleting...":"Delete"]})]})]})})]})}function Ze({visuals:t,selectedIds:n,allFilteredSelected:l,someFilteredSelected:a,onSelectAll:c,onToggleSelection:o,onAddVisual:u,onOpenVisual:p,onEditDetails:d,onShareVisual:f,onDeleteVisual:i,onDuplicateVisual:x,duplicatingId:h,isDeleting:g,isConsoleMode:v}){return e.jsxs("div",{className:"min-w-[48rem]",children:[e.jsxs("div",{className:"grid h-9 grid-cols-[2.5rem_minmax(14rem,1.8fr)_minmax(10rem,1fr)_8rem_7rem_5rem_5.5rem] items-center border-b border-border/60 px-3 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(s.Checkbox,{checked:l?!0:a?"indeterminate":!1,onCheckedChange:c,"aria-label":"Select all visuals"}),e.jsx("span",{children:"Name"}),e.jsx("span",{children:"Created by"}),e.jsx("span",{children:"Updated"}),e.jsx("span",{children:"Visibility"}),e.jsx("span",{className:"text-right",children:"Shared"}),e.jsx("span",{className:"text-right",children:"Actions"})]}),t.map(y=>e.jsx(Je,{visual:y,selected:n.has(y.id),onToggleSelection:o,onAddVisual:u,onOpenVisual:p,onEditDetails:d,onShareVisual:f,onDeleteVisual:i,onDuplicateVisual:x,duplicatingId:h,isDeleting:g,isConsoleMode:v},y.id))]})}function Je({visual:t,selected:n,onToggleSelection:l,onAddVisual:a,onOpenVisual:c,onEditDetails:o,onShareVisual:u,onDeleteVisual:p,onDuplicateVisual:d,duplicatingId:f,isDeleting:i,isConsoleMode:x}){var v;const h=Ke(t.kind),g=()=>{a(t)};return e.jsxs("div",{className:r.cn("group grid min-h-12 grid-cols-[2.5rem_minmax(14rem,1.8fr)_minmax(10rem,1fr)_8rem_7rem_5rem_5.5rem] items-center border-b border-border/50 px-3 text-[13px] hover:bg-muted/50",n&&"bg-muted/70"),children:[e.jsx("div",{children:e.jsx(s.Checkbox,{checked:n,onCheckedChange:()=>l(t.id),"aria-label":`Select ${t.title||"visual"}`})}),e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 rounded-[4px] text-left outline-none focus-visible:ring-1 focus-visible:ring-ring",onClick:g,"aria-label":`Add ${t.title||"visual"} to dashboard`,children:[e.jsx(h,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-foreground",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),((v=t.description)==null?void 0:v.trim())&&e.jsx("div",{className:"truncate text-[11px] text-muted-foreground",title:t.description,children:t.description})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-[9px] font-medium text-muted-foreground",children:Xe(t,x)}),e.jsx("span",{className:"truncate text-muted-foreground",children:we(t,x)})]}),e.jsx("span",{className:"text-muted-foreground",children:Ae(t.updatedAt)}),e.jsx(Qe,{visual:t}),e.jsx("span",{className:"text-right tabular-nums text-muted-foreground",children:t.ownership.sharedCount>0?t.ownership.sharedCount:"—"}),e.jsx(et,{visual:t,onOpenVisual:c,onEditDetails:o,onShareVisual:u,onDeleteVisual:p,onDuplicateVisual:d,duplicatingId:f,isDeleting:i,isConsoleMode:x})]})}function et({visual:t,onOpenVisual:n,onEditDetails:l,onShareVisual:a,onDeleteVisual:c,onDuplicateVisual:o,duplicatingId:u,isDeleting:p,isConsoleMode:d}){return e.jsxs("div",{className:"flex items-center justify-end gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",onClick:f=>f.stopPropagation(),children:[e.jsx(r.Button,{size:"xs",variant:"ghost",className:"w-7 px-0",onClick:()=>n(t),"aria-label":"Edit visual",children:e.jsx(s.PenLine,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(r.Button,{size:"xs",variant:"ghost",className:"w-7 px-0","aria-label":"More actions",children:e.jsx(s.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[60] w-44 rounded-[6px] border-border/60 p-1 shadow-sm",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>n(t),children:[e.jsx(s.PenLine,{className:"h-3.5 w-3.5"}),"Edit visual"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>o(t.id),disabled:u===t.id,children:[u===t.id?e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(s.Copy,{className:"h-3.5 w-3.5"}),u===t.id?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsxs(s.DropdownMenuItem,{onClick:()=>l(t),children:[e.jsx(s.PenLine,{className:"h-3.5 w-3.5"}),"Edit details"]}),t.permissions.canShare&&e.jsxs(s.DropdownMenuItem,{onClick:()=>a(t),children:[e.jsx(s.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{className:"text-destructive focus:bg-destructive/10 focus:text-destructive",onClick:()=>c(t),disabled:p,children:[e.jsx(s.Trash2,{className:"h-3.5 w-3.5"}),p?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-1.5 text-[11px] text-muted-foreground",children:[Be(t,d)&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:we(t,d)})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:Ae(t.updatedAt)})]})]})]})]})]})}function tt({open:t,onOpenChange:n,isLibraryVisual:l,currentVisualName:a,isSaving:c=!1,destinationMode:o="both",onConfirm:u}){const[p,d]=m.useState(l&&a?`Copy of ${a}`:a||""),[f,i]=m.useState("");m.useEffect(()=>{t&&(d(l&&a?`Copy of ${a}`:a||""),i(""))},[t,l,a]);const x=!!p.trim(),h=o==="local"?{saveToLibrary:!1,saveToCurrentDashboard:!0,badgeType:"local",description:"Creates a local copy on the current dashboard.",actionLabel:"Add to Dashboard (Local)"}:o==="library"?{saveToLibrary:!0,saveToCurrentDashboard:!1,badgeType:"library",description:"Creates a reusable visual in Visual Library.",actionLabel:"Save as Library Visual"}:{saveToLibrary:!0,saveToCurrentDashboard:!0,badgeType:"linked",description:"Creates a new library visual and adds a linked copy to this dashboard.",actionLabel:"Save Copy as Linked Visual"},g=()=>{!x||c||u({name:p.trim(),description:f.trim()||void 0,saveToLibrary:h.saveToLibrary,saveToCurrentDashboard:h.saveToCurrentDashboard})};return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[500px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Save Visual As"}),h.badgeType!=="local"&&e.jsx(R.VisualBadge,{type:h.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(s.DialogDescription,{children:h.description})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(r.Label,{htmlFor:"name",children:"Name"}),e.jsx(r.Input,{id:"name",value:p,onChange:v=>d(v.target.value),placeholder:"Enter visual name",disabled:c})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(r.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:f,onChange:v=>i(v.target.value),placeholder:"Enter visual description",rows:3,disabled:c})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(r.Button,{variant:"outline",onClick:()=>n(!1),disabled:c,children:"Cancel"}),e.jsxs(r.Button,{onClick:g,disabled:!x||c,children:[c&&e.jsx(r.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),h.actionLabel]})]})]})})}function st(){const[t,n]=m.useState(!1),[l,a]=m.useState(!1),[c,o]=m.useState(null),[u,p]=m.useState(null),d=r.useEditorStore(b=>b.frame),f=r.useEditorStore(b=>b.card),i=s.useSelectedVisual(),x=r.useDashboardStore(b=>b.selectedSheetId),h=r.useDashboardStore(b=>b.dashboard),{getUpdatedFrame:g}=R.useVisualUtils(),{selectVisual:v}=s.useManagementActions(),{addFrame:y,setSelectedFrameId:S,setIsVisualEditing:B}=r.useDashboardActions(),D=s.useResolveExistingFrameSemanticExecutionPayload(),w=!!(d!=null&&d.visualId),k=(()=>{var b,j;return((b=d==null?void 0:d.cards)==null?void 0:b.length)===1&&((j=d.cards[0])!=null&&j.title)?d.cards[0].title:i!=null&&i.title?i.title:(f==null?void 0:f.title)||"Untitled Visual"})(),A=s.useCreateVisualWithFrame(b=>{b!=null&&b.id&&(v(b),l&&c&&u&&x&&(async()=>{try{const j={...c,id:Ce.v4(),visualId:b.id};y(x,j,{position:"end",semanticExecutionPayload:u}),S(j.id),a(!1),o(null),p(null),B(!1)}catch(j){console.error("Failed to promote semantic metadata for saved visual:",j),r.ue.error(j instanceof Error?j.message:"Failed to prepare semantic metadata for the saved visual")}})(),n(!1))});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async b=>{if(!x){r.ue.error("No sheet selected");return}const j=g(),L=r.getDynamicFrameSaveIssue(j);if(L){r.ue.error(L);return}const $=j.cards.length===1?{...j,cards:j.cards.map(E=>({...E,title:b.name}))}:j;if(b.saveToLibrary){let E=null;if(b.saveToCurrentDashboard)try{E=await D($,{previousFrame:r.findDashboardFrameById(h,$.id)})}catch(_){console.error("Failed to prepare semantic metadata before saving visual:",_),r.ue.error(_ instanceof Error?_.message:"Failed to prepare semantic metadata for the saved visual");return}a(b.saveToCurrentDashboard),o($),p(E);const M={title:b.name,description:b.description,frameObject:$,isPrivate:!1};A.mutate(M)}else if(b.saveToCurrentDashboard){const E={...$,id:Ce.v4(),visualId:void 0};try{const M=await D($,{previousFrame:r.findDashboardFrameById(h,$.id)});y(x,E,{position:"end",semanticExecutionPayload:M}),S(E.id),r.ue.success("Visual saved to dashboard"),n(!1),B(!1)}catch(M){console.error("Failed to save visual to dashboard:",M),r.ue.error(M instanceof Error?M.message:"Failed to prepare semantic metadata for the visual")}}},isLibraryVisual:w,currentVisualName:k,isSaving:A.isPending}}function rt(t={}){const{isInspectionMode:n}=s.useDashboardInteractionMode(),l=r.useEditorStore(E=>E.frame),a=r.useEditorStore(E=>E.editorContext),c=s.useManagementStore(E=>E.selectedVisual),o=r.useDashboardStore(E=>E.selectedFrameId),u=r.useDashboardStore(E=>E.selectedSheetId),p=r.useDashboardStore(E=>E.dashboard),{setIsVisualEditing:d,updateFrame:f}=r.useDashboardActions(),[i,x]=m.useState(!1),[h,g]=m.useState("both"),v=s.useResolveExistingFrameSemanticExecutionPayload(),y=(a==null?void 0:a.type)==="documentSection",S=!!(l!=null&&l.visualId||c!=null&&c.id),B=!!(l!=null&&l.visualId&&o),D=S&&!B,{saveAsDialogOpen:w,setSaveAsDialogOpen:k,handleSaveAs:A,isLibraryVisual:T,currentVisualName:b,isSaving:j}=st(),{getUpdatedFrame:L}=R.useVisualUtils();if(n)return e.jsxs(e.Fragment,{children:[e.jsx(R.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(R.EditorCancelButton,{})]});if(y)return e.jsxs(e.Fragment,{children:[e.jsx(R.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(R.EditorCancelButton,{})]});const I=async()=>{if(!u){r.ue.error("No sheet selected");return}if(i)return;x(!0);const E=L(),M=r.getDynamicFrameSaveIssue(E);if(M){x(!1),r.ue.error(M);return}const _={...E,visualId:void 0},oe=r.findDashboardFrameById(p,_.id);try{const Q=await v(_,{previousFrame:oe});f(u,_,{semanticExecutionPayload:Q})}catch(Q){console.error("Failed to apply local semantic metadata:",Q),x(!1),r.ue.error(Q instanceof Error?Q.message:"Failed to prepare semantic metadata for this visual");return}setTimeout(()=>{x(!1),r.ue.success("Changes applied. Visual is now local to this dashboard"),d(!1)},300)},$=E=>{g(E),k(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!S&&e.jsx(R.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),S&&D&&e.jsx(R.VisualSaveButton,{className:"!rounded-none",variant:"default"}),S&&B&&e.jsx(R.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(r.Button,{variant:"default",size:"xs",className:"w-7 !rounded-none border-l border-primary-foreground/20 px-0","aria-label":"Open visual save options",disabled:j||i,children:e.jsx(K.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"min-w-[220px] rounded-control border border-border/60 p-1 shadow-sm",children:[B&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:I,disabled:i,children:[e.jsx(r.Check,{className:"h-3.5 w-3.5"}),i?"Applying...":"Apply Locally"]}),e.jsx(s.DropdownMenuSeparator,{})]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>$("local"),disabled:j,children:[e.jsx(s.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>$("library"),disabled:j,children:[e.jsx(R.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>$("both"),disabled:j,children:[e.jsx(R.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(R.EditorCancelButton,{}),e.jsx(tt,{open:w,onOpenChange:E=>{j||k(E)},isLibraryVisual:T,currentVisualName:b,isSaving:j,destinationMode:h,onConfirm:A})]})}function nt({className:t}){const n=r.useEditorStore(i=>i.isDevMode),l=r.useEditorStore(i=>i.card.type),a=r.useDashboardStore(i=>i.isVisualEditing),{setIsDevMode:c}=r.useEditorActions(),{config:o}=m.useContext(s.SemaphorContext).tokenProps,u=(o==null?void 0:o.showAdvancedMode)!==!1;if(!a||!u||!Ce.supportsSqlEditor(l))return null;const p=n?_e.MousePointer2:s.CodeXml,d=n?"Visual editor":"SQL editor",f=n?"Switch to visual editor":"Switch to SQL editor";return e.jsxs("button",{type:"button","aria-label":f,title:f,onClick:()=>c(!n),className:r.cn("inline-flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 text-[12px] font-medium text-foreground transition-colors hover:bg-muted/40 focus-visible:border-ring focus-visible:outline-none",t),children:[e.jsx(p,{className:"h-3 w-3 text-muted-foreground"}),d]})}function at({open:t,onOpenChange:n,onSave:l,onDiscard:a,isSaving:c,title:o="Unsaved changes",description:u="You have unsaved changes to this dashboard. What would you like to do?",cancelLabel:p="Cancel",discardLabel:d="Discard",saveLabel:f="Save"}){const i=x=>{!x&&c||n(x)};return e.jsx(s.AlertDialog,{open:t,onOpenChange:i,children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:o}),e.jsx(s.AlertDialogDescription,{children:u})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(r.Button,{type:"button",size:"xs",onClick:a,disabled:c,variant:"ghost",className:"mr-auto text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",children:d}),e.jsx(s.AlertDialogCancel,{disabled:c,children:p}),e.jsx(r.Button,{type:"button",size:"xs",onClick:l,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(r.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):f})]})]})})}function Ne(t,n){return{id:t.id,status:t.status,progress:t.progress!==void 0?t.progress:t.status==="completed"?100:t.totalChunks===null?null:t.totalChunks>0?Math.round(t.completedChunks/t.totalChunks*100):0,totalRows:t.totalRows,totalChunks:t.totalChunks,rowsProcessed:t.processedRows,completedChunks:t.completedChunks,completedAt:t.completedAt?new Date(t.completedAt):void 0,lastUpdatedAt:new Date,fileSize:t.fileSize,error:t.error,downloadUrl:n}}const ot=1e4,it=15e3,lt=3e4,ct=3e4,dt=12e4,Ee=2*60*60*1e3;function ut(t){const n=Date.now()-t.getTime();return n<ct?ot:n<dt?it:lt}function ht(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),l=s.useExportStore(h=>h.activeExports),[a,c]=m.useState(typeof document<"u"?!document.hidden:!0),o=m.useRef(null),u=m.useRef(!1),p=m.useRef(void 0),d=n==null?void 0:n.apiServiceUrl,f=t==null?void 0:t.accessToken,i=m.useCallback(()=>{const h=s.useExportStore.getState().activeExports;return Array.from(h.values()).filter(g=>s.isExportInProgress(g.status))},[]);m.useEffect(()=>{if(typeof document>"u")return;const h=()=>{c(!document.hidden)};return document.addEventListener("visibilitychange",h),()=>{document.removeEventListener("visibilitychange",h)}},[]);const x=m.useCallback(async()=>{if(!d||!f){u.current=!1;return}const h=i();if(h.length===0){u.current=!1;return}const g=Date.now(),v=h.filter(w=>g-w.startedAt.getTime()>Ee);if(v.length>0){const{updateExport:w}=s.useExportStore.getState().actions;for(const k of v)w(k.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const y=h.filter(w=>g-w.startedAt.getTime()<=Ee);if(y.length===0){u.current=!1;return}const S=await Promise.allSettled(y.map(async w=>{try{const k=await s.getExportStatus(d,f,w.id);let A;if(k.status==="completed")try{A=await s.getDownloadUrl(d,f,w.id)}catch(T){console.error(`[useExportPolling] Failed to get download URL for ${w.id}:`,T)}return Ne(k,A)}catch(k){return console.error(`[useExportPolling] Failed to poll export ${w.id}:`,k),null}})),{updateExport:B}=s.useExportStore.getState().actions;for(const w of S)w.status==="fulfilled"&&w.value&&B(w.value.id,w.value);const D=i();if(D.length>0&&!document.hidden){const w=D.reduce((A,T)=>T.startedAt<A?T.startedAt:A,D[0].startedAt),k=ut(w);o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{var A;(A=p.current)==null||A.call(p)},k)}else u.current=!1},[d,f,i]);return m.useEffect(()=>{p.current=x},[x]),m.useEffect(()=>{var g;i().length>0&&a&&!u.current&&(u.current=!0,(g=p.current)==null||g.call(p))},[l,a,i]),m.useEffect(()=>{var g;const h=i();a&&h.length>0&&!u.current&&(u.current=!0,(g=p.current)==null||g.call(p))},[a,i]),m.useEffect(()=>{!a&&o.current&&(clearTimeout(o.current),o.current=null,u.current=!1)},[a]),m.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),{isPolling:u.current,isTabVisible:a,inProgressCount:i().length}}function xt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),l=s.useExportStore(p=>p.activeExports),{addExport:a}=s.useExportActions(),c=m.useRef(!1),o=n==null?void 0:n.apiServiceUrl,u=t==null?void 0:t.accessToken;m.useEffect(()=>{if(c.current||!o||!u)return;(async()=>{try{const{exports:d}=await s.getExports(o,u,{status:["pending","processing","chunking","compacting","completed","failed"],limit:20});for(const f of d){if(l.has(f.id))continue;let i;if(f.status==="completed")try{i=await s.getDownloadUrl(o,u,f.id)}catch(h){console.error(`[useExportRecovery] Failed to get download URL for ${f.id}:`,h)}const x={...Ne(f,i),title:mt(f),startedAt:new Date(f.createdAt),expiresAt:new Date(f.expiresAt)};a(x)}c.current=!0}catch(d){console.error("[useExportRecovery] Failed to recover exports:",d),c.current=!0}})()},[o,u,a,l])}function mt(t){return t.title?t.title:s.isExportInProgress(t.status)?"Export in progress...":t.status==="completed"?"Export completed":t.status==="failed"?"Export failed":"Export"}function Ie({export:t,onRemove:n}){const l=()=>{t.downloadUrl&&window.open(t.downloadUrl,"_blank")},a=p=>{p.stopPropagation(),n==null||n(t.id)},c=()=>{switch(t.status){case"completed":return e.jsx(s.CircleCheck,{className:"mt-0.5 h-5 w-5 shrink-0 text-green-600"});case"failed":return e.jsx(qe,{className:"mt-0.5 h-5 w-5 shrink-0 text-destructive"});default:return e.jsx(r.LoaderCircle,{className:"text-foreground-muted mt-0.5 h-5 w-5 shrink-0 animate-spin"})}},o=s.isExportInProgress(t.status),u=(()=>{switch(t.status){case"pending":return"Queued...";case"processing":return"Processing...";case"chunking":return"Processing...";case"compacting":return"Finalizing...";default:return"Processing..."}})();return e.jsxs("div",{className:"group p-4 transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-3",children:[c(),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h4",{className:"mb-1 truncate text-sm font-medium",children:t.title}),t.status==="completed"&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[t.totalRows!==null&&e.jsxs("span",{children:[t.totalRows.toLocaleString()," rows"]}),t.fileSize&&e.jsxs(e.Fragment,{children:[t.totalRows!==null&&e.jsx("span",{children:"•"}),e.jsx("span",{children:s.formatFileSize(t.fileSize)})]})]}),o&&e.jsx("div",{className:"text-xs text-muted-foreground",children:u}),t.status==="failed"&&e.jsx("div",{className:"whitespace-pre-wrap break-words text-xs text-destructive",children:t.error||"Export failed"})]})]}),e.jsx(r.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:a,"aria-label":"Remove notification",children:e.jsx(K.X,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"ml-8",children:[t.status==="completed"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Se.formatDistanceToNow(t.startedAt,{addSuffix:!0})}),t.downloadUrl&&e.jsxs(r.Button,{size:"sm",variant:"outline",className:"h-8 bg-transparent",onClick:l,children:[e.jsx(s.Download,{className:"mr-1.5 h-3.5 w-3.5"}),"Download"]})]}),o&&e.jsxs("div",{children:[t.progress!==null&&e.jsx(s.Progress,{value:t.progress,className:"h-1.5"}),(t.progress!==null||t.rowsProcessed!==void 0)&&e.jsx("span",{className:"mt-1 block text-xs text-muted-foreground",children:t.progress===null?`${t.rowsProcessed.toLocaleString()} rows processed`:`${t.progress}% complete`})]}),t.status==="failed"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Se.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function Fe(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),l=s.useExportStore(y=>y.activeExports),{clearCompleted:a,removeExport:c,updateExport:o}=s.useExportActions(),[u,p]=m.useState(!1),[d,f]=m.useState(!1),i=Array.from(l.values()).sort((y,S)=>S.startedAt.getTime()-y.startedAt.getTime()),x=i.some(y=>y.status==="completed"||y.status==="failed"),h=m.useCallback(async()=>{const y=n==null?void 0:n.apiServiceUrl,S=t==null?void 0:t.accessToken;if(!(!y||!S)){p(!0);try{const B=Array.from(l.values());await Promise.all(B.map(async D=>{try{const w=await s.getExportStatus(y,S,D.id);let k;if(w.status==="completed")try{k=await s.getDownloadUrl(y,S,D.id)}catch(A){console.error(`Failed to get download URL for ${D.id}:`,A)}o(D.id,Ne(w,k))}catch(w){o(D.id,{downloadUrl:void 0}),console.error(`Failed to refresh export ${D.id}:`,w)}}))}finally{p(!1)}}},[l,t==null?void 0:t.accessToken,n==null?void 0:n.apiServiceUrl,o]),g=m.useCallback(async()=>{const y=n==null?void 0:n.apiServiceUrl,S=t==null?void 0:t.accessToken;if(!y||!S){a();return}f(!0);try{const B=i.filter(w=>w.status==="completed"||w.status==="failed"),D=await Promise.allSettled(B.map(async w=>(await s.cancelExport(y,S,w.id),w.id)));for(const w of D)w.status==="fulfilled"?c(w.value):console.error("Failed to delete export:",w.reason)}finally{f(!1)}},[i,n==null?void 0:n.apiServiceUrl,t==null?void 0:t.accessToken,a,c]),v=m.useCallback(async y=>{const S=n==null?void 0:n.apiServiceUrl,B=t==null?void 0:t.accessToken;if(S&&B)try{await s.cancelExport(S,B,y),c(y);return}catch(D){console.error(`Failed to cancel export ${y}:`,D)}c(y)},[n==null?void 0:n.apiServiceUrl,t==null?void 0:t.accessToken,c]);return i.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(De,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active exports"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Large exports will appear here"})]}):e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h4",{className:"font-semibold",children:"Exports"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(r.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:h,disabled:u,title:"Refresh status",children:e.jsx(s.RefreshCw,{className:`h-4 w-4 ${u?"animate-spin":""}`})}),x&&e.jsx(r.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-sm",onClick:g,disabled:d,children:d?"Clearing...":"Clear all"})]})]}),e.jsx("div",{className:"max-h-[350px] overflow-y-auto",children:e.jsx("div",{className:"divide-y",children:i.map(y=>e.jsx(Ie,{export:y,onRemove:v},y.id))})})]})}function pt({variant:t}){const n=s.useExportStore(d=>d.activeExports),l=s.useInProgressExportsCount(),a=n.size>0,c=Array.from(n.values()).some(d=>d.status==="completed"||d.status==="failed"),u=l>0?l>9?"9+":String(l):null,p=a;return e.jsxs(r.Popover,{children:[e.jsx(r.PopoverTrigger,{asChild:!0,children:e.jsxs(r.Button,{variant:t??"ghost",size:"xs",className:"relative w-7 px-0 text-muted-foreground hover:text-foreground","aria-label":"Export notifications",children:[e.jsx(s.Bell,{className:"h-3.5 w-3.5"}),p&&e.jsx("span",{className:`absolute flex items-center justify-center rounded-full bg-primary text-primary-foreground ${u?"-right-0.5 -top-0.5 h-3.5 min-w-3.5 px-0.5 text-[9px] font-semibold":"right-1 top-1 h-1.5 w-1.5"}`,children:u})]})}),e.jsx(r.PopoverContent,{className:"w-80 p-0",align:"end",sideOffset:8,children:e.jsx(Fe,{})})]})}function ft(t){if(t)return{renamed:t.type==="rename"?{oldId:t.oldId,newId:t.newId}:void 0,removedControlId:t.type==="remove"?t.controlId:void 0,cardBindingsById:t.type==="add"||t.type==="update"?t.cardBindingsById:void 0,affectedBindingControlIds:t.type==="add"||t.type==="update"?t.affectedBindingControlIds:void 0}}function Le({open:t,onOpenChange:n,trigger:l,showTrigger:a=!0,initialMode:c="manage"}){const o=c==="create",{forceClose:u,handleOpenChange:p,isCreateFlowActive:d,preventPassiveDismissDuringCreate:f,resolvedOpen:i,setIsCreateFlowActive:x}=R.useCreateFlowOverlayState({open:t,onOpenChange:n,initialCreateFlowActive:c==="create",dismissMode:a?"passive":"explicit-only"}),h=r.useDashboardStore(j=>j.dashboard),{setDashboardControlsModel:g}=r.useDashboardActions(),{participants:v}=s.useDashboardStructuralParticipants(r.getDashboardCards(h)),y=Array.from(new Map(v.flatMap(j=>j.fieldChoices.map(L=>{var I;return[L.value,{option:L,target:(I=j.fieldTargetMap)==null?void 0:I[L.value]}]}))).values()),S=Array.from(new Map(v.flatMap(j=>j.metricChoices.map(L=>{var I;return[L.value,{option:L,target:(I=j.metricTargetMap)==null?void 0:I[L.value]}]}))).values()),B=r.collectDashboardControlIds({...h||{},controls:[]}),D=s.buildDashboardStructuralParticipantIdsByControlId(h),w=(j,L,I)=>{g(j,L,ft(I))},k=m.useCallback(()=>{if(o){u();return}x(!1)},[o,u,x]),A=e.jsx(R.ControlDefinitionListEditor,{scope:"dashboard",controls:h.controls||[],reservedControlIds:B,defaultValues:h.defaultControlValues||{},usageByControlId:s.buildDashboardControlUsageById(h),availableFieldChoices:y,availableMetricChoices:S,structuralParticipants:v,structuralParticipantIdsByControlId:D,initialCreateFlow:c==="create",onCreateFlowActiveChange:x,onCreateFlowComplete:k,onChange:w,emptyMessage:"No dashboard controls yet."}),T=d?"Add dashboard control":"Dashboard Controls",b=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Dashboard Controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add shared controls viewers can use across the dashboard. Each card can decide how to respond to the same control."})]}),A]});return a?e.jsxs(r.Popover,{open:i,onOpenChange:p,children:[e.jsx(r.PopoverTrigger,{asChild:!0,children:l||e.jsxs(r.Button,{variant:"outline",className:"h-7 px-2",size:"sm",children:[e.jsx(r.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Controls"]})}),e.jsx(r.PopoverContent,{className:"w-[620px] max-w-[95vw] space-y-4",align:"end",onEscapeKeyDown:f,onPointerDownOutside:f,children:b})]}):e.jsx(s.Dialog,{open:i,onOpenChange:p,children:e.jsxs(s.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:f,onPointerDownOutside:f,children:[e.jsxs(s.DialogHeader,{className:d?"space-y-0":void 0,children:[e.jsx(s.DialogTitle,{className:"text-[15px]",children:T}),e.jsx(s.DialogDescription,{className:d?"sr-only":"text-[13px]",children:d?"Configure and add a shared dashboard control.":"Add shared controls viewers can use across the dashboard. Each card can decide how to respond to the same control."})]}),e.jsx("div",{className:"min-h-0 overflow-y-auto pr-1",children:A})]})})}const gt=["enum","multi_enum","text","number","boolean","date"];function Te({open:t,onOpenChange:n,initialMode:l="manage"}){var b;const a=l==="create",{forceClose:c,handleOpenChange:o,isCreateFlowActive:u,preventPassiveDismissDuringCreate:p,resolvedOpen:d,setIsCreateFlowActive:f}=R.useCreateFlowOverlayState({open:t,onOpenChange:n,initialCreateFlowActive:l==="create",dismissMode:"explicit-only"}),i=r.useDashboardStore(j=>j.dashboard),x=r.useDashboardStore(j=>j.selectedSheetId),{setDashboardInputs:h}=r.useDashboardActions(),g=(b=i.sheets)==null?void 0:b.find(j=>j.id===x),v=(g==null?void 0:g.kind)==="document"&&!!g.document,y=m.useMemo(()=>v&&(g!=null&&g.document)?s.getDocumentSheetDashboardInputs(i,g.id):[],[i,v,g==null?void 0:g.document,g==null?void 0:g.id]),S=m.useMemo(()=>y.filter(j=>j.kind==="control"),[y]),B=m.useMemo(()=>S.map(j=>j.control),[S]),D=m.useMemo(()=>vt(B),[B]),w=m.useMemo(()=>bt(i),[i]),k=m.useCallback(()=>{if(a){c();return}f(!1)},[a,c,f]),A=m.useCallback((j,L,I)=>{!v||!(g!=null&&g.document)||h(Ct({allInputs:i.inputs||[],documentSheetId:g.id,currentDocumentInputs:y,nextControls:j,nextDefaultValues:L,change:I}))},[i.inputs,y,v,g,h]);if(!v||!(g!=null&&g.document))return null;const T=u?"Add document control":"Document Controls";return e.jsx(s.Dialog,{open:d,onOpenChange:o,children:e.jsxs(s.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:p,onPointerDownOutside:p,children:[e.jsxs(s.DialogHeader,{className:u?"space-y-0":void 0,children:[e.jsx(s.DialogTitle,{className:"text-[15px]",children:T}),e.jsx(s.DialogDescription,{className:u?"sr-only":"text-[13px]",children:u?"Configure and add a document-local control input.":"Add document-local control inputs. They are stored on this document sheet and are not dashboard controls."})]}),e.jsx("div",{className:"min-h-0 overflow-y-auto pr-1",children:e.jsx(R.ControlDefinitionListEditor,{scope:"dashboard",controls:B,reservedControlIds:w,defaultValues:D,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:gt,initialCreateFlow:l==="create",onCreateFlowActiveChange:f,onCreateFlowComplete:k,onChange:A,emptyMessage:"No document controls yet."})})]})})}function bt(t){return(t.controls||[]).map(n=>n.id)}function vt(t){const n={};for(const l of t)l.defaultValue!==void 0&&(n[l.id]=l.defaultValue);return n}function jt(t,n){return n?Object.prototype.hasOwnProperty.call(n,t.id)?{...t,defaultValue:n[t.id]}:t.defaultValue===void 0?t:{...t,defaultValue:void 0}:t.defaultValue===void 0?t:{...t,defaultValue:void 0}}function Ct({allInputs:t,documentSheetId:n,currentDocumentInputs:l,nextControls:a,nextDefaultValues:c,change:o}){const u=new Map(a.map(h=>[h.id,jt(h,c)])),p=(o==null?void 0:o.type)==="rename"?{oldId:o.oldId,newId:o.newId}:null,d=new Set,f=[];for(const h of l){if(h.kind!=="control"){f.push(h);continue}const g=u.get(h.control.id)||((p==null?void 0:p.oldId)===h.control.id?u.get(p.newId):void 0);if(!g)continue;d.add(g.id);const v=r.createUniqueDashboardInputVariableNameFromName(g.id,[...t,...f].filter(S=>S.id!==h.id)),y=g.id===v?g:{...g,id:v};f.push({...h,label:y.label,variableName:v,requiredAtExecution:y.requiredAtExecution,control:y})}for(const h of u.values())d.has(h.id)||f.push(s.createDashboardControlInputFromControl({control:h,existingInputs:[...t,...f],sheetId:n}));const i=new Set(l.map(h=>h.id));return[...t.filter(h=>!i.has(h.id)),...f]}function Me({showFilters:t,onShowFiltersChange:n,pickerContent:l,settingsContent:a,size:c="default",className:o,primaryButtonClassName:u,secondaryButtonClassName:p,pickerContentClassName:d,settingsContentClassName:f}){const i=c==="toolbar",[x,h]=m.useState(!1),g=s.useSurfaceAppearance("interactive");return e.jsxs("div",{className:r.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",i?"h-8":"h-7",o),children:[e.jsxs(r.Popover,{open:t,onOpenChange:n,children:[e.jsx(r.PopoverTrigger,{asChild:!0,children:e.jsxs(r.Button,{variant:"ghost",size:"xs",className:r.cn("h-full rounded-none border-0 bg-transparent pl-2.5 pr-2 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",u),children:[t?e.jsx(R.FilterX,{className:"h-3.5 w-3.5"}):e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),"Filter"]})}),e.jsx(r.PopoverContent,{align:"end",sideOffset:6,className:r.cn("w-auto rounded-card border border-border/60 p-0 shadow-[0_10px_28px_rgba(0,0,0,0.14)] dark:shadow-[0_10px_28px_rgba(0,0,0,0.5)]",d),style:g.contentStyle,children:l})]}),e.jsxs(r.Popover,{open:x,onOpenChange:h,children:[e.jsx(r.PopoverTrigger,{asChild:!0,children:e.jsx(r.Button,{variant:"ghost",size:"xs",className:r.cn("h-full w-7 rounded-none border-0 border-l border-border/60 bg-transparent px-0 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",p),"aria-label":"Filter and control actions",children:e.jsx(K.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsx(r.PopoverContent,{align:"end",sideOffset:6,className:r.cn("w-auto rounded-card border border-border/60 p-0 shadow-[0_10px_28px_rgba(0,0,0,0.14)] dark:shadow-[0_10px_28px_rgba(0,0,0,0.5)]",f),style:g.contentStyle,children:a(()=>h(!1))})]})]})}function yt(){R.useSyncLegacyEditorState();const t=r.useDashboardStore(d=>d.selectedSheetId),n=r.useDashboardStore(d=>d.selectedFrameId),l=r.useDashboardStore(d=>d.dashboard),a=r.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:c}=r.useDashboardActions(),{setCard:o}=r.useEditorActions(),u=r.useEditorStore(d=>d.card.dataSource);return m.useEffect(()=>{var f,i;let d=a();if(!d){const x=(f=l==null?void 0:l.sheets)==null?void 0:f.find(g=>g.id===t),h=(i=x==null?void 0:x.frames)==null?void 0:i[0];h&&(c(h.id),d=h)}if(d){const x=d.cards.find(h=>h.id===d.activeCardId);x&&o(x)}},[a,t,n,l,c,o]),{hasEntities:!!(u!=null&&u.selectedEntities&&u.selectedEntities.length>0)}}function wt(){const t=r.useDashboardStore(d=>d.dashboard),n=r.useDashboardStore(d=>d.semanticExecutionPayload),l=r.useDashboardStore(d=>d.actions.addFilter),{hasEntities:a}=yt(),{isLoading:c}=s.useFilterableFields(),o=m.useMemo(()=>r.getGlobalDateFilterCoverage(t,n),[t,n]),p=!r.getGlobalDateFilter(t.filters)&&o.hasEligibleCards&&!c;return e.jsxs("div",{className:"flex h-[520px] w-[400px] flex-col",children:[p&&e.jsx("div",{className:"border-b border-border/60 p-2",children:e.jsxs("button",{type:"button",onClick:()=>l(r.createDefaultGlobalDateFilter()),title:`Applies to ${o.eligibleCardCount} of ${o.totalCardCount} date-aware cards`,className:"flex w-full items-start gap-2 rounded-control px-2 py-1.5 text-left outline-none transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-border",children:[e.jsx($e,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"text-[12px] font-medium text-foreground",children:"Add global date filter"}),e.jsx("span",{className:"text-[11px] leading-[1.4] text-muted-foreground",children:"One date range across all date-aware cards."})]})]})}),!a&&e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-3 h-10 w-10 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-1 text-[13px] font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Configure a data source for this card to enable filtering."})]}),a&&e.jsx("div",{className:"flex flex-1 overflow-hidden",children:e.jsx(s.FilterableFieldsPanel,{context:"filter"})})]})}const ke=!1;function Nt({onAddFilter:t,onAddControl:n,onManageControls:l,onDismiss:a}){const c=r.useDashboardStore(p=>p.dashboard.filterLayout),{setFilterLayout:o}=r.useDashboardActions();c!=null&&c.displayMode;const u=(c==null?void 0:c.toolbarWrap)??!1;return c==null||c.showDownloadButton,e.jsxs("div",{className:"w-[300px]",children:[e.jsxs("div",{className:"p-1",children:[e.jsx(je,{icon:s.Filter,label:"Add filter",onClick:()=>{t(),a()}}),e.jsx(je,{icon:r.SlidersHorizontal,label:"Add control",onClick:()=>{n(),a()}}),e.jsx(je,{icon:s.Pencil,label:"Manage controls",onClick:()=>{l(),a()}})]}),e.jsx("div",{className:"border-t border-border/60"}),e.jsxs("div",{className:"space-y-1 p-2",children:[e.jsx("p",{className:"px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Display"}),ke,e.jsx(St,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:u,onCheckedChange:p=>o({toolbarWrap:p===!0})}),ke]})]})}function je({icon:t,label:n,onClick:l}){return e.jsxs("button",{type:"button",onClick:l,className:"flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] text-foreground outline-none transition-colors hover:bg-muted/40 focus-visible:bg-muted/40",children:[e.jsx(t,{className:"h-3.5 w-3.5 text-muted-foreground"}),n]})}function St({id:t,label:n,checked:l,onCheckedChange:a}){return e.jsxs("div",{className:"flex items-center gap-2 rounded-control px-1 py-1 transition-colors hover:bg-muted/40 focus-within:bg-muted/40",children:[e.jsx(s.Checkbox,{id:t,checked:l,onCheckedChange:a}),e.jsx(r.Label,{htmlFor:t,className:"cursor-pointer text-[12px] font-normal leading-[1.3]",children:n})]})}function Dt({size:t,className:n,primaryButtonClassName:l,secondaryButtonClassName:a,pickerContentClassName:c,settingsContentClassName:o}){var T;const[u,p]=m.useState(null),d=r.useDashboardStore(b=>b.dashboard),f=r.useDashboardStore(b=>b.selectedSheetId),i=r.useDashboardStore(b=>b.showFilters),x=s.useAssistantLayoutStore(b=>b.setPanelOpen),h=r.useDashboardStore(b=>b.actions),{setDocumentInspectorTab:g,setShowFilters:v}=h,y=(T=d.sheets)==null?void 0:T.find(b=>b.id===f),S=r.isDocumentSheet(y),B=m.useCallback(b=>{window.setTimeout(()=>{p(b)},0)},[]),D=m.useCallback(b=>{if(S&&f){b&&g(f,"inputs");return}b&&x("dashboard",!1),v(b)},[S,f,g,x,v]),w=m.useCallback(()=>{D(!0)},[D]),k=m.useCallback(()=>{B("create")},[B]),A=m.useCallback(()=>{B("manage")},[B]);return e.jsxs(e.Fragment,{children:[e.jsx(Me,{showFilters:S?!1:i,onShowFiltersChange:D,pickerContent:e.jsx(wt,{}),settingsContent:b=>e.jsx(Nt,{onAddFilter:w,onAddControl:k,onManageControls:A,onDismiss:b}),size:t,className:n,primaryButtonClassName:l,secondaryButtonClassName:a,pickerContentClassName:c,settingsContentClassName:o}),u?S?e.jsx(Te,{open:!0,onOpenChange:b=>{b||p(null)},initialMode:u}):e.jsx(Le,{open:!0,onOpenChange:b=>{b||p(null)},showTrigger:!1,initialMode:u}):null]})}function Pe({disabled:t,briefingCount:n,className:l,onClick:a}){const c=typeof n=="number"&&n>0;return e.jsxs(r.Button,{type:"button",size:"xs",variant:"outline",disabled:t,className:r.cn("gap-1.5",l),onClick:a,"aria-label":"Reports & briefings",children:[e.jsx(He,{className:"h-3.5 w-3.5"}),"Reports & briefings",c?e.jsx("span",{className:"ml-0.5 rounded-control bg-muted px-1 text-[10px] tabular-nums text-foreground/70",children:n}):null]})}const Et="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Re="inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",be="inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50";function kt(t){return t==="dashboard"?"This dashboard":"Project"}function At(t){if(!t)return"Never";const n=new Date(t);if(Number.isNaN(n.getTime()))return"Unknown";const l=Date.now()-n.getTime(),a=Math.round(l/6e4);if(a<1)return"now";if(a<60)return`${a}m ago`;const c=Math.round(a/60);if(c<24)return`${c}h ago`;const o=Math.round(c/24);if(o<7)return`${o}d ago`;const u=Math.round(o/7);return u<5?`${u}w ago`:`${Math.round(o/30)}mo ago`}function Bt(t){return t.scheduleExpr?X.describeBriefingSchedule(t.scheduleExpr,t.timezone||"UTC")??"Invalid schedule":"On demand"}function It(t){if(t.lastRunStatus){const n=t.lastRunStatus.toString().toUpperCase();return n==="SUCCESS"?"Last run completed.":n==="FAILED"?"Last run failed.":`Last run ${t.lastRunStatus.toString().toLowerCase()}`}return null}function Ve(t){return t.hasActiveRun?"Running":t.lastRunStatus?`Last run ${t.lastRunStatus.toString().toLowerCase()}`:"Idle"}function Ft(t){return t.source.type==="dashboard"?"This dashboard":"Project"}function Lt({activeView:t,onChange:n}){return e.jsx("div",{className:"flex shrink-0 items-center gap-1 rounded-control bg-muted p-0.5",role:"tablist","aria-label":"Briefing source view",children:["dashboard","project"].map(l=>{const a=t===l;return e.jsx("button",{type:"button",role:"tab","aria-selected":a,onClick:()=>n(l),className:r.cn("h-6 rounded-[3px] px-2 text-[11px] transition-colors",a?"bg-background font-medium text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:kt(l)},l)})})}function Tt({briefings:t,dashboardLabel:n,sourceView:l,error:a,loading:c,onSourceViewChange:o,onClose:u,onEdit:p,onNew:d,canCreate:f,canCreateScheduledReport:i,analyticalBriefingsEnabled:x,onRunNow:h,onTogglePause:g,onDelete:v,selectingId:y,busyId:S,manageBriefingsHref:B,contentKind:D,hideHeader:w=!1}){const k=t.length,A=t.filter(I=>I.status==="ACTIVE").length,T=D==="reports"?k===1?"report":"reports":D==="briefings"?k===1?"briefing":"briefings":k===1?"item":"items",b=t.find(I=>I.hasActiveRun)??null,j=D??"reports & briefings",L=l==="dashboard"?n:`Project ${j}`;return e.jsxs("section",{"aria-label":`Dashboard ${j.replace("&","and")}`,className:"flex h-full min-h-0 flex-col bg-background text-foreground",children:[w?null:e.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:Et,children:j}),e.jsx("h2",{className:"mt-0.5 truncate text-[14px] font-semibold leading-5",children:L})]}),e.jsx("button",{type:"button",onClick:u,className:"rounded-control p-1 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`Close ${j.replace("&","and")} panel`,children:e.jsx(K.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border px-4 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(Lt,{activeView:l,onChange:o}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground",children:c&&k===0?e.jsxs("span",{children:["Loading ",j,"…"]}):k===0?e.jsxs("span",{children:["No ",j," yet"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-medium text-foreground/80",children:[k," ",T]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[A," active"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[c?e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):null,k>0&&f?x&&i?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{className:be,children:[e.jsx(s.Plus,{className:"h-3 w-3"})," New"]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>d("scheduled_report"),children:"Schedule a report"}),e.jsx(s.DropdownMenuItem,{onClick:()=>d("analytical_briefing"),children:"Create analytical briefing"})]})]}):i?e.jsxs("button",{onClick:()=>d("scheduled_report"),className:be,children:[e.jsx(s.Plus,{className:"h-3 w-3"})," Schedule report"]}):x?e.jsxs("button",{onClick:()=>d("analytical_briefing"),className:be,children:[e.jsx(s.Plus,{className:"h-3 w-3"})," New briefing"]}):null:null]})]}),b?e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/60 px-4 py-2 text-[12px]",children:[e.jsx(r.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:b.name}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground",children:Ve(b)})]}):null,e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[a?e.jsx("div",{className:"m-4 rounded-card border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:a}):null,!c&&t.length===0&&!a?e.jsx(Mt,{onNew:d,canCreate:f,canCreateScheduledReport:i,analyticalBriefingsEnabled:x,contentKind:D}):null,t.map(I=>e.jsx(Rt,{briefing:I,isOpening:y===I.id,isBusy:S===I.id,onOpen:()=>p(I.id),onRunNow:()=>h(I),onTogglePause:()=>g(I),onDelete:()=>v(I)},I.id))]}),B?e.jsx("div",{className:"border-t border-border px-4 py-2.5",children:e.jsxs("a",{href:B,className:r.cn(Re,"h-6 px-1 text-[11px]"),children:["Manage all reports & briefings",e.jsx(ze,{className:"h-3 w-3"})]})}):null]})}function Mt({onNew:t,canCreate:n,canCreateScheduledReport:l,analyticalBriefingsEnabled:a,contentKind:c}){const o=c==="reports"?{title:"No reports yet",description:"Schedule an emailed dashboard or visual report to see it here."}:c==="briefings"?{title:"No briefings yet",description:"Create an analytical briefing to monitor this dashboard and brief your team."}:null;return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-8 py-12 text-center",children:[e.jsx(Pt,{className:"mb-5 h-[88px] w-[112px] text-border"}),e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:(o==null?void 0:o.title)??"Have an analyst brief your team"}),e.jsx("p",{className:"mt-1.5 max-w-[320px] text-[12px] leading-5 text-muted-foreground",children:(o==null?void 0:o.description)??"Describe what to watch. An analyst digs into this dashboard and the data behind it, then briefs your team on the cadence you choose."}),n?e.jsxs("div",{className:"mt-4 flex flex-wrap justify-center gap-2",children:[l?e.jsxs("button",{onClick:()=>t("scheduled_report"),className:be,children:[e.jsx(s.Plus,{className:"h-3 w-3"})," Schedule a report"]}):null,a?e.jsx("button",{onClick:()=>t("analytical_briefing"),className:Re,children:"Create analytical briefing"}):null]}):null]})}function Pt({className:t}){return e.jsxs("svg",{viewBox:"0 0 112 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"presentation","aria-hidden":"true",className:t,children:[e.jsx("rect",{x:"22",y:"6",width:"60",height:"72",rx:"3",stroke:"currentColor",strokeWidth:"1.25"}),e.jsx("line",{x1:"30",y1:"16",x2:"64",y2:"16",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),e.jsx("line",{x1:"30",y1:"21",x2:"52",y2:"21",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",opacity:"0.5"}),e.jsx("circle",{cx:"31",cy:"32",r:"1",fill:"currentColor",opacity:"0.6"}),e.jsx("line",{x1:"35",y1:"32",x2:"72",y2:"32",stroke:"currentColor",strokeWidth:"1",opacity:"0.4",strokeLinecap:"round"}),e.jsx("circle",{cx:"31",cy:"38",r:"1",fill:"currentColor",opacity:"0.6"}),e.jsx("line",{x1:"35",y1:"38",x2:"68",y2:"38",stroke:"currentColor",strokeWidth:"1",opacity:"0.4",strokeLinecap:"round"}),e.jsx("circle",{cx:"31",cy:"44",r:"1",fill:"currentColor",opacity:"0.6"}),e.jsx("line",{x1:"35",y1:"44",x2:"74",y2:"44",stroke:"currentColor",strokeWidth:"1",opacity:"0.4",strokeLinecap:"round"}),e.jsx("rect",{x:"30",y:"64",width:"5",height:"8",rx:"0.5",fill:"currentColor",opacity:"0.55"}),e.jsx("rect",{x:"38",y:"60",width:"5",height:"12",rx:"0.5",fill:"currentColor",opacity:"0.7"}),e.jsx("rect",{x:"46",y:"56",width:"5",height:"16",rx:"0.5",fill:"currentColor",opacity:"0.85"}),e.jsx("rect",{x:"54",y:"62",width:"5",height:"10",rx:"0.5",fill:"currentColor",opacity:"0.6"}),e.jsx("rect",{x:"62",y:"58",width:"5",height:"14",rx:"0.5",fill:"currentColor",opacity:"0.75"}),e.jsx("circle",{cx:"86",cy:"62",r:"10",fill:"var(--background, white)",stroke:"currentColor",strokeWidth:"1.25"}),e.jsx("line",{x1:"93.5",y1:"69.5",x2:"100",y2:"76",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}function Rt({briefing:t,isOpening:n,isBusy:l,onOpen:a,onRunNow:c,onTogglePause:o,onDelete:u}){const p=t.status==="PAUSED",d=t.hasActiveRun,f=It(t),i=At(t.lastRunAt),x=t.lastRunStatus,h=X.getBriefingPresentation(t),g=x==="SUCCESS"?s.briefingTone.success.dot:x==="FAILED"?s.briefingTone.danger.dot:x?s.briefingTone.warning.dot:s.briefingTone.neutral.dot;return e.jsxs("div",{className:r.cn("group relative border-b border-border/60 px-4 py-3 transition-colors hover:bg-muted/60",p&&"opacity-70"),children:[e.jsxs("div",{role:"button",tabIndex:0,onClick:a,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),a())},className:"cursor-pointer pr-8",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.name}),p?e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:"· Paused"}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:h.typeLabel}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{children:Ft(t)}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx(s.Clock,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:Bt(t)}),t.lastRunAt?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:["Last run ",i]})]}):null]}),f||d?e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5 text-[12px] leading-[1.5] text-foreground/80",children:[d?e.jsx(r.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground/70"}):e.jsx("span",{className:r.cn("inline-block h-1.5 w-1.5 shrink-0 rounded-full",g)}),e.jsx("span",{className:"truncate",children:d?Ve(t):f})]}):null]}),e.jsx("div",{className:"absolute right-3 top-3",children:l?e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):n?e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",onClick:v=>v.stopPropagation(),className:"inline-flex h-6 w-6 items-center justify-center rounded-control text-muted-foreground/70 opacity-60 hover:bg-muted hover:text-foreground/80 focus-visible:opacity-100 group-hover:opacity-100","aria-label":`${h.noun==="report"?"Report":"Briefing"} actions`,children:e.jsx(s.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-44",children:[e.jsxs(s.DropdownMenuItem,{onClick:a,children:[e.jsx(s.Pencil,{className:"h-3.5 w-3.5"}),"Edit ",h.noun]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),c()},children:[e.jsx(s.Zap,{className:"h-3.5 w-3.5"}),"Run now"]}),t.scheduleExpr?e.jsx(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),o()},children:p?e.jsxs(e.Fragment,{children:[e.jsx(s.Play,{className:"h-3.5 w-3.5"}),"Resume"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Pause,{className:"h-3.5 w-3.5"}),"Pause"]})}):null,e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),u()},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(s.Trash2,{className:"h-3.5 w-3.5"}),"Delete ",h.noun]})]})]})})]})}const Vt=2e3,Ut=20*6e4;function Ot(t){return(t==null?void 0:t.trim())||"This dashboard"}function _t(t){return t==="This dashboard"?"Watch this dashboard":`Watch ${t}`}function zt(t,n,l){return n!=="dashboard"?t:t.filter(a=>a.source.type==="dashboard"&&a.source.dashboardId===l)}async function $t(t){const l=[];let a=1,c=0,o=Number.POSITIVE_INFINITY;for(;c<o;){const u=await t.apiClient.listBriefings(t.apiServiceUrl,t.token,{scope:"organization",page:a,pageSize:100});if(l.push(...u.briefings),c+=u.briefings.length,o=u.total,u.briefings.length===0||c>=o)break;a+=1}return l}const qt={listBriefings:s.listBriefings,getBriefing:s.getBriefing,pauseBriefing:s.pauseBriefing,resumeBriefing:s.resumeBriefing,deleteBriefing:s.deleteBriefing,runBriefingNow:s.runBriefingNow};function Ht({briefingId:t,initialRun:n,apiServiceUrl:l,token:a,onTerminal:c,onTimeout:o,onExpand:u}){const[p,d]=m.useState(n),{startRun:f}=s.useBriefingRunPolling({apiServiceUrl:l,token:a,intervalMs:Vt,timeoutMs:Ut,fetchRun:({apiServiceUrl:x,token:h,runId:g})=>s.getBriefingRun(x,h,t,g),onRun:x=>{d(x)},onTerminalRun:x=>{c(x)},onTimeout:()=>{o()}}),i=m.useRef(!1);return m.useEffect(()=>{i.current||(i.current=!0,s.isActiveBriefingRunStatus(n.status)?f(n):s.isTerminalBriefingRunStatus(n.status)&&c(n))},[n,c,f]),e.jsx(s.BackgroundRunPill,{run:p,onExpand:u})}function Wt(t){return e.jsx(s.BriefingUiCapabilitiesBoundary,{children:e.jsx(Gt,{...t})})}function Gt({dashboardId:t,dashboardTitle:n,apiServiceUrl:l,token:a,disabled:c,className:o,manageBriefingsHref:u,open:p,onOpenChange:d,hideTrigger:f=!1,workflowIntent:i,client:x}){const{authToken:h,tokenProps:g}=s.useSemaphorContext(),v=s.useBriefingUiCapabilities(),y=!i||v.canCreate&&(i==="scheduled_report"||v.analyticalBriefingsEnabled),[S,B]=m.useState(!1),D=p??S,w=N=>{p===void 0&&B(N),d==null||d(N)},[k,A]=m.useState(i?"author":"list"),[T,b]=m.useState(i??"analytical_briefing"),[j,L]=m.useState("dashboard"),[I,$]=m.useState([]),[E,M]=m.useState(null),_=i&&!y&&!E?"list":k,[oe,Q]=m.useState(!1),[J,he]=m.useState(null),[xe,ee]=m.useState(null),[z,W]=m.useState(null),[te,G]=m.useState(null),me=m.useRef(null),ie=m.useRef(D);m.useEffect(()=>{const N=D&&!ie.current;ie.current=D,!(!N||!i)&&(M(null),L("dashboard"),b(i),A("author"),G(null))},[D,i]);const[re,ne]=m.useState(null),[H,le]=m.useState(null),U=l??(g==null?void 0:g.apiServiceUrl),O=a??(h==null?void 0:h.accessToken),Z=m.useMemo(()=>({...qt,...x}),[x]),ae=Ot(n),pe=m.useMemo(()=>{const N=zt(I,j,t);if(!i)return N;const P=i==="scheduled_report"?"report":"briefing";return N.filter(fe=>X.getBriefingPresentation(fe).noun===P)},[t,I,j,i]),ve=m.useMemo(()=>j==="dashboard"?{source:{type:"dashboard",dashboardId:t},label:ae,detail:_t(ae)}:{source:{type:"project"},label:"This project",detail:"Use any data in this project."},[t,ae,j]),ce=!!(U&&O),de=X.getBriefingCreationIntents({canCreate:v.canCreate,analyticalBriefingsEnabled:v.analyticalBriefingsEnabled,scheduledReportAvailable:j==="dashboard"}),q=m.useCallback(async()=>{if(!(!U||!O)){Q(!0),G(null);try{$(await $t({apiClient:Z,apiServiceUrl:U,token:O}))}catch(N){G(N instanceof Error?N.message:"Could not load briefings.")}finally{Q(!1)}}},[Z,U,O]);m.useEffect(()=>{!D||_!=="list"||!ce||q()},[ce,_,q,D]);const ue=()=>{M(null),L("dashboard"),A("list"),w(!0)},C=N=>{M(null),b(N),A("author")},F=async N=>{if(!(!U||!O)){he(N),G(null);try{const P=await Z.getBriefing(U,O,N);M(P.briefing),A("author")}catch(P){G(P instanceof Error?P.message:"Could not open briefing.")}finally{he(null)}}},V=async N=>{if(!(!U||!O)){ee(N.id);try{await Z.runBriefingNow(U,O,N.id,{requestId:Xt()}),q()}catch(P){r.ue.error(P instanceof Error?P.message:"Could not start the run.")}finally{ee(null)}}},Y=async N=>{if(!U||!O)return;const{noun:P}=X.getBriefingPresentation(N),fe=P==="report"?"Report":"Briefing";ee(N.id);try{const ge=N.status==="PAUSED"?await Z.resumeBriefing(U,O,N.id):await Z.pauseBriefing(U,O,N.id);r.ue.success(ge.briefing.status==="PAUSED"?`${fe} paused`:`${fe} resumed`),q()}catch(ge){r.ue.error(ge instanceof Error?ge.message:`Could not update the ${P} status.`)}finally{ee(null)}},se=async()=>{if(!z||!U||!O)return;const N=z;ee(N.id);try{await Z.deleteBriefing(U,O,N.id);const{noun:P}=X.getBriefingPresentation(N);r.ue.success(`${P==="report"?"Report":"Briefing"} deleted`),W(null),q()}catch(P){r.ue.error(P instanceof Error?P.message:"Could not delete the briefing.")}finally{ee(null)}},Ue=pe.length;return v.surfaceVisible?e.jsxs(s.Sheet,{open:D,onOpenChange:w,children:[f?null:e.jsx(Pe,{disabled:c||!ce,briefingCount:Ue,className:o,onClick:ue}),e.jsxs(s.SheetContent,{ref:me,side:"right",hideClose:!0,className:"flex h-full w-full flex-col overflow-hidden p-0 outline-none sm:max-w-[560px]",onOpenAutoFocus:N=>{var P;N.preventDefault(),(P=me.current)==null||P.focus({preventScroll:!0})},children:[e.jsxs(s.SheetHeader,{className:"sr-only",children:[e.jsx(s.SheetTitle,{children:"Reports & briefings"}),e.jsx(s.SheetDescription,{children:"Manage reports and briefings for this dashboard."})]}),i?e.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-3 border-b border-border pl-4 pr-3 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-5",role:"tablist","aria-label":i==="scheduled_report"?"Email report workflow":"Analytical briefing workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":_==="author",disabled:!y,className:r.cn("-mb-px border-b-2 px-0.5 pb-2 text-[12px] transition-colors",_==="author"?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground",!y&&"cursor-not-allowed opacity-50"),onClick:()=>{y&&(M(null),b(i),L("dashboard"),A("author"))},children:E?`Edit ${X.getBriefingPresentation(E).noun}`:i==="scheduled_report"?"Schedule report":"Create briefing"}),e.jsx("button",{type:"button",role:"tab","aria-selected":_==="list",className:r.cn("-mb-px border-b-2 px-0.5 pb-2 text-[12px] transition-colors",_==="list"?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),onClick:()=>A("list"),children:i==="scheduled_report"?"Manage reports":"Manage briefings"})]}),e.jsx("button",{type:"button",onClick:()=>w(!1),className:"rounded-control p-1 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":i==="scheduled_report"?"Close email report workflow":"Close analytical briefing workflow",children:e.jsx(K.X,{className:"h-3.5 w-3.5"})})]}):null,_==="list"?e.jsx(Tt,{briefings:pe,dashboardLabel:ae,sourceView:j,error:te,loading:oe,onSourceViewChange:L,onClose:()=>w(!1),onEdit:N=>{F(N)},onNew:C,canCreate:!i&&de.length>0,canCreateScheduledReport:de.includes("scheduled_report"),analyticalBriefingsEnabled:de.includes("analytical_briefing"),onRunNow:N=>{V(N)},onTogglePause:N=>{Y(N)},onDelete:N=>W(N),selectingId:J,busyId:xe,manageBriefingsHref:u,contentKind:i==="scheduled_report"?"reports":i==="analytical_briefing"?"briefings":void 0,hideHeader:!!i}):e.jsx(s.BriefingAuthor,{apiServiceUrl:U,token:O,briefing:E,intent:T,sourceContext:E?void 0:ve,title:E?`Edit ${X.getBriefingPresentation(E).noun}`:T==="scheduled_report"?"Schedule report":"Create analytical briefing",hideHeader:!!i,className:"h-full min-h-0 max-w-none border-0 shadow-none",onBack:i?void 0:()=>A("list"),onCancel:()=>w(!1),onDeleted:()=>{const N=E?X.getBriefingPresentation(E).noun:"briefing";r.ue.success(`${N==="report"?"Report":"Briefing"} deleted`),M(null),A("list"),q()},onRunStarted:()=>{},onSaved:N=>{M(N),q()},onMinimizeRun:({briefing:N,run:P})=>{ne({briefing:N,run:P}),w(!1)}})]}),re&&U&&O?e.jsx(Ht,{briefingId:re.briefing.id,initialRun:re.run,apiServiceUrl:U,token:O,onTerminal:N=>{le({briefing:re.briefing,run:N}),ne(null),q()},onTimeout:()=>{ne(null),q()},onExpand:()=>{M(re.briefing),A("author"),ne(null),w(!0)}}):null,H?e.jsx("div",{className:"fixed bottom-4 right-4 z-50 w-[360px]",children:e.jsx(s.RunCompletionBanner,{title:H.run.status==="SUCCESS"?`${H.briefing.name} is ready`:`${H.briefing.name} run failed`,durationSeconds:H.run.startedAt&&H.run.completedAt?Math.max(0,Math.floor((new Date(H.run.completedAt).getTime()-new Date(H.run.startedAt).getTime())/1e3)):null,status:H.run.status==="SUCCESS"?"success":"failed",onView:()=>{M(H.briefing),A("author"),le(null),w(!0)},onDismiss:()=>le(null)})}):null,e.jsx(s.AlertDialog,{open:!!z,onOpenChange:N=>{N||W(null)},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsxs(s.AlertDialogTitle,{children:["Delete"," ",z?X.getBriefingPresentation(z).noun:"briefing","?"]}),e.jsxs(s.AlertDialogDescription,{children:["This permanently deletes ",e.jsx("strong",{children:z==null?void 0:z.name}),". Recipients will stop receiving it."]})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsxs(s.AlertDialogAction,{className:"bg-destructive/90 hover:bg-destructive",onClick:se,children:["Delete"," ",z?X.getBriefingPresentation(z).noun:"briefing"]})]})]})})]}):null}function Xt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-now-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}exports.AdvancedModeToggle=nt;exports.DashboardBriefingLauncher=Wt;exports.DashboardControlsSettings=Le;exports.DashboardFilterControlsButton=Me;exports.DashboardFilterControlsLauncher=Dt;exports.DocumentControlsSettings=Te;exports.ExportNotificationItem=Ie;exports.ExportNotificationList=Fe;exports.NotificationBell=pt;exports.UnsavedChangesAlert=at;exports.VisualEditingControls=rt;exports.VisualsLibraryDialog=Ye;exports.WatchDashboardButton=Pe;exports.useExportPolling=ht;exports.useExportRecovery=xt;
@@ -1 +0,0 @@
1
- "use strict";const r=require("zod"),n=require("./validators-4dRtYUI1.cjs"),I={answerSummary:"string",responseDetail:"responseDetail",mode:"string",comparisonKind:"string",executionResult:"executionResult",compiledQuery:"unknown",data:"unknown",resultSets:"record",analysisWarnings:"unknownArray",columns:"unknownArray",records:"recordArray",rowCount:"number",rowLimitExceeded:"boolean",output:"string",querySpec:"unknown",metadata:"record",validation:"validationResult",coverage:"coverage",diagnosticFeedback:"diagnosticFeedback",missingFields:"stringArray",warnings:"unknownArray",comparison:"unknown",population:"population",comparisons:"recordArray",fieldsUsed:"compactExecutionFieldArray",primary:"recordArray",contributors:"recordArray",segments:"recordArray",periodChanges:"recordArray",changes:"recordArray",largestNegativeChanges:"recordArray",largestPositiveChanges:"recordArray",drivers:"recordArray",absoluteDeltaDrivers:"recordArray",largestNegativeDrivers:"recordArray",largestPositiveDrivers:"recordArray",periodRows:"recordArray",sql:"unknown",omitted:"stringArray"},ke=Object.freeze({coordinates:2e4}),v=r.z.string().uuid(),p=r.z.string().min(1),Ae=r.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);function m(i,s,e){i.addIssue({code:"custom",path:s,message:e})}function h(i,s,e){new Set(i).size!==i.length&&m(s,e,"Duplicate identity.")}const Z=r.z.object({id:p,axis:n.matrixAxisSchema,parent:n.matrixPathSchema,position:r.z.union([r.z.object({kind:r.z.literal("first")}).strict(),r.z.object({kind:r.z.enum(["after","before"]),cursor:p}).strict()]),size:Ae}).strict(),K=r.z.object({paths:r.z.array(n.matrixPathSchema).readonly(),pageIds:r.z.array(p).readonly()}).strict(),ee=r.z.object({id:p,rows:K,columns:K,measureIds:r.z.array(v).min(1).readonly()}).strict(),D=r.z.object({pages:r.z.array(Z).readonly(),blocks:r.z.array(ee).readonly()}).strict().superRefine((i,s)=>{!i.pages.length&&!i.blocks.length&&m(s,[],"Request at least one page or block."),h([...i.pages,...i.blocks].map(e=>e.id),s,[]);for(const e of i.blocks){h(e.measureIds,s,["blocks",e.id,"measureIds"]);for(const t of["rows","columns"])for(const a of e[t].pageIds)i.pages.some(o=>o.id===a&&o.axis===t)||m(s,["blocks",e.id,t],"Page reference must name a page on this axis in this operation.")}}),Ie=r.z.object({spec:n.matrixSpecSchema,request:D}).strict().superRefine(({spec:i,request:s},e)=>{for(const t of s.pages)n.checkMatrixPath(i,t.axis,t.parent,e,["pages",t.id],!0),t.parent.length>=i[t.axis].length&&m(e,["pages",t.id],"Cannot request children of a leaf or empty axis.");for(const t of s.blocks){t.measureIds.some(a=>!i.measures.some(o=>o.id===a))&&m(e,["blocks",t.id],"Unknown block measure.");for(const a of["rows","columns"])for(const o of t[a].paths)n.checkMatrixPath(i,a,o,e,["blocks",t.id,a])}}),se=r.z.object({requestId:p,axis:n.matrixAxisSchema,parent:n.matrixPathSchema,members:r.z.array(r.z.object({path:n.matrixPathSchema}).strict()).readonly(),before:p.nullable(),after:p.nullable(),exactCount:r.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}).strict().superRefine((i,s)=>{i.parent.some(t=>t.member.kind==="others")&&m(s,["parent"],"Others has no children.");const e=i.members.filter(({path:t})=>{var a;return((a=t[t.length-1])==null?void 0:a.member.kind)==="others"});e.length>1&&m(s,["members"],"A page may contain Others only once."),e.length&&(i.members[i.members.length-1]!==e[0]&&m(s,["members"],"Others must be the last page member."),i.after!==null&&m(s,["after"],"Others must end the branch.")),new Set(i.members.map(t=>{var a;return(a=t.path[t.path.length-1])==null?void 0:a.levelId})).size>1&&m(s,["members"],"One page must contain one child level."),h(i.members.map(t=>n.matrixPathKey(t.path)),s,["members"]);for(const t of i.members)(t.path.length!==i.parent.length+1||n.matrixPathKey(t.path.slice(0,-1))!==n.matrixPathKey(i.parent))&&m(s,["members"],"Page members must be immediate children.")}),te=r.z.object({requestId:p,coverage:r.z.object({rowPaths:r.z.array(n.matrixPathSchema).readonly(),columnPaths:r.z.array(n.matrixPathSchema).readonly(),measureIds:r.z.array(v).readonly()}).strict(),cells:r.z.array(n.matrixCoordinateSchema.extend({value:n.semaphorScalarValueSchema}).strict()).readonly()}).strict().superRefine((i,s)=>{const e=i.coverage.rowPaths.map(n.matrixPathKey),t=i.coverage.columnPaths.map(n.matrixPathKey);h(e,s,["coverage","rowPaths"]),h(t,s,["coverage","columnPaths"]),h(i.coverage.measureIds,s,["coverage","measureIds"]);const a=new Set(e),o=new Set(t),d=new Set(i.coverage.measureIds);h(i.cells.map(c=>JSON.stringify([n.matrixPathKey(c.rowPath),n.matrixPathKey(c.columnPath),c.measureId])),s,["cells"]);for(const c of i.cells)(!a.has(n.matrixPathKey(c.rowPath))||!o.has(n.matrixPathKey(c.columnPath))||!d.has(c.measureId))&&m(s,["cells"],"Cell is outside certified coverage.")}),N=r.z.object({id:v,column:n.semaphorResultColumnSchema,nativeDataType:p,semanticFormat:n.semaphorValueFormatSchema.optional()}).strict(),ie=r.z.object({levels:r.z.array(N).readonly(),measures:r.z.array(N).readonly()}).strict(),_=r.z.object({code:r.z.enum(["invalid_request","unsupported_capability","stale_cursor","forbidden","budget_exceeded","source_truncated","execution_failed","cancelled"]),message:p,retryable:r.z.boolean(),scope:r.z.union([r.z.object({kind:r.z.literal("operation")}).strict(),r.z.object({kind:r.z.enum(["page","block"]),requestId:p}).strict()])}).strict(),re=r.z.object({dialect:r.z.enum(["postgres","clickhouse","duckdb"]),aggregates:r.z.array(n.matrixAggregateSchema).readonly()}).strict(),B=r.z.object({queryIdentity:p,descriptors:ie,capabilities:re,pages:r.z.array(se).readonly(),blocks:r.z.array(te).readonly(),failures:r.z.array(_).readonly()}).strict().superRefine((i,s)=>{const e=new Set(i.descriptors.levels.map(o=>o.id)),t=new Set(i.descriptors.measures.map(o=>o.id)),a=i.pages.flatMap(o=>[o.parent,...o.members.map(d=>d.path)]);for(const o of i.blocks)a.push(...o.coverage.rowPaths,...o.coverage.columnPaths),o.coverage.measureIds.some(d=>!t.has(d))&&m(s,["blocks",o.requestId],"Coverage references an unknown measure descriptor.");a.some(o=>o.some(d=>!e.has(d.levelId)))&&m(s,["descriptors"],"Acquired paths require level descriptors."),h([...i.descriptors.levels,...i.descriptors.measures].map(o=>o.id),s,["descriptors"]),h([...i.pages,...i.blocks].map(o=>o.requestId),s,[]),h(i.failures.map(o=>o.scope.kind==="operation"?"operation":o.scope.requestId),s,["failures"]);for(const o of i.failures)if(o.scope.kind==="operation")m(s,["failures"],"Operation failure cannot accompany acquired data.");else{const d=o.scope.requestId;[...i.pages,...i.blocks].some(c=>c.requestId===d)&&m(s,["failures"],"A requested unit cannot both succeed and fail.")}}),_e=r.z.union([r.z.object({status:r.z.enum(["success","partial"]),window:B}).strict(),r.z.object({status:r.z.literal("failed"),failure:_}).strict()]).superRefine((i,s)=>{if(i.status==="failed")return;const{window:e}=i;!e.pages.length&&!e.blocks.length&&m(s,["window"],"A window outcome requires successful acquired work."),i.status==="success"!=(e.failures.length===0)&&m(s,["status"],"Status must match failure coverage.")}),M=r.z.object({kind:r.z.literal("matrix"),window:B}).strict(),ae=r.z.enum(["member","subtotal","grand_total"]),oe=r.z.discriminatedUnion("kind",[r.z.object({kind:r.z.literal("hierarchy"),label:r.z.string()}).strict(),r.z.object({kind:r.z.literal("level"),levelId:v,label:r.z.string()}).strict(),r.z.object({kind:r.z.literal("measure"),measureId:v,columnPath:n.matrixPathSchema,role:ae,label:r.z.string()}).strict()]),ne=r.z.object({columns:r.z.array(oe).readonly(),descriptors:ie}).strict(),O=r.z.union([r.z.object({kind:r.z.literal("value"),value:n.semaphorScalarValueSchema.refine(i=>i!==null)}).strict(),r.z.object({kind:r.z.enum(["null","empty"])}).strict()]),ue=r.z.discriminatedUnion("kind",[r.z.object({kind:r.z.literal("layout"),rowPath:n.matrixPathSchema,role:ae,values:r.z.array(O).readonly()}).strict(),r.z.object({kind:r.z.literal("flat"),rowPath:n.matrixPathSchema,columnPath:n.matrixPathSchema,values:r.z.array(O).readonly()}).strict()]),Re=r.z.discriminatedUnion("kind",[r.z.object({kind:r.z.literal("layout"),layout:ne,next:p}).strict(),r.z.object({kind:r.z.literal("rows"),rows:r.z.array(ue).readonly(),next:p.nullable()}).strict()]),T=r.z.object({intent:n.matrixAnalyticalIntentSchema,matrixWindowRequest:D}).strict(),A="semaphor-data-app-codegen-summary/v1",xe="semaphor-data-app-codegen-summary-validator/v2",Ee=new Set(["metric","records","matrix","analysis","sql_fallback"]),Ce=new Set(["semaphor.metric","semaphor.records","semaphor.matrix","semaphor.analysis","semaphor.sql"]),qe=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]),je=new Set(["absolute_delta","largest_negative","largest_positive","positive_and_negative","all"]),ce=new Set(["source","id","label","measures","primaryMeasure","dateField","timeGrain","dimensions","comparison","orderBy","filters","relationshipHint","limit","derivedFields"]),Fe=new Set([...ce,"analysis","timeWindow","filters","driverMode","includePopulation","calendarContext","chartTitle","chartType"]),Ke=new Set(["source","id","label","fields","dateField","timeGrain","timeWindow","filters","orderBy","relationshipHint","limit","pagination","totals","derivedFields"]),Ne=new Set(["source","id","label","sql","defaultParameters","pythonCode","fields","limit","pagination","rationale"]),Oe=new Set(["kpi","line_chart","bar_chart","stacked_bar_chart","pie_chart","donut_chart","area_chart","table","matrix","narrative","text_block","custom"]),Pe=new Set(["missing_measure","missing_dimension","missing_date","missing_relationship","missing_semantic_role","missing_current_app_state","raw_identifier_filter_options","unsupported_change_intent","ambiguous_field_grounding","bounded_intent_unavailable","invalid_bounded_intent_output","latest_snapshot_selector_not_modeled","unsupported_grain","requires_sql_escape_hatch","unsupported_sdk_capability"]);function De(i){return V(i).ok}function V(i){const s=[];if(!i||typeof i!="object")return{ok:!1,issues:["Summary must be an object."]};const e=i;return e.schemaVersion!==A&&s.push(`schemaVersion must be ${A}.`),(typeof e.title!="string"||!e.title.trim())&&s.push("title is required."),Array.isArray(e.sources)||s.push("sources must be an array."),Array.isArray(e.inputs)||s.push("inputs must be an array."),Array.isArray(e.views)||s.push("views must be an array."),Array.isArray(e.filterContracts)||s.push("filterContracts must be an array."),(!e.implementationChecklist||typeof e.implementationChecklist!="object")&&s.push("implementationChecklist must be an object."),e.implementationChecklist&&typeof e.implementationChecklist=="object"&&s.push(...Me(e.implementationChecklist)),Array.isArray(e.sources)&&e.sources.forEach((t,a)=>{s.push(...R(t,`sources.${a}`))}),Array.isArray(e.inputs)&&e.inputs.forEach((t,a)=>{s.push(...Te(t,`inputs.${a}`))}),Array.isArray(e.views)&&e.views.forEach((t,a)=>{s.push(...Ve(t,`views.${a}`))}),Array.isArray(e.filterContracts)&&e.filterContracts.forEach((t,a)=>{s.push(...Ze(t,`filterContracts.${a}`))}),e.unsupportedInsights!==void 0&&(Array.isArray(e.unsupportedInsights)?e.unsupportedInsights.forEach((t,a)=>{s.push(...fs(t,`unsupportedInsights.${a}`))}):s.push("unsupportedInsights must be an array.")),s.push(...Be(e)),{ok:s.length===0,issues:s}}function Be(i){const s=Array.isArray(i.unsupportedInsights)&&i.unsupportedInsights.some(d=>{var c;return H.has((c=u(d))==null?void 0:c.reason)}),e=Array.isArray(i.views)&&i.views.some(d=>{var l;const c=u((l=u(d))==null?void 0:l.computation);return(c==null?void 0:c.kind)==="unsupported"&&H.has(c.reason)});if(!s&&!e)return[];const t=[],a=u(i.validation);(a==null?void 0:a.status)!=="blocked"&&t.push("validation.status must be blocked when semantic model repair gaps are present.");const o=u(i.nextRequiredTool);return(o==null?void 0:o.name)!=="semaphor_propose_semantic_model_change"&&t.push("nextRequiredTool.name must be semaphor_propose_semantic_model_change when semantic model repair gaps are present."),t}const H=new Set(["missing_relationship","raw_identifier_filter_options"]);function R(i,s){const e=u(i);return e?e.kind==="semantic"?typeof e.domainId=="string"&&e.domainId.trim()&&typeof e.datasetName=="string"&&e.datasetName.trim()?[]:[`${s} must include sourceKey or a supported source identity.`]:typeof e.sourceKey=="string"&&e.sourceKey.trim()?[]:e.kind==="physical"&&typeof e.tableName=="string"&&e.tableName.trim()&&typeof e.connectionId=="string"&&e.connectionId.trim()?[]:e.kind==="sql"&&typeof e.connectionId=="string"&&e.connectionId.trim()?[]:[`${s} must include sourceKey or a supported source identity.`]:[`${s} must be an object.`]}function Me(i){const s=u(i);if(!s)return["implementationChecklist must be an object."];const e=[],t=["requiredDevtools","requiredInputOptions","filterScopeByInput","bindingsByView","validationCommands","browserSmokeChecks"];for(const o of t)o in s||e.push(`implementationChecklist.${o} is required.`);const a=u(s.requiredDevtools);return a?typeof a.mountRootDevtools!="boolean"&&e.push("implementationChecklist.requiredDevtools.mountRootDevtools must be a boolean."):e.push("implementationChecklist.requiredDevtools must be an object."),Array.isArray(s.requiredInputOptions)||e.push("implementationChecklist.requiredInputOptions must be an array."),Array.isArray(s.filterScopeByInput)||e.push("implementationChecklist.filterScopeByInput must be an array."),u(s.bindingsByView)||e.push("implementationChecklist.bindingsByView must be an object."),y(s.validationCommands)||e.push("implementationChecklist.validationCommands must be an array of strings."),y(s.browserSmokeChecks)||e.push("implementationChecklist.browserSmokeChecks must be an array of strings."),e}function Te(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return(typeof e.id!="string"||!e.id.trim())&&t.push(`${s}.id is required.`),e.fieldRef&&t.push(...f(e.fieldRef,`${s}.fieldRef`)),t.push(...le(e.optionQuery,`${s}.optionQuery`)),y(e.appliesToViewIds)||t.push(`${s}.appliesToViewIds must be an array of strings.`),e.bindings!==void 0&&!Array.isArray(e.bindings)&&t.push(`${s}.bindings must be an array.`),Array.isArray(e.bindings)&&e.bindings.forEach((a,o)=>{const d=u(a);if(!d){t.push(`${s}.bindings.${o} must be an object.`);return}y(d.appliesToViewIds)||t.push(`${s}.bindings.${o}.appliesToViewIds must be an array of strings.`),t.push(...f(d.fieldRef,`${s}.bindings.${o}.fieldRef`))}),t}function Ve(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];if((typeof e.id!="string"||!e.id.trim())&&t.push(`${s}.id is required.`),e.visualSpec!==void 0&&t.push(...ns(e.visualSpec,`${s}.visualSpec`)),e.computation!==void 0&&t.push(...ps(e.computation,`${s}.computation`)),os(e))return t.push(...E(e,`${s}`)),e.fields!==void 0&&(Array.isArray(e.fields)?e.fields.forEach((l,g)=>{t.push(...f(l,`${s}.fields.${g}`))}):t.push(`${s}.fields must be an array.`)),e.queryKind!==void 0&&t.push(`${s}.queryKind is not allowed for non-executable views.`),e.sdkBuilder!==void 0&&t.push(`${s}.sdkBuilder is not allowed for non-executable views.`),e.sdkSpec!==void 0&&t.push(`${s}.sdkSpec is not allowed for non-executable views.`),t;if(!Array.isArray(e.fields))return t.push(`${s}.fields must be an array.`),(e.sdkSpec!==void 0||e.sdkBuilder!==void 0)&&t.push(`${s}.fields must be an array for executable views.`),t.push(...E(e,`${s}`)),t;e.fields.forEach((l,g)=>{t.push(...f(l,`${s}.fields.${g}`))}),z(e.queryKind)||t.push(`${s}.queryKind must be a supported codegen query kind.`),e.sdkBuilder!==void 0&&!pe(e.sdkBuilder)&&t.push(`${s}.sdkBuilder must be a supported SDK builder.`),e.metricBindingKeys!==void 0&&(Array.isArray(e.metricBindingKeys)?e.metricBindingKeys.some(l=>typeof l!="string"||l.trim().length===0)&&t.push(`${s}.metricBindingKeys must be an array of strings.`):t.push(`${s}.metricBindingKeys must be an array of strings.`));const a=u(e.sdkSpec),o=(a==null?void 0:a.builder)==="semaphor.metric";o&&(!Array.isArray(e.metricBindingKeys)||e.metricBindingKeys.length===0)&&t.push(`${s}.metricBindingKeys is required for metric views.`);const d=Ue(e);o&&Array.isArray(e.metricBindingKeys)&&d&&JSON.stringify(e.metricBindingKeys)!==JSON.stringify(d)&&t.push(`${s}.metricBindingKeys must match the generated metric field binding keys in order.`);const c=u(e.computation);return(c==null?void 0:c.kind)==="server_query"&&z(e.queryKind)&&z(c.queryKind)&&c.queryKind!==e.queryKind&&t.push(`${s}.computation.queryKind must match queryKind.`),t.push(...es({value:e.sdkSpec,path:`${s}.sdkSpec`,queryKind:typeof e.queryKind=="string"?e.queryKind:void 0,sdkBuilder:typeof e.sdkBuilder=="string"?e.sdkBuilder:void 0}),...E(e,`${s}`)),t}function Ue(i){const s=u(i.sdkSpec);if((s==null?void 0:s.builder)!=="semaphor.metric")return;const e=u(s.spec);if(!e)return;const a=[e.primaryMeasure,...Array.isArray(e.measures)?e.measures:[]].map(Le).filter(o=>!!o);return Array.from(new Map(a.map(o=>[o.identity,o.bindingKey])).values())}function Le(i){const s=u(i);if(!s||typeof s.name!="string"||!s.name.trim())return;const e=Ge(s);return e?{identity:JSON.stringify({source:e,name:s.name,aggregate:de(s)}),bindingKey:Qe(s)}:void 0}function Ge(i){if(typeof i.sourceKey=="string"&&i.sourceKey.trim())return{sourceKey:i.sourceKey};const s=u(i.source);if(s)return{kind:s.kind,domainId:s.domainId,datasetId:s.datasetId,datasetName:s.datasetName,name:s.name}}function Qe(i){return typeof i.sourceKey=="string"&&i.sourceKey.trim()?[i.sourceKey,de(i),i.name].filter(Boolean).join(":"):n.semaphorMetricMeasureBindingKey(i)}function de(i){return n.semaphorMetricAggregate(i)}function E(i,s){var g;const e=u((g=u(i.visualSpec))==null?void 0:g.tableBehavior),t=u(i.sdkSpec),a=u(t==null?void 0:t.spec),o=typeof(t==null?void 0:t.builder)=="string"?t.builder:void 0,d=o==="semaphor.records"?u(a==null?void 0:a.totals):void 0,c=[];if(!e)return d&&c.push(`${s}.sdkSpec.spec.totals is only allowed when tableBehavior.totals.mode is server.`),c;const l=u(e.totals);return l?(l.mode==="server"&&(o!=="semaphor.records"&&c.push(`${s}.visualSpec.tableBehavior.totals.mode server is only supported for semaphor.records views.`),!d||d.mode!=="server"?c.push(`${s}.sdkSpec.spec.totals.mode must be server when tableBehavior.totals.mode is server.`):c.push(...We({left:l.measures,right:d.measures,leftPath:`${s}.visualSpec.tableBehavior.totals.measures`,rightPath:`${s}.sdkSpec.spec.totals.measures`}))),l.mode!=="server"&&d&&c.push(`${s}.sdkSpec.spec.totals is only allowed when tableBehavior.totals.mode is server.`),o==="semaphor.sql"&&l.mode!=="none"&&c.push(`${s}.visualSpec.tableBehavior.totals.mode must be none for semaphor.sql views.`),o==="semaphor.sql"&&u(a==null?void 0:a.totals)&&c.push(`${s}.sdkSpec.spec.totals is not supported for semaphor.sql.`),c):(d&&c.push(`${s}.sdkSpec.spec.totals is only allowed when tableBehavior.totals.mode is server.`),c)}function We({left:i,right:s,leftPath:e,rightPath:t}){if(!Array.isArray(i)||!Array.isArray(s))return[`${t} must match ${e}.`];const a=[];return i.length!==s.length?(a.push(`${t} must match ${e}.`),a):(i.forEach((o,d)=>{He(u(o),u(s[d]))||a.push(`${t}.${d} must match ${e}.${d}.`)}),a)}function He(i,s){return!i||!s?!1:i.name===s.name&&(i.role||"measure")===(s.role||"measure")&&Y(i)===Y(s)&&Ye(i,s)}function Y(i){return typeof i.aggregate=="string"?i.aggregate.toUpperCase():"SUM"}function Ye(i,s){const e=u(i.source),t=u(s.source);if(Xe(e,t))return!1;const a=X(i),o=X(s);if(a.size>0||o.size>0){for(const d of a)if(o.has(d))return!0;return!1}return!e||!t||e.kind!==t.kind?!1:e.kind==="semantic"?e.domainId===t.domainId&&e.datasetName===t.datasetName&&(e.datasetId===void 0||t.datasetId===void 0||e.datasetId===t.datasetId):e.kind==="physical"?e.connectionId===t.connectionId&&e.tableName===t.tableName:e.kind==="sql"?e.connectionId===t.connectionId:!1}function Xe(i,s){if(!i||!s||i.kind!=="semantic"||s.kind!=="semantic")return!1;const e=typeof i.datasetId=="string"?i.datasetId.trim():"",t=typeof s.datasetId=="string"?s.datasetId.trim():"";return!!(e&&t&&e!==t)}function X(i){const s=typeof i.sourceKey=="string"?i.sourceKey.trim():"";return s?new Set([s]):Je(u(i.source))}function Je(i){const s=new Set;if(!i)return s;const e=typeof i.sourceKey=="string"?i.sourceKey.trim():"";if(e&&s.add(e),i.kind==="semantic"){const t=typeof i.domainId=="string"?i.domainId:"",a=typeof i.datasetName=="string"?i.datasetName:"",o=typeof i.datasetId=="string"?i.datasetId:"";t&&o&&s.add(`semantic:${t}:datasetId:${o}`),t&&a&&s.add(`semantic:${t}:datasetName:${a}`)}if(i.kind==="physical"){const t=typeof i.connectionId=="string"?i.connectionId:"",a=typeof i.tableName=="string"?i.tableName:"",o=typeof i.databaseName=="string"?i.databaseName:"",d=typeof i.schemaName=="string"?i.schemaName:"";t&&a&&(s.add(["physical",t,o,d,a].join(":")),s.add(`physical:${t}:${a}`))}if(i.kind==="sql"){const t=typeof i.connectionId=="string"?i.connectionId:"",a=typeof i.dialect=="string"?i.dialect:"",o=typeof i.label=="string"?i.label:"";t&&(s.add(["sql",t,a,o].join(":")),s.add(`sql:${t}`))}return s}function Ze(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];if(e.fieldRef&&t.push(...f(e.fieldRef,`${s}.fieldRef`)),(typeof e.inputId!="string"||!e.inputId.trim())&&t.push(`${s}.inputId is required.`),t.push(...le(e.optionQuery,`${s}.optionQuery`)),y(e.appliesToViewIds)||t.push(`${s}.appliesToViewIds must be an array of strings.`),y(e.notAppliedToViewIds)||t.push(`${s}.notAppliedToViewIds must be an array of strings.`),!Array.isArray(e.bindings))t.push(`${s}.bindings must be an array.`);else{const a=y(e.appliesToViewIds)?new Set(e.appliesToViewIds):void 0,o=y(e.notAppliedToViewIds)?new Set(e.notAppliedToViewIds):void 0;e.bindings.forEach((d,c)=>{const l=u(d);if(!l){t.push(`${s}.bindings.${c} must be an object.`);return}typeof l.viewId!="string"||!l.viewId?t.push(`${s}.bindings.${c}.viewId is required.`):(a&&!a.has(l.viewId)&&t.push(`${s}.bindings.${c}.viewId must be included in appliesToViewIds.`),o!=null&&o.has(l.viewId)&&t.push(`${s}.bindings.${c}.viewId must not be listed in notAppliedToViewIds.`)),t.push(...f(l.fieldRef,`${s}.bindings.${c}.fieldRef`))})}return t}function le(i,s){if(i===void 0)return[];const e=u(i);if(!e)return[`${s} must be an object.`];const t=[...b(e.valueFieldRef,`${s}.valueFieldRef`),...b(e.labelFieldRef,`${s}.labelFieldRef`),...b(e.filterFieldRef,`${s}.filterFieldRef`)];if(e.builder!=="semaphor.inputOptions"&&t.push(`${s}.builder must be semaphor.inputOptions.`),typeof e.sourceKey!="string"&&e.source===void 0&&t.push(`${s} must include source or sourceKey.`),e.source!==void 0){const a=u(e.source);!a||a.kind!=="semantic"&&a.kind!=="physical"?t.push(`${s}.source.kind must be semantic or physical.`):t.push(...R(e.source,`${s}.source`))}return u(e.valueFieldRef)||t.push(`${s}.valueFieldRef is required.`),u(e.labelFieldRef)||t.push(`${s}.labelFieldRef is required.`),e.limit!==void 0&&(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<=0)&&t.push(`${s}.limit must be a positive integer.`),t}function es(i){var a;const s=u(i.value);if(!s)return[`${i.path} is required for executable views.`];const e=[];if(!pe(s.builder))return e.push(`${i.path}.builder must be a supported SDK builder.`),e;i.sdkBuilder&&s.builder!==i.sdkBuilder&&e.push(`${i.path}.builder must match sdkBuilder.`),i.queryKind&&z(i.queryKind)&&s.builder!==as(i.queryKind)&&e.push(`${i.path}.builder must match queryKind.`);const t=u(s.spec);if(!t)return e.push(`${i.path}.spec must be an object.`),e;switch(s.builder){case"semaphor.metric":e.push(...w(t,ce,`${i.path}.spec`),...k(t,i.path),...C(t.measures,`${i.path}.spec.measures`),...b(t.primaryMeasure,`${i.path}.spec.primaryMeasure`),...b(t.dateField,`${i.path}.spec.dateField`),...q(t.dimensions,`${i.path}.spec.dimensions`),...j(t.orderBy,`${i.path}.spec.orderBy`),...F(t.filters,`${i.path}.spec.filters`));break;case"semaphor.analysis":e.push(...w(t,Fe,`${i.path}.spec`),...k(t,i.path),...C(t.measures,`${i.path}.spec.measures`),...b(t.primaryMeasure,`${i.path}.spec.primaryMeasure`),...b(t.dateField,`${i.path}.spec.dateField`),...q(t.dimensions,`${i.path}.spec.dimensions`),...j(t.orderBy,`${i.path}.spec.orderBy`),...F(t.filters,`${i.path}.spec.filters`),...ss(t,`${i.path}.spec`));break;case"semaphor.records":e.push(...w(t,Ke,`${i.path}.spec`),...k(t,i.path),...C(t.fields,`${i.path}.spec.fields`),...b(t.dateField,`${i.path}.spec.dateField`),...j(t.orderBy,`${i.path}.spec.orderBy`),...F(t.filters,`${i.path}.spec.filters`),...ts(t.totals,`${i.path}.spec.totals`));break;case"semaphor.matrix":{const{id:o,label:d,matrixWindowRequest:c,...l}=t;for(const[$,x]of Object.entries({id:o,label:d}))x!==void 0&&(typeof x!="string"||!x.trim())&&e.push(`${i.path}.spec.${$} must be a nonempty string.`);const g=T.safeParse({intent:{...l,kind:"matrix"},matrixWindowRequest:c});g.success||e.push(...g.error.issues.map($=>`${i.path}.spec.${$.path.join(".")}: ${$.message}`));break}case"semaphor.sql":e.push(...w(t,Ne,`${i.path}.spec`),...k(t,i.path)),((a=u(t.source))==null?void 0:a.kind)!=="sql"&&e.push(`${i.path}.spec.source.kind must be sql.`),(typeof t.sql!="string"||!t.sql.trim())&&e.push(`${i.path}.spec.sql is required.`),e.push(...q(t.fields,`${i.path}.spec.fields`));break}return e}function ss(i,s){const e=[];if(i.driverMode!==void 0&&!je.has(i.driverMode)&&e.push(`${s}.driverMode must be a supported analysis driver mode.`),i.includePopulation!==void 0&&typeof i.includePopulation!="boolean"&&e.push(`${s}.includePopulation must be a boolean.`),i.calendarContext!==void 0){const t=u(i.calendarContext);if(!t)e.push(`${s}.calendarContext must be an object.`);else{t.tz!==void 0&&typeof t.tz!="string"&&e.push(`${s}.calendarContext.tz must be a string.`),t.weekStart!==void 0&&(typeof t.weekStart!="number"||!Number.isInteger(t.weekStart)||t.weekStart<0||t.weekStart>6)&&e.push(`${s}.calendarContext.weekStart must be an integer between 0 and 6.`);const a=t.anchor;if(a!==void 0&&a!=="now"){const o=u(a);(!o||typeof o.iso!="string"||!o.iso.trim())&&e.push(`${s}.calendarContext.anchor must be now or { iso }.`)}}}return e}function ts(i,s){if(i===void 0)return[];const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return e.mode!=="server"&&t.push(`${s}.mode must be server.`),!Array.isArray(e.measures)||e.measures.length===0?t.push(`${s}.measures must include at least one measure.`):e.measures.forEach((a,o)=>{var d;t.push(...fe(a,`${s}.measures.${o}`)),((d=u(a))==null?void 0:d.role)!=="measure"&&t.push(`${s}.measures.${o}.role must be measure.`)}),t}function w(i,s,e){const t=[];return Object.keys(i).forEach(a=>{s.has(a)||t.push(`${e}.${a} is not supported for this SDK builder.`)}),t}function k(i,s){return u(i.source)?R(i.source,`${s}.spec.source`):[`${s}.spec.source must be an object.`]}function C(i,s){const e=rs(i,s);return Array.isArray(i)&&i.forEach((t,a)=>{e.push(...f(t,`${s}.${a}`))}),e}function q(i,s){if(i===void 0)return[];if(!Array.isArray(i))return[`${s} must be an array.`];const e=[];return i.forEach((t,a)=>{e.push(...f(t,`${s}.${a}`))}),e}function j(i,s){if(i===void 0)return[];const e=u(i);return e?[...f(e.field,`${s}.field`),...is(e.direction,`${s}.direction`)]:[`${s} must be an object.`]}function is(i,s){return i==="asc"||i==="desc"?[]:[`${s} must be asc or desc.`]}function F(i,s){if(i===void 0)return[];if(!Array.isArray(i))return[`${s} must be an array.`];const e=[];return i.forEach((t,a)=>{const o=u(t);if(!o){e.push(`${s}.${a} must be an object.`);return}e.push(...f(o.field,`${s}.${a}.field`))}),e}function rs(i,s){return!Array.isArray(i)||i.length===0?[`${s} must be a non-empty array.`]:[]}function as(i){switch(i){case"metric":return"semaphor.metric";case"records":return"semaphor.records";case"matrix":return"semaphor.matrix";case"analysis":return"semaphor.analysis";case"sql_fallback":return"semaphor.sql"}}function os(i){const s=u(i.computation),e=u(i.visualSpec);return(s==null?void 0:s.kind)==="presentation_only"||(s==null?void 0:s.kind)==="derived"||(s==null?void 0:s.kind)==="unsupported"||i.visual==="text_block"||(e==null?void 0:e.visualType)==="text_block"}function ns(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return Oe.has(e.visualType)||t.push(`${s}.visualType must be a supported visual type.`),e.limit!==void 0&&(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<=0)&&t.push(`${s}.limit must be a positive integer.`),e.tableBehavior!==void 0&&t.push(...us(e.tableBehavior,`${s}.tableBehavior`)),t}function us(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return e.tableMode!=="bounded"&&e.tableMode!=="server_paginated"&&e.tableMode!=="server_windowed"&&t.push(`${s}.tableMode must be a supported table mode.`),t.push(...cs(e.height,`${s}.height`),...ds(e.pagination,`${s}.pagination`),...ls(e.sorting,`${s}.sorting`),...ms(e.totals,`${s}.totals`)),typeof e.serverSideRequired!="boolean"&&t.push(`${s}.serverSideRequired must be a boolean.`),t}function cs(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return(typeof e.maxPx!="number"||!Number.isInteger(e.maxPx)||e.maxPx<=0)&&t.push(`${s}.maxPx must be a positive integer.`),e.scroll!=="vertical"&&e.scroll!=="both"&&t.push(`${s}.scroll must be vertical or both.`),typeof e.stickyHeader!="boolean"&&t.push(`${s}.stickyHeader must be a boolean.`),t}function ds(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return e.mode!=="none"&&e.mode!=="server"&&e.mode!=="client_for_bounded_rows"&&t.push(`${s}.mode must be a supported pagination mode.`),e.pageSize!==void 0&&(typeof e.pageSize!="number"||!Number.isInteger(e.pageSize)||e.pageSize<=0)&&t.push(`${s}.pageSize must be a positive integer.`),e.readsFrom!==void 0&&e.readsFrom!=="result.pagination"&&t.push(`${s}.readsFrom must be result.pagination.`),t}function ls(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return e.mode!=="server"&&e.mode!=="client_for_bounded_rows"&&t.push(`${s}.mode must be a supported sorting mode.`),e.defaultField!==void 0&&(typeof e.defaultField!="string"||!e.defaultField.trim())&&t.push(`${s}.defaultField must be a non-empty string.`),e.defaultDirection!==void 0&&e.defaultDirection!=="asc"&&e.defaultDirection!=="desc"&&t.push(`${s}.defaultDirection must be asc or desc.`),e.resetPageOnChange!==void 0&&typeof e.resetPageOnChange!="boolean"&&t.push(`${s}.resetPageOnChange must be a boolean.`),t}function ms(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return e.mode!=="none"&&e.mode!=="server"&&e.mode!=="local"?(t.push(`${s}.mode must be none, server, or local.`),t):e.mode==="none"?(e.measures!==void 0&&t.push(`${s}.measures is not allowed when mode is none.`),e.label!==void 0&&t.push(`${s}.label is not allowed when mode is none.`),t):e.mode==="server"?(!Array.isArray(e.measures)||e.measures.length===0?t.push(`${s}.measures must include at least one measure when mode is server.`):e.measures.forEach((a,o)=>{var d;t.push(...fe(a,`${s}.measures.${o}`)),((d=u(a))==null?void 0:d.role)!=="measure"&&t.push(`${s}.measures.${o}.role must be measure.`)}),e.label!==void 0&&t.push(`${s}.label is not allowed when mode is server.`),t):(e.mode==="local"&&(e.label!=="Displayed rows"&&e.label!=="Current page"&&t.push(`${s}.label must be Displayed rows or Current page when mode is local.`),e.measures!==void 0&&t.push(`${s}.measures is not allowed when mode is local.`)),t)}function ps(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];switch(e.kind){case"server_query":z(e.queryKind)||t.push(`${s}.queryKind must be a supported codegen query kind.`),e.queryOwnership!==void 0&&e.queryOwnership!=="view_owned"&&e.queryOwnership!=="shared_query"&&t.push(`${s}.queryOwnership must be view_owned or shared_query.`),e.sourceKeys!==void 0&&!y(e.sourceKeys)&&t.push(`${s}.sourceKeys must be an array of strings.`),e.fieldNames!==void 0&&!y(e.fieldNames)&&t.push(`${s}.fieldNames must be an array of strings.`);break;case"derived":(typeof e.upstreamViewId!="string"||!e.upstreamViewId.trim())&&t.push(`${s}.upstreamViewId is required.`),(typeof e.derivation!="string"||!e.derivation.trim())&&t.push(`${s}.derivation is required.`);break;case"presentation_only":break;case"unsupported":(typeof e.reason!="string"||!e.reason.trim())&&t.push(`${s}.reason is required.`),(typeof e.suggestedModelingFix!="string"||!e.suggestedModelingFix.trim())&&t.push(`${s}.suggestedModelingFix is required.`);break;default:t.push(`${s}.kind must be a supported computation kind.`)}return t}function fs(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];for(const o of["title","requestedQuestion","suggestedModelingFix"])(typeof e[o]!="string"||!e[o].trim())&&t.push(`${s}.${o} is required.`);return Pe.has(e.reason)||t.push(`${s}.reason must be a supported unsupported insight reason.`),(e.relationshipCandidate!==void 0||e.nextRepairAction!==void 0)&&e.reason!=="missing_relationship"&&t.push(`${s} relationship repair metadata is only valid for missing_relationship unsupported insights.`),e.diagnostic!==void 0&&t.push(...hs(e.diagnostic,`${s}.diagnostic`,e.reason)),e.relationshipCandidate!==void 0&&t.push(...gs(e.relationshipCandidate,`${s}.relationshipCandidate`)),e.nextRepairAction!==void 0&&t.push(...ys(e.nextRepairAction,`${s}.nextRepairAction`)),t}function hs(i,s,e){const t=u(i);if(!t)return[`${s} must be an object.`];const a=[],o=new Set(["kind","inputId","inputLabel","optionSource","optionField","missingEvidence"]);Object.keys(t).forEach(c=>{o.has(c)||a.push(`${s}.${c} is not supported; raw identifier diagnostics support only kind, inputId, inputLabel, optionSource, optionField, and missingEvidence.`)}),e!=="raw_identifier_filter_options"&&a.push(`${s} is only valid for raw_identifier_filter_options unsupported insights.`),t.kind!=="raw_identifier_filter_options"&&a.push(`${s}.kind must be raw_identifier_filter_options.`);for(const c of["inputId","inputLabel"])(typeof t[c]!="string"||!t[c].trim())&&a.push(`${s}.${c} must be a non-empty string.`);a.push(...P(t.optionSource,`${s}.optionSource`)),a.push(...me(t.optionField,`${s}.optionField`));const d=new Set(["display_field","relationship_display_path"]);return!Array.isArray(t.missingEvidence)||t.missingEvidence.length===0?a.push(`${s}.missingEvidence must be a non-empty evidence array.`):t.missingEvidence.forEach((c,l)=>{d.has(c)||a.push(`${s}.missingEvidence.${l} must be display_field or relationship_display_path.`)}),a}function ys(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[],a=new Set(["tool","reason"]);return Object.keys(e).forEach(o=>{a.has(o)||t.push(`${s}.${o} is not supported; repair actions support only tool and reason.`)}),e.tool!=="semaphor_propose_semantic_model_change"&&t.push(`${s}.tool must be semaphor_propose_semantic_model_change.`),e.reason!=="missing_relationship"&&t.push(`${s}.reason must be missing_relationship.`),t}function gs(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[],a=new Set(["source","sourceFields","target","targetFields"]);Object.keys(e).forEach(o=>{a.has(o)||t.push(`${s}.${o} is not supported; relationship candidates support only source, sourceFields, target, and targetFields.`)}),t.push(...P(e.source,`${s}.source`)),t.push(...P(e.target,`${s}.target`));for(const o of["sourceFields","targetFields"]){const d=e[o];if(!Array.isArray(d)||d.length===0){t.push(`${s}.${o} must be a non-empty endpoint field array.`);continue}d.forEach((c,l)=>{t.push(...me(c,`${s}.${o}.${l}`))})}return t}function me(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[],a=new Set(["name","label","role","dataType"]);return Object.keys(e).forEach(o=>{a.has(o)||t.push(`${s}.${o} is not supported; relationship candidate fields are scoped by their endpoint and support only name, label, role, and dataType.`)}),(typeof e.name!="string"||!e.name.trim())&&t.push(`${s}.name must be a non-empty string.`),e.role!==void 0&&(typeof e.role!="string"||!["dimension","measure","date","id","unknown"].includes(e.role))&&t.push(`${s}.role must be dimension, measure, date, id, or unknown.`),e.dataType!==void 0&&(typeof e.dataType!="string"||!["string","number","boolean","date","datetime","unknown"].includes(e.dataType))&&t.push(`${s}.dataType must be string, number, boolean, date, datetime, or unknown.`),t}function P(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[],a=new Set(["kind","domainId","datasetName","datasetId","label","sourceKey"]);return Object.keys(e).forEach(o=>{a.has(o)||t.push(`${s}.${o} is not supported; relationship candidate sources support only semantic identity fields.`)}),e.kind!=="semantic"&&t.push(`${s} must use semantic source identity.`),(typeof e.domainId!="string"||!e.domainId.trim()||typeof e.datasetName!="string"||!e.datasetName.trim())&&t.push(`${s} must include semantic domainId and datasetName.`),t}function z(i){return Ee.has(i)}function pe(i){return Ce.has(i)}function b(i,s){return i===void 0?[]:f(i,s)}function f(i,s){const e=u(i);if(!e)return[`${s} must be an object.`];const t=[];return(typeof e.name!="string"||!e.name.trim())&&t.push(`${s}.name is required.`),!e.source&&typeof e.sourceKey!="string"&&t.push(`${s} must include source or sourceKey.`),e.aggregate!==void 0&&!qe.has(e.aggregate)&&t.push(`${s}.aggregate must be a supported aggregate function.`),t}function fe(i,s){const e=u(i),t=f(i,s);if(!e||typeof e.sourceKey=="string"&&e.sourceKey.trim())return t;if(e.source!==void 0){const o=R(e.source,`${s}.source`);return o.length===0||t.push(...o),t}return t.includes(`${s} must include source or sourceKey.`)||t.push(`${s} must include source or sourceKey.`),t}function u(i){return i&&typeof i=="object"&&!Array.isArray(i)?i:void 0}function y(i){return Array.isArray(i)&&i.every(s=>typeof s=="string")}const he=r.z.union([n.semaphorMetricResultSchema,n.semaphorRecordsResultSchema,n.semaphorInputOptionsResultSchema,n.semaphorSqlResultSchema,M]),ye=r.z.object({status:r.z.enum(["not_required","resolved","missing","ambiguous","fanout_risk","unknown"]),requiredSources:r.z.array(n.semaphorSourceRefSchema).optional(),relationshipsUsed:r.z.array(r.z.string()).optional(),missingSources:r.z.array(r.z.string()).optional(),warnings:r.z.array(r.z.string()).optional(),message:r.z.string().optional(),recommendedNextStep:r.z.string().optional(),joinPlanSummary:r.z.object({baseSource:n.semaphorSourceRefSchema.optional(),joinedSources:r.z.array(n.semaphorSourceRefSchema).optional(),joinCount:r.z.number().optional()}).passthrough().optional(),fanoutRisk:r.z.object({status:r.z.enum(["none","warning","error","unknown"]),message:r.z.string().optional()}).passthrough().optional()}).passthrough(),J=r.z.enum(["ambiguous_fields","empty_result","missing_grounded_fields","missing_relationship","no_grounded_query","partial_result","presentation_incomplete","query_validation_failed","unsafe_join"]),U=r.z.object({version:r.z.literal(1),status:r.z.enum(["answered","partial","blocked"]),summary:r.z.string(),answered:r.z.array(r.z.object({slotId:r.z.string().optional(),queryId:r.z.string().optional(),summary:r.z.string(),evidenceIds:r.z.array(r.z.string()).optional(),fieldsUsed:r.z.array(n.semaphorExecutionFieldRefSchema).optional()}).passthrough()),blocked:r.z.array(r.z.object({slotId:r.z.string().optional(),queryId:r.z.string().optional(),reasonCode:J,message:r.z.string(),missingFields:r.z.array(r.z.string()).optional(),availableFields:r.z.array(r.z.string()).optional(),ambiguousFields:r.z.array(r.z.string()).optional(),missingRelationships:r.z.array(r.z.string()).optional(),evidenceIds:r.z.array(r.z.string()).optional(),neededFromUser:r.z.array(r.z.string()).optional(),recommendedNextStep:r.z.string().optional()}).passthrough()),semanticModelRecommendations:r.z.array(r.z.object({reasonCode:J,message:r.z.string(),recommendedNextStep:r.z.string().optional()}).passthrough()).optional()}).passthrough(),L=r.z.object({scope:r.z.literal("filtered_query"),measures:r.z.record(n.nullableScalarSchema)}).passthrough(),G=r.z.object({answeredObligations:r.z.array(r.z.string()),missingObligations:r.z.array(r.z.string()),warnings:r.z.array(n.semaphorAnalyticsValidationIssueSchema).optional()}).passthrough(),Q=r.z.object({intentId:r.z.string().optional(),queryId:r.z.string().optional(),status:r.z.enum(["answered","partial","failed"]),resultShape:r.z.enum(["metric","records","inputOptions","sql","matrix","period_change","analysis"]).optional(),intent:r.z.unknown().optional(),compiledQuery:r.z.unknown().optional(),fieldsUsed:r.z.array(n.semaphorExecutionFieldRefSchema).optional(),result:he.optional(),validation:n.semaphorAnalyticsValidationResultSchema,coverage:G.optional(),missingFields:r.z.array(r.z.string()).optional(),warnings:r.z.array(r.z.string()).optional(),relationshipDiagnostics:ye.optional(),diagnosticFeedback:U.optional(),population:L.optional(),metadata:r.z.record(r.z.string(),r.z.unknown()).optional()}).passthrough(),ge=Q;function bs(i){switch(i){case"boolean":return r.z.boolean().optional();case"compactExecutionFieldArray":return r.z.array(n.semaphorCompactFieldRefSchema).optional();case"coverage":return G.optional();case"diagnosticFeedback":return U.optional();case"executionFieldArray":return r.z.array(n.semaphorExecutionFieldRefSchema).optional();case"executionResult":return ge.optional();case"number":return r.z.number().finite().optional();case"population":return L.optional();case"record":return n.recordSchema.optional();case"recordArray":return n.recordArraySchema.optional();case"responseDetail":return r.z.enum(["compact","standard","debug"]).optional();case"string":return r.z.string().optional();case"stringArray":return r.z.array(r.z.string()).optional();case"unknown":return r.z.unknown().optional();case"unknownArray":return r.z.array(r.z.unknown()).optional();case"validationResult":return n.semaphorAnalyticsValidationResultSchema.optional()}}const be=Object.fromEntries(Object.entries(I).map(([i,s])=>[i,bs(s)])),Se=r.z.object(be).strict(),W=r.z.object({sourceKey:r.z.string().optional(),kind:r.z.enum(["semantic","physical","sql"]).optional(),domainId:r.z.string().optional(),datasetName:r.z.string().optional(),datasetId:r.z.string().optional(),connectionId:r.z.string().optional(),tableName:r.z.string().optional(),label:r.z.string().optional()}).passthrough(),S=r.z.object({name:r.z.string(),label:r.z.string().optional(),role:r.z.enum(["dimension","measure","date","id","unknown"]).optional(),dataType:r.z.enum(["string","number","boolean","date","datetime","unknown"]).optional(),aggregate:n.semaphorAggregateFunctionSchema.optional(),sourceKey:r.z.string().optional(),source:W.optional()}).passthrough(),ze=r.z.object({id:r.z.string().optional(),builder:r.z.literal("semaphor.inputOptions"),source:W.optional(),sourceKey:r.z.string().optional(),valueFieldRef:S,labelFieldRef:S,filterFieldRef:S.optional(),population:r.z.unknown().optional(),dependencies:r.z.unknown().optional(),limit:r.z.number().int().positive().optional(),spec:n.recordSchema.optional()}).passthrough(),ve=r.z.object({appliesToViewIds:r.z.array(r.z.string()).optional(),viewId:r.z.string().optional(),fieldRef:S,relationshipHint:r.z.unknown().optional(),relationshipsUsed:r.z.array(n.recordSchema).optional()}).passthrough(),Ss=r.z.object({id:r.z.string(),label:r.z.string().optional(),type:r.z.string().optional(),serverSide:r.z.boolean().optional(),fieldRef:S.optional(),optionQuery:ze.optional(),bindings:r.z.array(ve).optional(),appliesToViewIds:r.z.array(r.z.string()),relationshipHint:r.z.unknown().optional(),relationshipsUsed:r.z.array(n.recordSchema).optional()}).passthrough(),zs=r.z.object({builder:r.z.enum(["semaphor.metric","semaphor.records","semaphor.matrix","semaphor.analysis","semaphor.sql"]),spec:n.recordSchema,fallbackReason:n.recordSchema.optional()}).passthrough(),vs=r.z.object({id:r.z.string(),title:r.z.string().optional(),purpose:r.z.string().optional(),sourcePresentation:r.z.object({sourceKeys:r.z.array(r.z.string()).optional(),sourceLabels:r.z.array(r.z.string()).optional()}).passthrough().optional(),visual:r.z.string().optional(),visualSpec:n.recordSchema.optional(),queryKind:r.z.enum(["metric","records","matrix","analysis","sql_fallback"]).optional(),sdkBuilder:r.z.enum(["semaphor.metric","semaphor.records","semaphor.matrix","semaphor.analysis","semaphor.sql"]).optional(),sdkSpec:zs.optional(),fields:r.z.array(S).optional(),computation:n.recordSchema.optional(),uxExpectations:r.z.array(r.z.string()).optional(),validation:n.recordSchema.optional()}).passthrough(),$s=r.z.object({inputId:r.z.string(),label:r.z.string().optional(),type:r.z.string().optional(),serverSide:r.z.boolean().optional(),fieldRef:S.optional(),optionQuery:ze.optional(),bindings:r.z.array(ve),appliesToViewIds:r.z.array(r.z.string()),notAppliedToViewIds:r.z.array(r.z.string())}).passthrough(),ws=r.z.object({schemaVersion:r.z.literal(A),title:r.z.string(),purpose:r.z.string().optional(),userGoal:r.z.string().optional(),nextStep:r.z.string().optional(),sources:r.z.array(W),inputs:r.z.array(Ss),views:r.z.array(vs),filterContracts:r.z.array($s),implementationChecklist:r.z.object({schemaVersion:r.z.string().optional(),requiredDevtools:r.z.object({mountRootDevtools:r.z.boolean(),providerDebugBridge:r.z.string().optional(),panelPosition:r.z.string().optional(),forbidden:r.z.array(r.z.string()).optional()}).passthrough(),requiredInputOptions:r.z.array(n.recordSchema),filterScopeByInput:r.z.array(n.recordSchema),bindingsByView:r.z.record(r.z.string(),r.z.array(n.recordSchema)),validationCommands:r.z.array(r.z.string()),browserSmokeChecks:r.z.array(r.z.string())}).passthrough(),nextRequiredTool:r.z.object({name:r.z.string(),reason:r.z.string().optional()}).optional(),unsupportedInsights:r.z.array(r.z.object({title:r.z.string(),requestedQuestion:r.z.string(),reason:r.z.string(),suggestedModelingFix:r.z.string()}).passthrough()).optional(),assumptions:r.z.array(r.z.string()).optional(),validation:n.recordSchema.optional()}).passthrough().superRefine((i,s)=>{const e=V(i);for(const t of e.issues)s.addIssue({code:r.z.ZodIssueCode.custom,message:t})}),ks=new Set(Object.keys(I));function As(){return Object.keys(I)}function $e(i){return ks.has(i)}function Is(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Semaphor analyze result must be an object.");const e=Object.keys(i).filter(t=>!$e(t));if(e.length)throw new Error(`Semaphor analyze result contains unsupported top-level field(s): ${e.join(", ")}.`);return Se.parse(i)}const we=r.z.object({runtimeFilters:n.matrixSpecSchema.innerType().shape.filters,runtimeSorts:n.matrixSpecSchema.innerType().shape.sorts.optional()});function _s(i){return we.parse(i)}const Rs={compiledQuery:r.z.never().optional(),intent:T.shape.intent,resultShape:r.z.literal("matrix"),result:M.optional(),metadata:r.z.object({rowLimitExceeded:r.z.boolean(),matrixFailure:_.optional()}).passthrough()},xs=Q.extend(Rs),Es=xs.superRefine((i,s)=>{i.status==="failed"==!!i.result&&s.addIssue({code:"custom",message:"Only answered or partial Matrix execution carries a window."}),i.result&&i.status==="partial"!=i.result.window.failures.length>0&&s.addIssue({code:"custom",message:"Matrix execution status must match acquired window failures."})});exports.MATRIX_WINDOW_LIMITS=ke;exports.SEMAPHOR_ANALYZE_RESULT_FIELD_CONTRACT=I;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION=A;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION=xe;exports.analyticsExecutionEnvelopeSchema=Q;exports.getSemaphorAnalyzeResultFieldNames=As;exports.isSemaphorAnalyzeResultFieldName=$e;exports.isSemaphorDataAppCodegenSummary=De;exports.matrixAxisPageSchema=se;exports.matrixBlockRequestSchema=ee;exports.matrixCapabilitiesSchema=re;exports.matrixCellBlockSchema=te;exports.matrixDescriptorSchema=N;exports.matrixExecutionResultSchema=Es;exports.matrixExportBatchSchema=Re;exports.matrixExportColumnSchema=oe;exports.matrixExportLayoutSchema=ne;exports.matrixExportRowSchema=ue;exports.matrixExportValueSchema=O;exports.matrixFailureSchema=_;exports.matrixOperationRequestSchema=T;exports.matrixPageRequestSchema=Z;exports.matrixPathSelectionSchema=K;exports.matrixResultSchema=M;exports.matrixRuntimeInputsSchema=we;exports.matrixWindowInputSchema=Ie;exports.matrixWindowOutcomeSchema=_e;exports.matrixWindowRequestSchema=D;exports.matrixWindowSchema=B;exports.parseMatrixRuntimeInputs=_s;exports.parseSemaphorAnalyzeResult=Is;exports.semaphorAnalyticsCoverageSchema=G;exports.semaphorAnalyticsDiagnosticFeedbackSchema=U;exports.semaphorAnalyticsExecutionResultSchema=ge;exports.semaphorAnalyticsPopulationSchema=L;exports.semaphorAnalyticsResultSchema=he;exports.semaphorAnalyzeResultSchema=Se;exports.semaphorAnalyzeResultShape=be;exports.semaphorDataAppCodegenSummarySchema=ws;exports.semaphorRelationshipDiagnosticsSchema=ye;exports.validateSemaphorDataAppCodegenSummary=V;