react-semaphor 0.1.519 → 0.1.520

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 (84) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/package.json +25 -48
  3. package/dist/analytics-protocol/index.cjs +0 -1
  4. package/dist/appearance/index.cjs +0 -1
  5. package/dist/appearance-runtime/index.cjs +0 -1
  6. package/dist/brand-studio/index.cjs +0 -16
  7. package/dist/briefings/index.cjs +0 -1
  8. package/dist/chunks/appearance-context-DzqCdhB4.cjs +0 -1
  9. package/dist/chunks/appearance-runtime-provider-D5pkvgE4.cjs +0 -1
  10. package/dist/chunks/braces-v55uLCAK.cjs +0 -6
  11. package/dist/chunks/calculated-field-identity-5bg9oHTw.cjs +0 -1
  12. package/dist/chunks/canonical-result-keys-Cb96edol.cjs +0 -1
  13. package/dist/chunks/card-config-utils-z86y6tSq.cjs +0 -1
  14. package/dist/chunks/color-CyB5o13F.cjs +0 -4
  15. package/dist/chunks/column-bands-CU0byntA.cjs +0 -1
  16. package/dist/chunks/common-types-nBuCd3u2.cjs +0 -1
  17. package/dist/chunks/constants-B00YUv89.cjs +0 -1
  18. package/dist/chunks/dashboard-briefing-launcher-edgVkxY9.cjs +0 -21
  19. package/dist/chunks/dashboard-controls-BU4GRhTj.cjs +0 -52
  20. package/dist/chunks/dashboard-date-comparison-definition-Y6JZwpcr.cjs +0 -1
  21. package/dist/chunks/dashboard-json--bOkkyj1.cjs +0 -1
  22. package/dist/chunks/edit-dashboard-visual-4H05QT83.cjs +0 -172
  23. package/dist/chunks/editor-action-buttons-DZcRlo61.cjs +0 -16
  24. package/dist/chunks/field-aggregations-pH_3kymD.cjs +0 -1
  25. package/dist/chunks/field-dependencies-EB485TdB.cjs +0 -1
  26. package/dist/chunks/index-CapO5Uw9.cjs +0 -4
  27. package/dist/chunks/index-Cx3qmRUB.cjs +0 -1
  28. package/dist/chunks/index-D4ah3SrH.cjs +0 -1434
  29. package/dist/chunks/layout-grid-xm8pqtx0.cjs +0 -6
  30. package/dist/chunks/matrix-analytical-definition-BWd159lN.cjs +0 -1
  31. package/dist/chunks/matrix-card-C2RjEYZ8.cjs +0 -1
  32. package/dist/chunks/matrix-continuation-6nhDy-lF.cjs +0 -1
  33. package/dist/chunks/matrix-control-sources-BvEJF7d3.cjs +0 -1
  34. package/dist/chunks/matrix-definition-DanUT11P.cjs +0 -1
  35. package/dist/chunks/matrix-formatter-Qk8xsR05.cjs +0 -1
  36. package/dist/chunks/matrix-member-presentation-DvXDEo0U.cjs +0 -1
  37. package/dist/chunks/matrix-operation-contract-0RxoU_M3.cjs +0 -1
  38. package/dist/chunks/metric-comparison-CUmltzpz.cjs +0 -1
  39. package/dist/chunks/mouse-pointer-2-DX4A_XZw.cjs +0 -6
  40. package/dist/chunks/normalize-dashboard-for-dirty-check-BYtBA708.cjs +0 -1
  41. package/dist/chunks/numeric-presentation-mY6wJMdB.cjs +0 -1
  42. package/dist/chunks/operators-DEfKaU_V.cjs +0 -1
  43. package/dist/chunks/palette-BN-jYtaK.cjs +0 -6
  44. package/dist/chunks/pivot-header-presentation-DV2aBB6p.cjs +0 -5
  45. package/dist/chunks/pivot-result-identity-gquWljbd.cjs +0 -1
  46. package/dist/chunks/pivot-result-lifecycle-OXAgoIYm.cjs +0 -1
  47. package/dist/chunks/raw-temporal-CYdOOyR5.cjs +0 -1
  48. package/dist/chunks/raw-temporal-contract-CklMVG_1.cjs +0 -1
  49. package/dist/chunks/report-preferences-dialog-CZISeLGV.cjs +0 -1
  50. package/dist/chunks/report-runtime-context-CzSrCBsu.cjs +0 -1
  51. package/dist/chunks/save-3dYRmehL.cjs +0 -6
  52. package/dist/chunks/selection-reducer-Kl22OzIk.cjs +0 -26
  53. package/dist/chunks/semantic-format-Bd7HmLG_.cjs +0 -1
  54. package/dist/chunks/source-entity-resolution-R46X34SE.cjs +0 -1
  55. package/dist/chunks/stable-serialize-jqCpyZvd.cjs +0 -1
  56. package/dist/chunks/switch-C0520nRt.cjs +0 -134
  57. package/dist/chunks/temporal-bucket-4YEPEKlJ.cjs +0 -1
  58. package/dist/chunks/temporal-bucket-contract-nTv6gvX5.cjs +0 -1
  59. package/dist/chunks/temporal-input-presentation-BIOSVWCL.cjs +0 -1
  60. package/dist/chunks/token-types-aWrzwonf.cjs +0 -1
  61. package/dist/chunks/update-policy-DRDLWe7Y.cjs +0 -3
  62. package/dist/chunks/use-debounced-dirty-check-XHSwAefL.cjs +0 -1
  63. package/dist/chunks/validators-DFeDcdpA.cjs +0 -1
  64. package/dist/chunks/x-B6ghREd2.cjs +0 -31
  65. package/dist/dashboard/index.cjs +0 -1
  66. package/dist/dashboard-assistant/index.cjs +0 -1
  67. package/dist/dashboard-authoring/index.cjs +0 -3
  68. package/dist/data-app-builder/index.cjs +0 -51
  69. package/dist/data-app-builder-browser-runtime/index.cjs +0 -1
  70. package/dist/data-app-codegen/index.cjs +0 -1
  71. package/dist/data-app-codegen-node/index.cjs +0 -660
  72. package/dist/data-app-sdk/index.cjs +0 -117
  73. package/dist/data-app-sdk-adapters/index.cjs +0 -1
  74. package/dist/data-app-sdk-validation/index.cjs +0 -1
  75. package/dist/format-utils/index.cjs +0 -3
  76. package/dist/index.cjs +0 -1
  77. package/dist/layouts/index.cjs +0 -1
  78. package/dist/pdf-export-policy/index.cjs +0 -1
  79. package/dist/pdf-table-layout/index.cjs +0 -1
  80. package/dist/report-runtime-context/index.cjs +0 -1
  81. package/dist/shared/index.cjs +0 -1
  82. package/dist/surfboard/index.cjs +0 -1
  83. package/dist/types/index.cjs +0 -1
  84. package/dist/value-format-preferences/index.cjs +0 -1
@@ -1,16 +0,0 @@
1
- "use strict";const J=require("./x-B6ghREd2.cjs"),C=require("react"),r=require("./switch-C0520nRt.cjs"),y=require("./index-D4ah3SrH.cjs"),e=require("react/jsx-runtime");require("./card-config-utils-z86y6tSq.cjs");const Te=require("./validators-DFeDcdpA.cjs");require("./matrix-operation-contract-0RxoU_M3.cjs");require("../value-format-preferences/index.cjs");const ge=require("./selection-reducer-Kl22OzIk.cjs"),Fe=require("./index-CapO5Uw9.cjs"),Se=require("./save-3dYRmehL.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 Ve=J.createLucideIcon("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/**
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 je=J.createLucideIcon("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/**
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 ke=J.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);function Ie(s){const[a,i]=C.useState(null),[n,c]=C.useState(null),u=y.useEnsureReactGlobals();return C.useEffect(()=>{if(!s||s.trim()===""){i(null),c(null);return}if(!u)return;(async()=>{try{if(!s.startsWith("http://")&&!s.startsWith("https://"))throw new Error(`Invalid URL format: ${s}`);try{new URL(s)}catch{throw new Error(`Invalid URL: ${s}`)}const p=`${s.endsWith("/")?s:`${s}/`}index.js`;try{if(!(await fetch(p,{method:"HEAD"})).ok)throw new Error(`Module not found at ${p}`)}catch{}const v=await import(p);if(typeof v.useChartStore!="function")throw new Error("useChartStore is not a function");i(()=>v.useChartStore),c(null)}catch(h){const p=h instanceof Error?h.message:"Unknown error";console.error("Failed to load remote chart store:",p),c(p),i(null)}})()},[s,u]),a}function Le(s,a){if(s.length===0)return"";const i=s.find(n=>{var c,u;return((c=n.customCardPreferences)==null?void 0:c.visualType)==="multiple"||!!((u=n.customCardPreferences)!=null&&u.dataInputCardIds)});if(i)return i.id;if(a){const n=s.find(c=>c.id===a);if(n){const c=n.tabTitle;if(c=="All__Header")return s[0].id;if(c&&c.endsWith("__Header")){const m=c.split("__")[0],h=s.find(p=>p.tabTitle===m);return h?h.id:s[0].id}return a}}return s[0].id}const Ae=s=>{if(!s||!("detailTableBackup"in s))return s;const{detailTableBackup:a,...i}=s;return i};async function be(s,a,i,n,c="Opening library visual..."){if(!a||!i)throw new Error("Missing auth token or visual ID");const u=["resource-by-id","visual",i],m=n.getQueryData(u);if(m)return console.log("Using cached visual data for:",i),{data:m,fromCache:!0};console.log("Fetching visual data from network for:",i);const h=r.ue.loading(c,{position:"top-center"});try{const p=await fetch(`${s}/management/v1/visuals/${i}`,{headers:{Authorization:`Bearer ${a}`}});if(!p.ok)throw new Error("Failed to load visual");const v=await p.json();return n.setQueryData(u,v),r.ue.dismiss(h),{data:v,fromCache:!1}}catch(p){throw r.ue.dismiss(h),p}}function Ne(s){if(typeof s=="string")return JSON.parse(s);if(typeof s=="object")return s;throw new Error("Invalid frame object format")}function _e(s,a){var u,m;const i=(s==null?void 0:s.frameObject)??((u=s==null?void 0:s.visual)==null?void 0:u.frameObject);if(!i)return!1;const n=Ne(i);if(!(n!=null&&n.cards)||n.cards.length===0)return!1;const c=(m=n.cards)==null?void 0:m.find(h=>h.id===n.activeCardId);return c?(y.setupEditorWithCard({...a,frame:n,card:c,visualId:(s==null?void 0:s.id)||n.visualId}),!0):!1}function qe(){const s=r.useEditorStore(n=>{var c;return((c=n.card.customCardPreferences)==null?void 0:c.url)||""}),a=Ie(s);return{getUpdatedFrame:C.useCallback(()=>{var L;y.flushPendingEditorDrafts();const{frame:n,card:c,isDevMode:u,isShowingVisual:m,selectedSchemaName:h,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:b,selectedConnectionId:f}=r.useEditorStore.getState(),j=c.sql,D=(L=a==null?void 0:a.getState())==null?void 0:L.settings,k=r.buildSavedEditorCard(c,{isDevMode:u,cardSql:j,isShowingVisual:m,selectedSchemaName:h,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:b,selectedConnectionId:f,remoteChartSettings:D,stripConfig:Ae}),E=n.cards.map(O=>O.id===c.id?k:O);return{...n,cards:E,activeCardId:Le(E,n.activeCardId)}},[a])}}function ae(){const{authToken:s,tokenProps:a}=y.useSemaphorContext(),i=y.useQueryClient(),n=y.useAddFrameWithFreshSemanticExecutionPayload(),c=y.useSelectedVisual(),{selectVisual:u}=y.useManagementActions(),{setFrame:m,setCard:h,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:b,updateDataSource:f,setQueryResultColumns:j,setSelectedConnectionId:D,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:L,setSelectedDatamodelId:O,setFilterValues:H,setInlineFilterValuesMap:U,setApplyFilters:z,clearEditorContext:W}=r.useEditorActions(),{setIsDashboardEditing:V,setIsVisualEditing:o,setSelectedFrameId:w,clearSelectedFrameId:Q}=r.useDashboardActions(),M=r.useDashboardStore(A=>A.selectedSheetId),K=r.useDashboardStore(A=>A.selectedFrameId),P=r.useDashboardStore(A=>A.dashboard),X=r.useDashboardStore(A=>A.filterValues),B=r.useDashboardStore(A=>A.inlineFilterValuesMap),Y=y.useVisualById((c==null?void 0:c.id)||"",{enabled:!!(c!=null&&c.id)&&!!(s!=null&&s.accessToken)}),Z=C.useCallback(async A=>{try{u(A),Q(),W();const{data:I,fromCache:$}=await be(a.apiServiceUrl,(s==null?void 0:s.accessToken)||"",A.id,i,"Opening library visual...");if(!_e(I,{setFrame:m,setCard:h,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:b,updateDataSource:f,setQueryResultColumns:j,setSelectedConnectionId:D,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:L,setSelectedDatamodelId:O,setFilterValues:H,setInlineFilterValuesMap:U,setApplyFilters:z,setIsDashboardEditing:V,setIsVisualEditing:o,dashboard:P,selectedSheetId:M,selectedFrameId:K,filterValues:X,inlineFilterValuesMap:B}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:$}}catch(I){return console.error("Error editing visual:",I),{success:!1,error:"Failed to load visual for editing"}}},[s==null?void 0:s.accessToken,a.apiServiceUrl,i,u,m,h,V,o,p,v,b,f,j,D,k,E,L,O,H,U,z,W,Q,P,M,K,X,B]),ne=C.useCallback(async A=>{var $;const I=q=>(r.ue.error(q),{success:!1,error:q});try{if(u(A),!M)return I("No sheet selected. Please select a sheet first.");const{data:q,fromCache:oe}=await be(a.apiServiceUrl,(s==null?void 0:s.accessToken)||"",A.id,i,"Adding visual to dashboard..."),re=(q==null?void 0:q.frameObject)??(($=q==null?void 0:q.visual)==null?void 0:$.frameObject);if(!re)return I("Visual has no frame data");const R=Ne(re);if(!(R!=null&&R.cards)||R.cards.length===0)return I("Visual frame is malformed");const te={...y.cloneLinkedFrameWithSourceMapping(R),visualId:A.id};return await n(M,te,"end"),V(!0),w(te.id),{success:!0,fromCache:oe}}catch(q){return console.error("Error adding visual:",q),I(q instanceof Error?q.message:"Failed to add visual to dashboard")}},[s==null?void 0:s.accessToken,a.apiServiceUrl,i,u,M,V,w,n]);return{visual:Y.data,isLoading:Y.isLoading,isError:Y.isError,error:Y.error,handleEditLibraryVisual:Z,handleAddLibraryVisual:ne,getUpdatedFrame:qe().getUpdatedFrame,refetch:Y.refetch}}function Be(){const s=r.useEditorStore(m=>m.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:i,setSelectedSchemaName:n,setSelectedTableName:c,setSelectedDatamodelId:u}=r.useEditorActions();C.useEffect(()=>{var D;if(!s)return;const{tableName:m,schemaName:h,databaseName:p,connectionId:v}=y.extractTableMetadata(s),b=(D=s.selectedEntities)==null?void 0:D[0],j=(b==null?void 0:b.type)==="model"&&"id"in b?b.id:"";a(v||""),i(p||""),n(h||""),c(m||""),u(j)},[s,a,i,n,c,u])}function Me(s,a){return{...s,sql:"",python:"",config:void 0,customCfg:"",preferences:{},interactionConfig:void 0,linkedInteractionTargetOverrides:void 0,dynamicCardPreferences:void 0,customCardPreferences:a?s.customCardPreferences:void 0,visualizationMode:"builtin",type:a?s.type:"bar"}}function Ee(){const{setTempQueryData:s}=r.useEditorActions(),a=y.useQueryClient(),i=r.useEditorStore(U=>U.tempQueryData),n=r.useEditorStore(U=>U.card),c=y.useEffectiveEditorCardType(),u=C.useMemo(()=>c!==n.type?{...n,type:c}:n,[n,c]),{queryKey:m}=y.useEditorCardQuery(u),{setCardSql:h,setSqlGen:p,setCardPython:v,setCardCustomCfg:b,setCardPreferences:f,clearQueryConfig:j,setCardConfig:D,setCardType:k,setFrame:E,setCard:L,setActiveTabCardId:O}=r.useEditorActions();function H(){var Q,M,K,P;const U=a.getQueryData(m);i!=null&&i.queryData||s({queryKey:m,queryData:U}),a.setQueryData(m,null),a.removeQueries({queryKey:m,exact:!0}),h(""),p({}),j(),D(void 0),v(""),b(""),f({});const z=r.useEditorStore.getState().frame,W=r.useEditorStore.getState().card,V=Fe.findCustomVisualConfigCard(z,W),o=((Q=V==null?void 0:V.customCardPreferences)==null?void 0:Q.visualType)==="multiple"||!!((M=V==null?void 0:V.customCardPreferences)!=null&&M.dataInputCardIds)||(((K=V==null?void 0:V.customCardPreferences)==null?void 0:K.minInputs)||0)>1||(((P=V==null?void 0:V.customCardPreferences)==null?void 0:P.maxInputs)||0)>1,w=Me(W,o);E({...z,cards:z.cards.map(X=>X.id===w.id?w:X)}),O(w.id),L(w),o||k("bar")}return H}function Oe({type:s,isLinked:a,className:i,showLabel:n=!1,showLocal:c=!1}){const u=r.useDashboardStore(E=>E.selectedFrameId),m=y.useManagementStore(E=>E.selectedVisual),h=r.useEditorStore(E=>E.frame);let p;if(s)p=s;else if(a!==void 0)p=a?"linked":"library";else if(!!!(h!=null&&h.visualId||m!=null&&m.id)&&u)p="local";else if(m&&!u)p="library";else if(h!=null&&h.visualId&&u)p="linked";else if(m!=null&&m.id&&u)p="library";else return null;if(p==="local"&&!c)return null;const v={local:"border-slate-200/70 bg-slate-50/80 text-slate-700 shadow-sm hover:bg-slate-100/80 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:bg-slate-800/80",linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},b={local:"Local to this dashboard: Changes made here only affect this dashboard copy.",linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},f={local:"border-slate-200 bg-slate-50 text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100",linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},j={local:"fill-slate-50 dark:fill-slate-900",linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},D={local:e.jsx("span",{className:"h-2 w-2 rounded-full bg-current/70"}),linked:e.jsx(ke,{className:"h-3.5 w-3.5"}),library:e.jsx(je,{className:"h-3.5 w-3.5"})},k={local:"Local",linked:"Linked",library:"Library"};return e.jsx(r.TooltipProvider,{children:e.jsxs(r.Tooltip,{delayDuration:300,children:[e.jsx(r.TooltipTrigger,{asChild:!0,children:e.jsxs(y.Badge,{variant:"outline",className:r.cn("cursor-help select-none transition-all",v[p],i),children:[D[p],n&&e.jsx("span",{className:"ml-1 text-xs font-medium leading-none",children:k[p]})]})}),e.jsxs(r.TooltipContent,{side:"bottom",className:r.cn("max-w-xs",f[p]),children:[e.jsx(r.TooltipArrow,{className:j[p]}),e.jsx("p",{children:b[p]})]})]})})}function we(s){const{control:a,onChange:i}=s;return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(r.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(r.Input,{size:"xs",value:a.label,placeholder:"Control label",onChange:n=>i(n.target.value)})]})}function Ue(s){const{currentStep:a,labels:i}=s;return e.jsx("div",{className:"sticky top-0 z-10 -mx-1 border-b border-border/60 bg-background/95 px-1 pb-2.5 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:e.jsx("div",{className:"flex flex-wrap items-center gap-2 sm:gap-2.5",children:i.map((n,c)=>{const u=c+1,m=u===a,h=u<a;return e.jsxs(C.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:r.cn("flex h-5 w-5 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",m?"border-foreground bg-foreground text-background":h?"border-foreground/30 bg-foreground/10 text-foreground":"border-border/60 bg-background text-muted-foreground"),children:u}),e.jsx("span",{className:r.cn("text-[12px]",m?"font-medium text-foreground":"text-muted-foreground"),children:n})]}),c<i.length-1?e.jsx("span",{className:"h-px w-4 bg-border/60 sm:w-6","aria-hidden":"true"}):null]},n)})})})}function se(s){const{secondary:a,tertiary:i,primary:n}=s;return e.jsxs("div",{className:"sticky bottom-0 z-10 -mx-1 flex justify-end gap-2 border-t bg-background/95 px-1 pb-1 pt-3 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:[a,i,n]})}function Re(s){const{control:a,scope:i,detail:n}=s;return e.jsxs("div",{className:"flex items-start gap-2.5 rounded-control border border-border/60 bg-muted/30 px-3 py-2.5",children:[e.jsx(y.CircleCheck,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:a.label}),e.jsxs("div",{className:"text-[12px] text-muted-foreground",children:[r.getFriendlyTypeOption(a.type).label," ·"," ",r.getControlOptionPreview(a)," ·"," ",r.getPlacementLabel(i,a.placement)]}),n?e.jsx("div",{className:"text-[12px] text-muted-foreground",children:n}):null]})]})}function ye(s){const{control:a,defaultValue:i,availableFieldChoices:n,availableMetricChoices:c,previewControlDefinitions:u,previewControlValues:m,onControlChange:h,onLabelChange:p,onDefaultValueChange:v,onBack:b,onNext:f,nextDisabled:j}=s;return e.jsxs("div",{className:"space-y-3",children:[e.jsx(we,{control:a,onChange:p}),e.jsx(y.ControlDefinitionOptionsEditor,{control:a,availableFieldChoices:n,availableMetricChoices:c,previewControlDefinitions:u,previewControlValues:m,controlLifecycle:"create",onChange:h}),e.jsx(y.ControlDefaultValueEditor,{control:a,value:i,onChange:v,allowNoDefault:!0,allowCardDefault:!0,hint:"This is the value viewers will see first.",previewControlDefinitions:u,previewControlValues:m}),e.jsx(se,{secondary:e.jsx(r.Button,{type:"button",variant:"outline",size:"xs",onClick:b,children:"Back"}),primary:e.jsx(r.Button,{type:"button",size:"xs",onClick:f,disabled:j,children:"Next"})})]})}const ze=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]);function Ce(s){const{text:a,ariaLabel:i}=s,[n,c]=C.useState(!1);return e.jsxs("button",{type:"button","aria-label":i,onClick:async()=>{try{await navigator.clipboard.writeText(a),c(!0),setTimeout(()=>c(!1),1200)}catch(u){console.error("Failed to copy",u)}},className:"group flex w-full items-center justify-between gap-2 rounded-control bg-muted/40 px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",children:[e.jsx("code",{className:"min-w-0 truncate font-mono text-[12px] text-foreground",children:a}),e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:n?"Copied":"Click to copy"})]})}function ve(s){const{control:a,scope:i,createdReference:n,explorerContent:c,sqlDescription:u,summaryDetail:m,onBack:h,onCancel:p,onDone:v}=s,b=ze.has(a.type),f=n.match(/\[\[param\.(.+?)\]\]/),j=f?`{{ param('${f[1]}') }}`:"";return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Re,{control:a,scope:i,detail:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"How cards use this control"}),e.jsxs("div",{className:"divide-y divide-border/60 overflow-hidden rounded-control border border-border/60",children:[b?e.jsxs("div",{className:"space-y-1 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Explorer cards"}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:c})]}):null,e.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL cards"}),e.jsx(Ce,{text:n,ariaLabel:"Copy SQL control reference"}),j?e.jsx(Ce,{text:j,ariaLabel:"Copy Jinja control reference"}):null,e.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[u," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/template-expressions",target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-foreground",children:"Template expressions docs"}),"."]})]})]})]}),e.jsx(se,{secondary:e.jsx(r.Button,{type:"button",variant:"outline",size:"xs",onClick:h,children:"Back"}),tertiary:e.jsx(r.Button,{type:"button",variant:"outline",size:"xs",onClick:p,children:"Cancel"}),primary:e.jsx(r.Button,{type:"button",size:"xs",onClick:v,children:"Done"})})]})}function Qe(s){const a=r.createBlankControl(s.scope,s.existingControls,s.reservedIds),i=s.type===a.type?{...a,label:r.DEFAULT_LABEL_BY_TYPE[s.type]}:{...r.applyControlTypeChange({controls:[{...a,label:r.DEFAULT_LABEL_BY_TYPE[s.type]}],controlId:a.id,nextType:s.type}).controls[0],label:r.DEFAULT_LABEL_BY_TYPE[s.type]};return{step:2,control:i,defaultValue:r.getDefaultValueForType(i,void 0)}}function $e({scope:s,controls:a,reservedControlIds:i,defaultValues:n,onChange:c,emptyMessage:u,initialCreateFlow:m=!1,usageByControlId:h,availableFieldChoices:p,availableMetricChoices:v,structuralParticipants:b,structuralParticipantIdsByControlId:f,card:j,allowedControlTypes:D,onCreateFlowActiveChange:k,onCreateFlowComplete:E}){const L=C.useMemo(()=>new Set(i||[]),[i]),O=r.getPlacementOptionsForScope(s),H=r.getDefaultPlacement(s),[U,z]=C.useState(null),[W,V]=C.useState(null),[o,w]=C.useState(()=>m?{step:1,control:r.createBlankControl(s,a,Array.from(L))}:null),Q=C.useRef({}),M=C.useRef(void 0),K=C.useRef(m),P=C.useMemo(()=>{const t=r.getFriendlyControlTypeOptions({scope:s,card:j});if(!D)return t;const d=new Set(D);return t.filter(l=>d.has(l.value))},[D,j,s]),X=C.useCallback(t=>{const d=r.getFriendlyControlTypeOptions({scope:s,card:j,includeType:D?void 0:t});if(!D)return d;const l=new Set(D);return d.filter(x=>l.has(x.value))},[D,j,s]),B=C.useCallback(t=>s==="dashboard"&&(t==="field_selector"||t==="metric_selector"),[s]),Y=C.useMemo(()=>o?r.getEligibleParticipantsForStructuralControl(b||[],o.control.type):[],[o,b]),Z=C.useMemo(()=>{if(!o)return{fields:p||[],metrics:v||[]};if(!B(o.control.type))return{fields:p||[],metrics:v||[]};const t=o.selectedCardIds||[],d=r.getCompatibleStructuralChoiceCatalog({controlType:o.control.type,participants:b||[],selectedCardIds:t});return{fields:o.control.type==="field_selector"?d.choices.map(l=>({option:l,target:d.fieldTargetMap[l.value]})):[],metrics:o.control.type==="metric_selector"?d.choices.map(l=>({option:l,target:d.metricTargetMap[l.value]})):[]}},[p,v,o,B,b]);C.useEffect(()=>{k==null||k(!!o)},[o,k]),C.useEffect(()=>{const t=m&&!K.current;K.current=m,t&&(w({step:1,control:r.createBlankControl(s,a,Array.from(L))}),V(null),z(null))},[a,m,L,s]);const ne=t=>{if(!B(t.type))return{fields:p||[],metrics:v||[]};const d=(f==null?void 0:f[t.id])||[];if(d.length===0)return{fields:p||[],metrics:v||[]};const l=r.getCompatibleStructuralChoiceCatalog({controlType:t.type,participants:b||[],selectedCardIds:d});return{fields:t.type==="field_selector"?l.choices.map(x=>({option:x,target:l.fieldTargetMap[x.value]})):[],metrics:t.type==="metric_selector"?l.choices.map(x=>({option:x,target:l.metricTargetMap[x.value]})):[]}},A=t=>{if(!B(t.control.type))return{nextControl:t.control,cardBindingsById:void 0};const d=(f==null?void 0:f[t.control.id])||[],l=r.getCompatibleStructuralChoiceCatalog({controlType:t.control.type,participants:b||[],selectedCardIds:t.nextSelectedCardIds}),x=r.reconcileStructuralControlChoices({control:t.control,choices:l.choices}),S=Object.fromEntries(d.filter(N=>!t.nextSelectedCardIds.includes(N)).map(N=>[N,void 0]));return t.nextSelectedCardIds.length>0&&x.source.kind==="manual"&&x.source.options.length>0&&Object.assign(S,r.buildStructuralControlBindingsForParticipants({control:x,participants:b||[],selectedCardIds:t.nextSelectedCardIds,matrixTargetIds:t.matrixTargetIds})),{nextControl:x,cardBindingsById:S}},I=C.useCallback((t,d=n,l={type:"update"})=>{const x=t.map(S=>(r.resolveAuthoringControlDefaultValue({control:S,defaultValues:d}),r.syncSqlQueryControlExecutionRequirement(S)));c(x,d,l)},[n,c]),$=(t,d)=>{const l=a.find(F=>F.id===t);let x=a.map(F=>F.id!==t?F:d(F));const S=x.find(F=>F.id===t);let N,g;if(S&&(!l||r.structuralControlBindingsChanged({control:l},{control:S}))&&s==="dashboard"&&(S.type==="field_selector"||S.type==="metric_selector")){const F=(f==null?void 0:f[S.id])||[],ee=A({control:S,nextSelectedCardIds:F});x=x.map(G=>G.id===t?ee.nextControl:G),N=ee.cardBindingsById,g=[S.id]}else if(l&&(!S||!r.isStructuralSelectorControlType(S.type))&&s==="dashboard"&&(l.type==="field_selector"||l.type==="metric_selector")){const F=(f==null?void 0:f[l.id])||[];N=Object.fromEntries(F.map(ee=>[ee,void 0])),g=[l.id]}const T=x.find(F=>F.id===t);let _=n;if(l&&T){const F=r.resolveAuthoringControlDefaultValue({control:l,defaultValues:n});l.source.kind==="manual"&&T.source.kind==="sql_query"&&(Q.current[t]=F);const ee=F===void 0&&l.source.kind==="sql_query"&&T.source.kind==="manual"?Q.current[t]:F,G=r.getNextEditedControlDefaultValue({previousControl:l,nextControl:T,currentDefaultValue:ee});T.source.kind==="manual"&&(Q.current[t]=G),n&&(_={...n},G===void 0?delete _[t]:_[t]=G),x=x.map(he=>he.id===t?{...T,defaultValue:G}:he)}I(x,_,{type:"update",cardBindingsById:N,affectedBindingControlIds:g})},q=(t,d)=>{if(!d.trim())return;const l=r.normalizeDashboardInputVariableName(d);if(l===t||L.has(l)||a.some(N=>N.id===l&&N.id!==t))return;const x=a.map(N=>N.id===t?{...N,id:l}:N);if(!n){I(x,void 0,{type:"rename",oldId:t,newId:l});return}const S={...n};Object.prototype.hasOwnProperty.call(S,t)&&(S[l]=S[t],delete S[t]),I(x,S,{type:"rename",oldId:t,newId:l})},oe=t=>{const d=a.filter(x=>x.id!==t);if(!n){I(d,void 0,{type:"remove",controlId:t});return}const l={...n};delete l[t],I(d,l,{type:"remove",controlId:t})},re=C.useCallback(()=>{M.current=void 0,w({step:1,control:r.createBlankControl(s,a,Array.from(L))}),V(null),z(null)},[a,L,s]),R=t=>{w(d=>d&&(()=>{const l=t(d.control);d.control.source.kind==="manual"&&l.source.kind==="sql_query"&&(M.current=d.defaultValue);const x=d.defaultValue===void 0&&d.control.source.kind==="sql_query"&&l.source.kind==="manual"?M.current:d.defaultValue,S=r.getNextEditedControlDefaultValue({previousControl:d.control,nextControl:l,currentDefaultValue:x});return l.source.kind==="manual"&&(M.current=S),{...d,control:l,defaultValue:S}})())},te=t=>{w(d=>d&&(d.control.source.kind==="manual"&&(M.current=t),{...d,defaultValue:t}))},le=(()=>{if(!o)return!1;if(o.step===2&&B(o.control.type))return(o.selectedCardIds||[]).length>0&&r.hasStructuralMatrixTargets({participants:b||[],selectedCardIds:o.selectedCardIds||[],control:o.control,selected:o.matrixTargetIds});if(o.step!==2&&o.step!==3||!o.control.label.trim())return!1;const d=o.control.source.kind==="sql_query"?o.control:r.ensureManualSource(o.control);if(d.source.kind==="manual"&&(r.needsManualOptions(d)&&d.source.options.length===0||d.source.options.some(x=>x.label.trim().length===0||x.value.trim().length===0)))return!1;if(d.source.kind==="sql_query"){const{connectionId:l,sql:x,valueColumn:S}=d.source;return l.trim().length>0&&x.trim().length>0&&S.trim().length>0}return r.hasConcreteDefaultValue(r.getDefaultValueForType(d,o.defaultValue))})(),pe=()=>{var N;if(!o)return;const t=r.ensureManualSource(o.control),d=r.deriveUniqueControlId({label:t.label,fallbackId:t.id,existingControls:a,reservedIds:Array.from(L)}),l={...t,id:d},x=s==="dashboard"&&(l.type==="field_selector"||l.type==="metric_selector")&&((N=o.selectedCardIds)!=null&&N.length)?r.buildStructuralControlBindingsForParticipants({control:l,participants:b||[],selectedCardIds:o.selectedCardIds,matrixTargetIds:o.matrixTargetIds}):void 0,S=r.getDefaultValueForType(l,o.defaultValue);w({step:s==="dashboard"&&(l.type==="field_selector"||l.type==="metric_selector")?4:3,control:l,defaultValue:S,createdControlId:d,selectedCardIds:o.selectedCardIds,matrixTargetIds:o.matrixTargetIds,cardBindingsById:x})},ie=C.useCallback(()=>{w(null)},[]),me=C.useCallback(()=>{if(!(o!=null&&o.createdControlId)){w(null);return}const t=o.control,d=o.createdControlId,l=r.getDefaultValueForType(t,o.defaultValue);if(n){const x={...n};l===void 0?delete x[d]:x[d]=l,I([...a,{...t,defaultValue:l}],x,{type:"add",cardBindingsById:o.cardBindingsById})}else I([...a,{...t,defaultValue:l}],void 0,{type:"add",cardBindingsById:o.cardBindingsById});V(d),w(null),E==null||E()},[a,o,n,I,E]),De=o?B(o.control.type)?["Choose type","Select cards","Configure","Finish"]:["Choose type","Configure","Finish"]:[],fe=o!=null&&o.createdControlId?`[[param.${o.createdControlId}]]`:o?`[[param.${r.slugifyControlValue(o.control.label)||o.control.id}]]`:"",de=r.buildAuthoringPreviewControlValues({controls:a,defaultValues:n}),ce=o?[...a,o.control]:a,xe=o?r.buildAuthoringPreviewControlValues({controls:ce,defaultValues:n,overrides:[{controlId:o.control.id,value:o.defaultValue}]}):de;return e.jsxs("div",{className:"space-y-4",children:[o?e.jsxs("div",{className:"space-y-4 pb-1",children:[e.jsx(Ue,{currentStep:o.step,labels:De}),o.step===1&&(()=>{const t=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]),d=new Set(["date","text"]),l=P.filter(N=>!t.has(N.value)&&!d.has(N.value)),x=P.filter(N=>t.has(N.value)),S=N=>e.jsxs("button",{type:"button",className:"rounded-control border border-border/60 bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none",onClick:()=>w(Qe({scope:s,existingControls:a,reservedIds:Array.from(L),type:N.value})),children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:N.label}),e.jsx("p",{className:"mt-0.5 text-[12px] text-muted-foreground",children:N.description})]},N.value);return e.jsxs("div",{className:"space-y-4",children:[s==="card"&&(j==null?void 0:j.sql)==null?e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Explorer cards support displayed metric, group by field, aggregation, and time grain controls here."}):null,l.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Input controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:l.map(S)})]}),x.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data-driven controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:x.map(S)})]}),e.jsx(se,{secondary:e.jsx(r.Button,{type:"button",variant:"outline",size:"xs",onClick:ie,children:"Back to controls"})})]})})(),o.step===2&&B(o.control.type)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(we,{control:o.control,onChange:t=>R(d=>({...d,label:t}))}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Choose which cards should respond to this shared control."})]}),Y.length===0?e.jsx("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground",children:"No eligible cards are available yet. Add compatible metrics or group-by fields to cards first."}):e.jsx("div",{className:"space-y-1 rounded-control border border-border/60 bg-background p-2",children:Y.map(t=>{const d=(o.selectedCardIds||[]).includes(t.cardId);return e.jsxs("label",{className:"flex items-start gap-2 rounded-control px-1.5 py-1 text-[13px] hover:bg-muted/40",children:[e.jsx(y.Checkbox,{checked:d,onCheckedChange:l=>w(x=>x&&{...x,selectedCardIds:l===!0?[...x.selectedCardIds||[],t.cardId]:(x.selectedCardIds||[]).filter(S=>S!==t.cardId)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground",children:t.title}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:o.control.type==="field_selector"?`${t.fieldChoices.length} compatible group-by fields`:`${t.metricChoices.length} compatible metrics`})]})]},t.cardId)})}),e.jsx(y.MatrixStructuralTargets,{participants:Y,selectedCardIds:o.selectedCardIds||[],control:o.control,selected:o.matrixTargetIds,onChange:(t,d)=>w(l=>l&&{...l,matrixTargetIds:{...l.matrixTargetIds,[t]:d}})}),e.jsx(se,{secondary:e.jsx(r.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>w(t=>t&&{...t,step:1,selectedCardIds:[]}),children:"Back"}),primary:e.jsx(r.Button,{type:"button",size:"xs",onClick:()=>w(t=>t&&{...t,step:3}),disabled:!le,children:"Next"})})]}),o.step===2&&!B(o.control.type)&&e.jsx(ye,{control:o.control,defaultValue:o.defaultValue,availableFieldChoices:Z.fields,availableMetricChoices:Z.metrics,previewControlDefinitions:ce,previewControlValues:xe,onControlChange:t=>R(()=>t),onLabelChange:t=>R(d=>({...d,label:t})),onDefaultValueChange:te,onBack:()=>w(t=>t&&{...t,step:1}),onNext:pe,nextDisabled:!le}),o.step===3&&B(o.control.type)&&e.jsx(ye,{control:o.control,defaultValue:o.defaultValue,availableFieldChoices:Z.fields,availableMetricChoices:Z.metrics,previewControlDefinitions:ce,previewControlValues:xe,onControlChange:t=>R(()=>t),onLabelChange:t=>R(d=>({...d,label:t})),onDefaultValueChange:te,onBack:()=>w(t=>t&&{...t,step:2}),onNext:pe,nextDisabled:!le}),o.step===3&&!B(o.control.type)&&e.jsx(ve,{control:o.control,scope:s,createdReference:fe,explorerContent:e.jsxs(e.Fragment,{children:["Open the card and use"," ",e.jsx("span",{className:"font-medium text-foreground",children:"Settings → Controls"})," ","to choose what this control changes."]}),sqlDescription:"Reference this control directly in the SQL editor.",onBack:()=>w(t=>t&&{...t,step:2}),onCancel:ie,onDone:me}),o.step===4&&B(o.control.type)&&e.jsx(ve,{control:o.control,scope:s,createdReference:fe,summaryDetail:e.jsxs(e.Fragment,{children:["Used by ",(o.selectedCardIds||[]).length," selected card",(o.selectedCardIds||[]).length===1?"":"s"]}),explorerContent:e.jsx(e.Fragment,{children:"Selected cards have been set up to respond to this control automatically."}),sqlDescription:"SQL cards can still reference this control directly in the SQL editor.",onBack:()=>w(t=>t&&{...t,step:3}),onCancel:ie,onDone:me})]}):null,!o&&a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:u}):null,!o&&a.map(t=>{const d=ne(t),l=h==null?void 0:h[t.id],x=r.resolveAuthoringControlDefaultValue({control:t,defaultValues:n}),S=W===t.id,N="inline-flex shrink-0 items-center rounded-[4px] border border-border/60 bg-muted/40 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground";return e.jsxs("div",{className:"rounded-control border border-border/60",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 rounded-control text-left focus:outline-none focus-visible:bg-muted/40",onClick:()=>V(g=>g===t.id?null:t.id),children:[S?e.jsx(J.ChevronDown,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(ge.ChevronRight,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.label||"Untitled control"}),e.jsx("span",{className:N,children:r.getFriendlyTypeOption(t.type).label}),e.jsx("span",{className:N,children:r.getPlacementLabel(s,t.placement)})]}),e.jsxs("div",{className:"mt-0.5 text-[12px] text-muted-foreground",children:[r.getControlOptionPreview(t),l!=null&&l.status?` · ${l.status}`:""]})]})]}),e.jsx(r.Button,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>oe(t.id),"aria-label":`Remove ${t.label}`,children:e.jsx(y.Trash2,{className:"h-3.5 w-3.5"})})]}),S&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(r.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(r.Input,{size:"xs",value:t.label,placeholder:"Control label",onChange:g=>$(t.id,T=>({...T,label:g.target.value}))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(r.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),e.jsxs(r.Select,{value:t.type,onValueChange:g=>{const T=r.applyControlTypeChange({controls:a,controlId:t.id,nextType:g,defaultValues:n});I(T.controls,T.defaultValues)},children:[e.jsx(r.SelectTrigger,{size:"xs",children:e.jsx(r.SelectValue,{})}),e.jsx(r.SelectContent,{children:X(t.type).map(g=>e.jsx(r.SelectItem,{value:g.value,children:g.label},g.value))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(r.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Show in"}),e.jsxs(r.Select,{value:t.placement||H,onValueChange:g=>$(t.id,T=>({...T,placement:g})),children:[e.jsx(r.SelectTrigger,{size:"xs",children:e.jsx(r.SelectValue,{})}),e.jsx(r.SelectContent,{children:O.map(g=>e.jsx(r.SelectItem,{value:g.value,children:g.label},g.value))})]})]})]}),B(t.type)?e.jsxs(e.Fragment,{children:[e.jsx(y.StructuralParticipantSelector,{type:t.type,participants:r.getEligibleParticipantsForStructuralControl(b||[],t.type).map(g=>({cardId:g.cardId,title:g.title,choiceCount:t.type==="field_selector"?g.fieldChoices.length:g.metricChoices.length})),selectedCardIds:(f==null?void 0:f[t.id])||[],onChange:g=>{const T=A({control:t,nextSelectedCardIds:g}),_=a.map(F=>F.id===t.id?T.nextControl:F);I(_,n,{type:"update",cardBindingsById:T.cardBindingsById})}}),e.jsx(y.MatrixStructuralTargets,{participants:b||[],selectedCardIds:(f==null?void 0:f[t.id])||[],control:t,onChange:(g,T)=>{const _=A({control:t,nextSelectedCardIds:(f==null?void 0:f[t.id])||[],matrixTargetIds:{[g]:T}});I(a.map(F=>F.id===t.id?_.nextControl:F),n,{type:"update",cardBindingsById:_.cardBindingsById})}})]}):null,e.jsx(y.ControlDefinitionOptionsEditor,{control:t,availableFieldChoices:d.fields,availableMetricChoices:d.metrics,previewControlDefinitions:a,previewControlValues:de,controlLifecycle:"edit",onChange:g=>$(t.id,()=>g)}),t.initialValueStrategy==="saved_default"&&e.jsx(y.ControlDefaultValueEditor,{control:t,value:x,allowNoDefault:!0,allowCardDefault:!0,previewControlDefinitions:a,previewControlValues:de,onChange:g=>{const T=a.map(_=>_.id===t.id?{..._,defaultValue:g}:_);if(t.source.kind==="manual"&&(Q.current[t.id]=g),n){const _={...n};g===void 0?delete _[t.id]:_[t.id]=g,I(T,_);return}I(T,void 0)}}),e.jsxs(y.Collapsible,{open:U===t.id,onOpenChange:g=>z(g?t.id:null),children:[e.jsx(y.CollapsibleTrigger,{asChild:!0,children:e.jsxs(r.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-2 gap-1 text-muted-foreground hover:text-foreground",children:[U===t.id?e.jsx(J.ChevronDown,{className:"h-3.5 w-3.5"}):e.jsx(ge.ChevronRight,{className:"h-3.5 w-3.5"}),"Advanced"]})}),e.jsxs(y.CollapsibleContent,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(r.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Variable name"}),e.jsx(y.ControlIdInput,{controlId:t.id,onCommit:g=>q(t.id,g)},t.id)]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(r.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Initial value"}),e.jsxs(r.Select,{value:t.initialValueStrategy,onValueChange:g=>$(t.id,T=>({...T,initialValueStrategy:g})),children:[e.jsx(r.SelectTrigger,{size:"xs",children:e.jsx(r.SelectValue,{})}),e.jsx(r.SelectContent,{children:r.INITIAL_VALUE_STRATEGY_OPTIONS.map(g=>e.jsx(r.SelectItem,{value:g.value,children:g.label},g.value))})]})]})]}),e.jsx(y.ControlVisibilitySettings,{control:t,onChange:g=>$(t.id,()=>g)})]})]})]})]},t.id)}),!o&&e.jsxs(r.Button,{type:"button",variant:"outline",size:"xs",onClick:re,children:[e.jsx(y.Plus,{className:"h-3.5 w-3.5"}),"Add control"]})]})}function Ye(s){const{open:a,onOpenChange:i,initialCreateFlowActive:n=!1,dismissMode:c="passive"}=s,u=a!==void 0,[m,h]=C.useState(!1),[p,v]=C.useState(n),b=u?a:m,f=C.useCallback(k=>{!k&&p&&c==="passive"||(u||h(k),k||v(!1),i==null||i(k))},[u,p,c,i]),j=C.useCallback(()=>{u||h(!1),v(!1),i==null||i(!1)},[u,i]);C.useEffect(()=>{b||v(!1)},[b]);const D=C.useCallback(k=>{p&&k.preventDefault()},[p]);return{forceClose:j,handleOpenChange:f,isCreateFlowActive:p,preventPassiveDismissDuringCreate:D,resolvedOpen:b,setIsCreateFlowActive:v}}function ue(s){var i;for(const n of s.cards)if(n.type==="matrixTable"&&!Te.matrixConfigSchema.safeParse((i=n.config)==null?void 0:i.matrix).success)return r.ue.error("Matrix requires at least one row field, one metric, and valid settings."),!1;const a=r.getDynamicFrameSaveIssue(s);return a?(r.ue.error(a),!1):!0}function He({className:s,variant:a="outline"}){const i=r.useEditorStore(u=>u.onSave),{getUpdatedFrame:n}=ae();function c(){const u=n();ue(u)&&(i==null||i(u))}return e.jsxs(r.Button,{onClick:c,className:s,size:"xs",variant:a,children:[e.jsx(r.Check,{className:"h-3.5 w-3.5"}),"Accept"]})}function Ke({className:s,variant:a="default"}){const i=y.useQueryClient(),[n,c]=C.useState(!1),{setIsVisualEditing:u}=r.useDashboardActions(),{getUpdatedFrame:m}=ae(),h=y.useSelectedVisual(),p=r.useEditorStore(f=>f.frame),v=y.useUpdateVisualMutation(),b=()=>{const f=m();if(!ue(f))return;const j=(p==null?void 0:p.visualId)||(h==null?void 0:h.id);if(!j){r.ue.error("No visual to save");return}c(!0),v.mutate({visualId:j,data:{frameObject:f}},{onSuccess:()=>{c(!1),r.ue.success("Visual updated successfully"),i.invalidateQueries({queryKey:["resource-by-id","visual",j],exact:!0})},onError:()=>{c(!1),r.ue.error("Failed to update visual")}})};return e.jsx(r.Button,{onClick:b,className:s,size:"xs",variant:a,children:n?e.jsxs(e.Fragment,{children:[e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving"]}):e.jsxs(e.Fragment,{children:[e.jsx(Se.Save,{className:"h-3.5 w-3.5"}),"Save to Library"]})})}function Pe({className:s}){const a=y.useQueryClient(),[i,n]=C.useState(!1),c=y.useSelectedVisual(),u=r.useEditorStore(k=>k.frame),m=r.useDashboardStore(k=>k.selectedSheetId),h=r.useDashboardStore(k=>k.dashboard),{updateFrame:p,setIsVisualEditing:v}=r.useDashboardActions(),{getUpdatedFrame:b}=ae(),f=y.useUpdateVisualMutation(),j=y.useResolveExistingFrameSemanticExecutionPayload(),D=async()=>{if(!m){r.ue.error("No sheet selected");return}const k=(u==null?void 0:u.visualId)||(c==null?void 0:c.id);if(!k){r.ue.error("No visual to update");return}n(!0);try{const E=b();if(!ue(E)){n(!1);return}const L={...E,visualId:k},O=r.findDashboardFrameById(h,L.id),H=await j(L,{previousFrame:O});await f.mutateAsync({visualId:k,data:{frameObject:E}}),p(m,L,{semanticExecutionPayload:H}),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",k]}),r.ue.success("Saved to library and applied locally"),setTimeout(()=>{v(!1)},300)}catch(E){console.error("Failed to save and apply:",E),r.ue.error(E instanceof Error?E.message:"Failed to save and apply changes")}finally{n(!1)}};return e.jsx(r.Button,{onClick:D,className:s,size:"xs",variant:"default",disabled:i,children:i?e.jsxs(e.Fragment,{children:[e.jsx(r.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Se.Save,{className:"h-3.5 w-3.5"}),"Save & Apply"]})})}function We({className:s}){const{setTempQueryData:a,setSqlGen:i}=r.useEditorActions(),n=y.useQueryClient(),c=r.useEditorStore(f=>f.tempQueryData),u=r.useEditorStore(f=>f.onClose),m=r.useEditorStore(f=>f.card),h=y.useEffectiveEditorCardType(),p=C.useMemo(()=>h!==m.type?{...m,type:h}:m,[m,h]),{queryKey:v}=y.useEditorCardQuery(p);function b(){if(c){const{queryKey:f,queryData:j}=c;f&&j&&n.setQueryData(f,j)}i({}),u==null||u()}return e.jsxs(r.Button,{onClick:b,className:s,size:"xs",variant:"outline",children:[e.jsx(J.X,{className:"h-3.5 w-3.5"}),"Close"]})}function Xe({label:s="Clear",variant:a="secondary",className:i}={}){const n=Ee();return e.jsxs(r.Button,{onClick:n,className:i,size:"xs",variant:a,children:[e.jsx(J.X,{className:"h-3.5 w-3.5"}),s]})}exports.ControlDefinitionListEditor=$e;exports.EditorAcceptButton=He;exports.EditorCancelButton=We;exports.EditorClearButton=Xe;exports.FilterX=Ve;exports.Library=je;exports.Link2=ke;exports.VisualBadge=Oe;exports.VisualSaveAndApplyButton=Pe;exports.VisualSaveButton=Ke;exports.useCreateFlowOverlayState=Ye;exports.useEditorClearAction=Ee;exports.useSyncLegacyEditorState=Be;exports.useVisualUtils=ae;
@@ -1 +0,0 @@
1
- "use strict";const C=require("./validators-DFeDcdpA.cjs"),oe=require("./matrix-operation-contract-0RxoU_M3.cjs"),ie=require("./metric-comparison-CUmltzpz.cjs"),u=require("zod"),ke=require("./source-entity-resolution-R46X34SE.cjs"),Te=require("./field-dependencies-EB485TdB.cjs"),J=require("./matrix-card-C2RjEYZ8.cjs"),I=require("./temporal-bucket-4YEPEKlJ.cjs"),re=require("../value-format-preferences/index.cjs"),B=8,L=6,w=Object.freeze([]);function se(e){switch(e.type){case"table":case"chart":return e.card?[e.card]:w;case"kpi":return Array.isArray(e.cards)?e.cards:w;default:return w}}function Ee(e,t){switch(e.type){case"table":case"chart":{if(!e.card)return e;const n=t(e.card);return n===e.card?e:{...e,card:n}}case"kpi":{if(!Array.isArray(e.cards))return e;const n=e.cards.map(t);return n.every((o,i)=>o===e.cards[i])?e:{...e,cards:n}}default:return e}}function Ie(e){var n;const t=[];for(const o of e.sheets||[]){const i=o.id;for(const s of o.cards||[])t.push({kind:"sheetCard",sheetId:i,cardId:s.id,card:s});for(const s of o.frames||[])for(const r of s.cards||[])t.push({kind:"frameCard",sheetId:i,frameId:s.id,cardId:r.id,card:r});for(const s of((n=o.document)==null?void 0:n.sections)||[])for(const r of se(s))t.push({kind:"documentSectionCard",sheetId:i,sectionId:s.id,cardId:r.id,card:r})}return t}function $(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ae(e){if(!$(e))return[{path:"",message:"must be an object."}];const t=[];e.title!==void 0&&typeof e.title!="string"&&t.push({path:"title",message:"must be a string."});const n=e.cards;if(!Array.isArray(n))t.push({path:"cards",message:"must be an array of KPI cards."});else{(n.length<1||n.length>B)&&t.push({path:"cards",message:`must hold 1 to ${B} KPI cards.`});const i=new Set;n.forEach((s,r)=>{if(!$(s)){t.push({path:`cards[${r}]`,message:"must be a card."});return}typeof s.id!="string"||!s.id?t.push({path:`cards[${r}].id`,message:"must be a non-empty string."}):i.has(s.id)?t.push({path:`cards[${r}].id`,message:`duplicates card id '${s.id}'.`}):i.add(s.id),s.type!=="kpi"&&t.push({path:`cards[${r}].type`,message:"must be 'kpi'."})})}const o=e.kpi;return $(o)?(o.layout!=="tiles"&&o.layout!=="lines"?t.push({path:"kpi.layout",message:"must be 'tiles' or 'lines'."}):o.layout==="tiles"&&Array.isArray(n)&&n.length>L&&t.push({path:"kpi.layout",message:`must be 'lines' for more than ${L} KPI cards.`}),o.columns!==void 0&&o.columns!==1&&o.columns!==2&&t.push({path:"kpi.columns",message:"must be 1 or 2."})):t.push({path:"kpi",message:"must be an object."}),t}const P=new Set(["previous_period","same_period_last_year","start_vs_end","target"]),De=new Set([...P,"none",""]);function h(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ae(e){const t=h(e.preferences)?e.preferences:void 0,n=t&&h(t.kpiVisualOptions)?t.kpiVisualOptions:void 0,o=t&&h(t.tableVisualOptions)?t.tableVisualOptions:void 0;return{preferences:t,kpiOptions:n,kpiComparison:n&&h(n.metricComparison)?n.metricComparison:void 0,kpiComparisonPresent:!!n&&"metricComparison"in n,tableOptions:o,tableComparison:o&&h(o.metricComparison)?o.metricComparison:void 0,tableComparisonPresent:!!o&&"metricComparison"in o}}function G(e){const t=[],n=(o,i)=>{if(Array.isArray(o)){o.forEach((r,a)=>n(r,`${i}[${a}]`));return}if(!h(o))return;const s=o.config;if(h(s)){const r=ae(o),a=!!(r.kpiComparisonPresent||r.tableComparisonPresent),m=s.metricColumns,p=Array.isArray(m)?m.flatMap((l,c)=>h(l)?[{index:c,metric:l}]:[]):[];if((p.some(({metric:l})=>"comparisonType"in l)||a)&&t.push({path:i,card:o,metrics:p,malformedMetricIndexes:Array.isArray(m)?m.flatMap((l,c)=>h(l)?[]:[c]):[],malformedMetricColumns:"metricColumns"in s&&!Array.isArray(m),hasLegacyPresentation:a}),"metricColumns"in s||a)return}Object.entries(o).forEach(([r,a])=>n(a,i?`${i}.${r}`:r))};return n(e,"$"),t}const ce={difference:"difference",change:"percent_change",change_difference:"both",ratio:"ratio"};function Q(e,t){if(!e)return;const n=Object.fromEntries(t.flatMap(o=>typeof e[o]=="string"?[[o,e[o]]]:[]));return Object.keys(n).length?n:void 0}function Oe(e,t,n){if(e!==void 0){if(!h(e)){n.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:t,message:"Legacy comparison formatOptions must be an object."});return}Object.entries(e).forEach(([o,i])=>{if(o==="decimalPlaces"){(typeof i!="number"||!Number.isInteger(i)||i<0||i>6)&&n.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.decimalPlaces`,message:"Legacy comparison decimalPlaces must be an integer from 0 through 6."});return}o==="type"&&(i===void 0||i==="auto")||i!==void 0&&n.push({severity:"error",code:"unsupported_comparison_format",path:`${t}.${o}`,message:`Legacy comparison format option "${o}" has no canonical presentation mapping.`})})}}function R(e,t){const n=t==="kpi"?e.calculationType:e.calculatedAs,o=t==="table"&&n===void 0?"both":ce[String(n)],i=h(e.formatOptions)?e.formatOptions:void 0,s=h(e.conditionalLabels)?e.conditionalLabels:void 0,r=h(t==="kpi"?e.colorConfig:e.colors)?t==="kpi"?e.colorConfig:e.colors:void 0,a={};if(o&&(a.displayMode=o),typeof(i==null?void 0:i.decimalPlaces)=="number"&&(a.precision=i.decimalPlaces),t==="kpi"){const l=e.showArrow!==!1,c=e.showColor!==!1;a.indicatorStyle=l?c?"arrow_badge":"arrow":c?"badge":"none",a.showColor=c,(e.position==="left"||e.position==="right"||e.position==="top")&&(a.position=e.position),typeof e.conditionalLabel=="boolean"&&(a.conditionalLabel=e.conditionalLabel),typeof e.labelName=="string"&&(a.labelName=e.labelName)}else(e.indicatorStyle==="arrow_badge"||e.indicatorStyle==="arrow"||e.indicatorStyle==="badge"||e.indicatorStyle==="none")&&(a.indicatorStyle=e.indicatorStyle);const m=s?{...Q(s,["increase","decrease"]),...typeof s.noChange=="string"?{neutral:s.noChange}:typeof s.neutral=="string"?{neutral:s.neutral}:{}}:void 0;m&&Object.keys(m).length&&(a.conditionalLabels=m);const p=r?{...Q(r,["increase","decrease"]),...typeof r.noChange=="string"?{neutral:r.noChange}:typeof r.neutral=="string"?{neutral:r.neutral}:{}}:void 0;return p&&Object.keys(p).length&&(a.colors=p),a}function X(e){return{...ie.COMPARISON_PRESENTATION_DEFAULTS,...e}}function W(e){return e.some(({metric:t})=>t.comparisonType==="previous_period"||t.comparisonType==="same_period_last_year"||t.comparisonType==="target"?!0:h(t.comparison)&&t.comparison.mode==="explicit")}function F(e){const t=e.card.config;return e.metrics.length===2&&(t.groupByColumns===void 0||Array.isArray(t.groupByColumns)&&t.groupByColumns.length===0)}function Z(e,t,n,o){const i=t==="kpi"?["enabled","calculationType","formatOptions","showArrow","showColor","conditionalLabel","labelName","position","conditionalLabels","colorConfig","lowerIsBetter"]:["calculatedAs","indicatorStyle","formatOptions","colors","lowerIsBetter"];Object.keys(e).forEach(l=>{i.includes(l)||o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.${l}`,message:`Unknown legacy comparison presentation field "${l}" cannot be dropped automatically.`})});const s=t==="kpi"?"calculationType":"calculatedAs";e[s]!==void 0&&!ce[String(e[s])]&&o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.${s}`,message:`Legacy comparison ${s} is unsupported.`}),t==="kpi"&&e.position!==void 0&&!["left","right","top"].includes(String(e.position))&&o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.position`,message:"Legacy comparison position is unsupported."}),t==="kpi"&&e.labelName!==void 0&&typeof e.labelName!="string"&&o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.labelName`,message:"Legacy comparison labelName must be a string."}),(t==="kpi"?[["conditionalLabels",["increase","decrease","noChange"]],["colorConfig",["increase","decrease","noChange"]]]:[["colors",["increase","decrease","neutral"]]]).forEach(([l,c])=>{if(e[l]!==void 0){if(!h(e[l])){o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.${l}`,message:`Legacy comparison ${l} must be an object.`});return}Object.entries(e[l]).forEach(([b,d])=>{c.includes(b)?typeof d!="string"&&o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.${l}.${b}`,message:`Legacy comparison ${l}.${b} must be a string.`}):o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.${l}.${b}`,message:`Unknown legacy comparison ${l} field "${b}" cannot be dropped automatically.`})})}}),(t==="kpi"?["enabled","showArrow","showColor","conditionalLabel","lowerIsBetter"]:["lowerIsBetter"]).forEach(l=>{e[l]!==void 0&&typeof e[l]!="boolean"&&o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.${l}`,message:`Legacy comparison ${l} must be a boolean.`})}),t==="table"&&e.indicatorStyle!==void 0&&!["arrow_badge","arrow","badge","none"].includes(String(e.indicatorStyle))&&o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n}.indicatorStyle`,message:"Legacy comparison indicatorStyle is unsupported."}),Oe(e.formatOptions,`${n}.formatOptions`,o);const m=R(e,t);ie.validateComparisonPresentationSpec(m,n).errors.forEach(l=>{o.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:l.path||n,message:l.message})})}function ee(e){const t=ae(e.card),n=t.kpiComparison?R(t.kpiComparison,"kpi"):void 0,o=t.tableComparison?R(t.tableComparison,"table"):void 0;return{namespaces:t,kpi:n,table:o,presentation:n||o}}function Ne(e){const t=h(e.preferences)?e.preferences:{},n=h(t.kpiVisualOptions)?t.kpiVisualOptions:{},o=h(n.metricComparison)?n.metricComparison:{},i=h(t.tableVisualOptions)?t.tableVisualOptions:{},s=h(i.metricComparison)?i.metricComparison:{};return n.lowerIsBetter===!0||o.lowerIsBetter===!0||s.lowerIsBetter===!0?"lower_is_better":"higher_is_better"}function Pe(e){switch(e.comparisonType){case"previous_period":return{mode:"explicit",spec:{kind:"previous_period"}};case"same_period_last_year":return{mode:"explicit",spec:{kind:"previous_year"}};case"target":return{mode:"explicit",spec:{kind:"target",targetValue:e.targetValue}};default:return}}function Se(e){const t=h(e.preferences)?e.preferences:void 0;if(!t)return;const n=h(t.kpiVisualOptions)?t.kpiVisualOptions:void 0;n&&delete n.lowerIsBetter;const o=h(t.tableVisualOptions)?t.tableVisualOptions:void 0,i=o&&h(o.metricComparison)?o.metricComparison:void 0;i&&delete i.lowerIsBetter}function we(e){const t=G(e);if(!t.length)return{document:e,changed:!1,changes:[],diagnostics:[]};const n=[];if(t.forEach(r=>{var a,m,p,l;if(r.malformedMetricColumns&&n.push({severity:"error",code:"malformed_metric_columns",path:`${r.path}.config.metricColumns`,message:"Metric columns must be an array before comparison migration."}),r.malformedMetricIndexes.forEach(c=>{n.push({severity:"error",code:"malformed_metric_columns",path:`${r.path}.config.metricColumns[${c}]`,message:"Metric columns must contain objects before comparison migration."})}),r.metrics.forEach(({metric:c,index:b})=>{if(!("comparisonType"in c))return;const d=`${r.path}.config.metricColumns[${b}]`,y=String(c.comparisonType||"");"comparison"in c&&n.push({severity:"error",code:"conflicting_comparison_contracts",path:d,message:"Metric contains both legacy and canonical comparison configuration; resolve the conflict before migration."});const _=h(c.parameters)?c.parameters:void 0,M=_&&h(_.windowTransform)?_.windowTransform:void 0;P.has(y)&&(M==null?void 0:M.function)==="previous_period_delta"&&n.push({severity:"error",code:"conflicting_comparison_window_transform",path:d,message:"A metric cannot combine baseline comparison with previous_period_delta; resolve the authoring intent before migration."}),De.has(y)||n.push({severity:"error",code:"unsupported_comparison_type",path:`${d}.comparisonType`,message:`Unsupported legacy metric comparison type "${y}".`}),c.comparisonType==="target"&&(typeof c.targetValue!="number"||!Number.isFinite(c.targetValue))&&n.push({severity:"error",code:"invalid_target_value",path:`${d}.targetValue`,message:"Legacy target comparison requires a finite metric targetValue."}),c.comparisonType==="start_vs_end"&&n.push({severity:"error",code:"unsupported_start_vs_end",path:`${d}.comparisonType`,message:"start_vs_end is retired and cannot be migrated automatically."}),c.targetValue!==void 0&&c.comparisonType!=="target"&&n.push({severity:"warning",code:"stray_target_value",path:`${d}.targetValue`,message:"Dead non-target targetValue will be removed without changing the baseline."})}),r.hasLegacyPresentation){const{namespaces:c,kpi:b,table:d}=ee(r),y=[(a=c.kpiOptions)==null?void 0:a.lowerIsBetter,(m=c.kpiComparison)==null?void 0:m.lowerIsBetter,(p=c.tableComparison)==null?void 0:p.lowerIsBetter].filter(_=>typeof _=="boolean");new Set(y).size>1&&n.push({severity:"error",code:"conflicting_legacy_polarity",path:`${r.path}.preferences`,message:"Legacy comparison polarity values disagree; resolve the conflict before migration."}),((l=c.kpiOptions)==null?void 0:l.lowerIsBetter)!==void 0&&typeof c.kpiOptions.lowerIsBetter!="boolean"&&n.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${r.path}.preferences.kpiVisualOptions.lowerIsBetter`,message:"Legacy comparison lowerIsBetter must be a boolean."}),c.kpiComparisonPresent&&!c.kpiComparison&&n.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${r.path}.preferences.kpiVisualOptions.metricComparison`,message:"Legacy KPI comparison presentation must be an object."}),c.tableComparisonPresent&&!c.tableComparison&&n.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${r.path}.preferences.tableVisualOptions.metricComparison`,message:"Legacy table comparison presentation must be an object."}),"comparisonPresentation"in(c.preferences||{})&&n.push({severity:"error",code:"conflicting_comparison_presentation_contracts",path:`${r.path}.preferences.comparisonPresentation`,message:"Card contains both legacy and canonical comparison presentation; resolve the conflict before migration."}),c.kpiComparison&&typeof c.kpiComparison.enabled=="boolean"&&"metricPairComparisonEnabled"in(c.preferences||{})&&F(r)&&n.push({severity:"error",code:"conflicting_comparison_presentation_contracts",path:`${r.path}.preferences.metricPairComparisonEnabled`,message:"Card contains both legacy and canonical metric-pair enablement; resolve the conflict before migration."}),c.kpiComparison&&Z(c.kpiComparison,"kpi",`${r.path}.preferences.kpiVisualOptions.metricComparison`,n),c.tableComparison&&Z(c.tableComparison,"table",`${r.path}.preferences.tableVisualOptions.metricComparison`,n),b&&d&&JSON.stringify(X(b))!==JSON.stringify(X(d))&&n.push({severity:"error",code:"conflicting_legacy_presentation_namespaces",path:`${r.path}.preferences`,message:"KPI and table comparison presentation values disagree; resolve the conflict before migration."})}}),n.some(r=>r.severity==="error"))return{document:e,changed:!1,changes:[],diagnostics:n};const o=JSON.parse(JSON.stringify(e)),i=G(o),s=[];return i.forEach(r=>{var m;const a=Ne(r.card);if(r.metrics.forEach(({metric:p,index:l})=>{if(!("comparisonType"in p))return;const c=String(p.comparisonType||""),b=`${r.path}.config.metricColumns[${l}]`,d=Pe(p),y=["comparisonType"];delete p.comparisonType,"targetValue"in p&&(delete p.targetValue,y.push("targetValue")),"comparisonDisplay"in p&&(delete p.comparisonDisplay,y.push("comparisonDisplay")),d?p.comparison=d:delete p.comparison,P.has(c)&&(p.comparisonPolarity=a),s.push({kind:"metric",path:b,metricId:typeof p.id=="string"?p.id:void 0,legacyType:c,comparison:d,comparisonPolarity:P.has(c)?a:void 0,removedFields:y})}),Se(r.card),r.hasLegacyPresentation){const{namespaces:p,presentation:l}=ee(r),c=(m=p.kpiComparison)==null?void 0:m.enabled,b={...l};typeof c=="boolean"&&W(r.metrics)&&(b.showComparison=c);const d=typeof c=="boolean"&&F(r)?c:void 0,y=typeof c=="boolean"&&!W(r.metrics)&&!F(r)?["kpiVisualOptions.metricComparison.enabled"]:void 0,_=p.preferences,M=[];r.metrics.forEach(({metric:N})=>{"comparisonPolarity"in N||(N.comparisonPolarity=a,typeof N.id=="string"&&M.push(N.id))}),Object.keys(b).length&&(_.comparisonPresentation=b),d!==void 0&&(_.metricPairComparisonEnabled=d),p.kpiOptions&&delete p.kpiOptions.metricComparison,p.tableOptions&&delete p.tableOptions.metricComparison,s.push({kind:"presentation",path:`${r.path}.preferences`,comparisonPresentation:Object.keys(b).length?b:void 0,metricPairComparisonEnabled:d,comparisonPolarityMetricIds:M,intentionallyDiscardedFields:y,removedFields:[...p.kpiComparison?["kpiVisualOptions.metricComparison"]:[],...p.tableComparison?["tableVisualOptions.metricComparison"]:[]]})}}),{document:o,changed:!0,changes:s,diagnostics:n}}function f(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function le(e){return Array.from(new Set(e.filter(t=>!!t)))}function $e(e){const t=f(e.table),n=f(e.schema),o=f(e.catalog)||f(e.database);return t?le([t,n?`${n}.${t}`:null,o?`${o}.${t}`:null,o&&n?`${o}.${n}.${t}`:null]):[]}function te(e){const t=f(e.table)||f(e.tableName);return le([f(e.name),f(e.alias),...$e({table:t,schema:f(e.schema)||f(e.schemaName),catalog:f(e.catalog),database:f(e.database)||f(e.databaseName)})])}function Fe(e,t){const n=f(e.domainId),o=f(t.domainId);if(n&&o&&n!==o)return!0;if(e.type==="dataset")return!1;const i=f(e.id),s=f(t.id);if(i&&s&&i!==s)return!0;const r=f(e.connectionId),a=f(t.connectionId);return!!(r&&a&&r!==a)}function V(e,t=!1){return f(e.table)||f(e.tableName)||(e.type!=="dataset"||t?f(e.name):null)}function x(e){return f(e.catalog)||f(e.database)||f(e.databaseName)}function j(e){return f(e.schema)||f(e.schemaName)}function S(e){return e.length===1?e[0]:void 0}function ze(e,t){const n=V(t,!0),o=x(t),i=j(t);if(!(!n||!o&&!i))return S(e.filter(s=>{const r=s;return!(V(r)!==n||o&&x(r)!==o||i&&j(r)!==i)}))}function A(e,t){if(!t||!(e!=null&&e.length))return;const n=e.filter(a=>!Fe(a,t));if(t.type==="dataset"){const a=f(t.id);if(a)return S(n.filter(p=>p.type==="dataset"&&f(p.id)===a));if(f(t.domainId)){const p=f(t.name);return S(n.filter(l=>l.type==="dataset"&&f(l.name)===p))}}let o=[];if(t.type==="dataset"){const a=f(t.name);if(o=n.filter(m=>m.type==="dataset"&&f(m.name)===a),o.length===1)return o[0]}if(!!(V(t,!0)&&(x(t)||j(t))))return ze(n,t);if(o.length>1)return;const s=te(t);if(s.length===0)return;const r=n.filter(a=>te(a).some(p=>s.includes(p)));return S(r)}function z(e,t){const n=A(e,t);return n?{...t,...n}:t}function Be(e,t){const n=t||[];return n.length===0?e:{...e,baseEntity:z(n,e.baseEntity),joins:e.joins.map(o=>({...o,source:z(n,o.source),target:z(n,o.target)}))}}function Le(e,t){if(!(e!=null&&e.joins.length))return[];const n=[e.baseEntity,...e.joins.flatMap(i=>[i.source,i.target])],o=[];return n.forEach(i=>{!A(t,i)&&!A(o,i)&&o.push(i)}),o}function T(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function E(e){return T(e)&&typeof e.name=="string"}function H(e){return!T(e)||e.kind!=="semantic"&&e.kind!=="physical"||(e.kind==="semantic"?[e.datasetId,e.datasetName,e.connectionId]:[e.databaseName,e.schemaName]).some(n=>n!==void 0&&typeof n!="string")?!1:C.hasCompleteSemaphorSourceIdentity(e)}function Re(e){return[...e.groupByColumns??[],...e.metricColumns??[],...e.pivotByColumns??[],...e.detailColumns??[],...e.sortByColumns??[]]}function U(e){return e?[...(e.conditions??[]).flatMap(t=>t.field?[t.field]:[]),...(e.groups??[]).flatMap(U)]:[]}function pe(e){var o,i;const t="parameters"in e?U((o=e.parameters)==null?void 0:o.filters):[],n=((i=e.calculatedFormula)==null?void 0:i.inputFields)??[];return[...t,...n.flatMap(s=>pe(s))]}function me(e){const t=Array.isArray(e==null?void 0:e.selectedEntities)?e.selectedEntities.filter(E):[];return C.mergeSemaphorSourcesByIdentity(t.flatMap(n=>{const o=Y(n,e);return o?[o]:[]}))}function q(e,t){const n=t.filter(o=>C.semaphorSourcesReferToSameDataset(o,e));return n.length===1?n[0]:void 0}function Ve(e,t){if(t.kind==="semantic")return!!(e.entityId&&e.entityId===t.datasetId||e.entityName&&e.entityName===t.datasetName);const n=[t.databaseName,t.schemaName,t.tableName].filter(o=>!!o).join(".");return!!(e.entityName===t.tableName||e.qualifiedEntityName&&e.qualifiedEntityName===n)}function xe(e,t){const n=Array.isArray(t==null?void 0:t.selectedEntities)?t.selectedEntities.filter(E):[],o=e.entityName||e.qualifiedEntityName;if(!o)return;const i=e.entityId?A(n,{type:"dataset",id:e.entityId,name:o}):void 0;if(i)return Y(i,t);const s=A(n,{type:(t==null?void 0:t.mode)==="semanticDomain"?"dataset":"table",name:(t==null?void 0:t.mode)==="semanticDomain"?o:e.qualifiedEntityName||o});if(s&&!((t==null?void 0:t.mode)==="semanticDomain"&&e.entityId&&![e.entityName,e.qualifiedEntityName,s.name,s.type==="dataset"&&"table"in s?s.table:void 0].filter(a=>!!a).includes(e.entityId)))return Y(s,t)}function je(e,t,n){var s,r,a;const o=!!(C.hasSyntheticCalculatedFieldOwner(e)||(r=(s=e.calculatedFormula)==null?void 0:s.inputFields)!=null&&r.length||(a=e.derivedField)!=null&&a.inputs&&Object.keys(e.derivedField.inputs).length>0);if(e.source&&!o){const m=q(e.source,n);return m?[m]:[]}const i=Te.resolveFieldDatasetDependencies(e).datasets;return C.mergeSemaphorSourcesByIdentity(i.flatMap(m=>{const l=e.source&&Ve(m,e.source)&&q(e.source,n)||xe(m,t);return l?[l]:[]}))}function qe(e,t){const n=me(t),o=Re(e),i=U(e.filters),s=[...i,...[...o,...i].flatMap(pe)];return C.mergeSemaphorSourcesByIdentity([...o,...s].flatMap(r=>je(r,t,n)))}function He(e,t,n){var i;return H(e)?!!!((i=t==null?void 0:t.selectedEntities)!=null&&i.length)||!n?e:q(e,me(t)):void 0}function Y(e,t){var p,l;const n=Array.isArray(t==null?void 0:t.selectedEntities)?t.selectedEntities.filter(E):void 0,o=A(n,e),i=o?{...e,...o}:e,s="domainId"in i&&typeof i.domainId=="string"&&!!i.domainId.trim();if((t==null?void 0:t.mode)==="semanticDomain"&&!s)return;if((t==null?void 0:t.mode)!=="database"&&i.type==="dataset"){const c=ke.resolveSemaphorSemanticDatasetEntity({entities:[i],semanticDomainId:t==null?void 0:t.semanticDomainId,connectionId:t==null?void 0:t.connectionId,fieldEntityType:"dataset"},{includePhysicalDatasets:!0});if(c.kind==="resolved"){const b="label"in i&&typeof i.label=="string"?i.label:void 0;return{...c.source,...b?{label:b}:{}}}}if((t==null?void 0:t.mode)==="semanticDomain")return;const r=i.connectionId||(t==null?void 0:t.connectionId),a=i.type==="dataset"&&"table"in i&&i.table?i.table:i.name;if(!r||!a)return;const m={kind:"physical",connectionId:r,connectionType:i.connectionType||(t==null?void 0:t.connectionType),tableName:a,databaseName:i.database||((p=t==null?void 0:t.dbSelection)==null?void 0:p.database),schemaName:i.schema||((l=t==null?void 0:t.dbSelection)==null?void 0:l.schema),dialect:i.dialect};return H(m)?m:void 0}function Ue(e,t){var a,m;const n=Y(e,t);if(!n)return;const o=e.type==="dataset"&&"table"in e&&typeof e.table=="string"?e.table.trim():void 0,i=n.kind==="physical"?n.tableName:o,s=e.connectionId||(t==null?void 0:t.connectionId),r=i&&s?{connectionId:s,databaseName:e.database||((a=t==null?void 0:t.dbSelection)==null?void 0:a.database),schemaName:e.schema||((m=t==null?void 0:t.dbSelection)==null?void 0:m.schema),tableName:i}:void 0;return{source:n,...r?{executionTable:r}:{}}}function ue(e){const t=T(e.dataSource)?e.dataSource:void 0;if(typeof e.sql=="string"&&e.sql.trim()){const a=[],m=Array.isArray(t==null?void 0:t.selectedEntities)?t.selectedEntities:[];for(const p of m){if(!E(p))continue;const l=Ue(p,t);l&&!a.some(c=>C.semaphorSourcesReferToSameDataset(c.source,l.source))&&a.push(l)}return{cardId:e.id,kind:"sql",pinnedCatalogSources:a}}if(!T(e.config))return{cardId:e.id,kind:"unconfigured"};const n=e.config,o=[],i=J.inspectMatrixCardConfig(e);if(i.status==="invalid")return{cardId:e.id,kind:"unconfigured"};const s=i.status==="ready"?i.config:void 0;if(e.type==="matrixTable"&&!s)return{cardId:e.id,kind:"unconfigured"};s&&o.push(...J.matrixDefinitionSources(s.spec).filter(H));const r=(s==null?void 0:s.spec.joinPlan)??(T(n.joinPlan)?n.joinPlan:void 0);if(r){const a=Array.isArray(r.joins)?r.joins:[],m=[r.baseEntity];for(const l of a)T(l)&&m.push(l.source,l.target);let p=!1;for(const l of m){if(!E(l)){p=!0;continue}const c=Y(l,t);c?o.push(c):p=!0}p&&(o.length=0)}else if(e.type!=="matrixTable"){const a=Array.isArray(t==null?void 0:t.selectedEntities)?t.selectedEntities:[];if(a.length===1&&E(a[0])){const p=Y(a[0],t);p&&o.push(p)}o.push(...qe(n,t));const m=He(n.queryBaseSource,t,o.length>0);m&&o.push(m)}return{cardId:e.id,kind:"config",executableSources:C.mergeSemaphorSourcesByIdentity(o)}}function Ke(e,t){return(e.kind==="config"?e.executableSources:e.kind==="sql"?e.pinnedCatalogSources.map(o=>o.source):[]).some(o=>C.semaphorSourcesReferToSameDataset(o,t))}function de(e,t){if(e.kind==="config")return e.executableSources.find(n=>C.semaphorSourcesReferToSameDataset(n,t))}function Je(e,t){var n;return(n=fe(e,t))==null?void 0:n.source}function fe(e,t){if(e.kind==="sql")return e.pinnedCatalogSources.find(n=>C.semaphorSourcesReferToSameDataset(n.source,t))}const he={rowMembers:!0,columnMembers:!0,cells:!0};function be(e,t){return{enabled:t==="on",fields:e.type==="detailTable"?{kind:"clickedCell"}:{kind:"wholeRow"},multipleSelection:!0,selectionCheckboxes:"auto",...e.type==="matrixTable"?{matrixSources:{...he}}:{},targets:{kind:"allSheets"},cardMappings:[]}}const Ge=["string","number","boolean","date","datetime"];function Qe(e){return(e.kind==="semantic"?[e.datasetId,e.datasetName]:[e.tableName,[e.databaseName,e.schemaName,e.tableName].filter(Boolean).join(".")]).filter(t=>!!t).map(t=>C.normalizeAnalyticsCatalogName(t))}function ge(e,t){if(t.kind!=="config"||e.expression||e.calculatedFormula)return;const n=C.normalizeAnalyticsCatalogDataType(e.dataType);if(!Ge.includes(n))return;let o;if(e.source)o=de(t,e.source);else{const i=[e.entityId,e.entityName,e.qualifiedEntityName].filter(r=>!!r).map(r=>C.normalizeAnalyticsCatalogName(r)),s=t.executableSources.filter(r=>Qe(r).some(a=>i.includes(a)));s.length===1?o=s[0]:!s.length&&t.executableSources.length===1&&(o=t.executableSources[0])}if(!(!o||!e.name))return{name:e.name,source:o,dataType:n,...e.sourceField&&e.sourceField!==e.name?{sourceField:e.sourceField}:{}}}function Xe(e,t){const{matrixSources:n,...o}=t,i=t.fields.kind==="chosenColumns"?{kind:"chosenColumns",clickedFieldKeys:[...new Set(t.fields.clickedFieldKeys)]}:t.fields;return{...o,fields:i,...e.type==="matrixTable"?{matrixSources:n??{...he}}:{}}}function We(e,t){var c,b;if(e.clickToFilter)return Xe(e,e.clickToFilter);const n=be(e,t),o=(((c=e.interactionConfig)==null?void 0:c.interactions)??[]).filter(d=>d.mode==="clickFilter");if(!o.length)return n;const i=ue(e);let s=!1;const r=[];for(const d of o){if(((b=d.trigger)==null?void 0:b.type)!=="attribute"){s=!0;continue}const y=ge(d.trigger.field,i);if(!y){s=!0;continue}const _=oe.selectionFieldKey(y);r.includes(_)||r.push(_)}const a=o.every(d=>d.applyToCardIds!==void 0),m=[...new Set(o.flatMap(d=>d.applyToCardIds??[]))],p=o.filter(d=>d.applyToCardIds===void 0),l=a?[]:[...new Set(p.flatMap(d=>d.excludeCardIds??[]))].filter(d=>p.every(y=>{var _;return(_=y.excludeCardIds)==null?void 0:_.includes(d)}));return{...n,enabled:!0,fields:s||!r.length?{kind:"wholeRow"}:{kind:"chosenColumns",clickedFieldKeys:r},targets:a?{kind:"cards",cardIds:m}:{kind:"allSheets"},cardMappings:l.map(d=>({kind:"excluded",cardId:d}))}}const ye=u.z.union([u.z.object({kind:u.z.literal("allSheets"),sheetKinds:u.z.array(u.z.enum(["dashboard","document"])).optional()}).strict(),u.z.object({kind:u.z.literal("sheets"),sheetIds:u.z.array(u.z.string())}).strict(),u.z.object({kind:u.z.literal("cards"),cardIds:u.z.array(u.z.string())}).strict(),u.z.object({kind:u.z.literal("documentSections"),sheetId:u.z.string(),sectionIds:u.z.array(u.z.string())}).strict()]),Ce=u.z.union([u.z.object({kind:u.z.literal("bound"),cardId:u.z.string().min(1),clickedFieldKey:u.z.string().min(1),target:u.z.object({kind:u.z.literal("field"),field:oe.selectionFieldSchema}).strict()}).strict(),u.z.object({kind:u.z.literal("excluded"),cardId:u.z.string().min(1)}).strict()]),Ze=u.z.object({enabled:u.z.boolean(),fields:u.z.union([u.z.object({kind:u.z.literal("wholeRow")}).strict(),u.z.object({kind:u.z.literal("clickedCell")}).strict(),u.z.object({kind:u.z.literal("chosenColumns"),clickedFieldKeys:u.z.array(u.z.string().min(1))}).strict()]),multipleSelection:u.z.boolean(),selectionCheckboxes:u.z.enum(["auto","always","never"]),matrixSources:u.z.object({rowMembers:u.z.boolean(),columnMembers:u.z.boolean(),cells:u.z.boolean()}).strict().optional(),targets:ye,cardMappings:u.z.array(Ce)}).strict(),et=u.z.boolean(),tt=u.z.object({targets:ye.nullable().optional(),cardMappings:u.z.array(Ce).nullable().optional()}).strict(),_e=["bar","horizontalBar","line","area","stackedArea","combo","stackedBar","stackedLine"],nt=new Set(_e);function ve(e){return typeof e=="string"&&nt.has(e)}function ot(e){return e==="detailTable"||e==="table"||e==="aggregateTable"||e==="pivotTable"||e==="custom"||ve(e)}function ne(e){return!!(e!=null&&e.trim())}function it(e){return ne(e.sql)||ne(e.normalizedPython)?"freeform":e.hasExecutableConfig?"config":"none"}const O={type:"temporal_bucket",presentation:{mode:"auto"}},v={value:"auto",label:"Automatic",format:O};function g(e,t){return{value:`pattern:${e}`,label:t,format:{type:"temporal_bucket",presentation:{mode:"pattern",pattern:e}}}}function D(e,t){return{value:`preset:${e}`,label:t,format:{type:"temporal_bucket",presentation:{mode:"preset",preset:e}}}}function k(e){return{...g(e,"Custom format…"),value:"custom",custom:!0}}const K={second:[v,g("HH:mm:ss","14:30:45 (HH:mm:ss)"),g("YYYY-MM-DD HH:mm:ss","2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"),k("DD/MM/YYYY HH:mm:ss")],minute:[v,g("HH:mm","14:30 (HH:mm)"),g("YYYY-MM-DD HH:mm","2024-01-15 14:30 (YYYY-MM-DD HH:mm)"),k("DD/MM/YYYY HH:mm")],hour:[v,g("HH","14 (HH)"),g("YYYY-MM-DD HH","2024-01-15 14 (YYYY-MM-DD HH)"),k("DD/MM/YYYY HH")],day:[v,g("YYYY-MM-DD","2024-01-15 (YYYY-MM-DD)"),g("MM/DD/YYYY","01/15/2024 (MM/DD/YYYY)"),g("DD/MM/YYYY","15/01/2024 (DD/MM/YYYY)"),g("MMM DD, YYYY","Jan 15, 2024 (MMM DD, YYYY)"),g("MMMM DD, YYYY","January 15, 2024 (MMMM DD, YYYY)"),k("YYYY/MM/DD")],week:[v,D("week_of_short","Week of Jan 15, 2024"),D("week_of_long","Week of January 15, 2024"),g("YYYY-MM-DD","2024-01-15 (YYYY-MM-DD)"),k("YYYY/MM/DD")],month:[v,g("MMM YYYY","Jan 2024 (MMM YYYY)"),g("MMMM YYYY","January 2024 (MMMM YYYY)"),g("YYYY-MM","2024-01 (YYYY-MM)"),g("MM/YYYY","01/2024 (MM/YYYY)"),g("YYYY MMM","2024 Jan (YYYY MMM)"),k("YYYY/MM")],quarter:[v,D("quarter_short","Q1 2024"),D("quarter_long","1st Quarter 2024")],year:[v,g("YYYY","2024 (YYYY)"),g("YY","24 (YY)")]},rt={second:"2026-07-31T14:05:09",minute:"2026-07-31T14:05:00",hour:"2026-07-31T14:00:00",day:"2026-07-31",week:"2026-07-27",month:"2026-07-01",quarter:"2026-07-01",year:"2026-01-01"};function Ye(e,t,n=re.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES){return I.formatTemporalBucket({value:rt[t],metadata:{kind:"temporal_bucket",granularity:t,calendar:{tz:"UTC",weekStart:1,...e.presentation.mode==="preset"&&(e.presentation.preset==="fiscal_quarter_short"||e.presentation.preset==="fiscal_year")?{fiscalCalendar:{kind:"month_aligned",yearStartMonth:7}}:{}}},format:e.presentation.mode==="auto"?{type:"temporal_bucket",locale:n.locale,presentation:{mode:"auto",styles:{dateStyle:n.dateStyle,dateTime:{...n.dateTime}}}}:{type:"temporal_bucket",locale:n.locale,presentation:e.presentation}})}function st(e,t,n=re.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES){const o=K[e],i=(t==null?void 0:t.presentation.mode)==="preset"?t.presentation.preset:void 0,s=i&&t&&I.validateTemporalBucketFormatApplicability(t,e).ok&&!o.some(a=>{var m;return((m=a.format)==null?void 0:m.presentation.mode)==="preset"&&a.format.presentation.preset===i})?D(i,i):void 0;return(s?[...o,s]:o).map(a=>{if(!a.format||a.custom)return a;const m=Ye(a.format,e,n);return a.format.presentation.mode==="pattern"?{...a,label:`${m} (${a.format.presentation.pattern})`}:a.format.presentation.mode==="auto"?{...a,label:`Automatic (${m})`}:{...a,label:m}})}function at(e,t){const n=K[t];if(e.presentation.mode==="pattern"){const o=e.presentation.pattern,i=n.find(s=>{var r;return((r=s.format)==null?void 0:r.presentation.mode)==="pattern"&&s.format.presentation.pattern===o});return{value:(i==null?void 0:i.value)??"custom",customPattern:i!=null&&i.custom||!i?o:"",format:e}}if(e.presentation.mode==="preset"){const o=e.presentation.preset,i=n.find(r=>{var a;return((a=r.format)==null?void 0:a.presentation.mode)==="preset"&&r.format.presentation.preset===o}),s=I.validateTemporalBucketFormatApplicability(e,t).ok;return i?{value:i.value,customPattern:"",format:e}:s?{value:`preset:${o}`,customPattern:"",format:e}:{value:"auto",customPattern:"",format:O}}return{value:"auto",customPattern:"",format:e}}function ct(e,t,n=""){var r;const o=K[e].find(a=>a.value===t),i=t.startsWith("preset:")?t.slice(7):void 0,s=t==="custom"?{type:"temporal_bucket",presentation:{mode:"pattern",pattern:n.trim()||(((r=o==null?void 0:o.format)==null?void 0:r.presentation.mode)==="pattern"?o.format.presentation.pattern:"")}}:(o==null?void 0:o.format)??(i&&I.isTemporalBucketPreset(i)?{type:"temporal_bucket",presentation:{mode:"preset",preset:i}}:void 0);return!s||!I.validateTemporalBucketFormatApplicability(s,e).ok?O:s}function lt(e,t){return I.validateTemporalBucketFormatApplicability(e,t).ok?e:O}const Me=[{value:"COUNT",label:"Count"},{value:"DISTINCT",label:"Count Distinct"}],pt=[...Me,{value:"SUM",label:"Sum"},{value:"AVG",label:"Average"},{value:"MIN",label:"Min"},{value:"MAX",label:"Max"},{value:"MEDIAN",label:"Median"}];function mt(e){return C.normalizeAnalyticsCatalogDataType(e)==="number"?pt:Me}exports.AUTOMATIC_TEMPORAL_BUCKET_FORMAT=O;exports.DOCUMENT_KPI_SECTION_MAX_CARDS=B;exports.DOCUMENT_KPI_SECTION_MAX_TILES=L;exports.SEMAPHOR_CARTESIAN_CHART_TYPES=_e;exports.buildDashboardCardSourceIndex=ue;exports.clickToFilterSettingsSchema=Ze;exports.dashboardCardFilterSourceInventoryContains=Ke;exports.defaultClickToFilterSettings=be;exports.findDashboardCardExecutableSource=de;exports.findDashboardCardPinnedCatalogSource=Je;exports.findDashboardSqlPinnedCatalogSource=fe;exports.findOrphanedJoinPlanEntities=Le;exports.getDocumentKpiSectionShapeIssues=Ae;exports.getDocumentSectionCards=se;exports.getFieldAggregationOptions=mt;exports.getTemporalBucketAuthoringOptions=st;exports.getTemporalBucketAuthoringSelection=at;exports.isSemaphorCartesianChartType=ve;exports.linkedClickToFilterOverridesSchema=tt;exports.listDashboardCardLocations=Ie;exports.mapDocumentSectionCards=Ee;exports.normalizeClickToFilterSettings=We;exports.normalizeJoinPlanEntityReferences=Be;exports.previewTemporalBucketAuthoringFormat=Ye;exports.reconcileTemporalBucketAuthoringFormat=lt;exports.resolveDashboardEntitySource=Y;exports.resolveTemporalBucketAuthoringFormat=ct;exports.resolveTemporalResultOwner=it;exports.respondsToSelectionsSchema=et;exports.selectionFieldFromExplorerField=ge;exports.supportsCanonicalDashboardTemporalResult=ot;exports.transformComparisonDocument=we;
@@ -1 +0,0 @@
1
- "use strict";const q=require("./validators-DFeDcdpA.cjs"),f={includeMetricFilterDatasets:!0,preferQualifiedIdentity:!1};function N(e){if(!e)return;if(e.kind==="semantic")return{entityName:e.datasetName,entityId:e.datasetId,label:e.label};const t=[e.databaseName,e.schemaName,e.tableName].filter(i=>!!(i&&i.trim())).join(".");return{entityName:e.tableName,qualifiedEntityName:t.includes(".")?t:void 0,label:e.label}}function w(e){var i;const t=N(e.source);return t?`${(i=e.source)==null?void 0:i.kind}:${t.qualifiedEntityName||t.entityName}`:""}function b(e){return[e.id,e.qualifiedEntityName,e.entityId,e.entityName,e.qualifiedFieldName,e.name,w(e)].join("|")}function x(e){return[e.entityName,e.qualifiedEntityName||"",e.entityId||""].join("|")}function O(e){return e.entityName||e.qualifiedEntityName||""}function g(e){var t,i;return!!(e.expression||e.derivedField||(i=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&i.length)}function k(e){return q.hasSyntheticCalculatedFieldOwner(e)?!0:e.entityName||e.qualifiedEntityName?!1:!e.source||g(e)}function y(e,t){const i=x(t);e.found.has(i)||e.found.set(i,t)}function d(e,t){var D,E,I;if(!e)return;const i=b(e);if(t.visitedFields.has(i))return;t.visitedFields.add(i);const n=k(e);if(!n){const u=!e.entityName&&!e.qualifiedEntityName?N(e.source):void 0;y(t,u||{entityName:e.entityName||"",entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName,label:e.source&&e.source.kind==="semantic"?e.source.label:void 0})}t.includeMetricFilterDatasets&&"parameters"in e&&((D=e.parameters)!=null&&D.filters)&&F(e.parameters.filters,t);const l=(E=e.calculatedFormula)==null?void 0:E.inputFields,a=!!(l&&l.length>0);a&&l.forEach(u=>d(u,t));let r=!1,s=!1;const c=a||(I=e.derivedField)==null?void 0:I.inputs;if(c&&Object.keys(c).length>0)for(const u of Object.values(c)){const o=u.field.source;if(!o){a||(s=!0);continue}if(o.kind==="sql"){s=!0;continue}if(o.kind==="semantic")y(t,{entityName:o.datasetName,entityId:o.datasetId,label:o.label});else{const S=[o.databaseName,o.schemaName,o.tableName].filter(h=>!!(h&&h.trim())).join(".");y(t,{entityName:o.tableName,qualifiedEntityName:S.includes(".")?S:void 0,label:o.label})}r=!0}s&&(t.complete=!1),n&&!a&&!r&&(t.complete=!1)}function F(e,t){if(e&&!t.visitedGroups.has(e.id)){t.visitedGroups.add(e.id);for(const i of e.conditions||[])d(i.field,t);for(const i of e.groups||[])F(i,t)}}function m(e,t=new Set,i=new Set){return{found:new Map,complete:!0,visitedFields:t,visitedGroups:i,includeMetricFilterDatasets:e}}function p(e,t){var n;const i=(n=e.qualifiedEntityName)!=null&&n.includes(".")?e.qualifiedEntityName:void 0;return t==="qualifiedOnly"?i:t==="preferQualified"?i||e.entityName||void 0:e.entityName||void 0}function Q(e){const t=m(!1);return d(e,t),{datasets:Array.from(t.found.values()),complete:t.complete}}function v(e,t,i=new Set,n=new Set,l=f){const a={...f,...l},r=m(a.includeMetricFilterDatasets,i,n);d(e,r),r.found.forEach(s=>{const c=p(s,a.preferQualifiedIdentity?"preferQualified":"name");c&&t.add(c)})}function j(e,t){v(e,t,new Set,new Set,{preferQualifiedIdentity:!0})}function M(e,t,i=new Set,n=new Set){const l=m(!0,i,n);d(e,l),l.found.forEach(a=>{const r=p(a,"qualifiedOnly");r&&t.add(r)})}function A(e,t,i=new Set,n=new Set){v(e,t,i,n,{includeMetricFilterDatasets:!1})}function G(e,t,i=new Set,n=new Set,l=f){const a={...f,...l},r=m(a.includeMetricFilterDatasets,i,n);F(e,r),r.found.forEach(s=>{const c=p(s,a.preferQualifiedIdentity?"preferQualified":"name");c&&t.add(c)})}function T(e,t){return t!=null&&t[e]?t[e]:(e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,n=>n.toUpperCase())}exports.collectDatasetNamesFromExplorerField=v;exports.collectDatasetNamesFromFilterGroup=G;exports.collectExecutionDatasetNamesFromExplorerField=A;exports.collectPreferredDatasetNamesFromExplorerField=j;exports.collectQualifiedDatasetNamesFromExplorerField=M;exports.datasetRefFromSource=N;exports.dependencyDisplayIdentity=O;exports.humanizeDatasetName=T;exports.resolveFieldDatasetDependencies=Q;
@@ -1,4 +0,0 @@
1
- "use strict";var St=Object.defineProperty;var $t=(e,r,t)=>r in e?St(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var R=(e,r,t)=>$t(e,typeof r!="symbol"?r+"":r,t);const ve=require("./numeric-presentation-mY6wJMdB.cjs"),K=require("./validators-DFeDcdpA.cjs");require("./matrix-continuation-6nhDy-lF.cjs");const Re=require("./matrix-operation-contract-0RxoU_M3.cjs"),be=require("../value-format-preferences/index.cjs"),A=require("./pivot-result-lifecycle-OXAgoIYm.cjs"),T=require("zod"),kt=require("./matrix-definition-DanUT11P.cjs"),P=require("./card-config-utils-z86y6tSq.cjs"),_t=require("./matrix-card-C2RjEYZ8.cjs"),Z=require("./field-aggregations-pH_3kymD.cjs"),B=require("./raw-temporal-CYdOOyR5.cjs"),N=require("./pivot-result-identity-gquWljbd.cjs"),Fe=require("./temporal-bucket-contract-nTv6gvX5.cjs"),Y=require("./temporal-bucket-4YEPEKlJ.cjs"),Me=require("./raw-temporal-contract-CklMVG_1.cjs"),se=require("./canonical-result-keys-Cb96edol.cjs"),Oe=`import pandas as pd
2
- df = pd.DataFrame(data) # 'data' contains the query result
3
- result = df.to_dict('records') # must return 'result' as [dict] type
4
- `;function Rt(e){return{databaseName:(e==null?void 0:e.lastSelectedDatabase)||"",schemaName:(e==null?void 0:e.lastSelectedSchema)||"",tableName:(e==null?void 0:e.lastSelectedTable)||"",datamodelId:(e==null?void 0:e.datamodelId)||""}}function G(e){return e===Oe?"":e}function X(e,r=e.config){return Z.resolveTemporalResultOwner({hasExecutableConfig:P.hasValidCardConfig(r,e.type),sql:e.sql,normalizedPython:G(e.python||"")})}class ze extends Error{constructor(t){super(`ambiguous_temporal_grain: Temporal field "${t}" has saved presentation but no valid grouping grain. Reconfigure and resave the field.`);R(this,"code","ambiguous_temporal_grain");R(this,"fieldId");this.name="AmbiguousGroupedTemporalGrainError",this.fieldId=t}}function Ft(e){return P.hasSavedTemporalBucketPresentation(e)||e.semanticTemporalPresentation!=null}function Ke(e){if(!e.id||!["date","datetime"].includes(K.normalizeAnalyticsCatalogDataType(e.dataType)))return;if(K.isSemaphorTimeGrain(e.granularity))return e;if(!Ft(e))return;if(!P.readSavedTemporalBucketFormat({fieldId:e.id,dataType:e.dataType,granularity:e.granularity,format:e.format,dateFormat:e.dateFormat,customFormat:e.customFormat}).ok)throw new ze(e.id);return{...e,granularity:"day"}}function Ie(e){const r=e.cardConfig??e.card.config;if(!r||!e.supportsCardType(e.card.type)||Z.resolveTemporalResultOwner({hasExecutableConfig:P.hasValidCardConfig(r),sql:e.card.sql,normalizedPython:G(e.card.python||"")})!=="config")return;const t=[...(r.groupByColumns||[]).map(n=>({...n,role:"groupby"})),...e.card.type==="pivotTable"?(r.pivotByColumns||[]).map(n=>({...n,role:"pivotby"})):[]];return{cardType:e.card.type,cardConfig:r,fields:t.flatMap(n=>{const o=Ke(n);return o?[o]:[]})}}function At(e){if(P.isShelfCard(e.card))return Ie({...e,card:e.card,supportsCardType:r=>r==="table"})}function Bt(e){if(P.isShelfCard(e.card))return Ie({...e,card:e.card,supportsCardType:Z.isSemaphorCartesianChartType})}function Ne(e){if(P.isShelfCard(e.card))return Ie({...e,card:e.card,supportsCardType:r=>r!=="detailTable"&&Z.supportsCanonicalDashboardTemporalResult(r)})}const Ae=new WeakMap;function qe(e){const r=Ae.get(e);if(r)return r;const t=A.parseCanonicalPivotResultTransport(e);return Ae.set(e,t),t}function Q(e,r){const t=e??[],n=r??[];return t.length===n.length&&t.every((o,a)=>o===n[a])}function Le(e,r){const t=A.derivePivotResultContractExpectations({groupByFields:r.groupByColumns,metricFields:r.metricColumns,pivotByFields:r.pivotByColumns,detailFields:r.detailColumns});return Q(e.expectedRoleFieldIds.groupby,t.expectedRoleFieldIds.groupby)&&Q(e.expectedRoleFieldIds.metric,t.expectedRoleFieldIds.metric)&&Q(e.expectedRoleFieldIds.pivotby,t.expectedRoleFieldIds.pivotby)&&Q(e.expectedRoleFieldIds.detail,t.expectedRoleFieldIds.detail)&&Q(e.expectedMetricAliases,t.expectedMetricAliases)}class Dt extends Error{constructor(t){super(`missing_resolved_temporal_format: Saved presentation is missing temporal field "${t.fieldId}" for card "${t.cardId}". Resave the report or Briefing to capture the current dashboard presentation.`);R(this,"code","missing_resolved_temporal_format");R(this,"deliveryBlocking",!0);R(this,"dashboardId");R(this,"cardId");R(this,"fieldId");this.name="MissingResolvedTemporalPresentationError",this.dashboardId=t.dashboardId,this.cardId=t.cardId,this.fieldId=t.fieldId}}class me extends Error{constructor(t){super(`missing_temporal_bucket_metadata: Result column "${t.columnKey}" is missing temporal bucket metadata for field "${t.fieldId}" on card "${t.cardId}". Refresh the report and resave the delivery if the problem persists.`);R(this,"code","missing_temporal_bucket_metadata");R(this,"deliveryBlocking",!0);R(this,"cardId");R(this,"fieldId");R(this,"columnKey");this.name="MissingTemporalResultMetadataError",this.cardId=t.cardId,this.fieldId=t.fieldId,this.columnKey=t.columnKey}}class V extends Error{constructor(t,n,o){super(`${t}: ${n}`);R(this,"deliveryBlocking",!0);this.code=t,this.context=o,this.name="DashboardTemporalBoundaryError"}}function Ve(e,r){return`${r}:${e}`}function Ue(e){var r,t;return(t=(r=e.presentation)==null?void 0:r.byFieldRole)==null?void 0:t.get(Ve(e.fieldId,e.role))}function Pt(e){var t;if((((t=e.cardConfig.metricColumns)==null?void 0:t.length)||0)>0||e.binding.role!=="metric")return!1;const r=e.binding.outputKey||e.binding.rawKey;return e.columns.some(n=>{var o;return n.role==="measure"&&n.dataType==="number"&&(n.key===r||((o=n.pivotIdentity)==null?void 0:o.metricId)===K.SEMAPHOR_GENERATED_COUNT_METRIC_ID)})}function Mt(e,r){return!r||r.byColumnKey.size===0?e.map(t=>({...t})):e.map(t=>{const n={...t};return r.byColumnKey.forEach((o,a)=>{Object.prototype.hasOwnProperty.call(t,a)&&(n[a]=Ce({value:t[a],presentation:o}))}),n})}function Ot(e){var p;if(!e.result||typeof e.result!="object")return!1;const r=e.result;if(e.expectedResultOwner!==void 0&&r.resultOwner!==e.expectedResultOwner)return!1;const t=e.activation;if(!t||t.cardType!=="pivotTable"&&t.fields.length===0)return!0;const n=Array.isArray(r.records)?r.records.length:void 0,o=(t.cardConfig.pivotByColumns||[]).map(d=>d.id);if(t.cardType==="pivotTable")try{const d=qe(r);if(!Le(d.pivotResultContract,t.cardConfig))return!1;if(d.pivotResultState==="loaded_empty")return!0;const v=d.columns.filter(C=>d.pivotResultContract.columnKinds[C.key]==="pivot_metric"),h=v.filter(C=>{var g;return(((g=C.pivotIdentity)==null?void 0:g.members.length)??0)>0}),b=v.length>0&&v.every(C=>{var g;return((g=C.pivotIdentity)==null?void 0:g.members.length)===0&&N.isPivotEmptyTupleAllowed({expectedPivotFieldIds:o,classification:d.pivotResultContract.columnClassifications[C.key]})});return t.fields.every(C=>{var $;const g=N.resolveQueryColumnKeyMapEntry(d.columnKeyMap,C.id,C.role);if(!g)return!1;if(g.role==="pivotby"){const _=h.flatMap(M=>{var H;return((H=M.pivotIdentity)==null?void 0:H.members.filter(xt=>xt.fieldId===C.id))??[]});return _.length===0?b:_.every(M=>{var H;return((H=M.temporalBucket)==null?void 0:H.granularity)===C.granularity})}const w=d.columns.find(_=>_.key===(g.outputKey||g.rawKey));return(($=w==null?void 0:w.temporalBucket)==null?void 0:$.granularity)===C.granularity})}catch(d){if(d instanceof A.PivotResultLifecycleError)return!1;throw d}if(n===0)return!0;const a=r.columnKeyMap;if(!a||!a.byRole||typeof a.byRole!="object"||Array.isArray(a.byRole))return!1;const i=[...(t.cardConfig.groupByColumns||[]).map(d=>({field:d,role:"groupby"})),...(t.cardConfig.metricColumns||[]).map(d=>({field:d,role:"metric"})),...(t.cardConfig.pivotByColumns||[]).map(d=>({field:d,role:"pivotby"})),...(t.cardConfig.detailColumns||[]).map(d=>({field:d,role:"detail"}))],l=new Set(i.map(({field:d,role:v})=>`${v}:${d.id}`)),m=new Map((r.columns||[]).map(d=>[d.key,d])),c=N.resolveQueryColumnKeyMapEntry(a,K.SEMAPHOR_GENERATED_COUNT_METRIC_ID,"metric");if(c){if(!Pt({cardConfig:t.cardConfig,binding:c,columns:r.columns||[]}))return!1;l.add(`metric:${K.SEMAPHOR_GENERATED_COUNT_METRIC_ID}`)}const s=Object.entries(a.byRole).flatMap(([d,v])=>Object.keys(v||{}).map(h=>`${d}:${h}`));if(s.length!==l.size||s.some(d=>!l.has(d))||i.some(({field:d,role:v})=>!N.resolveQueryColumnKeyMapEntry(a,d.id,v)))return!1;try{N.requirePivotResultColumnIdentities((r.columns||[]).map(d=>({key:d.key,pivotIdentity:d.pivotIdentity})),{expectedPivotFieldIds:o,columnClassifications:r.columnMetadata})}catch(d){if(d instanceof N.PivotResultIdentityError)return!1;throw d}const u=(r.columns||[]).filter(d=>{const v=d.pivotIdentity;return!!(v&&v.members.length>0)});return n!==0&&((p=t.cardConfig.pivotByColumns)!=null&&p.length)&&u.length===0?!1:t.fields.every(d=>{var b;const v=N.resolveQueryColumnKeyMapEntry(a,d.id,d.role);if(!v)return!1;if(v.role==="pivotby"){const g=u.flatMap(w=>{var $;return(($=w.pivotIdentity)==null?void 0:$.members)??[]}).filter(w=>w.fieldId===d.id);return u.length===0?n===0:g.length>0&&g.every(w=>{var $;return(($=w.temporalBucket)==null?void 0:$.granularity)===d.granularity})}const h=m.get(v.outputKey||v.rawKey);return((b=h==null?void 0:h.temporalBucket)==null?void 0:b.granularity)===d.granularity})}function oe(e,r){const t=e.semanticTemporalPresentation,n=r==="card"?{format:e.format,dateFormat:e.dateFormat}:{format:t==null?void 0:t.format};if(!P.hasSavedTemporalBucketPresentation(n))return;const o=P.readSavedTemporalBucketFormat({fieldId:e.id,dataType:e.dataType,granularity:r==="semantic"?t==null?void 0:t.granularity:e.granularity,...r==="card"?{format:e.format,dateFormat:e.dateFormat,customFormat:e.customFormat}:{format:t==null?void 0:t.format}});if(!o.ok)throw new Error(o.error.code);return o.format}function zt(e,r,t=be.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES){const n=oe(e,"card"),o=oe(e,"semantic"),a=e.semanticTemporalPresentation;return Y.resolveTemporalBucketPresentation({metadata:r,...n?{cardFormat:n}:{},...o&&a?{semanticFormat:{granularity:a.granularity,format:o}}:{},locale:t.locale,styles:{dateStyle:t.dateStyle,dateTime:t.dateTime}})}function je(e,r=Y.DEFAULT_RESOLVED_TEMPORAL_STYLE_SET,t="en-US"){var i;const n=oe(e,"card"),o=((i=e.semanticTemporalPresentation)==null?void 0:i.granularity)===e.granularity?oe(e,"semantic"):void 0,a=n&&n.presentation.mode!=="auto"?n:o&&o.presentation.mode!=="auto"?o:{presentation:{mode:"auto"}};return a.presentation.mode==="auto"?{type:"temporal_bucket",locale:t,presentation:{mode:"auto",styles:r}}:{type:"temporal_bucket",locale:t,presentation:a.presentation}}function Kt(e){const r=e.activation;if(!r)return{byColumnKey:new Map,byFieldId:new Map,byFieldRole:new Map};if(e.resultRowCount===0)return{byColumnKey:new Map,byFieldId:new Map,byFieldRole:new Map};const t=new Map((e.columns||[]).map(c=>[c.key,c])),n=new Map,o=new Map,a=new Map,i=r.fields.reduce((c,s)=>(c.set(s.id,(c.get(s.id)||0)+1),c),new Map),l=(c,s)=>{a.set(Ve(c.id,c.role),s),i.get(c.id)===1&&o.set(c.id,s)},m=(c,s,u)=>{if(s.granularity!==c.granularity)throw new V("invalid_temporal_bucket_metadata",`Result identity "${u}" declares ${s.granularity} buckets for active ${c.granularity} field "${c.id}".`,{cardId:e.card.id,fieldId:c.id,columnKey:u});const p=e.executionSnapshot&&e.dashboardId?A.findResolvedTemporalBucketFormat({snapshot:e.executionSnapshot,scope:{dashboardId:e.dashboardId,cardId:e.card.id,...e.attachmentIndex!==void 0?{attachmentIndex:e.attachmentIndex}:{}},target:{kind:"field",fieldId:c.id,role:c.role}}):void 0;if(e.executionSnapshot&&!p)throw new Dt({dashboardId:e.dashboardId,cardId:e.card.id,fieldId:c.id});return{columnKey:u,fieldId:c.id,role:c.role,metadata:s,resolved:p?Y.resolveTemporalBucketPresentation({metadata:s,cardFormat:p,locale:p.locale,...p.presentation.mode==="auto"?{styles:p.presentation.styles}:{}}):zt(c,s,e.valueFormatPreferences??be.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES)}};for(const c of r.fields){const s=N.resolveQueryColumnKeyMapEntry(e.columnKeyMap,c.id,c.role);if(!s){if(e.columns===void 0&&e.columnKeyMap===void 0&&(e.resultRowCount===void 0||e.resultRowCount===0))continue;throw new V("missing_temporal_column_binding",`Activated temporal field "${c.id}" has no authoritative result-column binding.`,{cardId:e.card.id,fieldId:c.id,columnKey:c.name})}if(s.role==="pivotby"){const h=(e.columns||[]).filter($=>$.pivotIdentity!==void 0),b=h.flatMap($=>{var _;return(((_=$.pivotIdentity)==null?void 0:_.members)||[]).filter(M=>M.fieldId===c.id).map(M=>({column:$,member:M}))});if(b.length===0){if(h.length===0&&(e.card.type!=="pivotTable"||e.resultRowCount===0))continue;throw new me({cardId:e.card.id,fieldId:c.id,columnKey:s.outputKey||s.rawKey})}const C=b[0];if(!C.member.temporalBucket)throw new me({cardId:e.card.id,fieldId:c.id,columnKey:C.column.key});const g=Fe.validateTemporalBucketMetadata(C.member.temporalBucket);if(!g.ok||!g.value)throw new V("invalid_temporal_bucket_metadata",g.ok?`Pivot result column "${C.column.key}" has no validated temporal bucket metadata.`:g.error.message,{cardId:e.card.id,fieldId:c.id,columnKey:C.column.key});const w=m(c,g.value,C.column.key);for(const{column:$,member:_}of b)if(!_.temporalBucket||JSON.stringify(_.temporalBucket)!==JSON.stringify(C.member.temporalBucket))throw new V("invalid_temporal_bucket_metadata",`Pivot result column "${$.key}" has contradictory bucket metadata for field "${c.id}".`,{cardId:e.card.id,fieldId:c.id,columnKey:$.key});l(c,w);continue}const u=s.outputKey||s.rawKey,p=t.get(u);if(!(p!=null&&p.temporalBucket))throw new me({cardId:e.card.id,fieldId:c.id,columnKey:u});const d=Fe.validateTemporalBucketResultColumn(p,{metadataRequired:!0});if(!d.ok||!d.value)throw new V("invalid_temporal_bucket_metadata",d.ok?`Result column "${u}" has no validated temporal bucket metadata.`:d.error.message,{cardId:e.card.id,fieldId:c.id,columnKey:u});const v=m(c,d.value,u);n.set(u,v),l(c,v)}return{byColumnKey:n,byFieldId:o,byFieldRole:a}}function Nt(e){var t,n;const r=e.role?Ue({presentation:e.presentation,fieldId:e.fieldId,role:e.role}):(n=(t=e.presentation)==null?void 0:t.byFieldId)==null?void 0:n.get(e.fieldId);return r?Ce({value:e.value,presentation:r}):e.value===null||e.value===void 0?"":String(e.value)}function Ce(e){if(e.value===null||e.value===void 0)return"(Blank)";if(typeof e.value!="string")throw new V("invalid_temporal_bucket_value",`Canonical temporal column "${e.presentation.columnKey}" must contain a string or null.`,{fieldId:e.presentation.fieldId,columnKey:e.presentation.columnKey});try{return Y.formatTemporalBucket({value:e.value,metadata:e.presentation.metadata,format:e.presentation.resolved.format})}catch(r){throw r instanceof Y.TemporalBucketContractError?new V(r.code,r.message,{fieldId:e.presentation.fieldId,columnKey:e.presentation.columnKey}):r}}class k extends Error{constructor(r,t,n){super(`${r}: ${t}`),this.code=r,this.context=n,Object.setPrototypeOf(this,k.prototype),this.name="RawTemporalPresentationBoundaryError"}}function Ge(){return{type:"raw_temporal",presentation:{mode:"auto"}}}function qt(e){if(e.locale||e.relative||e.timezone&&e.timezone!=="auto"||e.sourceTimezone&&e.sourceTimezone!=="auto"||e.prefix||e.suffix)throw new k("invalid_raw_temporal_format","Activated raw temporal presentation contains unsupported locale, relative-time, timezone, prefix, or suffix settings.")}function He(e){const r=e.format;if((r==null?void 0:r.type)==="date"&&(qt(r),r.pattern))return{type:"raw_temporal",presentation:{mode:"pattern",dialect:"semaphor_tokens",pattern:r.pattern}};if(r)throw new k("invalid_raw_temporal_format",`Raw temporal detail field "${e.id}" has an incompatible authored format.`,{fieldId:e.id});if(e.dateFormat==="custom"){if(!e.customFormat)throw new k("invalid_raw_temporal_format",`Raw temporal detail field "${e.id}" selects a custom pattern but has no customFormat.`,{fieldId:e.id});return{type:"raw_temporal",presentation:{mode:"pattern",dialect:"semaphor_tokens",pattern:e.customFormat}}}return e.dateFormat?{type:"raw_temporal",presentation:{mode:"pattern",dialect:"semaphor_tokens",pattern:e.dateFormat}}:Ge()}function ce(e){var i;if(e!=null&&e.useRelativeTime)return;if(!e)return Ge();if(e.useCustomFormat&&!((i=e.customFormat)!=null&&i.trim()))throw new k("invalid_raw_temporal_format","Declared SQL temporal presentation selects a custom pattern but has no customFormat.",{reason:"missing_declared_sql_custom_date_format"});const r=e.useCustomFormat&&e.customFormat?e.customFormat:e.format,t=e.timezone,n=e.sourceTimezone,o=t&&t!=="auto"?{timezone:t}:void 0,a={sourceTimezone:n&&n!=="auto"?n:"UTC"};return r?{type:"raw_temporal",...o,...a,presentation:{mode:"pattern",dialect:"date_fns",pattern:r}}:{type:"raw_temporal",...o,...a,presentation:{mode:"auto"}}}function Lt(e){return e==="instant"?"yyyy-MM-dd'T'HH:mm:ssXXX":e==="wall_datetime"?"yyyy-MM-dd'T'HH:mm:ss":"yyyy-MM-dd"}function Vt(e){B.validateRawTemporalPattern({dialect:"date_fns",pattern:e.pattern,valueKind:e.valueKind})}function Ut(e){const r=ce(e.settings);if(!r)throw new k("invalid_raw_temporal_format","Relative-time SQL presentation does not have an absolute date preview.");const t=e.valueKind??(r.presentation.mode==="pattern"?"instant":"date"),n={kind:"raw_temporal",valueKind:t},o=e.value??(t==="date"?"2023-05-15":t==="wall_datetime"?"2023-05-15T14:30:45":"2023-05-15T14:30:45Z"),a=B.prepareRawTemporalFormatter({metadata:n,format:B.resolveRawTemporalFormat({format:r,preferences:e.preferences,calendar:{tz:e.calendarTimezone}})})(o);if(!a.ok)throw new k("invalid_raw_temporal_format",a.diagnostic.message);return a.text}function jt(e){try{return{ok:!0,text:Ut(e)}}catch(r){return{ok:!1,message:r instanceof Error?r.message:"Invalid SQL temporal presentation."}}}function Te(e){var t;const r=e.effectiveCardConfig??e.card.config;return X(e.card,r)==="freeform"&&!!((t=e.card.sql)!=null&&t.trim())&&!G(e.card.python||"").trim()}function Qe(e){var r,t;return e.type!=="table"&&e.type!=="detailTable"||!Te({card:e})?!1:Object.values(((t=(r=e.preferences)==null?void 0:r.tablePrefs)==null?void 0:t.columnSettingsMap)||{}).some(n=>{var o,a,i;return n.type==="date"&&((o=n.dateFormat)==null?void 0:o.useRelativeTime)!==!0&&((a=n.dateFormat)==null?void 0:a.useCustomFormat)===!0&&!((i=n.dateFormat.customFormat)!=null&&i.trim())})}function Gt(e){var t,n,o;if(!Qe(e))return e;const r=((n=(t=e.preferences)==null?void 0:t.tablePrefs)==null?void 0:n.columnSettingsMap)||{};return{...e,preferences:{...e.preferences,tablePrefs:{...(o=e.preferences)==null?void 0:o.tablePrefs,columnSettingsMap:Object.fromEntries(Object.entries(r).map(([a,i])=>{var l,m,c;return[a,i.type==="date"&&((l=i.dateFormat)==null?void 0:l.useRelativeTime)!==!0&&((m=i.dateFormat)==null?void 0:m.useCustomFormat)===!0&&!((c=i.dateFormat.customFormat)!=null&&c.trim())?{...i,dateFormat:{...i.dateFormat,format:"",useCustomFormat:!1,customFormat:""}}:i]}))}}}}function Ht(){return{activatedColumnKeys:new Set,byColumnKey:new Map,byFieldId:new Map}}function he(e,r){return e===void 0?{kind:"invalid",error:r}:{kind:"invalid",error:e instanceof k?e:e instanceof B.RawTemporalFormatContractError?new k(e.code,e.message,r.context):new k(r.code,e instanceof Error?e.message:r.message,r.context)}}function We(e){var o;if(e.cardType!=="detailTable"||e.resultOwner!=="config")return{kind:"inactive"};if(!e.result)return{kind:"loading"};const{records:r,columns:t,columnKeyMap:n}=e.result;if(!Array.isArray(r)||!Array.isArray(t)||!n)return he(void 0,new k("missing_raw_temporal_result_contract","Activated raw temporal detail results require records, columns, and columnKeyMap atomically."));try{const a=t.filter(s=>s.rawTemporal);if(a.length===0)return{kind:"inactive"};const i=new Map((((o=e.effectiveCardConfig)==null?void 0:o.detailColumns)||[]).map(s=>[s.id,s])),l=new Map,m=new Map;for(const s of a){const u=Array.from(i).flatMap(([w,$])=>{const _=N.resolveQueryColumnKeyMapEntry(n,w,"detail");return _&&_.role==="detail"&&(_.outputKey??_.rawKey)===s.key?[{field:$,binding:_}]:[]}),p=u.length===1?u[0]:null;if(!p||typeof p.binding.rawKey!="string"||p.binding.rawKey.trim().length===0||p.binding.outputKey!==void 0&&(typeof p.binding.outputKey!="string"||p.binding.outputKey.trim().length===0))throw new k("missing_raw_temporal_column_binding",`Raw temporal result column "${s.key}" does not have one valid exact detail result binding.`,{columnKey:s.key});const{field:d,binding:v}=p,h=v.outputKey??v.rawKey,b=Me.validateRawTemporalResultColumn(s,{metadataRequired:!0});if(!b)throw new k("invalid_raw_temporal_metadata",`Raw temporal result column "${h}" has no metadata.`,{fieldId:d.id,columnKey:h});const C=B.resolveRawTemporalFormat({format:He(d),preferences:e.preferences,calendar:e.calendar}),g={fieldId:d.id,columnKey:h,metadata:b,format:C,formatValue:B.prepareRawTemporalFormatter({metadata:b,format:C})};for(let w=0;w<r.length;w+=1)if(!Object.prototype.hasOwnProperty.call(r[w],h)||r[w][h]===void 0)throw new k("missing_raw_temporal_result_contract",`Raw temporal result row ${w} is missing column "${h}".`,{fieldId:d.id,columnKey:h});l.set(h,g),m.set(d.id,g)}const c={activatedColumnKeys:new Set(l.keys()),byColumnKey:l,byFieldId:m};return r.length===0?{kind:"loaded_empty",presentation:c}:{kind:"loaded_valid",presentation:c}}catch(a){return he(a,new k("invalid_raw_temporal_metadata","Activated raw temporal result metadata is invalid."))}}function Ye(e){var n,o,a;const r=e.effectiveCardConfig??e.card.config,t=X(e.card,r);if(e.card.type==="detailTable"&&t==="config"){const i=!!((n=e.columns)!=null&&n.some(l=>l.rawTemporal));return i&&e.records!==void 0&&!e.columnKeyMap?{kind:"invalid",error:new k("missing_raw_temporal_result_contract","Activated raw temporal detail results require records, columns, and columnKeyMap atomically.")}:e.records!==void 0&&!i?{kind:"inactive"}:Be(We({cardType:e.card.type,resultOwner:t,effectiveCardConfig:r,result:e.records===void 0||!e.columns||!e.columnKeyMap?void 0:{records:e.records,columns:e.columns,columnKeyMap:e.columnKeyMap},preferences:e.preferences,calendar:e.calendar}),e)}return Be(Wt({resultOwner:t,sql:e.card.sql,normalizedPython:G(e.card.python||""),records:e.records,columns:e.columns,columnSettings:(a=(o=e.card.preferences)==null?void 0:o.tablePrefs)==null?void 0:a.columnSettingsMap,preferences:e.preferences,calendar:e.calendar}),e)}function Qt(e){var n,o,a;const r=e.effectiveCardConfig??e.card.config,t=X(e.card,r);return e.card.type==="detailTable"&&t==="config"?!!((n=e.columns)!=null&&n.some(i=>i.rawTemporal)):Te(e)?Object.values(((a=(o=e.card.preferences)==null?void 0:o.tablePrefs)==null?void 0:a.columnSettingsMap)||{}).some(i=>{var l;return i.type==="date"&&!((l=i.dateFormat)!=null&&l.useRelativeTime)}):!1}function Be(e,r){if(!r.executionSnapshot||e.kind==="inactive"||e.kind==="loading"||e.kind==="invalid")return e;if(!r.dashboardId)return{kind:"invalid",error:new k("missing_raw_temporal_result_contract","A dashboard ID is required to resolve the captured raw temporal presentation.")};const t=new Map,n=new Map;for(const o of e.presentation.activatedColumnKeys){const a=A.findResolvedRawTemporalFormat({snapshot:r.executionSnapshot,scope:{dashboardId:r.dashboardId,cardId:r.card.id,...r.attachmentIndex!==void 0?{attachmentIndex:r.attachmentIndex}:{}},target:{kind:"column",columnKey:o}});if(!a)return{kind:"invalid",error:new A.MissingResolvedRawTemporalFormatError(o)};const i=e.presentation.byColumnKey.get(o);if(!i)continue;const l={...i,format:a,formatValue:B.prepareRawTemporalFormatter({metadata:i.metadata,format:a})};t.set(i.columnKey,l),i.fieldId&&n.set(i.fieldId,l)}return{...e,presentation:{activatedColumnKeys:e.presentation.activatedColumnKeys,byColumnKey:t,byFieldId:n}}}function Wt(e){var t,n;if(e.resultOwner!=="freeform"||!((t=e.sql)!=null&&t.trim())||(n=e.normalizedPython)!=null&&n.trim())return{kind:"inactive"};const r=Object.entries(e.columnSettings||{}).filter(([,o])=>{var a;return o.type==="date"&&!((a=o.dateFormat)!=null&&a.useRelativeTime)});if(r.length===0)return{kind:"inactive"};if(!e.records)return{kind:"loading"};try{const o=new Map,a=new Set(r.map(([c])=>c)),i=new Map,l=[...e.columns||[]];for(const[c,s]of r){const u=ce(s.dateFormat);if(!u)continue;const p=B.classifyDeclaredSqlTemporalColumn({columnKey:c,values:e.records.map(b=>{if(!Object.prototype.hasOwnProperty.call(b,c))throw new k("missing_raw_temporal_result_contract",`Declared SQL temporal column "${c}" is absent from a physical result row.`,{columnKey:c});const C=b[c];return C===null||typeof C=="string"?C:String(C)})});if(i.set(c,p),p.status!=="classified")continue;let d=l.findIndex(b=>b.key===c);if(e.columns&&d<0)throw new k("missing_raw_temporal_result_contract",`Classified SQL temporal column "${c}" is absent from result columns.`,{columnKey:c});d<0&&(d=l.length,l.push({key:c,name:c,label:c,role:"dimension",dataType:"string"}));const v={...l[d],role:"date",dataType:p.metadata.valueKind==="date"?"date":"datetime",rawTemporal:p.metadata};Me.validateRawTemporalResultColumn(v,{metadataRequired:!0}),l[d]=v;const h=B.resolveRawTemporalFormat({format:u,preferences:e.preferences,calendar:e.calendar});o.set(c,{columnKey:c,metadata:p.metadata,format:h,formatValue:B.prepareRawTemporalFormatter({metadata:p.metadata,format:h})})}const m={...Ht(),activatedColumnKeys:a,byColumnKey:o};return e.records.length===0?{kind:"loaded_empty",presentation:m,adaptedColumns:l,sqlClassifications:i}:{kind:"loaded_valid",presentation:m,adaptedColumns:l,sqlClassifications:i}}catch(o){return he(o,new k("invalid_raw_temporal_format","Declared SQL raw temporal presentation is invalid."))}}function Yt(e){if(e.value!==null&&typeof e.value!="string")return{value:e.value,label:String(e.value),result:{ok:!1,text:String(e.value),diagnostic:{code:"invalid_raw_temporal_value",message:`Raw temporal column "${e.presentation.columnKey}" must contain a string or null.`}}};const r=e.presentation.formatValue(e.value);return{value:e.value,label:r.text,result:r}}function Jt(e){if(!e.result||typeof e.result!="object")return!1;const r=e.result;if(e.expectedResultOwner!==void 0&&r.resultOwner!==e.expectedResultOwner||!Array.isArray(r.records))return!1;const t=Ye({card:e.card,effectiveCardConfig:e.effectiveCardConfig,records:r.records,columns:r.columns,columnKeyMap:r.columnKeyMap,preferences:be.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES,calendar:{tz:"UTC"}});return t.kind==="inactive"||t.kind==="loaded_empty"||t.kind==="loaded_valid"}function De(e){return!e||typeof e!="object"?!1:Array.isArray(e.cards)}function Je(e){if(!e)return null;if(typeof e=="string")try{const r=JSON.parse(e);return De(r)?r:null}catch{return null}return De(e)?e:null}function we(e){var r;return(r=e==null?void 0:e.cards)!=null&&r.length?e.activeCardId&&e.cards.find(t=>t.id===e.activeCardId)||e.cards[0]:null}function Zt(e){var t;const r=(e==null?void 0:e.frameObject)??((t=e==null?void 0:e.visual)==null?void 0:t.frameObject);return we(Je(r))}function le(e){if(!(e!=null&&e.expectedType))return"table";const r=Array.isArray(e.expectedType)?e.expectedType[0]:e.expectedType;return er(r)?r:"table"}const Xt=["bar","horizontalBar","line","area","stackedArea","combo","pie","doughnut","radar","polarArea","bubble","scatter","stackedBar","stackedLine","table","pivotTable","aggregateTable","detailTable","tableBuilder","kpi","pyramid","tornado","range","text","map","funnel","bullet","heatmap","treemap","custom"];function er(e){return Xt.includes(e)}function J(e){const r=e.position;if(typeof r=="number")return r;if(typeof r=="string"){const t=r.match(/\d+/);if(t){const n=Number(t[0]);if(!Number.isNaN(n))return n}}return Number.POSITIVE_INFINITY}function W(e){if(typeof e=="number")return{kind:"number",start:e,end:e};if(typeof e=="string"){const r=e.match(/^(\d+)$/);if(r){const o=Number(r[1]);return{kind:"number",start:o,end:o}}const t=e.match(/^(\d+)-(\d+)$/);if(t){const o=Number(t[1]),a=Number(t[2]);return{kind:"range",start:o,end:a}}const n=e.match(/^(\d+)\+$/);if(n)return{kind:"dynamic",start:Number(n[1]),end:Number.POSITIVE_INFINITY}}return null}function Ze(e){return!e||e.length===0?void 0:[...e].sort((t,n)=>J(t)-J(n))[0]}function Ee(e,r){if(!e||e.length===0)return;const t=[],n=[],o=[];e.forEach(s=>{const u=W(s.position);u&&(u.kind==="number"?t.push(s):u.kind==="range"?n.push(s):u.kind==="dynamic"&&o.push(s))});const a=t.find(s=>{const u=W(s.position);return(u==null?void 0:u.kind)==="number"&&u.start===r});if(a)return a;const l=n.sort((s,u)=>J(s)-J(u)).find(s=>{const u=W(s.position);return(u==null?void 0:u.kind)==="range"&&r>=u.start&&r<=u.end});if(l)return l;const c=o.map(s=>({slot:s,parsed:W(s.position)})).filter(s=>{var u;return((u=s.parsed)==null?void 0:u.kind)==="dynamic"}).sort((s,u)=>{var p,d;return(((p=s.parsed)==null?void 0:p.start)??0)-(((d=u.parsed)==null?void 0:d.start)??0)}).filter(s=>{var u;return r>=(((u=s.parsed)==null?void 0:u.start)??0)}).sort((s,u)=>{var p,d;return(((p=u.parsed)==null?void 0:p.start)??0)-(((d=s.parsed)==null?void 0:d.start)??0)})[0];return c==null?void 0:c.slot}function tr(e,r){const t=Ee(e,r);if(t)return le(t)}function Xe(e,r){var n;const t=(n=e==null?void 0:e.customCardPreferences)==null?void 0:n.slotIndex;return typeof t=="number"?t:r}function ge(e,r){var t;if(!((t=e==null?void 0:e.customCardPreferences)!=null&&t.url))return!1;if(e.type==="custom"||e.customCardPreferences.visualType==="multiple"||e.customCardPreferences.dataInputCardIds||(e.customCardPreferences.minInputs||0)>1||(e.customCardPreferences.maxInputs||0)>1)return!0;if(r&&r.length>1){const n=r.filter(o=>{var a;return typeof((a=o.customCardPreferences)==null?void 0:a.slotIndex)=="number"});if(n.length>1&&n.some(o=>o.id!==e.id))return!0}return!1}function et(e){const r=[];let t=-1;e.forEach((n,o)=>{const a=Xe(n,o);a>t&&(t=a),r[a]=n??null});for(let n=0;n<=t;n+=1)n in r||(r[n]=null);return r}function rr(e){return e.map((r,t)=>!r.customCardPreferences||r.customCardPreferences.slotIndex===t?r:{...r,customCardPreferences:{...r.customCardPreferences,slotIndex:t}})}function nr(e){const r=Ze(e);if(r)return le(r)}function or(e,r,t){if(!e)return;const n=tr(t,r);return e.type==="custom"&&n?n:e.type}function ar(e,r,t){var v;const n={dataSource:t.dataSource,connectionId:t.connectionId,lastSelectedDatabase:t.lastSelectedDatabase,lastSelectedSchema:t.lastSelectedSchema,lastSelectedTable:t.lastSelectedTable,lastSelectedDatamodelId:t.lastSelectedDatamodelId,datamodelId:t.datamodelId},o={type:"component",visualType:"multiple",url:r.url,componentName:r.name,icon:r.icon,pluginChartType:r.chartType,minInputs:r.minInputs,maxInputs:r.maxInputs},a=r.minInputs||1,l=e.map(h=>({slot:h,parsed:W(h.position)})).filter(h=>h.parsed!==null).reduce((h,b)=>{const C=b.parsed.end;return Number.isFinite(C)?Math.max(h,C):h},-1),m=Math.max(a,l+1),c=Ze(e),s=c?J(c):0;let u=!1;const p=[];for(let h=0;h<m;h+=1){const b=Ee(e,h),C=le(b),g=!u&&h===s,w=h,$={...n,id:P.v4(),title:(g?c==null?void 0:c.label:b==null?void 0:b.label)||`Tab ${h+1}`,tabTitle:(g?c==null?void 0:c.label:b==null?void 0:b.label)||`Tab ${h+1}`,description:(g?c==null?void 0:c.description:b==null?void 0:b.description)||"",type:C,sql:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},...g&&{customCardPreferences:{...o,slotIndex:w}},...!g&&{customCardPreferences:{slotIndex:w}}};g&&(u=!0),p.push($)}if(!u&&p.length>0){const h=((v=p[0].customCardPreferences)==null?void 0:v.slotIndex)??0;p[0]={...p[0],type:p[0].type,customCardPreferences:{...o,slotIndex:h}}}const d=p.findIndex(h=>{var b;return!!((b=h.customCardPreferences)!=null&&b.url)});if(d>0){const[h]=p.splice(d,1);p.unshift(h)}return p}function tt({frame:e,configCard:r,isMultiInputVisual:t}){var o;if(!t||!r)return e.cards;const n=(o=r.customCardPreferences)==null?void 0:o.dataInputCardIds;return n?Object.keys(n).sort((a,i)=>Number(a)-Number(i)).map(a=>{var l;const i=(l=n[a])==null?void 0:l.cardId;return e.cards.find(m=>m.id===i)||null}):e.cards}function rt(e,r){return r&&ge(r,e.cards)?r:e.cards.find(t=>ge(t,e.cards))||null}function nt(e,r){var o,a;if(!e)return null;const t=r==null?void 0:r.visualType;if(t)return t;if(r!=null&&r.slots&&r.slots.length>0||((r==null?void 0:r.minInputs)||0)>1||((r==null?void 0:r.maxInputs)||0)>1||((r==null?void 0:r.dataInputs)||[]).length>1)return"multiple";const n=(o=e.customCardPreferences)==null?void 0:o.visualType;return n||((a=e.customCardPreferences)!=null&&a.dataInputCardIds?"multiple":null)}function ir(e){return e.visualType==="multiple"||e.slots&&e.slots.length>0||(e.minInputs||0)>1||(e.maxInputs||0)>1||(e.dataInputs||[]).length>1?"multiple":"single"}function cr(e){return Array.isArray(e)?{records:e}:e}class te extends Error{constructor(t){const n=t.cardId?`card "${t.cardId}"`:t.sheetId?`sheet "${t.sheetId}"`:`dashboard "${t.dashboardId}"`;super(`Unable to resolve ${n} while capturing report presentation. Refresh the authoring page and select the attachment again.`);R(this,"code","temporal_snapshot_target_not_found");R(this,"selection");this.name="TemporalSnapshotSelectionError",this.selection=t}}function lr(e,r){var o;const t=[],n=new Map;for(const a of r){if(a.dashboardId!==e.id)throw new te(a);const i=(e.sheets||[]).filter(m=>!a.sheetId||a.sheetId===m.id);if(a.sheetId&&i.length===0)throw new te(a);let l=!a.cardId;for(const m of i){const c=(((o=m.document)==null?void 0:o.sections)||[]).flatMap(p=>Z.getDocumentSectionCards(p)),s=(m.frames||[]).flatMap(p=>dr(p,a.cardId));s.length>0&&(l=!0);const u=[...s,...(m.cards||[]).filter(p=>!a.cardId||a.cardId===p.id),...c.filter(p=>!a.cardId||a.cardId===p.id)];for(const p of u){l=!0;const d=n.get(a.attachmentIndex)??new Set;d.has(p.id)||(d.add(p.id),n.set(a.attachmentIndex,d),t.push({card:p,...a.attachmentIndex!==void 0?{attachmentIndex:a.attachmentIndex}:{}}))}}if(!l)throw new te(a)}return t}function dr(e,r){var i;const t=r?(i=e.cards)==null?void 0:i.find(l=>l.id===r):we(e);if(!t)return[];const n=rt(e,t),o=(e.cards||[]).filter(l=>{var m;return typeof((m=l.customCardPreferences)==null?void 0:m.slotIndex)=="number"}).length>1,a=n!=null&&(nt(n)==="multiple"||o);return!n||!a?[t]:et(tt({frame:e,configCard:n,isMultiInputVisual:!0})).filter(l=>l!==null)}function sr(e){return lr(e.dashboard,e.selections).flatMap(({card:r,attachmentIndex:t})=>{var s,u,p,d;const n=((s=e.resolveCardConfig)==null?void 0:s.call(e,r))??r.config,o=Ne({card:r,cardConfig:n}),a={dashboardId:e.dashboard.id,cardId:r.id,...t!==void 0?{attachmentIndex:t}:{}},i=o?o.fields.map(v=>({scope:a,target:{kind:"field",fieldId:v.id,role:v.role},format:je(v,{dateStyle:e.valueFormatPreferences.dateStyle,dateTime:{...e.valueFormatPreferences.dateTime}},e.valueFormatPreferences.locale)})):[],l=[],m=X(r,n),c=G(r.python||"");if(r.type==="detailTable"&&m==="config"){const v=(n==null?void 0:n.detailColumns)||[],h=[...((n==null?void 0:n.groupByColumns)||[]).map(g=>({field:g,role:"groupby"})),...((n==null?void 0:n.metricColumns)||[]).map(g=>({field:g,role:"metric"})),...((n==null?void 0:n.pivotByColumns)||[]).map(g=>({field:g,role:"pivotby"})),...v.map(g=>({field:g,role:"detail"}))],b=new Map,C=new Set(h.map(({field:g,role:w})=>se.resolveCanonicalResultRawKey(g,w)));for(const{field:g}of h){const w=g.label;w&&b.set(w,(b.get(w)||0)+1)}for(const g of v){const w=K.normalizeAnalyticsCatalogDataType(g.dataType);if(w!=="date"&&w!=="datetime")continue;const $=se.resolveCanonicalDetailResultRawKey(g),_=g.label,M=se.resolveCanonicalResultOutputKey({label:_,labelCount:_&&b.get(_)||0,rawKey:$,rawKeys:C});if(!M)throw new te(a);l.push({scope:a,target:{kind:"column",columnKey:M},format:B.resolveRawTemporalFormat({format:He(g),preferences:e.valueFormatPreferences,calendar:e.calendar})})}}else if(m==="freeform"&&((u=r.sql)!=null&&u.trim())&&!c.trim())for(const[v,h]of Object.entries(((d=(p=r.preferences)==null?void 0:p.tablePrefs)==null?void 0:d.columnSettingsMap)||{})){if(h.type!=="date")continue;const b=ce(h.dateFormat);b&&l.push({scope:a,target:{kind:"column",columnKey:v},format:B.resolveRawTemporalFormat({format:b,preferences:e.valueFormatPreferences,calendar:e.calendar})})}return[...i,...l]})}const mr=new Set(["table","aggregateTable","pivotTable","detailTable"]),ur=new Set(["bar","horizontalBar","line","area","stackedArea","combo","pie","doughnut","radar","polarArea","bubble","scatter","stackedBar","stackedLine","table","pivotTable","aggregateTable","matrixTable","detailTable","kpi","pyramid","tornado","range","map","funnel","bullet","heatmap","treemap","custom"]);function fr(e){var o,a,i;const r=ur.has(e.type)&&(e.type!=="custom"||!!((o=e.customCardPreferences)!=null&&o.url));let t=!1;try{t=!!_t.readMatrixCardConfig(e)}catch{return{formats:[],defaultFormat:null}}return e.type==="text"||!r||!t&&P.isCardUnconfigured(e)?{formats:[],defaultFormat:null}:{formats:ot({cardType:e.type,allowDownload:(a=e.preferences)==null?void 0:a.allowDownload}),defaultFormat:at({cardType:e.type,allowDownload:(i=e.preferences)==null?void 0:i.allowDownload})}}function ot(e){return e.allowDownload===!1?["pdf"]:["pdf","csv"]}function at(e){return mr.has(e.cardType)&&e.allowDownload!==!1?"csv":"pdf"}function pr(e){const{config:r}=e,t=kt.resolveMatrixDefinition({spec:r.spec,presentation:r.presentation,defaults:r.defaultView,session:e.purpose==="manual"?e.session:void 0});return K.matrixExportRequestSchema.parse({spec:t.spec,presentation:t.presentation,...e.content==="flat"?{mode:"flat",format:"csv"}:{mode:"layout",format:e.format,expansion:e.content==="all"?{kind:"all"}:{kind:"current",rows:t.view.rows,columns:t.view.columns}}})}const it=T.z.object({connection_id:T.z.string().min(1),cardType:T.z.literal("matrixTable"),resultOwner:T.z.literal("config"),sql:T.z.literal("").optional(),python:T.z.literal("").optional(),tableStructure:T.z.never().optional(),cardDataSource:T.z.object({connectionId:T.z.string().min(1),connectionType:T.z.string().min(1),mode:T.z.enum(["database","semanticDomain"]),selectedEntities:T.z.array(T.z.unknown()),semanticDomainId:T.z.string().optional()}).passthrough(),active_filters:T.z.array(T.z.unknown()).default([])}).passthrough(),yr=it.extend({dashboardId:T.z.string().min(1),cardId:T.z.string().min(1),formatOptions:T.z.object({matrix:K.matrixExportRequestSchema,acquisition:T.z.literal("continuation").optional(),presentationExecutionSnapshot:T.z.unknown()}).passthrough().superRefine((e,r)=>{e.matrix.format==="csv"!=(e.acquisition==="continuation")&&r.addIssue({code:T.z.ZodIssueCode.custom,path:["acquisition"],message:"CSV requires continuation acquisition; PDF must not specify acquisition."})})});function hr(e){return{...e.controls,type:"card",dashboardId:e.dashboardId,cardId:e.cardId,title:e.title,cardType:"matrixTable",resultOwner:"config",sql:"",python:"",connection_id:e.dataSource.connectionId,cardDataSource:{...e.dataSource,mode:e.matrix.spec.source.kind==="semantic"?"semanticDomain":"database",semanticDomainId:e.matrix.spec.source.kind==="semantic"?e.matrix.spec.source.domainId:void 0},active_filters:e.activeFilters,formatOptions:{...e.matrix.format==="csv"?{acquisition:"continuation"}:{},matrix:e.matrix,delimiter:e.delimiter,includeHeaders:e.includeHeaders,timezone:e.reportContext.calendar.tz,presentationExecutionSnapshot:A.createPresentationExecutionSnapshot({reportContext:e.reportContext,resolvedFormats:[]})}}}const ue=T.z.number().int().nonnegative(),gr=T.z.discriminatedUnion("status",[T.z.object({status:T.z.literal("ok"),request:K.matrixExportRequestSchema,layout:Re.matrixExportLayoutSchema,rows:T.z.array(Re.matrixExportRowSchema).readonly(),usage:T.z.object({rows:ue,cells:ue,bytes:ue}).strict()}).strict(),T.z.object({status:T.z.literal("failed"),failure:T.z.object({code:T.z.enum(["invalid_request","unsupported_capability","stale_cursor","forbidden","budget_exceeded","source_truncated","execution_failed","cancelled"]),limit:T.z.enum(["rows","bytes"]).optional(),message:T.z.string().min(1),retryable:T.z.boolean()}).strict()}).strict()]);function vr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e,r,t){return vr(e)?e:(t.push({field:r,message:"Expected an object."}),{})}function z(e,r,t,n){const o=new Set(t);Object.keys(e).forEach(a=>{o.has(a)||n.push({field:`${r}.${a}`,message:"Unexpected property."})})}function U(e,r,t,n,o={}){if(e==null)return;if(typeof e!="string"){n.push({field:r,message:"Expected a string."});return}const a=o.trim===!1?e:e.trim();if(!o.allowEmpty&&a.length===0){n.push({field:r,message:"Expected a non-empty string."});return}if(a.length>t){n.push({field:r,message:`Expected ${t} characters or fewer.`});return}return a}function xe(e,r,t){const n=U(e,r,2e3,t);if(n)try{return new URL(n),n}catch{t.push({field:r,message:"Expected an absolute URL."});return}}function Pe(e,r,t){const n=O(e,r,t);z(n,r,["tokens","components"],t);const o={};if(n.tokens!==void 0){const a=O(n.tokens,`${r}.tokens`,t);z(a,`${r}.tokens`,["color","typography"],t);const i={};if(a.color!==void 0){const l=O(a.color,`${r}.tokens.color`,t),m=["background","foreground","muted","mutedForeground","border","primary","primaryForeground","positive","negative","warning","info"];z(l,`${r}.tokens.color`,m,t);const c={};m.forEach(s=>{const u=U(l[s],`${r}.tokens.color.${s}`,120,t);u!==void 0&&(c[s]=u)}),i.color=c}if(a.typography!==void 0){const l=O(a.typography,`${r}.tokens.typography`,t);z(l,`${r}.tokens.typography`,["fontFamily","monoFontFamily"],t);const m=U(l.fontFamily,`${r}.tokens.typography.fontFamily`,500,t,{allowEmpty:!0}),c=U(l.monoFontFamily,`${r}.tokens.typography.monoFontFamily`,500,t,{allowEmpty:!0});i.typography={...m!==void 0?{fontFamily:m}:{},...c!==void 0?{monoFontFamily:c}:{}}}o.tokens=i}if(n.components!==void 0){const a=O(n.components,`${r}.components`,t);if(z(a,`${r}.components`,["chart"],t),a.chart!==void 0){const i=O(a.chart,`${r}.components.chart`,t);z(i,`${r}.components.chart`,["palette"],t);let l;i.palette!==void 0&&(Array.isArray(i.palette)?i.palette.length>20?t.push({field:`${r}.components.chart.palette`,message:"Expected 20 colors or fewer."}):l=i.palette.map((m,c)=>U(m,`${r}.components.chart.palette.${c}`,120,t)).filter(m=>m!==void 0):t.push({field:`${r}.components.chart.palette`,message:"Expected an array."})),o.components={chart:l?{palette:l}:{}}}}return o}function br(e,r){const t="presentation.appearance",n=O(e,t,r);z(n,t,["version","schemes"],r);const o={};if(n.version!==void 0&&(typeof n.version!="number"||!Number.isFinite(n.version)?r.push({field:`${t}.version`,message:"Expected a number."}):o.version=n.version),n.schemes!==void 0){const a=O(n.schemes,`${t}.schemes`,r);z(a,`${t}.schemes`,["light","dark"],r),o.schemes={...a.light!==void 0?{light:Pe(a.light,`${t}.schemes.light`,r)}:{},...a.dark!==void 0?{dark:Pe(a.dark,`${t}.schemes.dark`,r)}:{}}}return o}function Ir(e,r){const t="presentation.brandOverrides",n=O(e,t,r);z(n,t,["brandName","logoUrl","link"],r);const o=U(n.brandName,`${t}.brandName`,200,r),a=xe(n.logoUrl,`${t}.logoUrl`,r),i=U(n.link,`${t}.link`,120,r);return{...o!==void 0?{brandName:o}:{},...a!==void 0?{logoUrl:a}:{},...i!==void 0?{link:i}:{}}}function Cr(e,r){const t="presentation.fragments",n=O(e,t,r),o=["preHeaderText","headerBannerHtml","signatureHtml","footerHtml","disclaimerHtml","unsubscribeUrl"];z(n,t,o,r);const a={};return o.forEach(i=>{const l=i==="unsubscribeUrl"?xe(n[i],`${t}.${i}`,r):U(n[i],`${t}.${i}`,i==="preHeaderText"?200:5e3,r,{trim:i==="preHeaderText"});l!==void 0&&(a[i]=l)}),a}function Tr(e){const r=[],t={};if(e.appearance!==void 0&&(t.appearance=br(e.appearance,r)),e.brandOverrides!==void 0&&(t.brandOverrides=Ir(e.brandOverrides,r)),e.fragments!==void 0&&(t.fragments=Cr(e.fragments,r)),e.viewUrl!==void 0){const n=xe(e.viewUrl,"presentation.viewUrl",r);n!==void 0&&(t.viewUrl=n)}return{value:t,issues:r}}const ct=["SUN","MON","TUE","WED","THU","FRI","SAT"],wr=new Map(ct.map((e,r)=>[e,r])),Er={cadence:"weekly",hour:9,minute:0,weekdays:[1]};function xr(e){if(typeof e!="string"||e.length===0||e!==e.trim()||/^(?:(?:UTC|GMT)[+-]|[+-]\d{2}:\d{2}$)/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}function Sr(e){return Number.isInteger(e.minute)&&e.minute>=0&&e.minute<=59&&Number.isInteger(e.hour)&&e.hour>=0&&e.hour<=23}function lt(e){if(e.length===0)return null;const r=[...e].sort((t,n)=>t-n);return r.some((t,n)=>!Number.isInteger(t)||t<0||t>6||n>0&&t===r[n-1])?null:r}function $r(e){if(!Sr(e))throw new Error("Choose a valid schedule time.");const r=`${e.minute} ${e.hour}`;switch(e.cadence){case"daily":return`${r} * * *`;case"weekly":{const t=lt(e.weekdays);if(!t)throw new Error("Choose at least one weekday.");return`${r} * * ${t.map(n=>ct[n]).join(",")}`}case"twice_monthly":return`${r} 1,15 * *`;case"monthly":return`${r} 1 * *`}}function dt(e){if(typeof e!="string"||e.length===0)return{ok:!1,issue:"Choose a supported schedule."};if(e!==e.trim()||e.includes(" "))return{ok:!1,issue:"Choose a supported schedule."};const r=e.split(" ");if(r.length!==5)return{ok:!1,issue:"Choose a supported schedule."};const[t,n,o,a,i]=r;if(!/^(0|[1-9]\d?)$/.test(t)||!/^(0|[1-9]\d?)$/.test(n))return{ok:!1,issue:"Choose a supported schedule."};const l=Number(t),m=Number(n);if(l>59||m>23||a!=="*")return{ok:!1,issue:"Choose a supported schedule."};if(o==="*"&&i==="*")return{ok:!0,value:{cadence:"daily",hour:m,minute:l,weekdays:[]}};if(o==="*"&&i!=="*"){const s=i.split(",").map(d=>wr.get(d));if(s.some(d=>d===void 0))return{ok:!1,issue:"Choose a supported schedule."};const u=s,p=lt(u);return!p||p.some((d,v)=>d!==u[v])?{ok:!1,issue:"Choose a supported schedule."}:{ok:!0,value:{cadence:"weekly",hour:m,minute:l,weekdays:p}}}return o==="1,15"&&i==="*"?{ok:!0,value:{cadence:"twice_monthly",hour:m,minute:l,weekdays:[]}}:o==="1"&&i==="*"?{ok:!0,value:{cadence:"monthly",hour:m,minute:l,weekdays:[]}}:{ok:!1,issue:"Choose a supported schedule."}}function kr(e,r,t){return new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(2020,0,1,e,r)))}function _r(e,r){var t;if(e==="UTC")return"UTC";try{return((t=new Intl.DateTimeFormat(r,{timeZone:e,timeZoneName:"longGeneric"}).formatToParts(new Date(Date.UTC(2020,0,1))).find(o=>o.type==="timeZoneName"))==null?void 0:t.value)??e}catch{return null}}function Rr(e,r,t="en-US"){const n=dt(e);if(!n.ok)return null;try{const o=kr(n.value.hour,n.value.minute,t),a=_r(r,t);if(!a)return null;switch(n.value.cadence){case"daily":return`Daily at ${o} ${a}`;case"weekly":{const i=new Intl.DateTimeFormat(t,{weekday:"long",timeZone:"UTC"});return`${n.value.weekdays.map(m=>i.format(new Date(Date.UTC(2023,0,1+m)))).join(" and ")} at ${o} ${a}`}case"twice_monthly":return`On the 1st and 15th at ${o} ${a}`;case"monthly":return`Monthly on the 1st at ${o} ${a}`}}catch{return null}}function Fr(e){return e!=null&&e.role?e.type==="tenant"?e.role==="POWER_USER":["AUTHOR","ADMIN","SUPER_ADMIN"].includes(e.role):!1}function Ar(e){return e.canCreate?[...e.scheduledReportAvailable?["scheduled_report"]:[],...e.analyticalBriefingsEnabled?["analytical_briefing"]:[]]:[]}function st(e){const r=(e==null?void 0:e.channels)??[];return r.length===1&&r[0]==="EMAIL"}function mt(e){return e.body.type==="generated_analysis"?"Analytical briefing":e.body.type==="custom_message"&&e.attachments.length>0&&st(e.deliveryConfig)?e.scheduleExpr?"Scheduled report":"On-demand report":"Plain briefing"}function Br(e){const r=mt(e),t=r==="Scheduled report"||r==="On-demand report"?"report":"briefing";return{typeLabel:r,noun:t,pluralNoun:t==="report"?"reports":"briefings"}}const ae="BRIEFING",ut=["markdown","html"],ie=["markdown"],re=20,y={name:500,description:2e3,instruction:5e4,customMessage:5e4,contentTitle:500,contentSummary:2e4,contentText:5e3,contentSql:5e4,contentItem:2e3,contentCell:500,attachmentTitle:500,presentationAudience:1e3,presentationTone:500,presentationFormat:2e3,id:500},F={maxBlocks:50,maxTableRows:100,maxTableColumns:20,maxTableCellCharacters:y.contentCell,maxParagraphCharacters:y.contentText,maxFindingCharacters:y.contentText,maxListItems:100,maxKpiTiles:8};function ft(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=e;if(typeof r.value!="number"||!Number.isFinite(r.value))return!1;const t=r.target;if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=t;return(n.kind==="metric"&&typeof n.metricId=="string"&&!!n.metricId.trim()||n.kind==="column"&&typeof n.columnKey=="string"&&!!n.columnKey.trim()||n.kind==="matrix_measure"&&typeof n.measureId=="string"&&!!n.measureId.trim())&&ve.parseResolvedNumericCanonicalFormat(r.format).ok}function pt(e){return e==null?"":ft(e)?ve.formatNumericCanonical(e.value,e.format):String(e)}function Dr(e){return[e.delta,e.percentChange].filter(r=>r!=null).map(pt).filter(Boolean).join(" / ")}const yt=new Set(ut),Pr=new Set(["EMAIL","WEBHOOK","SLACK","IN_APP","TELEGRAM"]),fe={maxToolCalls:{min:1,max:100},maxPlanningIterations:{min:1,max:10},maxRows:{min:1,max:1e5},timeoutMs:{min:1e3,max:30*6e4}},Mr=new Set(["letter","legal","a4","a3","tabloid"]),Or=new Set(["portrait","landscape"]),zr=new Set([",",";"," "]),Kr=new Set(["current","all"]),Nr=new Set(["concise","balanced","detailed"]),qr=new Set(["info","positive","warning","critical"]),Lr=new Set(["text","number","currency","percent","date","boolean"]),Vr=new Set(["left","center","right"]),Ur=["matrix","pageSize","orientation","includeFilters","includeTimestamp","delimiter","includeHeaders","useFormattedValues","sheetSelection","currentSheetId","currentSheetName","filterValues","inlineFilterValues","sheetFilterValues","filterLine","controlValues","controlDefinitions","cardControlDefinitions","controlBindings","tablePreferences","dashboardInputExecutionSnapshot","selectedSheetId","cardType","allowDownload","theme"];class ee extends Error{constructor(t){super(t.map(n=>`${n.field}: ${n.message}`).join("; "));R(this,"issues");this.name="BriefingContractError",this.issues=t}}function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function f(e,r,t){e.push({field:r,message:t})}function S(e,r,t){return ht(e)?e:(f(t,r,"Expected an object."),{})}function I(e,r,t,n){const o=new Set(t);Object.keys(e).forEach(a=>{o.has(a)||f(n,r?`${r}.${a}`:a,`Unexpected field "${a}".`)})}function E(e,r,t,n){if(typeof e!="string")return f(n,r,"Expected a string."),"";const o=e.trim();return o?(o.length>t&&f(n,r,`Must be ${t} characters or fewer.`),o):(f(n,r,"Required value cannot be empty."),"")}function x(e,r,t,n){if(e==null)return;if(typeof e!="string"){f(n,r,"Expected a string.");return}const o=e.trim();if(o)return o.length>t&&f(n,r,`Must be ${t} characters or fewer.`),o}function jr(e,r,t,n){if(typeof e!="string")return f(n,r,"Expected a string."),"";const o=e.trim();return o.length>t&&f(n,r,`Must be ${t} characters or fewer.`),o}function Gr(e,r,t){if(e!=null){if(!Number.isInteger(e)||Number(e)<0){f(t,r,"Expected a non-negative integer.");return}return Number(e)}}function D(e,r,t,n={}){if(e==null)return n.required?(f(t,r,"Expected at least one evidence id."),[]):void 0;if(!Array.isArray(e))return f(t,r,"Expected an array."),n.required?[]:void 0;const o=[];return e.forEach((a,i)=>{const l=E(a,`${r}.${i}`,y.id,t);l&&!o.includes(l)&&o.push(l)}),n.required&&o.length===0&&f(t,r,"Expected at least one evidence id."),o.length>0||n.required?o:void 0}function j(e,r,t,n){return e==null?r:typeof e!="boolean"?(f(n,t,"Expected a boolean."),r):e}function Hr(e,r){return e==null?"ACTIVE":e==="ACTIVE"||e==="PAUSED"||e==="DISABLED"?e:(f(r,"status","Expected ACTIVE, PAUSED, or DISABLED."),"ACTIVE")}function Qr(e){return e.includes("@")&&e.includes(".")&&!e.includes(" ")}function gt(e,r){if(e==null)return{type:"project"};const t=S(e,"source",r),n=t.type;return n==="project"?(I(t,"source",["type"],r),{type:"project"}):n==="dashboard"?(I(t,"source",["type","dashboardId"],r),{type:"dashboard",dashboardId:E(t.dashboardId,"source.dashboardId",y.id,r)}):(f(r,"source.type","Expected project or dashboard."),{type:"project"})}function vt(e,r){const t=S(e,"body",r),n=t.type;return n==="generated_analysis"?(I(t,"body",["type","instruction"],r),{type:"generated_analysis",instruction:E(t.instruction,"body.instruction",y.instruction,r)}):n==="custom_message"?(I(t,"body",["type","message"],r),{type:"custom_message",message:jr(t.message,"body.message",y.customMessage,r)}):n==="none"?(I(t,"body",["type"],r),{type:"none"}):(f(r,"body.type","Expected generated_analysis, custom_message, or none."),{type:"none"})}function Wr(e,r){if(e==null)return[...ie];if(!Array.isArray(e))return f(r,"presentation.artifactFormats","Expected an array."),[...ie];if(e.length===0)return f(r,"presentation.artifactFormats","Choose at least one artifact format."),[];const t=[];return e.forEach((n,o)=>{if(typeof n!="string"||!yt.has(n)){f(r,`presentation.artifactFormats.${o}`,"Expected markdown or html.");return}t.includes(n)||t.push(n)}),t}function bt(e,r){if(e==null)return{artifactFormats:[...ie],includeEvidence:!0,includeSql:!0};const t=S(e,"presentation",r);I(t,"presentation",["artifactFormats","includeEvidence","includeSql","audience","tone","format","appearance","brandOverrides","fragments","viewUrl"],r);const n={artifactFormats:Wr(t.artifactFormats,r),includeEvidence:j(t.includeEvidence,!0,"presentation.includeEvidence",r),includeSql:j(t.includeSql,!0,"presentation.includeSql",r)},o=x(t.audience,"presentation.audience",y.presentationAudience,r),a=x(t.tone,"presentation.tone",y.presentationTone,r),i=x(t.format,"presentation.format",y.presentationFormat,r);o&&(n.audience=o),a&&(n.tone=a),i&&(n.format=i);const l=Tr(t);return l.issues.forEach(m=>f(r,m.field,m.message)),Object.assign(n,l.value),n}function Yr(e,r,t){return Array.isArray(e)?(e.length===0&&f(t,r,"Expected at least one item."),e.length>F.maxListItems&&f(t,r,`Must have ${F.maxListItems} items or fewer.`),e.slice(0,F.maxListItems).map((n,o)=>E(n,`${r}.${o}`,y.contentItem,t)).filter(Boolean)):(f(t,r,"Expected an array."),[])}function Jr(e,r,t){const n=S(e,r,t);if(n.kind==="metric")return I(n,r,["kind","metricId"],t),{kind:"metric",metricId:E(n.metricId,`${r}.metricId`,y.id,t)};if(n.kind==="column")return I(n,r,["kind","columnKey"],t),{kind:"column",columnKey:E(n.columnKey,`${r}.columnKey`,y.id,t)};if(n.kind==="matrix_measure")return I(n,r,["kind","measureId"],t),{kind:"matrix_measure",measureId:E(n.measureId,`${r}.measureId`,y.id,t)};f(t,`${r}.kind`,"Expected metric, column, or matrix_measure.")}function It(e,r,t){if(e===null||typeof e!="object"||Array.isArray(e))return;const n=S(e,r,t);if(!Object.prototype.hasOwnProperty.call(n,"target")&&!Object.prototype.hasOwnProperty.call(n,"format"))return;I(n,r,["value","target","format"],t),(typeof n.value!="number"||!Number.isFinite(n.value))&&f(t,`${r}.value`,"Expected a finite number.");const o=Jr(n.target,`${r}.target`,t),a=ve.parseResolvedNumericCanonicalFormat(n.format);if(a.ok||a.issues.forEach(i=>f(t,i.path==="$"?`${r}.format`:`${r}.format.${i.path}`,i.message)),!(typeof n.value!="number"||!Number.isFinite(n.value)||!o||!a.ok))return{value:n.value,target:o,format:a.value}}function L(e,r,t){if(typeof e=="string")return e;if(typeof e=="number"){if(!Number.isFinite(e)){f(t,r,"Expected a finite number.");return}return e}const n=It(e,r,t);if(n)return n;f(t,r,"Expected a string, number, or structured numeric value.")}function Zr(e,r,t){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return typeof e=="string"&&e.length>y.contentCell?(f(t,r,`Must be ${y.contentCell} characters or fewer.`),e.slice(0,y.contentCell)):typeof e=="number"&&!Number.isFinite(e)?(f(t,r,"Expected a finite number."),null):e;const n=It(e,r,t);return n||(f(t,r,"Expected a string, number, boolean, structured numeric value, or null."),null)}function Xr(e,r,t){if(!Array.isArray(e))return f(t,r,"Expected an array."),[];e.length===0&&f(t,r,"Expected at least one column."),e.length>F.maxTableColumns&&f(t,r,`Must have ${F.maxTableColumns} columns or fewer.`);const n=new Set;return e.slice(0,F.maxTableColumns).map((o,a)=>{const i=`${r}.${a}`,l=S(o,i,t);I(l,i,["key","label","kind","align"],t);const m=E(l.key,`${i}.key`,y.id,t);m&&(n.has(m)&&f(t,`${i}.key`,"Column key must be unique."),n.add(m));const c=E(l.label,`${i}.label`,y.contentTitle,t),s=q(l.kind,`${i}.kind`,Lr,"text, number, currency, percent, date, or boolean",t),u=q(l.align,`${i}.align`,Vr,"left, center, or right",t);return{key:m,label:c,...s?{kind:s}:{},...u?{align:u}:{}}})}function en(e,r,t,n){if(!Array.isArray(e))return f(n,r,"Expected an array."),[];e.length>F.maxTableRows&&f(n,r,`Must have ${F.maxTableRows} rows or fewer.`);const o=new Set(t.map(a=>a.key).filter(Boolean));return e.slice(0,F.maxTableRows).map((a,i)=>{const l=`${r}.${i}`,m=S(a,l,n);return Object.keys(m).forEach(c=>{o.has(c)||f(n,`${l}.${c}`,`Unexpected table cell "${c}".`)}),Object.fromEntries(t.map(c=>[c.key,Zr(m[c.key]??null,`${l}.${c.key}`,n)]))})}function tn(e,r,t){const n=`content.blocks.${r}`,o=S(e,n,t),a=o.type;if(a==="heading"){I(o,n,["type","text","level","evidenceIds"],t);const i=o.level===void 0||o.level===null?void 0:o.level===2||o.level===3?o.level:void 0;o.level!==void 0&&o.level!==null&&i===void 0&&f(t,`${n}.level`,"Expected 2 or 3.");const l=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"heading",text:E(o.text,`${n}.text`,y.contentTitle,t),...i?{level:i}:{},...l?{evidenceIds:l}:{}}}if(a==="paragraph"){I(o,n,["type","text","evidenceIds"],t);const i=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"paragraph",text:E(o.text,`${n}.text`,y.contentText,t),...i?{evidenceIds:i}:{}}}if(a==="finding"){I(o,n,["type","title","text","severity","evidenceIds"],t);const i=x(o.title,`${n}.title`,y.contentTitle,t),l=q(o.severity,`${n}.severity`,qr,"info, positive, warning, or critical",t);return{type:"finding",...i?{title:i}:{},text:E(o.text,`${n}.text`,y.contentText,t),...l?{severity:l}:{},evidenceIds:D(o.evidenceIds,`${n}.evidenceIds`,t,{required:!0})??[]}}if(a==="bullets"||a==="actions"||a==="limitations"){I(o,n,["type","title","items","evidenceIds"],t);const i=x(o.title,`${n}.title`,y.contentTitle,t),l=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:a,...i?{title:i}:{},items:Yr(o.items,`${n}.items`,t),...l?{evidenceIds:l}:{}}}if(a==="metric"){I(o,n,["type","label","value","previousValue","delta","percentChange","unit","evidenceIds"],t);const i=L(o.value,`${n}.value`,t)??"";i===""&&f(t,`${n}.value`,"Expected a non-empty string, number, or structured numeric value.");const l=o.previousValue===void 0||o.previousValue===null?o.previousValue:L(o.previousValue,`${n}.previousValue`,t),m=o.delta===void 0||o.delta===null?o.delta:L(o.delta,`${n}.delta`,t),c=o.percentChange===void 0||o.percentChange===null?o.percentChange:L(o.percentChange,`${n}.percentChange`,t),s=x(o.unit,`${n}.unit`,y.contentTitle,t),u=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"metric",label:E(o.label,`${n}.label`,y.contentTitle,t),value:i,...l!==void 0?{previousValue:l}:{},...m!==void 0?{delta:m}:{},...c!==void 0?{percentChange:c}:{},...s?{unit:s}:{},...u?{evidenceIds:u}:{}}}if(a==="kpi_grid"){I(o,n,["type","title","tiles","evidenceIds"],t);const i=x(o.title,`${n}.title`,y.contentTitle,t),l=Array.isArray(o.tiles)?o.tiles:[];Array.isArray(o.tiles)||f(t,`${n}.tiles`,"Expected an array."),l.length===0&&f(t,`${n}.tiles`,"Expected at least one tile."),l.length>F.maxKpiTiles&&f(t,`${n}.tiles`,`Must have ${F.maxKpiTiles} tiles or fewer.`);const m=l.slice(0,F.maxKpiTiles).map((s,u)=>{const p=`${n}.tiles.${u}`,d=S(s,p,t);I(d,p,["label","value","previousValue","delta","percentChange","unit","evidenceIds"],t);const v=L(d.value,`${p}.value`,t)??"";v===""&&f(t,`${p}.value`,"Expected a non-empty string, number, or structured numeric value.");const h=d.previousValue===void 0||d.previousValue===null?d.previousValue:L(d.previousValue,`${p}.previousValue`,t),b=d.delta===void 0||d.delta===null?d.delta:L(d.delta,`${p}.delta`,t),C=d.percentChange===void 0||d.percentChange===null?d.percentChange:L(d.percentChange,`${p}.percentChange`,t),g=x(d.unit,`${p}.unit`,y.contentTitle,t),w=D(d.evidenceIds,`${p}.evidenceIds`,t);return{label:E(d.label,`${p}.label`,y.contentTitle,t),value:v,...h!==void 0?{previousValue:h}:{},...b!==void 0?{delta:b}:{},...C!==void 0?{percentChange:C}:{},...g?{unit:g}:{},...w?{evidenceIds:w}:{}}}),c=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"kpi_grid",...i?{title:i}:{},tiles:m,...c?{evidenceIds:c}:{}}}if(a==="progress"){I(o,n,["type","label","value","detail","evidenceIds"],t);const i=typeof o.value=="number"&&Number.isFinite(o.value)?o.value:0;(typeof o.value!="number"||!Number.isFinite(o.value))&&f(t,`${n}.value`,"Expected a finite number.");const l=x(o.detail,`${n}.detail`,y.contentText,t),m=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"progress",label:E(o.label,`${n}.label`,y.contentTitle,t),value:i,...l?{detail:l}:{},...m?{evidenceIds:m}:{}}}if(a==="table"){I(o,n,["type","id","title","columns","rows","caption","totalRows","evidenceIds"],t);const i=Xr(o.columns,`${n}.columns`,t),l=x(o.title,`${n}.title`,y.contentTitle,t),m=x(o.id,`${n}.id`,y.id,t),c=x(o.caption,`${n}.caption`,y.contentItem,t),s=Gr(o.totalRows,`${n}.totalRows`,t),u=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"table",...m?{id:m}:{},...l?{title:l}:{},columns:i,rows:en(o.rows,`${n}.rows`,i,t),...c?{caption:c}:{},...s!==void 0?{totalRows:s}:{},...u?{evidenceIds:u}:{}}}if(a==="evidence_appendix"){I(o,n,["type","title","evidenceIds"],t);const i=x(o.title,`${n}.title`,y.contentTitle,t);return{type:"evidence_appendix",...i?{title:i}:{},evidenceIds:D(o.evidenceIds,`${n}.evidenceIds`,t,{required:!0})??[]}}if(a==="sql"){I(o,n,["type","title","sql","evidenceIds"],t);const i=x(o.title,`${n}.title`,y.contentTitle,t),l=E(o.sql,`${n}.sql`,y.contentSql,t),m=D(o.evidenceIds,`${n}.evidenceIds`,t);return{type:"sql",...i?{title:i}:{},sql:l,...m?{evidenceIds:m}:{}}}return f(t,`${n}.type`,"Expected heading, paragraph, finding, bullets, metric, kpi_grid, progress, table, actions, limitations, sql, or evidence_appendix."),{type:"paragraph",text:""}}function Ct(e){const r=[],t=S(e,"content",r);I(t,"content",["version","title","summary","blocks"],r),t.version!==1&&f(r,"content.version","Expected version 1.");const n=x(t.title,"content.title",y.contentTitle,r),o=x(t.summary,"content.summary",y.contentSummary,r);Array.isArray(t.blocks)||f(r,"content.blocks","Expected an array.");const a=Array.isArray(t.blocks)?t.blocks:[];a.length===0&&f(r,"content.blocks","Expected at least one block."),a.length>F.maxBlocks&&f(r,"content.blocks",`Must have ${F.maxBlocks} blocks or fewer.`);const i=a.slice(0,F.maxBlocks).map((l,m)=>tn(l,m,r));return Se(r),{version:1,...n?{title:n}:{},...o?{summary:o}:{},blocks:i}}function rn(e){try{return{valid:!0,value:Ct(e),issues:[]}}catch(r){if(r instanceof ee)return{valid:!1,issues:r.issues};throw r}}function ne(e,r,t,n){return typeof e=="string"&&t.includes(e)?e:(f(n,r,`Expected ${t.join(" or ")}.`),t[0])}function q(e,r,t,n,o){if(e!=null){if(typeof e=="string"&&t.has(e))return e;f(o,r,`Expected ${n}.`)}}function nn(e,r,t){if(e!=null){if(!Array.isArray(e)){f(t,r,"Expected an array.");return}return e}}function on(e,r,t){if(e!=null){if(!ht(e)){f(t,r,"Expected an object.");return}return e}}function an(e,r,t){if(e==null)return;const n=S(e,r,t);I(n,r,Ur,t);const o={};if(n.matrix!==void 0){const c=S(n.matrix,`${r}.matrix`,t);I(c,`${r}.matrix`,["config","content"],t);const s=K.matrixConfigSchema.safeParse(c.config);s.success||f(t,`${r}.matrix.config`,"Expected a valid Matrix definition.");const u=q(c.content,`${r}.matrix.content`,new Set(["current","all","flat"]),"current, all, or flat",t);u||f(t,`${r}.matrix.content`,"Choose Matrix export content."),s.success&&u&&(o.matrix={config:s.data,content:u})}const a=q(n.pageSize,`${r}.pageSize`,Mr,"letter, legal, a4, a3, or tabloid",t),i=q(n.orientation,`${r}.orientation`,Or,"portrait or landscape",t),l=q(n.delimiter,`${r}.delimiter`,zr,"comma, semicolon, or tab",t),m=q(n.sheetSelection,`${r}.sheetSelection`,Kr,"current or all",t);a&&(o.pageSize=a),i&&(o.orientation=i),l&&(o.delimiter=l),m&&(o.sheetSelection=m);for(const c of["includeFilters","includeTimestamp","includeHeaders","useFormattedValues","allowDownload"])if(!(n[c]===void 0||n[c]===null)){if(typeof n[c]!="boolean"){f(t,`${r}.${c}`,"Expected a boolean.");continue}o[c]=n[c]}for(const c of["currentSheetId","currentSheetName","filterLine","selectedSheetId","cardType","theme"]){const s=x(n[c],`${r}.${c}`,y.id,t);s&&(o[c]=s)}for(const c of["filterValues","inlineFilterValues","sheetFilterValues","controlDefinitions","cardControlDefinitions","controlBindings"]){const s=nn(n[c],`${r}.${c}`,t);s&&(o[c]=s)}for(const c of["controlValues","tablePreferences","dashboardInputExecutionSnapshot"]){const s=on(n[c],`${r}.${c}`,t);s&&(o[c]=s)}return Object.keys(o).length>0?o:void 0}function pe(e,r,t,n){const o=x(r,t,y.attachmentTitle,n);return o&&(e.title=o),e}function ye(e,r,t,n){const o=an(r,t,n);return o&&(e.settings=o),e}function cn(e,r,t){const n=`attachments.${r}`,o=S(e,n,t),a=o.type;if(a==="dashboard"){I(o,n,["type","dashboardId","format","title","settings"],t);const i=pe({type:"dashboard",dashboardId:E(o.dashboardId,`${n}.dashboardId`,y.id,t),format:ne(o.format,`${n}.format`,["pdf"],t)},o.title,`${n}.title`,t);return ye(i,o.settings,`${n}.settings`,t)}if(a==="dashboard_sheet"||a==="document_sheet"){I(o,n,["type","dashboardId","sheetId","format","title","settings"],t);const i=pe({type:a,dashboardId:E(o.dashboardId,`${n}.dashboardId`,y.id,t),sheetId:E(o.sheetId,`${n}.sheetId`,y.id,t),format:ne(o.format,`${n}.format`,["pdf"],t)},o.title,`${n}.title`,t);return ye(i,o.settings,`${n}.settings`,t)}if(a==="card"){I(o,n,["type","dashboardId","cardId","format","title","settings"],t);const i=pe({type:"card",dashboardId:E(o.dashboardId,`${n}.dashboardId`,y.id,t),cardId:E(o.cardId,`${n}.cardId`,y.id,t),format:ne(o.format,`${n}.format`,["csv","pdf"],t)},o.title,`${n}.title`,t);return ye(i,o.settings,`${n}.settings`,t)}return f(t,`${n}.type`,"Expected dashboard, dashboard_sheet, document_sheet, or card."),{type:"dashboard",dashboardId:"",format:"pdf"}}function ln(e){switch(e.type){case"dashboard":return`${e.type}:${e.dashboardId}:${e.format}`;case"dashboard_sheet":case"document_sheet":return`${e.type}:${e.dashboardId}:${e.sheetId}:${e.format}`;case"card":return`${e.type}:${e.dashboardId}:${e.cardId}:${e.format}`}}function Tt(e,r){if(e==null)return[];if(!Array.isArray(e))return f(r,"attachments","Expected an array."),[];e.length>re&&f(r,"attachments",`Choose ${re} attachments or fewer.`);const t=e.slice(0,re).map((o,a)=>cn(o,a,r)),n=new Set;return t.forEach((o,a)=>{var l;(l=o.settings)!=null&&l.matrix&&(o.type!=="card"||o.settings.cardType!=="matrixTable"||o.settings.matrix.content==="flat"&&o.format!=="csv")&&f(r,`attachments.${a}.settings.matrix`,"Matrix settings require a matrixTable card attachment; flat content requires CSV.");const i=ln(o);n.has(i)&&f(r,`attachments.${a}`,"Duplicate attachment."),n.add(i)}),t}function wt(e,r){if(e==null)return;const t=S(e,"limits",r);I(t,"limits",Object.keys(fe),r);const n={};return Object.keys(fe).forEach(o=>{const a=t[o];if(a==null)return;const i=fe[o];if(typeof a!="number"||!Number.isInteger(a)||a<i.min||a>i.max){f(r,`limits.${o}`,`Expected an integer between ${i.min} and ${i.max}.`);return}n[o]=a}),Object.keys(n).length>0?n:void 0}function Se(e){if(e.length>0)throw new ee(e)}function Et(e,r,t){!(e.type==="generated_analysis"||e.type==="custom_message"&&!!e.message.trim())&&r.length===0&&f(t,"body","Add briefing instructions, a custom message, or at least one attachment.")}function dn(e,r,t){e==null||e.forEach((n,o)=>{const a=`${t}.${o}.scope`,i=n.scope.attachmentIndex;if(i===void 0)throw new A.PresentationExecutionSnapshotError(`${a}.attachmentIndex must identify the attachment that owns this presentation entry.`);const l=r[i];if(!l)throw new A.PresentationExecutionSnapshotError(`${a}.attachmentIndex must identify an existing attachment.`);if(n.scope.dashboardId!==l.dashboardId)throw new A.PresentationExecutionSnapshotError(`${a}.dashboardId must match the dashboard selected by the referenced attachment.`);if(l.type==="card"&&n.scope.cardId!==l.cardId)throw new A.PresentationExecutionSnapshotError(`${a}.cardId must match the card selected by the referenced attachment.`)})}function $e(e){const r=[],t=S(e,"jobConfig",r);I(t,"jobConfig",["kind","presentationExecutionSnapshot","source","body","attachments","presentation","limits"],r),t.kind!==ae&&f(r,"kind","Expected BRIEFING.");let n;try{n=A.parsePresentationExecutionSnapshot(t.presentationExecutionSnapshot)}catch(c){if(c instanceof A.PresentationExecutionSnapshotError)throw c;f(r,"jobConfig.presentationExecutionSnapshot",c instanceof Error?c.message:"Invalid presentation snapshot.")}const o=gt(t.source,r),a=vt(t.body,r),i=Tt(t.attachments,r),l=bt(t.presentation,r),m=wt(t.limits,r);return Et(a,i,r),dn(n==null?void 0:n.resolvedFormats,i,"jobConfig.presentationExecutionSnapshot.resolvedFormats"),Se(r),{kind:ae,presentationExecutionSnapshot:n,source:o,body:a,attachments:i,presentation:l,...m?{limits:m}:{}}}function sn(e){return $e({...e,kind:ae})}function ke(e,r,t,n="deliveryConfig.recipients"){const o=`${n}.${r}`,a=S(e,o,t),i=a.type;if(i==="email"){I(a,o,["type","address","name"],t);const l=E(a.address,`${o}.address`,y.id,t),m=x(a.name,`${o}.name`,y.attachmentTitle,t);return l&&!Qr(l)&&f(t,`${o}.address`,"Email address is invalid."),{type:"email",address:l,...m?{name:m}:{}}}return i==="user"?(I(a,o,["type","userId"],t),{type:"user",userId:E(a.userId,`${o}.userId`,y.id,t)}):i==="tenant_user"?(I(a,o,["type","tenantUserId"],t),{type:"tenant_user",tenantUserId:E(a.tenantUserId,`${o}.tenantUserId`,y.id,t)}):i==="group"?(I(a,o,["type","groupId"],t),{type:"group",groupId:E(a.groupId,`${o}.groupId`,y.id,t)}):(f(t,`${o}.type`,"Expected email, user, tenant_user, or group."),{type:"email",address:""})}function mn(e,r){return e==null?[]:Array.isArray(e)?e.map((t,n)=>ke(t,n,r)):(f(r,"deliveryConfig.recipients","Expected an array."),[])}function un(e,r){if(!Array.isArray(e))return f(r,"deliveryConfig.channels","Expected an array."),[];const t=[];return e.forEach((n,o)=>{if(!_e(n)){f(r,`deliveryConfig.channels.${o}`,"Expected EMAIL, WEBHOOK, SLACK, IN_APP, or TELEGRAM.");return}t.includes(n)||t.push(n)}),t}function fn(e,r,t){if(e==null)return;const n=S(e,r,t),o={};return Object.entries(n).forEach(([a,i])=>{if(typeof i!="string"){f(t,`${r}.${a}`,"Expected a string.");return}o[a]=i.trim()}),Object.keys(o).length>0?o:void 0}function pn(e,r,t){if(e==null)return;const n=S(e,r,t);I(n,r,["url","method","headers","secretEncrypted"],t);const o=n.method===void 0||n.method===null?void 0:ne(n.method,`${r}.method`,["POST","PUT"],t),a=fn(n.headers,`${r}.headers`,t),i=x(n.secretEncrypted,`${r}.secretEncrypted`,2e3,t);return{url:E(n.url,`${r}.url`,2e3,t),...o?{method:o}:{},...a?{headers:a}:{},...i?{secretEncrypted:i}:{}}}function yn(e,r,t){const n=S(e,r,t),o=n.type;if(o==="channel"){I(n,r,["type","channelId","channelName","isPrivate"],t);const a=x(n.channelName,`${r}.channelName`,y.attachmentTitle,t),i=n.isPrivate===void 0||n.isPrivate===null?void 0:j(n.isPrivate,!1,`${r}.isPrivate`,t);return{type:"channel",channelId:E(n.channelId,`${r}.channelId`,y.id,t),...a?{channelName:a}:{},...i!==void 0?{isPrivate:i}:{}}}return o==="dm"?(I(n,r,["type","recipient"],t),f(t,`${r}.type`,"Slack DM delivery is not supported in V1."),{type:"dm",recipient:ke(n.recipient,0,t,`${r}.recipient`)}):(f(t,`${r}.type`,"Expected channel."),{type:"channel",channelId:""})}function hn(e,r,t){if(e==null)return;if(!Array.isArray(e)){f(t,r,"Expected an array.");return}const n=e.map((o,a)=>ke(o,a,t,r));return n.length>0?n:void 0}function gn(e,r,t){if(e==null)return;const n=S(e,r,t);I(n,r,["destination","threadMentions","postThreadDetail","includeDashboardLink","includeBriefingLink"],t);const o=hn(n.threadMentions,`${r}.threadMentions`,t),a=j(n.postThreadDetail,!0,`${r}.postThreadDetail`,t),i=j(n.includeDashboardLink,!0,`${r}.includeDashboardLink`,t),l=j(n.includeBriefingLink,!0,`${r}.includeBriefingLink`,t);return{destination:yn(n.destination,`${r}.destination`,t),...o?{threadMentions:o}:{},...n.postThreadDetail!==void 0?{postThreadDetail:a}:{},...n.includeDashboardLink!==void 0?{includeDashboardLink:i}:{},...n.includeBriefingLink!==void 0?{includeBriefingLink:l}:{}}}function vn(e,r,t){const n=S(e,r,t);I(n,r,["subjectOverride","titleOverride","summaryOverride","actionBlockVisible","formatProfile","slackConfig","webhookConfig"],t);const o=q(n.formatProfile,`${r}.formatProfile`,Nr,"concise, balanced, or detailed",t),a=x(n.subjectOverride,`${r}.subjectOverride`,500,t),i=x(n.titleOverride,`${r}.titleOverride`,500,t),l=x(n.summaryOverride,`${r}.summaryOverride`,2e3,t),m=j(n.actionBlockVisible,!0,`${r}.actionBlockVisible`,t),c=pn(n.webhookConfig,`${r}.webhookConfig`,t),s=gn(n.slackConfig,`${r}.slackConfig`,t);return{...o?{formatProfile:o}:{},...a?{subjectOverride:a}:{},...i?{titleOverride:i}:{},...l?{summaryOverride:l}:{},...n.actionBlockVisible!==void 0?{actionBlockVisible:m}:{},...s?{slackConfig:s}:{},...c?{webhookConfig:c}:{}}}function bn(e,r){if(e==null)return;const t=S(e,"deliveryConfig.channelConfigs",r),n={};return Object.entries(t).forEach(([o,a])=>{if(!_e(o)){f(r,`deliveryConfig.channelConfigs.${o}`,"Expected a supported delivery channel.");return}n[o]=vn(a,`deliveryConfig.channelConfigs.${o}`,r)}),Object.keys(n).length>0?n:void 0}function In(e,r){var m,c,s;if(e==null)return null;const t=S(e,"deliveryConfig",r);I(t,"deliveryConfig",["recipients","channels","channelConfigs"],r);const n=bn(t.channelConfigs,r),o=mn(t.recipients,r),a=un(t.channels,r),i=((c=(m=n==null?void 0:n.SLACK)==null?void 0:m.slackConfig)==null?void 0:c.destination.type)==="channel"&&!!n.SLACK.slackConfig.destination.channelId.trim();return a.some(u=>u!=="SLACK")&&o.length===0&&f(r,"deliveryConfig.recipients","Add at least one recipient or remove delivery config."),a.length===0&&f(r,"deliveryConfig.channels","Choose at least one delivery channel or remove delivery config."),a.includes("SLACK")&&!i&&f(r,"deliveryConfig.channelConfigs.SLACK.slackConfig.destination.channelId","Choose a Slack channel destination."),!a.includes("SLACK")&&((s=n==null?void 0:n.SLACK)!=null&&s.slackConfig)&&f(r,"deliveryConfig.channelConfigs.SLACK","Slack config requires SLACK in deliveryConfig.channels."),{recipients:o,channels:a,...n?{channelConfigs:n}:{}}}function de(e){const r=[],t=S(e,"draft",r);I(t,"draft",["name","description","status","scheduleExpr","timezone","source","body","attachments","presentation","limits","deliveryConfig"],r);const n=E(t.name,"name",y.name,r),o=x(t.description,"description",y.description,r)??null,a=x(t.scheduleExpr,"scheduleExpr",500,r)??null,i=x(t.timezone,"timezone",200,r)??"UTC",l=Hr(t.status,r),m=gt(t.source,r),c=vt(t.body,r),s=Tt(t.attachments,r),u=bt(t.presentation,r),p=wt(t.limits,r),d=In(t.deliveryConfig,r);return Et(c,s,r),Se(r),{name:n,description:o,status:l,scheduleExpr:a,timezone:i,source:m,body:c,attachments:s,presentation:u,...p?{limits:p}:{},deliveryConfig:d}}function Cn(e){return de(e)}function Tn(e){return de(e)}function wn(e){try{return{valid:!0,value:de(e),issues:[]}}catch(r){if(r instanceof ee)return{valid:!1,issues:r.issues};throw r}}function En(e){try{return{valid:!0,value:$e(e),issues:[]}}catch(r){if(r instanceof ee)return{valid:!1,issues:r.issues};throw r}}function xn(e){return typeof e=="string"&&yt.has(e)}function _e(e){return typeof e=="string"&&Pr.has(e)}exports.AmbiguousGroupedTemporalGrainError=ze;exports.BRIEFING_ARTIFACT_FORMATS=ut;exports.BRIEFING_CONTENT_LIMITS=F;exports.BRIEFING_KIND=ae;exports.BRIEFING_TEXT_LIMITS=y;exports.BriefingContractError=ee;exports.DEFAULT_BRIEFING_ARTIFACT_FORMATS=ie;exports.DEFAULT_BRIEFING_SCHEDULE=Er;exports.DashboardTemporalBoundaryError=V;exports.MAX_BRIEFING_ATTACHMENTS=re;exports.PYTHON_DEFAULT_CODE=Oe;exports.RawTemporalPresentationBoundaryError=k;exports.buildBriefingJobConfig=sn;exports.buildBriefingScheduleExpr=$r;exports.buildCreateBriefingRequest=Cn;exports.buildDashboardCardTableConfig=Rt;exports.buildDashboardTemporalSnapshotEntries=sr;exports.buildMatrixDeliveryEnvelope=hr;exports.buildSlotOrderedCards=et;exports.buildUpdateBriefingRequest=Tn;exports.canCreateBriefingForUser=Fr;exports.captureMatrixExport=pr;exports.createCardsFromSlots=ar;exports.describeBriefingSchedule=Rr;exports.findCustomVisualConfigCard=rt;exports.formatBriefingComparisonValues=Dr;exports.formatBriefingDisplayValue=pt;exports.formatGroupedTemporalFieldValue=Nt;exports.formatGroupedTemporalRecords=Mt;exports.formatGroupedTemporalValue=Ce;exports.getActiveCardFromVisualResource=Zt;exports.getActiveFrameCard=we;exports.getBriefingCardAttachmentCapability=fr;exports.getBriefingCardAttachmentFormats=ot;exports.getBriefingCreationIntents=Ar;exports.getBriefingDisplayTypeLabel=mt;exports.getBriefingPresentation=Br;exports.getConfigSlotExpectedType=nr;exports.getCustomVisualInputCards=tt;exports.getDefaultBriefingCardAttachmentFormat=at;exports.getDefaultDeclaredSqlRawTemporalPattern=Lt;exports.getEffectiveCardTypeForSlot=or;exports.getSlotDefinitionForIndex=Ee;exports.getSlotExpectedChartType=le;exports.getSlotIndexForCard=Xe;exports.hasMissingDeclaredSqlCustomDateFormat=Qe;exports.inspectDeclaredSqlRawTemporalPreview=jt;exports.isBriefingArtifactFormat=xn;exports.isBriefingDeliveryChannel=_e;exports.isBriefingNumericValue=ft;exports.isCardRawTemporalPresentationActivated=Qt;exports.isCardRawTemporalResultCompatible=Jt;exports.isCustomVisualConfigCard=ge;exports.isDeclaredSqlRawTemporalPresentationCard=Te;exports.isEmailOnlyBriefingDelivery=st;exports.isGroupedTemporalResultCompatible=Ot;exports.isPivotResultContractCompatibleWithCardConfig=Le;exports.isValidBriefingTimezone=xr;exports.matrixDeliveryPayloadSchema=yr;exports.matrixDeliveryQuerySchema=it;exports.matrixLayoutReadResultSchema=gr;exports.normalizeBriefingContentDocument=Ct;exports.normalizeBriefingDraft=de;exports.normalizeBriefingJobConfig=$e;exports.normalizeDashboardCardPythonCode=G;exports.normalizeGroupedTemporalField=Ke;exports.normalizeMultiInputPayload=cr;exports.parseBriefingScheduleExpr=dt;exports.parseCanonicalPivotResultTransportOnce=qe;exports.parseFrameObject=Je;exports.presentRawTemporalCell=Yt;exports.reindexSlotCards=rr;exports.repairMissingDeclaredSqlCustomDateFormat=Gt;exports.resolveCardRawTemporalPresentation=Ye;exports.resolveCartesianTemporalActivation=Bt;exports.resolveDashboardCardResultOwner=X;exports.resolveDashboardTemporalActivation=Ne;exports.resolveDeclaredSqlRawTemporalFormat=ce;exports.resolveDetailTableRawTemporalPresentation=We;exports.resolveGroupedTemporalFieldPresentationByRole=Ue;exports.resolveGroupedTemporalFieldSnapshotFormat=je;exports.resolveGroupedTemporalPresentation=Kt;exports.resolveMultiInputType=nt;exports.resolveMultiInputTypeFromVisual=ir;exports.resolveRegularTableTemporalActivation=At;exports.validateBriefingContentDocument=rn;exports.validateBriefingDraft=wn;exports.validateBriefingJobConfig=En;exports.validateDeclaredSqlRawTemporalPattern=Vt;
@@ -1 +0,0 @@
1
- "use strict";const l=require("./color-CyB5o13F.cjs"),m=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316"],M={version:1,mode:"system",schemes:{light:{tokens:{color:{background:"hsl(0 0% 100%)",foreground:"hsl(240 5.9% 10%)",muted:"hsl(0 0% 98%)",mutedForeground:"hsl(240 3.8% 46.1%)",border:"hsl(240 5.9% 90%)",input:"hsl(240 5.9% 90%)",primary:"hsl(240 5.9% 10%)",primaryForeground:"hsl(0 0% 98%)",accent:"hsl(240 4.8% 95.9%)",accentForeground:"hsl(240 5.9% 10%)",selection:"hsl(217 91% 53%)",card:"hsl(0 0% 100%)",cardForeground:"hsl(240 5.9% 10%)",positive:"#16a34a",negative:"#dc2626",warning:"#d97706",info:"#0284c7",destructive:"hsl(0 72.2% 50.6%)",destructiveForeground:"hsl(0 0% 98%)"},typography:{fontFamily:l.SEMAPHOR_DEFAULT_FONT_FAMILY,headingFontFamily:l.SEMAPHOR_HEADING_FONT_FAMILY,monoFontFamily:l.SEMAPHOR_MONO_FONT_FAMILY,baseFontSize:14,density:"comfortable"},radius:{control:5,card:5,table:5,badge:999},spacing:{dashboardPadding:16,gridGap:12,cardPadding:16,controlGap:8,tableCellX:12,tableCellY:8},shadow:{card:"0 1px 2px rgba(15, 23, 42, 0.08)",popover:"0 12px 32px rgba(15, 23, 42, 0.14)",focusRing:"0 0 0 2px rgba(37, 99, 235, 0.35)"}},components:{chart:{palette:m},table:{density:"compact"}}},dark:{tokens:{color:{background:"hsl(240 10% 3.9%)",foreground:"hsl(0 0% 93%)",muted:"hsl(240 5.9% 10%)",mutedForeground:"hsl(240 5% 64.9%)",border:"hsl(240 3.7% 15.9%)",input:"hsl(240 3.7% 15.9%)",primary:"hsl(0 0% 98%)",primaryForeground:"hsl(240 5.9% 10%)",accent:"hsl(240 3.7% 15.9%)",accentForeground:"hsl(0 0% 93%)",selection:"hsl(217 91% 64%)",card:"hsl(240 10% 3.9%)",cardForeground:"hsl(0 0% 93%)",positive:"#22c55e",negative:"#f87171",warning:"#fbbf24",info:"#38bdf8",destructive:"hsl(0 62.8% 30.6%)",destructiveForeground:"hsl(0 0% 93%)"},typography:{fontFamily:l.SEMAPHOR_DEFAULT_FONT_FAMILY,headingFontFamily:l.SEMAPHOR_HEADING_FONT_FAMILY,monoFontFamily:l.SEMAPHOR_MONO_FONT_FAMILY,baseFontSize:14,density:"comfortable"},radius:{control:5,card:5,table:5,badge:999},spacing:{dashboardPadding:16,gridGap:12,cardPadding:16,controlGap:8,tableCellX:12,tableCellY:8},shadow:{card:"0 1px 2px rgba(0, 0, 0, 0.3)",popover:"0 12px 32px rgba(0, 0, 0, 0.45)",focusRing:"0 0 0 2px rgba(96, 165, 250, 0.35)"}},components:{chart:{palette:m},table:{density:"compact"}}}}},A=v(M);function v(e){if(typeof e!="object"||e===null||Object.isFrozen(e))return e;Object.freeze(e);for(const o of Object.values(e))v(o);return e}const y=1,w=new Set(["light","dark","system"]),x=new Set(["compact","comfortable","spacious"]),L=Object.fromEntries(["background","foreground","muted","mutedForeground","border","input","primary","primaryForeground","accent","accentForeground","selection","card","cardForeground","positive","negative","warning","info","destructive","destructiveForeground"].map(e=>[e,n])),j={fontFamily:d,headingFontFamily:d,monoFontFamily:d,baseFontSize:u,density:O},H={control:c,card:c,table:c,badge:c},I={dashboardPadding:c,gridGap:c,cardPadding:c,controlGap:c,tableCellX:c,tableCellY:c},D={card:d,popover:d,focusRing:d},g={background:n,foreground:n,borderColor:n,borderRadius:c,shadow:d,padding:c},z={...g,toolbarBackground:n},V={palette:K,background:n,foreground:n,gridColor:n,axisColor:n},Y={background:n,borderColor:n,borderRadius:c,shadow:d},f={density:O,container:t(Y),header:t({background:n,foreground:n,dividerColor:n,fontWeight:u,uppercase:b,sticky:b}),row:t({height:u,dividerColor:n,zebra:b,zebraBackground:n,hoverBackground:n,selectedBackground:n}),cell:t({paddingX:c,paddingY:c,verticalAlign:q,wrap:J}),subtotal:t({background:n,foreground:n,fontWeight:u}),grandTotal:t({background:n,foreground:n,fontWeight:u,borderColor:n}),pagination:t({background:n,foreground:n,borderColor:n})},U={color:t(L),typography:t(j),radius:t(H),spacing:t(I),shadow:t(D)},$={dashboard:t(g),card:t(g),interactive:t(z),chart:t(V),table:t(f),pivotTable:t(f),matrixTable:t(f),aggregateTable:t(f),pagination:t(g)},E={tokens:t(U),components:t($)},G={light:t(E),dark:t(E)},B={version:W,mode:X,schemes:t(G)};function P(e){const o=[];return t(B)(e,"$",o),C(e)&&!("version"in e)&&i(o,"$.version","invalid_version","version must be 1"),o.length>0?{success:!1,issues:o}:{success:!0,value:e,issues:[]}}function F(e){const o=P(e);if(o.success)return;const r=o.issues[0];throw new Error(`Invalid AppearanceSpec at ${r.path}: ${r.message}`)}function t(e){return(o,r,a)=>{if(!C(o)){i(a,r,"invalid_type","expected an object");return}for(const s of Object.keys(o)){const S=e[s],_=`${r}.${s}`;if(!S){i(a,_,"unsupported_field","field is not supported in AppearanceSpec V1");continue}S(o[s],_,a)}}}function W(e,o,r){e!==y&&i(r,o,"invalid_version","version must be 1")}function X(e,o,r){(typeof e!="string"||!w.has(e))&&i(r,o,"invalid_value","mode must be light, dark, or system")}function O(e,o,r){(typeof e!="string"||!x.has(e))&&i(r,o,"invalid_value","density must be compact, comfortable, or spacious")}function q(e,o,r){e!=="top"&&e!=="middle"&&e!=="bottom"&&i(r,o,"invalid_value","verticalAlign must be top, middle, or bottom")}function J(e,o,r){e!=="wrap"&&e!=="nowrap"&&i(r,o,"invalid_value","wrap must be wrap or nowrap")}function b(e,o,r){typeof e!="boolean"&&i(r,o,"invalid_type","expected a boolean")}function n(e,o,r){if(typeof e!="string"||e.trim()===""){i(r,o,"invalid_type","color must be a non-empty string");return}l.parseAppearanceColor(e)||i(r,o,"invalid_color","color must be a valid opaque CSS color")}function K(e,o,r){if(!Array.isArray(e)){i(r,o,"invalid_type","expected an array of colors");return}if(e.length===0){i(r,o,"invalid_value","palette must contain at least one color");return}e.forEach((a,s)=>n(a,`${o}[${s}]`,r))}function d(e,o,r){(typeof e!="string"||e.trim()==="")&&i(r,o,"invalid_type","expected a non-empty string")}function u(e,o,r){(typeof e!="number"||!Number.isFinite(e)||e<=0)&&i(r,o,"invalid_value","expected a positive number")}function c(e,o,r){(typeof e!="number"||!Number.isFinite(e)||e<0)&&i(r,o,"invalid_value","expected a non-negative number")}function i(e,o,r,a){e.push({path:o,code:r,message:a})}function C(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function k(e,o=A){return F(e),N(o,e)}function R(e,o){return F(o),N(e,o)}function N(e,o){return T(e,o)}function T(e,o){if(o===void 0)return p(e);if(Array.isArray(e)||Array.isArray(o))return p(o);if(h(e)&&h(o)){const r=p(e);for(const[a,s]of Object.entries(o)){if(a==="version"){r[a]=s;continue}r[a]=a in r?T(r[a],s):p(s)}return r}return p(o)}function p(e){return Array.isArray(e)?e.map(o=>p(o)):h(e)?Object.fromEntries(Object.entries(e).map(([o,r])=>[o,p(r)])):e}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Q(e={}){const o=e.defaults??A;let r=k({version:y},o);for(const a of[e.organizationAppearance,e.tokenAppearance,e.reactAppearance])a&&(r=R(r,a));return r}exports.APPEARANCE_SPEC_VERSION=y;exports.SEMAPHOR_DEFAULT_APPEARANCE_SPEC=A;exports.SEMAPHOR_DEFAULT_CHART_PALETTE=m;exports.assertValidAppearanceSpec=F;exports.mergeAppearanceSpecs=R;exports.normalizeAppearanceSpec=k;exports.resolveAppearance=Q;exports.validateAppearanceSpec=P;