react-semaphor 0.1.605 → 0.1.607

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 (151) hide show
  1. package/dist/analytics-protocol/index.js +1 -1
  2. package/dist/appearance-runtime/index.js +1 -1
  3. package/dist/assistant-context/index.js +1 -1
  4. package/dist/assistant-protocol/index.js +1 -1
  5. package/dist/brand-studio/index.js +2 -2
  6. package/dist/briefings/index.js +1 -1
  7. package/dist/chunks/add-to-dashboard-Bu3M9DpP.js +12 -0
  8. package/dist/chunks/appearance-provider-C4lPZcaN.js +613 -0
  9. package/dist/chunks/appearance-runtime-provider-De2VZS4F.js +1 -0
  10. package/dist/chunks/assistant-chat-B7Fngg8U.js +53 -0
  11. package/dist/chunks/attachment-filter-line-wJRB0GSP.js +1 -0
  12. package/dist/chunks/{bookmark-impact-BAtemeyK.js → bookmark-impact-DjrrJomS.js} +1 -1
  13. package/dist/chunks/bookmark-state-x9hJS83D.js +1 -0
  14. package/dist/chunks/{brand-C9APUFaP.js → brand-DgFcvKJI.js} +1 -1
  15. package/dist/chunks/{card-filter-builder-ClWrXB7P.js → card-filter-builder-CvxygmsE.js} +8 -3
  16. package/dist/chunks/check-input-7DVPUuco.js +1 -0
  17. package/dist/chunks/{comparison-window-caption-tguyN24S.js → comparison-window-caption-zUZDe4tL.js} +1 -1
  18. package/dist/chunks/compiler-XErOfUUx.js +1 -0
  19. package/dist/chunks/context-Cwj8Axgd.js +2 -0
  20. package/dist/chunks/currency-presentation-binding-w9WDUk3b.js +1 -0
  21. package/dist/chunks/custom-visual-inputs-D8U98aBz.js +1 -0
  22. package/dist/chunks/{dashboard-ChIcbVTx.js → dashboard-BEd6i29E.js} +1 -1
  23. package/dist/chunks/{dashboard-briefing-launcher-CwMlhkxV.js → dashboard-briefing-launcher-DMDYM9IA.js} +9 -14
  24. package/dist/chunks/{dashboard-controls-UCSAFCGA.js → dashboard-controls-5B2vCIjJ.js} +8 -8
  25. package/dist/chunks/{dashboard-json-B120hYDa.js → dashboard-json-C6r30x-5.js} +1 -1
  26. package/dist/chunks/dashboard-temporal-snapshot-Wki-YACw.js +1 -0
  27. package/dist/chunks/edit-dashboard-visual-F2w7v4iB.js +83 -0
  28. package/dist/chunks/{filter-line-WwUV5JzN.js → filter-line-COFQaF4_.js} +1 -1
  29. package/dist/chunks/filter-reach-preview-BWRGfSmb.js +1 -0
  30. package/dist/chunks/filter-value-text-BSAMEgve.js +1 -0
  31. package/dist/chunks/kpi-trend-rule-BcnKbY7d.js +1 -0
  32. package/dist/chunks/{layout-grid-CFzqJ7GC.js → layout-grid-DahW4ClC.js} +1 -1
  33. package/dist/chunks/matrix-analytical-definition-Bd-dXB8q.js +1 -0
  34. package/dist/chunks/{matrix-member-presentation-vVAv-aqg.js → matrix-member-presentation-CfvxPV-i.js} +1 -1
  35. package/dist/chunks/matrix-operation-contract-Cw7U53Ao.js +1 -0
  36. package/dist/chunks/metric-formatting-QDqXfQGY.js +1 -0
  37. package/dist/chunks/{numeric-range-options-C8tr-Bls.js → numeric-range-options-s6i_nDXg.js} +1 -1
  38. package/dist/chunks/{palette-NvEIuXHN.js → palette-CYvJHSqP.js} +1 -1
  39. package/dist/chunks/pivot-result-contract-expectations-BX5gLcze.js +1 -0
  40. package/dist/chunks/{pivot-result-identity-B0eWVMXg.js → pivot-result-identity-DOISzHU4.js} +1 -1
  41. package/dist/chunks/{raw-temporal-value-BHQ-ldpW.js → raw-temporal-value-Cssny3RJ.js} +1 -1
  42. package/dist/chunks/report-preferences-dialog-BNpB9byP.js +1 -0
  43. package/dist/chunks/{report-runtime-context-Cd1b5pku.js → report-runtime-context-B8HuY0bu.js} +1 -1
  44. package/dist/chunks/resolve-dashboard-input-context-B-0tONJg.js +8 -0
  45. package/dist/chunks/sandbox-host-Drf58_oU.js +197 -0
  46. package/dist/chunks/saved-dashboard-context-dbdbQ5bB.js +1 -0
  47. package/dist/chunks/{selection-filter-compiler-kYsRugss.js → selection-filter-compiler-DK8KkS9g.js} +1 -1
  48. package/dist/chunks/semaphor-ready-indicator-BSFsqsBJ.js +617 -0
  49. package/dist/chunks/set-oJDaJdtI.js +1 -0
  50. package/dist/chunks/slider-DAvAdfMC.js +599 -0
  51. package/dist/chunks/stored-dashboard-DmgJQcyZ.js +1 -0
  52. package/dist/chunks/table-cell-text-2x6r_oHO.js +1 -0
  53. package/dist/chunks/{table-export-sheet-xaczzWZF.js → table-export-sheet-CWqKiQu4.js} +1 -1
  54. package/dist/chunks/{token-types-1vzMWjI-.js → token-types-BSyWn2pb.js} +1 -1
  55. package/dist/chunks/{validators-Dg2kyF4_.js → validators-BPGmPz8-.js} +1 -1
  56. package/dist/chunks/{variable-draft-B4_xqr4Y.js → variable-draft-DGA22H2g.js} +1 -1
  57. package/dist/chunks/visual-contract-DQPKg5QW.js +143 -0
  58. package/dist/dashboard/index.js +1 -1
  59. package/dist/dashboard-authoring/index.js +1 -1
  60. package/dist/extensions/index.js +1 -0
  61. package/dist/format-utils/index.js +1 -1
  62. package/dist/index.js +1 -1
  63. package/dist/report-runtime-context/index.js +1 -1
  64. package/dist/style.css +1 -1
  65. package/dist/surfboard/index.js +1 -1
  66. package/dist/types/components/assistant/assistant-store.d.ts +19 -0
  67. package/dist/types/components/assistant/use-assistant.d.ts +4 -0
  68. package/dist/types/components/visual/data-table/hooks/use-data-table-logic.d.ts +2 -3
  69. package/dist/types/components/visual/data-table/table-cell-text.d.ts +93 -0
  70. package/dist/types/components/visual/data-table/types/data-table.d.ts +0 -1
  71. package/dist/types/extensions.d.ts +2 -0
  72. package/dist/types/index.js +1 -1
  73. package/dist/types/lib/charts/types.d.ts +3 -1
  74. package/dist/types/lib/dashboard/semantic-dataset-references.d.ts +0 -2
  75. package/dist/types/lib/matrix-table/matrix-card-adapter.d.ts +12 -12
  76. package/dist/types/lib/matrix-table/matrix-delivery.d.ts +25 -25
  77. package/dist/types/lib/stores/dashboard-store.d.ts +33 -2
  78. package/dist/types/lib/stores/editor-store.d.ts +8 -0
  79. package/dist/types/lib/types/common-types.d.ts +3 -0
  80. package/dist/types/lib/utils/card-definition.d.ts +12 -12
  81. package/dist/types/lib/utils/card-type-change.d.ts +9 -0
  82. package/dist/types/shared/analytics-protocol/analytics-base-schemas.d.ts +6 -6
  83. package/dist/types/shared/analytics-protocol/execution-input-schemas.d.ts +10 -10
  84. package/dist/types/shared/analytics-protocol/matrix-definition-contract.d.ts +248 -248
  85. package/dist/types/shared/analytics-protocol/matrix-operation-contract.d.ts +10 -10
  86. package/dist/types/shared/analytics-protocol/matrix-operation-request.d.ts +8 -8
  87. package/dist/types/shared/analytics-protocol/matrix-window-contract.d.ts +2 -2
  88. package/dist/types/shared/assistant-protocol/context.d.ts +26 -26
  89. package/dist/types/shared/assistant-protocol/parts.d.ts +4 -0
  90. package/dist/types/shared/assistant-protocol/request.d.ts +2 -1
  91. package/dist/types/shared/dashboard-authoring/card-data-source/card-base.d.ts +16 -6
  92. package/dist/types/shared/dashboard-authoring/card-settings/custom-visual-write.d.ts +44 -0
  93. package/dist/types/shared/dashboard-authoring/card-settings/index.d.ts +1 -0
  94. package/dist/types/shared/dashboard-authoring/changes/card-query-part.d.ts +1 -0
  95. package/dist/types/shared/dashboard-authoring/changes/card-types.d.ts +2 -2
  96. package/dist/types/shared/dashboard-authoring/changes/custom-visual-change.d.ts +57 -0
  97. package/dist/types/shared/dashboard-authoring/changes/dashboard-change.d.ts +61 -54
  98. package/dist/types/shared/dashboard-authoring/changes/diagnostics.d.ts +5 -1
  99. package/dist/types/shared/dashboard-authoring/changes/read-card-query.d.ts +5 -1
  100. package/dist/types/shared/dashboard-authoring/changes/resolve-dashboard-changes.d.ts +10 -0
  101. package/dist/types/shared/dashboard-authoring/conditional-formatting/schema.d.ts +60 -60
  102. package/dist/types/shared/dashboard-authoring/control-execution-contract.d.ts +4 -4
  103. package/dist/types/shared/dashboard-authoring/matrix-delivery.d.ts +48 -48
  104. package/dist/types/shared/dashboard-authoring/measure-calculations/index.d.ts +1 -1
  105. package/dist/types/shared/dashboard-authoring/measure-calculations/window-transforms.d.ts +2 -0
  106. package/dist/types/shared/dashboard-authoring/operations/operation-sentences.d.ts +8 -2
  107. package/dist/types/shared/dashboard-authoring/operations/operation-types.d.ts +11 -0
  108. package/dist/types/shared/dashboard-authoring/outline/outline-dashboard.d.ts +7 -0
  109. package/dist/types/shared/extensions/check-audits.d.ts +30 -0
  110. package/dist/types/shared/extensions/check-findings.d.ts +46 -0
  111. package/dist/types/shared/extensions/check-input.d.ts +23 -0
  112. package/dist/types/shared/extensions/check-renders.d.ts +44 -0
  113. package/dist/types/shared/extensions/check-runner.d.ts +19 -0
  114. package/dist/types/shared/extensions/index.d.ts +17 -0
  115. package/dist/types/shared/extensions/read-document.d.ts +18 -0
  116. package/dist/types/shared/extensions/sandbox-host.d.ts +63 -0
  117. package/dist/types/shared/extensions/saved-refs.d.ts +33 -0
  118. package/dist/types/shared/extensions/script-policy.d.ts +11 -0
  119. package/dist/types/shared/extensions/types.d.ts +186 -0
  120. package/dist/types/shared/extensions/visual-contract.d.ts +36 -0
  121. package/dist/types/shared/extensions/visual-payload.d.ts +75 -0
  122. package/dist/types/shared/extensions/visual-theme.d.ts +21 -0
  123. package/dist/types/shared/format-utils/formatters/number-formatter.d.ts +13 -6
  124. package/dist/types/shared/format-utils/matrix-continuation.d.ts +2 -2
  125. package/dist/types/shared/format-utils/matrix-export-presentation.d.ts +24 -24
  126. package/dist/types/shared/usage-events/details.d.ts +4 -4
  127. package/dist/types/shared/usage-events/envelope.d.ts +2 -2
  128. package/dist/usage-events/index.js +1 -1
  129. package/package.json +7 -2
  130. package/dist/chunks/add-to-dashboard-CEmZUf9o.js +0 -12
  131. package/dist/chunks/appearance-provider-CfoAVQuG.js +0 -608
  132. package/dist/chunks/appearance-runtime-provider-Bx8H-moR.js +0 -1
  133. package/dist/chunks/assistant-chat-DgUaCE9k.js +0 -51
  134. package/dist/chunks/attachment-filter-line-C_zHMhGh.js +0 -1
  135. package/dist/chunks/bookmark-state-DScd31KT.js +0 -1
  136. package/dist/chunks/context-CntvtZwC.js +0 -2
  137. package/dist/chunks/dashboard-temporal-snapshot-BFJKbp_6.js +0 -1
  138. package/dist/chunks/edit-dashboard-visual-DvHp03h_.js +0 -73
  139. package/dist/chunks/filter-reach-preview-C5M5_hf_.js +0 -1
  140. package/dist/chunks/filter-value-text-DqTHe_vu.js +0 -1
  141. package/dist/chunks/kpi-trend-rule-B87LNzcz.js +0 -1
  142. package/dist/chunks/matrix-analytical-definition-5T-2euHZ.js +0 -1
  143. package/dist/chunks/matrix-operation-contract-CWvcEsQ0.js +0 -1
  144. package/dist/chunks/pivot-result-contract-expectations-BNWhS8mv.js +0 -1
  145. package/dist/chunks/report-preferences-dialog-Bseb2Rlg.js +0 -1
  146. package/dist/chunks/resolve-dashboard-input-context-BDY7KwRe.js +0 -8
  147. package/dist/chunks/saved-dashboard-context-C3lWc4Dx.js +0 -1
  148. package/dist/chunks/semaphor-ready-indicator-BQarSo6S.js +0 -612
  149. package/dist/chunks/set-6mOnfQeH.js +0 -1
  150. package/dist/chunks/slider-BPnHdMGq.js +0 -4
  151. package/dist/chunks/stored-dashboard-DfrxDLhR.js +0 -1
@@ -1 +1 @@
1
- import{M as Pe,z as Z,y as Bt,E as Wt,F as Ut,H as Vt,J as Ht,x as zt,g as it,h as pe,j as Gt,o as Qt,k as Xt,b as Kt}from"./analytics-base-schemas-DMFrDqn_.js";import{z as s}from"zod";function Zt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";}function Jt(e){return!Array.isArray(e)||e.length===0||e.length>Pe||!e.every(Zt)?{ok:!1,error:`matchValues must be 1 to ${Pe} string, number or boolean values.`}:{ok:!0,values:e};}function en(e,t){const n=e.map((i,o)=>`${t[o]} ${nn(i)}`);return s.union(e,{errorMap:(i,o)=>{if(i.code!==s.ZodIssueCode.invalid_union)return{message:o.defaultError};const a=i.path.length,r=o.data&&typeof o.data=="object"&&!Array.isArray(o.data)?Object.keys(o.data):[],l=i.unionErrors.map((p,f)=>{const b=tn(e[f]);return{index:f,issues:p.issues,overlap:b?r.filter(A=>b.includes(A)).length:0};}).filter(({issues:p})=>!p.every(f=>f.code===s.ZodIssueCode.invalid_type&&f.path.length===a)).filter(({overlap:p})=>!r.length||p>0);if(!l.length){const p=r.length?` Its keys (${r.join(", ")}) belong to none of them.`:"";return{message:`Matches none of: ${n.join("; ")}.${p}`};}const c=l.reduce((p,f)=>f.overlap>p.overlap||f.overlap===p.overlap&&f.issues.length<p.issues.length?f:p),m=c.issues.slice(0,4).map(p=>{const f=p.path.slice(a).join(".");return f?`${p.message} at ${f}`:p.message;}),u=c.issues.length>4?` (and ${c.issues.length-4} more)`:"";return{message:`Matches none of: ${n.join("; ")}. Nearest is the ${t[c.index]}: ${m.join("; ")}${u}`};}});}function tn(e){let t=e;for(;t instanceof s.ZodEffects;)t=t._def.schema;return t instanceof s.ZodObject?Object.keys(t.shape):void 0;}function nn(e){let t=e;for(;t instanceof s.ZodEffects;)t=t._def.schema;return t instanceof s.ZodObject?`{ ${Object.entries(t.shape).map(([i,o])=>o.isOptional()?`${i}?`:i).join(", ")} }`:"";}const an={minute:5256e3,hour:87600,day:3650,week:520,month:120,quarter:40,year:10},N=s.enum(["day","week","month","quarter","year"]),sn=s.enum(["minute","hour"]),rn=s.enum(["minute","hour","day","week","month","quarter","year"]),fe=s.number().int().positive(),J=s.number().int(),D={lastSubDay:s.object({mode:s.literal("last"),n:fe,unit:sn,complete:s.literal(!1).optional(),relativeTo:s.literal("latest_data").optional()}),last:s.object({mode:s.literal("last"),n:fe,unit:N,complete:s.boolean().optional(),relativeTo:s.literal("latest_data").optional()}),this:s.object({mode:s.literal("this"),unit:N,toDate:s.boolean().optional(),boundary:s.enum(["first_day","last_day"]).optional()}),previous:s.object({mode:s.literal("previous"),unit:N}),between:s.object({mode:s.literal("between"),unit:N,from:J,to:J})},he={check:e=>e.boundary===void 0||e.unit==="month",message:'A month boundary requires unit "month".'},at=e=>s.object({kind:s.literal("periods"),unit:N,from:J,to:J,toDate:s.boolean().optional(),anchor:s.union([s.enum(["now","latest_data"]),e])}),st=s.object({lastComplete:N}),rt=at(st.strict()).strict(),W={periods:at(st),rolling:s.object({kind:s.literal("rolling"),unit:rn,n:fe,anchor:s.enum(["now","latest_data"])}),monthDay:s.object({kind:s.literal("monthDay"),day:s.enum(["first","last"])})},on={"<":"start",">=":"start","<=":"end",">":"end"};function ot(e){return on[e];}function ua(e,t){const n=ot(e);return n==="start"?[t[0]]:n==="end"?[t[1]]:[t[0],t[1]];}function dn(e,t){return e==="between"||e==="not between"?!0:ot(e)?!t||t.kind==="monthDay"||t.anchor!=="latest_data":!1;}function F(e,t={}){const n=ln(e);if(!(!n||dt(n,t)))return un(n);}function dt(e,t={}){if(e.kind==="periods")return e.from>e.to?{rule:"W1",message:`from (${e.from}) is after to (${e.to}).`,path:"from"}:e.toDate&&e.to!==0?{rule:"W2",message:`toDate needs to 0, not ${e.to}.`,path:"toDate"}:typeof e.anchor=="object"&&e.to>0?{rule:"W3",message:`A window ending at the last complete ${e.anchor.lastComplete} can't reach past it (to ${e.to}).`,path:"to"}:void 0;if(e.kind!=="rolling")return;if(!Number.isInteger(e.n)||e.n<1)return{rule:"W4",message:`n (${e.n}) must be a whole number of at least 1.`,path:"n"};const n=an[e.unit];if(t.authoring&&e.n>n)return{rule:"limit",message:`At most ${n} ${e.unit}s (ten years).`,path:"n",max:n};}function ln(e){if(!e||typeof e!="object")return;if("kind"in e){for(const r of Object.values(W)){const l=r.safeParse(e);if(l.success)return l.data;}return;}const t=D.lastSubDay.safeParse(e),n=t.success?t:D.last.safeParse(e);if(n.success){const{n:r,unit:l,complete:c,relativeTo:m}=n.data,u=m??"now";return c?{kind:"periods",unit:l,from:-r,to:-1,anchor:u}:{kind:"rolling",unit:l,n:r,anchor:u};}const i=D.this.safeParse(e);if(i.success){const{unit:r,toDate:l,boundary:c}=i.data;return he.check(i.data)?c?{kind:"monthDay",day:c==="first_day"?"first":"last"}:{kind:"periods",unit:r,from:0,to:0,...(l?{toDate:!0}:{}),anchor:"now"}:void 0;}const o=D.previous.safeParse(e);if(o.success)return{kind:"periods",unit:o.data.unit,from:-1,to:-1,anchor:"now"};const a=D.between.safeParse(e);if(a.success){const{unit:r,from:l,to:c}=a.data;return{kind:"periods",unit:r,from:l,to:c,anchor:"now"};}}function un(e){switch(e.kind){case"periods":{const{unit:t,anchor:n}=e;return typeof n=="object"&&n.lastComplete===t?{kind:"periods",unit:t,from:e.from-1,to:e.to-1,anchor:"now"}:{kind:"periods",unit:t,from:e.from,to:e.to,...(e.toDate?{toDate:!0}:{}),anchor:typeof n=="object"?{lastComplete:n.lastComplete}:n};}case"rolling":return{kind:"rolling",unit:e.unit,n:e.n,anchor:e.anchor};case"monthDay":return{kind:"monthDay",day:e.day};}}const y=(e,t,n,i)=>{const o=F(i);if(!o)throw new Error(`The preset ${e} is not a relative date window.`);return{id:e,label:t,category:n,window:o};},v=(e,t,n)=>({kind:"periods",unit:e,from:t,to:n,anchor:"now"}),C=(e,t)=>({kind:"rolling",unit:e,n:t,anchor:"now"}),cn=[y("last_30_minutes","Last 30 minutes","time",C("minute",30)),y("last_1_hour","Last 1 hour","time",C("hour",1)),y("last_4_hours","Last 4 hours","time",C("hour",4)),y("last_12_hours","Last 12 hours","time",C("hour",12)),y("last_24_hours","Last 24 hours","time",C("hour",24)),y("today","Today","day",v("day",0,0)),y("yesterday","Yesterday","day",v("day",-1,-1)),y("first_day_of_month","First day of the month","day",{kind:"monthDay",day:"first"}),y("last_day_of_month","Last day of the month","day",{kind:"monthDay",day:"last"}),y("last_7_days","Last 7 days","day",v("day",-6,0)),y("last_30_days","Last 30 days","day",v("day",-29,0)),y("last_90_days","Last 90 days","day",v("day",-89,0)),y("this_week","This week","week",v("week",0,0)),y("last_week","Last week","week",v("week",-1,-1)),y("last_2_weeks","Last 2 weeks","week",v("week",-2,-1)),y("this_month","This month","month",v("month",0,0)),y("last_month","Last month","month",v("month",-1,-1)),y("last_3_months","Last 3 months","month",v("month",-3,-1)),y("last_6_months","Last 6 months","month",v("month",-6,-1)),y("last_9_months","Last 9 months","month",v("month",-9,-1)),y("last_12_months","Last 12 months","month",v("month",-12,-1)),y("this_quarter","This quarter","quarter",v("quarter",0,0)),y("last_quarter","Last quarter","quarter",v("quarter",-1,-1)),y("last_4_quarters","Last 4 quarters","quarter",v("quarter",-4,-1)),y("this_year","This year","year",v("year",0,0)),y("last_year","Last year","year",v("year",-1,-1)),y("year_to_last_completed_month","Year to last completed month","year",{kind:"periods",unit:"year",from:0,to:0,toDate:!0,anchor:{lastComplete:"month"}})];function mn(e,t){return qe(e)===qe(t);}function qe(e){return JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([i],[o])=>i<o?-1:i>o?1:0)):n);}function Be(e){const t=cn.find(n=>lt(n.window,e));return{label:t?t.label:hn(e),...(t?{presetId:t.id}:{}),definition:ct(e)};}function pn(e,t){const n=F(e),i=F(t);return n&&i?lt(n,i):n||i?!1:mn(e??null,t??null);}function lt(e,t){return JSON.stringify(e)===JSON.stringify(t);}const M=(e,t)=>Math.abs(e)===1?t:`${t}s`;function G(e,t){if(e===0)return t==="day"?"today":`this ${t}`;if(e===-1)return t==="day"?"yesterday":`last ${t}`;if(e===1)return t==="day"?"tomorrow":`next ${t}`;const n=Math.abs(e);return e<0?`${n} ${M(n,t)} ago`:`${n} ${M(n,t)} ahead`;}const oe=e=>e.charAt(0).toUpperCase()+e.slice(1),fn={day:"yesterday",week:"last week",month:"last month",quarter:"last quarter",year:"last year"};function ut(e){return F({kind:"periods",unit:e.unit,from:e.from,to:e.to,anchor:"now"});}function hn(e){if(e.kind==="periods"&&typeof e.anchor=="object")return`${Be(ut(e)).label}, as of end of ${fn[e.anchor.lastComplete]}`;if(e.kind!=="monthDay"&&e.anchor==="latest_data"){const t=F({...e,anchor:"now"});return`${Be(t).label} of data`;}switch(e.kind){case"monthDay":return e.day==="first"?"First day of the month":"Last day of the month";case"rolling":return`Last ${e.n} ${M(e.n,e.unit)}`;case"periods":{const{unit:t,from:n,to:i}=e;if(e.toDate)return n===0?`This ${t} to date`:`${oe(G(n,t))} to date`;if(i===-1&&n<=-2)return`Last ${-n} ${M(-n,t)}`;if(n===i)return oe(G(n,t));const o=t==="day"?"today":`this ${t}`;return i===0&&n<0?`Last ${1-n} ${M(1-n,t)}, including ${o}`:n===1&&i>=2?`Next ${i} ${M(i,t)}`:n===0&&i>0?`Next ${i+1} ${M(i+1,t)}, including ${o}`:`${oe(G(n,t))} to ${G(i,t)}`;}}}const L=(e,t)=>`${e} ${t}${Math.abs(e)===1?"":"s"}`;function O(e,t){return e===0?`the current ${t}`:e<0?`${L(-e,t)} before the current one`:`${L(e,t)} after the current one`;}function ct(e){switch(e.kind){case"monthDay":return e.day==="first"?"the first day of the current month":"the last day of the current month";case"rolling":{const t=L(e.n,e.unit);return e.anchor==="latest_data"?`the last ${t}, up to the latest date in the data`:`the last ${t}, up to now`;}case"periods":{const{unit:t,from:n,to:i}=e;if(typeof e.anchor=="object"){const r=`the end of the last complete ${e.anchor.lastComplete}`;return e.toDate?n===0?`the current ${t} up to ${r}`:`from ${O(n,t)} up to ${r}`:`${ct(ut(e))}, as of ${r}`;}if(e.anchor==="latest_data"&&i===-1)return`the ${L(-n,t)} before the ${t} of the latest date in the data, whole ${t}s only`;const o=e.anchor==="latest_data"?"the latest date in the data":"now";if(e.toDate)return n===0?`the current ${t} up to ${o}`:`from ${O(n,t)} up to ${o}`;const a=e.anchor==="latest_data"?", counted from the latest date in the data":"";return n===0&&i===0?`the whole current ${t}${a}`:n===-1&&i===-1?`the ${t} before the current one`:i===-1?`the ${L(-n,t)} before the current ${t}, whole ${t}s only`:n===i?`${O(n,t)}${a}`:`from ${O(n,t)} through ${O(i,t)}${a}`;}}}const mt="Not a relative date window",gn=s.union([D.lastSubDay.strict(),D.last.strict(),D.this.strict().refine(he.check,{message:he.message,path:["boundary"]}),D.previous.strict(),D.between.strict(),rt,W.rolling.strict(),W.monthDay.strict()]).transform((e,t)=>{const n=F(e);return n||(t.addIssue({code:s.ZodIssueCode.custom,message:mt}),s.NEVER);}),E={periods:rt,rolling:W.rolling.strict(),monthDay:W.monthDay.strict()},ca=s.union([E.periods,E.rolling,E.monthDay]).transform((e,t)=>{const n=F(e,{authoring:!0});return n||(t.addIssue({code:s.ZodIssueCode.custom,message:mt}),s.NEVER);});function Q(e){return e.kind==="absolute";}const X="Use { kind: 'periods', unit, from, to, anchor } for whole periods (the last 3 complete months: from -3, to -1; this month: from 0, to 0) or { kind: 'rolling', unit, n, anchor } for elapsed time.",yn="Ask the user which.",Ie=/* @__PURE__ */new Set(["minute","hour"]);function ma(e,t){if(!e||!t)return e===t;if(Q(e)||Q(t)){if(!Q(e)||!Q(t))return!1;const n=i=>{var o;return(o=ie(i))==null?void 0:o.getTime();};return n(e.start)===n(t.start)&&n(e.end)===n(t.end);}return pn(e,t);}function Se(e,t){const n=ft(e,t);return n.ok?n:{ok:!1,refusal:$n(n.problem,t)};}function pa(e,t,n){const i=Se(e,t);if(!i.ok)return{...i.refusal,message:`${i.refusal.message} It stays while ${n} is left out.`};}const _n=s.object({kind:s.literal("absolute"),start:s.string(),end:s.string()}).strict(),bn={kind:"monthDay",day:"first"};function fa(e){const t=typeof e=="function"?e:()=>e,n=en([E.periods,E.rolling,E.monthDay,_n],["periods window","rolling window","month day window","absolute window"]);return s.preprocess((i,o)=>{const a=Se(i,{use:t(o.path)});return a.ok?a.window:(o.addIssue({code:s.ZodIssueCode.custom,message:pt(a.refusal),...(a.refusal.path?{path:[a.refusal.path]}:{})}),bn);},n);}const ge=" Fix: ";function pt(e){return`${e.message}${ge}${e.fix}`;}function ha(e){const t=e.indexOf(ge);return t>0?{message:e.slice(0,t),fix:e.slice(t+ge.length)}:void 0;}function ft(e,t){if(!e||typeof e!="object"||Array.isArray(e))return w("not_a_window","timeWindow must be an object.",`Send a window. ${X}`,[]);const n=e;if("value"in n||"completeness"in n||"period"in n||n.kind==="relative"||n.kind==="calendar")return w("old_form","timeWindow uses the window form: kind periods or rolling, with an anchor.",X,[]);if(n.kind==="absolute")return vn(n,t);const i=n.kind;if(i!=="periods"&&i!=="rolling"&&i!=="monthDay")return w("not_a_window",`timeWindow kind must be periods, rolling, monthDay or absolute${i===void 0?"":`, not ${JSON.stringify(i)}`}.`,X,[],"kind");if(i!=="monthDay"&&n.anchor===void 0)return In(n,t);if(n.unit==="second")return Sn(n);if(i==="periods"&&typeof n.unit=="string"&&Ie.has(n.unit))return wn(n);const o=E[i].safeParse(n);if(!o.success){const m=o.error.issues[0],u=m.path.join(".");return w("not_a_window",`timeWindow ${u?`${u}: `:""}${m.message}.`,`Send a ${i} window: ${xn(i)}.`,[],u||void 0);}const a=o.data,r=dt(a,{authoring:!0});if(r){if(r.rule==="limit"&&a.kind==="rolling")return w("over_limit",r.message,`Use at most ${r.max}, or the same span in a longer unit.`,[{...a,n:r.max}],"n");const m=r.rule==="W1"&&a.kind==="periods"?[{...a,from:a.to,to:a.from}]:[];return w("not_a_window",r.message,Dn(r.rule),m,r.path);}const l=kn(a,t);if(l)return l;const c=F(a,{authoring:!0});return c?{ok:!0,window:c}:w("not_a_window","timeWindow is not a window.",X,[]);}function vn(e,t){if(t.use==="filterDefault")return w("absolute_default","A filter's default moves with time.","Use a window that moves with time, or leave defaultPeriod out.",[{kind:"periods",unit:"month",from:-1,to:-1,anchor:"now"}]);const n=typeof e.start=="string"?ie(e.start):null,i=typeof e.end=="string"?ie(e.end):null;return!n||!i||n.getTime()>i.getTime()?w("absolute_invalid","start and end must be ISO dates or timestamps, start first.","Send start before end, as YYYY-MM-DD or an ISO timestamp.",[],n?"end":"start"):{ok:!0,window:{kind:"absolute",start:e.start,end:e.end}};}function In(e,t){const n=typeof e.unit=="string"?e.unit:"month",i=[{anchor:"now",words:'"now" counts from the run'},...(t.use==="filterDefault"?[]:[{anchor:"latest_data",words:'"latest_data" from the newest row'}]),...(e.kind==="periods"?[{anchor:{lastComplete:n},words:`{ "lastComplete": "${n}" } ends at the last complete ${n}`}]:[])];return w("missing_anchor","A window needs an anchor: where it counts from.",`Add an anchor: ${i.map(o=>o.words).join(", ")}.`,i.map(o=>({...e,anchor:o.anchor})),"anchor");}function Sn(e){const t=typeof e.n=="number"?e.n:0,n=[.../* @__PURE__ */new Set([Math.floor(t/60),Math.ceil(t/60)])].filter(i=>i>=1);return w("seconds","Windows count minutes, not seconds.","Round to whole minutes.",n.map(i=>({kind:"rolling",unit:"minute",n:i,anchor:e.anchor})),"unit");}function wn(e){const t=typeof e.from=="number"?e.from:0,i=(typeof e.to=="number"?e.to:0)-t+1;return w("sub_day_periods","Minutes and hours count elapsed time; there are no whole-minute or whole-hour periods.",`The nearest is the last ${i} ${String(e.unit)}s up to the anchor.`,i>=1?[{kind:"rolling",unit:e.unit,n:i,anchor:e.anchor}]:[],"unit");}function kn(e,t){if(!(t.use==="analysis"||e.kind==="monthDay")){if(e.kind==="rolling"&&!Ie.has(e.unit))return An(e);if(e.kind==="rolling"&&t.columnHasTime===!1)return w("sub_day_on_date","The date field has dates only, so it can't count minutes or hours.","Use whole days.",[{kind:"periods",unit:"day",from:0,to:0,anchor:e.anchor},{kind:"periods",unit:"day",from:-1,to:0,anchor:e.anchor}],"unit");if(t.use==="filterDefault"&&e.anchor==="latest_data")return w("data_anchor_default","A filter's default counts from the run, not from the latest data.","Count from the run instead.",[{...e,anchor:"now"}],"anchor");}}function An(e){const t=e.unit,n=e.n===1?`Choose the current ${t} so far, or the last complete ${t}.`:`Choose the current ${t} so far and the ${e.n-1} before it, or the last ${e.n} complete ${t}s.`;return w("rolling_days_saved",`A saved card or default counts whole ${t}s.`,n,[{kind:"periods",unit:t,from:1-e.n,to:0,anchor:e.anchor},{kind:"periods",unit:t,from:-e.n,to:-1,anchor:e.anchor}]);}function $n(e,t){const n=[],i=/* @__PURE__ */new Set(),o=[e.sentence],a=(m,u)=>{for(const p of m){const f=ft(p,t);if(f.ok){const b=JSON.stringify(p);i.has(b)||(i.add(b),n.push(p));}else u<4&&f.problem.repairs.length&&(o.includes(f.problem.sentence)||o.push(f.problem.sentence),a(f.problem.repairs,u+1));}};a(e.repairs,0);let r=o.join(" ");const l=n.some(m=>"unit"in m&&Ie.has(String(m.unit)));t.use!=="analysis"&&t.columnHasTime===void 0&&l&&(r=`${r.replace(/\.$/,"")}, if the date field has a time of day.`),n.length>1&&(r=`${r} ${yn}`);const c=n.length?` ${n.length>1?"Send one of":"Send"}: ${n.map(m=>JSON.stringify(m)).join("; ")}.`:"";return{reason:e.reason,message:e.message,fix:`${r}${c}`,suggestions:n,...(e.path?{path:e.path}:{})};}function w(e,t,n,i,o){return{ok:!1,problem:{reason:e,message:t,sentence:n,repairs:i,...(o?{path:o}:{})}};}function Dn(e){switch(e){case"W1":return"from must be at most to; -1 is the period before the anchor's.";case"W2":return"toDate needs to 0: the current period, up to the anchor.";case"W3":return"A window ending at the last complete period ends at or before it: to at most 0.";case"W4":case"limit":return"n is a whole number of at least 1.";}}function xn(e){switch(e){case"periods":return"{ kind: 'periods', unit: day | week | month | quarter | year, from, to, toDate?: true, anchor: 'now' | 'latest_data' | { lastComplete: unit } }";case"rolling":return"{ kind: 'rolling', unit: minute | hour | day | week | month | quarter | year, n, anchor: 'now' | 'latest_data' }";case"monthDay":return"{ kind: 'monthDay', day: 'first' | 'last' }";}}function d(e,t,n){return n?{code:e,message:t,path:n}:{code:e,message:t};}function h(e){return typeof e=="string"&&e.trim().length>0;}function Fn(e){const t=/* @__PURE__ */new Set();return Mn(e,n=>(t.add(n),`{${n}}`)),Array.from(t);}function Mn(e,t){let n="",i=0,o=0;for(;o<e.length;){const a=e[o];if(a==="'"||a==='"'){o=En(e,o);continue;}if(a==="{"){const r=e.indexOf("}",o+1);if(r===-1){o+=1;continue;}const l=e.slice(o+1,r);/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)&&(n+=e.slice(i,o)+t(l),i=r+1),o=r+1;continue;}o+=1;}return n+e.slice(i);}function En(e,t){const n=e[t];let i=t+1;for(;i<e.length;){if(e[i]===n){if(e[i+1]===n){i+=2;continue;}return i+1;}i+=1;}return e.length;}function g(e){return!!(e&&typeof e=="object"&&!Array.isArray(e));}const Nn=/* @__PURE__ */new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function we(e,t,n){if(!e||typeof e!="object"){n.push(d("missing_source","Analytics intent needs a source.",t));return;}if(e.kind==="semantic"){h(e.domainId)||n.push(d("missing_semantic_domain","Semantic source needs a domainId.",`${t}.domainId`)),h(e.datasetName)||n.push(d("missing_dataset_name","Semantic source needs a datasetName.",`${t}.datasetName`));return;}if(e.kind==="physical"){h(e.connectionId)||n.push(d("missing_connection_id","Physical source needs a connectionId.",`${t}.connectionId`)),h(e.tableName)||n.push(d("missing_table_name","Physical source needs a tableName.",`${t}.tableName`));return;}if(e.kind==="sql"){h(e.connectionId)||n.push(d("missing_connection_id","SQL source needs a connectionId.",`${t}.connectionId`));return;}n.push(d("invalid_source_kind","Source kind is not supported.",t));}function I(e,t,n,i={}){if(!e||!g(e)){i.required&&n.push(d("missing_field_ref","Field reference needs a name.",t));return;}h(e.name)||n.push(d("missing_field_ref","Field reference needs a name.",`${t}.name`)),e.source!==void 0&&we(e.source,`${t}.source`,n),ke(e.aggregate,`${t}.aggregate`,n);}function ke(e,t,n){e!==void 0&&(typeof e!="string"||!Nn.has(e))&&n.push(d("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",t));}const Tn=/* @__PURE__ */new Set(["measure","dimension","date","id","unknown"]),Rn=/* @__PURE__ */new Set(["row","aggregate"]),jn=/* @__PURE__ */new Set(["string","number","boolean","date","datetime","unknown"]);function Cn(e,t,n){if(e===void 0)return;if(!g(e)){n.push(d("invalid_value_format","Value format must be a structured object.",t));return;}const i=(e.type==="temporal_bucket"?Z:Bt).safeParse(e);if(i.success)return;const o=e.type==="temporal_bucket"?"invalid_temporal_bucket_format":"invalid_value_format";for(const a of i.error.issues)n.push(d(o,a.message,[t,...a.path.map(String)].filter(Boolean).join(".")));}const On=/* @__PURE__ */new Set(["additive","non_additive","ratio_of_sums","weighted","pre_aggregated","snapshot"]),Yn=/* @__PURE__ */new Set(["default","symmetric_aggregate","aggregate_then_join","weighted"]);function Ln(e,t,n){if(!e||!g(e)){n.push(d("invalid_derived_field_input","Derived field inputs must be structured input references.",t));return;}if(e.kind==="field"){I(e.field,`${t}.field`,n,{required:!0}),ke(e.aggregate,`${t}.aggregate`,n);return;}n.push(d("invalid_derived_field_input","Derived field input kind must be field.",`${t}.kind`));}function Ae(e){const t=[];if(!g(e))return t.push(d("invalid_derived_field","Derived field definition must be a structured object.")),{ok:!1,errors:t,warnings:[]};if(e.kind!=="derived_field"&&t.push(d("invalid_derived_field_kind","Derived field kind must be derived_field.","kind")),h(e.name)||t.push(d("invalid_derived_field_name","Derived field needs a name.","name")),h(e.label)||t.push(d("invalid_derived_field_label","Derived field needs a label.","label")),Tn.has(e.resultRole)||t.push(d("invalid_derived_field_role","Derived field resultRole must be measure, dimension, date, id, or unknown.","resultRole")),jn.has(e.dataType)||t.push(d("invalid_derived_field_data_type","Derived field dataType must be string, number, boolean, date, datetime, or unknown.","dataType")),Rn.has(e.computeStage)||t.push(d("invalid_derived_field_compute_stage","Derived field computeStage must be row or aggregate.","computeStage")),e.computeStage==="aggregate"&&e.resultRole!=="measure"&&t.push(d("invalid_derived_field_compute_stage","Aggregate-stage derived fields must have resultRole measure.","computeStage")),e.resultRole!=="measure"&&e.defaultAggregate!==void 0&&t.push(d("invalid_derived_field_aggregate","Only measure derived fields may declare defaultAggregate.","defaultAggregate")),e.computeStage==="row"&&e.resultRole==="measure"&&e.defaultAggregate===void 0&&t.push(d("missing_derived_field_default_aggregate","Row-stage measure derived fields must declare defaultAggregate so row results have explicit rollup semantics.","defaultAggregate")),ke(e.defaultAggregate,"defaultAggregate",t),e.aggregationBehavior!==void 0&&!On.has(e.aggregationBehavior)&&t.push(d("invalid_derived_field_aggregation_behavior","Derived field aggregationBehavior is not supported.","aggregationBehavior")),e.aggregationStrategy!==void 0&&!Yn.has(e.aggregationStrategy)&&t.push(d("invalid_derived_field_aggregation_strategy","Derived field aggregationStrategy is not supported.","aggregationStrategy")),h(e.expression)||t.push(d("invalid_derived_field_expression","Derived field needs a named-token expression.","expression")),e.expressionLanguage!==void 0&&e.expressionLanguage!=="semaphor_sql_template"&&t.push(d("invalid_derived_field_expression_language","Derived field expressionLanguage must be semaphor_sql_template.","expressionLanguage")),!g(e.inputs)||Object.keys(e.inputs).length===0?t.push(d("invalid_derived_field_inputs","Derived field needs at least one typed input.","inputs")):Object.entries(e.inputs).forEach(([i,o])=>{if(!h(i)){t.push(d("invalid_derived_field_input_name","Derived field input names must be non-empty strings.","inputs"));return;}Ln(o,`inputs.${i}`,t);}),h(e.expression)&&g(e.inputs)){const i=Fn(e.expression),o=new Set(i),a=Object.keys(e.inputs).filter(r=>h(r));i.forEach(r=>{Object.prototype.hasOwnProperty.call(e.inputs,r)||t.push(d("invalid_derived_field_expression_token",`Derived field expression token "{${r}}" needs a matching inputs.${r} entry.`,"expression"));}),a.forEach(r=>{o.has(r)||t.push(d("unused_derived_field_input",`Derived field input "${r}" is not referenced by expression.`,`inputs.${r}`));});}const n=e.format;return g(n)&&n.type==="temporal_bucket"?t.push(d("invalid_derived_field_format","Derived field computation metadata cannot own temporal bucket presentation; declare grain and format on the grouped field.","format")):Cn(n,"format",t),e.tags!==void 0&&(!Array.isArray(e.tags)||e.tags.some(i=>!h(i)))&&t.push(d("invalid_derived_field_tags","Derived field tags must be non-empty strings.","tags")),{ok:t.length===0,errors:t,warnings:[]};}const Y=s.string().min(1).refine(e=>e.trim().length>0,"Must not be blank."),$e=s.union([Wt.extend({domainId:Y,datasetName:Y}).strict(),Ut.extend({connectionId:Y,tableName:Y}).strict()]),ht=Vt.extend({name:Y,source:$e.optional()}).strict(),De=Ht.extend({format:zt.optional(),inputs:s.record(s.object({kind:s.literal("field"),field:ht,aggregate:it.optional()}).strict())}).strict().superRefine((e,t)=>{var n;for(const i of Ae(e).errors)t.addIssue({code:"custom",path:((n=i.path)==null?void 0:n.split("."))??[],message:i.message});}),Pn=ht.extend({derivedField:De.optional()}).strict();function xe(e){return typeof e=="string"?e.trim().toLowerCase():"";}function qn(e){return String(e.column_name||e.name||e.qualifiedFieldName||"");}function Bn(e){return Array.from(new Set([e.column_name,e.name,e.qualifiedFieldName,e.alias].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim())));}function Fe(e){const t=Ee(e);return t?Hn(t)?"number":t.includes("timestamp")||t.includes("datetime")||t.startsWith("time")?"datetime":t.includes("date")?"date":t.includes("bool")?"boolean":"string":"unknown";}const de=/* @__PURE__ */new Map([["int","integer"],["uint","integer"],["integer","integer"],["uinteger","integer"],["bigint","integer"],["ubigint","integer"],["smallint","integer"],["usmallint","integer"],["tinyint","integer"],["utinyint","integer"],["mediumint","integer"],["hugeint","integer"],["uhugeint","integer"],["numeric","decimal"],["decimal","decimal"],["float","float"],["double","float"],["real","float"],["bfloat16","float"],["number",null],["money",null],["currency",null],["percent",null]]),Wn=["int","uint","decimal","float"];function Un(e){return e.length>0&&Array.from(e).every(t=>t>="0"&&t<="9");}function Vn(e){var n;const t=(n=/^number\s*\(\s*\d+\s*,\s*(\d+)\s*\)$/.exec(e))==null?void 0:n[1];return t===void 0?null:Number(t)===0?"integer":"decimal";}function Me(e){const t=e.split(/[\s(]/,1)[0]||"";if(t==="number")return{numeric:!0,kind:Vn(e)};if(de.has(t))return{numeric:!0,kind:de.get(t)??null};const n=Wn.find(i=>t.startsWith(i)&&Un(t.slice(i.length)));return n?{numeric:!0,kind:de.get(n)??null}:{numeric:!1,kind:null};}function Hn(e){return Me(e).numeric;}function zn(e){return Me(Ee(e)).kind;}function ga(e){var o,a;const t=Ee(e),n=Me(t).kind;if(n==="integer")return 0;if(n!=="decimal")return null;const i=((o=/^(?:decimal|numeric|number)\s*\(\s*\d+\s*,\s*(\d+)\s*\)$/.exec(t))==null?void 0:o[1])??((a=/^decimal(?:32|64|128|256)\s*\(\s*(\d+)\s*\)$/.exec(t))==null?void 0:a[1]);return i===void 0?null:Number(i);}function Ee(e){let t=xe(e),n="";for(;t&&t!==n;)n=t,t=We(t,"nullable"),t=We(t,"lowcardinality");return t;}function We(e,t){const n=`${t}(`;return!e.startsWith(n)||!e.endsWith(")")?e:e.slice(n.length,-1).trim();}function Gn(e){const t=Fe(e);return t==="date"||t==="datetime";}function gt(e){return Gn(e.dataType||e.data_type);}function yt(e){const t=_t(e);return t==="id"||t==="row_id";}function Ue(e){const t=_t(e);return yt(e)||t.endsWith("_id")||t.endsWith("_key")||t.endsWith("_number");}function _t(e){return xe(qn(e)||e.name||e.alias).replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");}function bt(e,t={}){const n=xe(e.role);return n==="metric"||n==="measure"?!t.excludeIdentifiers||!Ue(e):n==="groupby"||n==="dimension"||n==="date"||n==="id"?!1:Fe(e.dataType||e.data_type)==="number"&&(!t.excludeIdentifiers||!Ue(e));}function ya(e){return!bt(e)&&!gt(e);}function _a(e){const t=/* @__PURE__ */new Set(),n=/* @__PURE__ */new Set(),i=/* @__PURE__ */new Set();for(const o of e){if(yt(o))continue;const a=Bn(o);if(a.length!==0){if(gt(o)){a.forEach(r=>n.add(r));continue;}if(bt(o,{excludeIdentifiers:!0})){a.forEach(r=>t.add(r));continue;}a.forEach(r=>i.add(r));}}return{validMeasureCandidates:Array.from(t).sort(),validDateCandidates:Array.from(n).sort(),validDimensionCandidates:Array.from(i).sort()};}const P=16*1024;function ee(e){const t=/^([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:[eE]([+-]?\d+))?$/.exec(e);return t?{sign:t[1],whole:t[2]??"",fraction:t[3]??t[4],exponent:Number(t[5]??"0")}:null;}function Ve(e){const{sign:t,whole:n,fraction:i="",exponent:o}=e,a=(n+i).replace(/^0+/,""),r=a.replace(/0+$/,""),l=o-i.length+a.length-r.length;return!Number.isSafeInteger(o)||!Number.isSafeInteger(l)?null:r?`${t==="-"?"-":""}${r}e${l}`:"0";}function ba(e){const t=ee(e);if(!t)return null;const n=t.sign==="+"?e.slice(1):e,i=Number(e);if(!Number.isFinite(i))return n;const o=Ve(t),a=ee(String(i));return o!==null&&a!==null&&o===Ve(a)?i:n;}function va(e){if(e.length>P)throw new RangeError("Exact numeric text exceeds 16 KiB.");const t=ee(e);if(!t)throw new TypeError("Expected finite decimal text.");const{sign:n,whole:i,fraction:o,exponent:a}=t,r=`${n}${i||"0"}${o?`.${o}`:""}`;return U(`${r}e${a}`);}function U(e){if(e.length>P)throw new RangeError("Exact numeric text exceeds 16 KiB.");const t=ee(e);if(!t||t.whole===""||t.fraction==="")throw new TypeError("Expected finite decimal text.");const{sign:n,whole:i,fraction:o="",exponent:a}=t;if(!Number.isSafeInteger(a)||Math.abs(a)>P)throw new RangeError("Exact numeric exponent exceeds the text budget.");const r=i+o,l=i.length+a;if(Math.max(r.length,l)+Math.max(0,-l)+3>P)throw new RangeError("Normalized exact numeric text exceeds 16 KiB.");let m;l<=0?m=`0.${"0".repeat(-l)}${r}`:l>=r.length?m=r+"0".repeat(l-r.length):m=`${r.slice(0,l)}.${r.slice(l)}`;const[u,p=""]=m.split("."),f=u.replace(/^0+(?=\d)/,""),b=p.replace(/0+$/,""),A=f+(b?`.${b}`:"");return n==="-"&&A!=="0"?`-${A}`:A;}function Ia(e,t){const n=e.startsWith("-"),i=t.startsWith("-");if(n!==i)return n?-1:1;const[o,a=""]=(n?e.slice(1):e).split("."),[r,l=""]=(i?t.slice(1):t).split(".");let c=Math.sign(o.length-r.length);if(!c&&o!==r&&(c=o<r?-1:1),!c){const m=Math.max(a.length,l.length),u=a.padEnd(m,"0"),p=l.padEnd(m,"0");c=u===p?0:u<p?-1:1;}return c===0?0:n?-c:c;}function Sa(e,t){if(typeof t=="number"&&!Number.isFinite(t))throw new TypeError("Numeric scale must be finite.");const n=[e,U(String(t))].map(a=>{const[r,l=""]=a.split(".");return{coefficient:BigInt(r+l),digits:l.length};}),i=n[0].coefficient*n[1].coefficient,o=n[0].digits+n[1].digits;return U(`${i}e-${o}`);}function Qn(e){try{return U(e)===e;}catch{return!1;}}const vt=s.object({kind:s.literal("exact_number"),type:s.enum(["integer","decimal"]),value:s.string().max(P).refine(Qn,"Expected canonical decimal text.")}).strict().superRefine((e,t)=>{e.type==="integer"&&e.value.includes(".")&&t.addIssue({code:"custom",path:["value"],message:"An integer cannot have fractional digits."});}),Xn=s.union([s.null(),s.string(),s.boolean(),s.number().finite(),vt]);function Kn(e,t){return vt.parse({kind:"exact_number",type:t,value:U(e)});}function wa(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="exact_number"&&"type"in e&&(e.type==="integer"||e.type==="decimal")&&"value"in e&&typeof e.value=="string";}function ka(e){const t=zn(e.nativeDataType);if(!t)throw new TypeError("Numeric result type is not established.");if(e.value===null)return null;if(t==="float"){if(typeof e.value!="number"||!Number.isFinite(e.value))throw new TypeError("Expected a finite floating-point result.");return e.value;}if(e.exactText===void 0)throw new TypeError("Exact numeric sidecar is required; rounded result values cannot substitute.");return Kn(e.exactText,t);}const Ne=s.string().uuid(),Te=s.enum(["rows","columns"]),Aa=s.enum(["member","subtotal","grand_total","others"]),Zn=s.discriminatedUnion("kind",[s.object({kind:s.literal("value"),value:Xn}).strict(),s.object({kind:s.literal("others"),rankingId:Ne}).strict()]),T=s.array(s.object({levelId:Ne,member:Zn}).strict()).readonly().superRefine((e,t)=>{new Set(e.map(n=>n.levelId)).size!==e.length&&t.addIssue({code:"custom",path:[],message:"Duplicate identity."}),e.some((n,i)=>n.member.kind==="others"&&i!==e.length-1)&&t.addIssue({code:"custom",path:[],message:"Others is terminal."});}),$a=s.object({rowPath:T,columnPath:T,measureId:Ne}).strict();function It(e){return JSON.stringify(e.map(({levelId:t,member:n})=>[t,n.kind==="others"?["others",n.rankingId]:typeof n.value=="object"&&n.value!==null?["exact_number",n.value.value]:[typeof n.value,n.value]]));}const ye="SEMAPHOR_CALCULATED_FIELD",Jn="calculated_fields";function ei(e){return(e==null?void 0:e.sourceField)||(e==null?void 0:e.name)||"";}const ti=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","YYYY-MM-DD HH:mm","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm Z","YYYY-MM-DD HH:mm:ss Z","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function Da(e){return e.role==="metric"&&"expression"in e&&!!e.expression;}function xa(e){return!!e.expression;}function ni(e){return!!(e&&(e.calculationRepresentation||e.expression||e.derivedField||e.calculatedFieldOrigin||e.calculatedFormula||_e(e)));}function St(e){var p,f,b;if(!e)return{representation:"physical",ownership:"local",completeness:"not-calculated",runtimeExecutable:!1,legacyManual:!1};const t=e.fieldScope==="domain"?"domain":"local",n=((p=e.derivedField)==null?void 0:p.computeStage)||((f=e.calculatedFormula)==null?void 0:f.computeStage),i=!e.calculatedFormula||Array.isArray(e.calculatedFormula.inputFields)&&e.calculatedFormula.inputFields.every(A=>{const Le=A&&ei(A);return typeof Le=="string"&&!!Le.trim();}),o=typeof e.expression=="string"&&!!e.expression.trim()&&i,a=e.calculationRepresentation;if(e.derivedField||a==="typed-derived"){const A=e.derivedField!==void 0&&Ae(e.derivedField).ok;return{representation:"typed-derived",ownership:t,completeness:(!a||a==="typed-derived")&&A&&(!e.expression&&!e.calculatedFormula||o)?"complete":"incomplete",computeStage:n,runtimeExecutable:o,legacyManual:!1};}if(!(!!a||ni(e)))return{representation:"physical",ownership:t,completeness:"not-calculated",runtimeExecutable:!1,legacyManual:!1};const l=n||(e.role==="groupby"||((b=e.calculatedFieldOrigin)==null?void 0:b.role)==="groupby"?"row":void 0),c=t==="domain"||_e(e)||e.fieldScope==="card"||e.fieldScope==="dashboard"?"manual":"inline-expression",m=a==="manual"||a==="inline-expression"?a:c,u=(!a||a==="manual"||a==="inline-expression")&&!(a==="inline-expression"&&_e(e));return{representation:m,ownership:t,completeness:o&&u?"complete":"incomplete",computeStage:l,runtimeExecutable:o,legacyManual:m==="manual"&&t==="local"&&!l};}function Fa(e){if(e.calculationRepresentation)return e;const{representation:t}=St(e);return t==="physical"?e:{...e,calculationRepresentation:t};}function Ma(e){return St(e).computeStage;}function Ea(e,t){return e==="aggregate"&&t==="default";}function Na(e){var n,i;const t=e;return!!(t!=null&&t.expression&&(i=(n=t.calculatedFormula)==null?void 0:n.inputFields)!=null&&i.length);}function Ta(e){return!!(e&&(e.entityName===ye||e.entityId===ye));}function _e(e){return e?[e.entityName,e.entityId,e.qualifiedEntityName].some(t=>t===ye||t===Jn):!1;}function ii(e){const t=kt(e);return t.length>0?t.join("."):void 0;}function Ra(e){const t=ii(e.qualifiedName),n=(t==null?void 0:t.split("."))||[];if(n.length===0)return{};const i={};let o=n.length-1;for(let a=e.capabilities.prefixLevels.length-1;a>=0&&o>=0;a-=1,o-=1)ri(i,e.capabilities.prefixLevels[a],n[o]);return i;}function ja(e){return!e.left.tableName||!e.right.tableName?!1:e.capabilities.prefixLevels.every(t=>{const n=R(e.left,t),i=R(e.right,t);return!n||!i||n===i;});}function Ca(e){return e.capabilities.prefixLevels.every(t=>{const n=R(e.requested,t);return n?R(e.allowed,t)===n:!0;});}function wt(e,t={}){const n=V(e),i={connectionId:t.connectionId,connectionType:e,path:["database","schema","table"],labels:{database:"Database",schema:"Schema",table:"Table"},prefixLevels:["database","schema","table"],dialect:"postgres",supportsFilterClause:!0};return n.includes("postgres")?{...i,prefixLevels:["schema","table"],dialect:"postgres"}:n.includes("mysql")?{...i,prefixLevels:["database","table"],dialect:"mysql",supportsFilterClause:!1}:n.includes("mssql")||n.includes("sqlserver")?{...i,dialect:"mssql",supportsFilterClause:!1}:n.includes("redshift")?{...i,prefixLevels:["schema","table"],dialect:"redshift"}:n.includes("snowflake")?{...i,dialect:"snowflake"}:n.includes("clickhouse")?{connectionId:t.connectionId,connectionType:e,path:["database","table"],labels:{database:"Database",table:"Table"},prefixLevels:["database","table"],dialect:"clickhouse",supportsFilterClause:!1}:n==="s3"||n==="api"?{connectionId:t.connectionId,connectionType:e,path:["table"],labels:{table:n==="api"?"API Table":"File Table"},prefixLevels:["table"],dialect:"duckdb",supportsFilterClause:!0}:n==="googlesheets"||n==="fileupload"?{connectionId:t.connectionId,connectionType:e,path:["table"],labels:{table:"Table"},prefixLevels:["table"],dialect:"postgres",supportsFilterClause:!0}:n==="bigquery"?{...i,labels:{database:"Project",schema:"Dataset",table:"Table"},prefixLevels:["schema","table"],dialect:"bigquery",supportsFilterClause:!1}:i;}const Re=["GoogleSheets","FileUpload","MySQL","MSSQL","PostgreSQL","BigQuery","Redshift","Snowflake","S3","clickhouse","API","none"];function Oa(e){if(!e)return;const t=Re.filter(n=>n!=="none"&&wt(n).dialect===e);return t.length===1?t[0]:void 0;}const ai={postgres:"PostgreSQL",sqlserver:"MSSQL"};function Ya(e){const t=V(e);if(t)return Re.find(n=>V(n)===t)??ai[t];}function La(e,t={}){return si(e)?wt(e,t):void 0;}function si(e){const t=V(e);if(t.includes("postgres"))return"postgres";if(t.includes("mysql"))return"mysql";if(t.includes("mssql")||t.includes("sqlserver"))return"mssql";if(t.includes("redshift"))return"redshift";if(t.includes("snowflake"))return"snowflake";if(t.includes("clickhouse"))return"clickhouse";if(t==="s3"||t==="api"||t==="googlesheets"||t==="fileupload"||t==="bigquery")return t;}function Pa(e){const t=V(e);switch(t){case"mysql":case"bigquery":case"redshift":case"snowflake":case"clickhouse":case"duckdb":case"sqlite":return t;case"mssql":case"sqlserver":return"mssql";case"postgres":case"postgresql":return"postgres";default:return"unknown";}}function qa(e){return e.capabilities.prefixLevels.every(t=>!!R(e.source,t));}function Ba(e){const t=e.quoteIdentifier??li;return e.capabilities.prefixLevels.map(n=>R(e.source,n)).filter(n=>!!n).map(n=>t(n,e.capabilities.dialect)).join(".");}function R(e,t){return t==="database"?e.databaseName:t==="schema"?e.schemaName:e.tableName;}function ri(e,t,n){t==="database"?e.databaseName=n:t==="schema"?e.schemaName=n:e.tableName=n;}const oi=[['"','"'],["`","`"],["[","]"]];function di(e){const t=e.trim();for(const[n,i]of oi)if(t.length>=2&&t.startsWith(n)&&t.endsWith(i))return t.slice(1,-1).split(i+i).join(i);return t;}function kt(e){const t=e==null?void 0:e.trim();if(!t)return[];const n=t.split(".").map(di);return n.some(i=>!i)?[]:n;}function Wa(e){const t=kt(e??void 0);return t[t.length-1]||"";}function li(e,t){return t==="mysql"||t==="bigquery"||t==="clickhouse"||t==="duckdb"?`\`${e.replace(/`/g,"``")}\``:t==="mssql"?`[${e.replace(/]/g,"]]")}]`:`"${e.replace(/"/g,'""')}"`;}function V(e){if(typeof e!="string")return"";const t=[];for(const n of e.trim().toLowerCase())ui(n)&&t.push(n);return t.join("");}function ui(e){const t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=122;}const k=s.string().min(1),He=s.enum(["groupby","metric","sortby","pivotby","detail"]),At=s.enum(["table","view","materialized view","model","file","dataset","url","upload"]),le=s.object({connectionId:k,connectionType:s.enum(Re),type:At,name:k,alias:s.string().optional(),id:k.optional(),domainId:k.optional(),datasetType:s.enum(["physical","virtual"]).optional(),label:s.string().optional(),description:s.string().optional(),dbObjectType:s.string().optional(),database:s.string().optional(),schema:s.string().optional(),dialect:s.enum(["mysql","postgres","bigquery","redshift","snowflake","clickhouse","duckdb","mssql"]).optional()}).strict(),te=s.lazy(()=>s.object({id:k,name:k,label:s.string(),derivedLabel:s.string().optional(),qualifiedFieldName:k,dataType:k,entityId:k,entityName:k,entityType:At,alias:s.string().optional(),sourceField:s.string().optional(),source:$e.optional(),nativeDataType:s.string().optional(),description:s.string().optional(),qualifiedEntityName:s.string().optional(),dateFormat:s.enum(ti).optional(),customFormat:s.string().optional(),granularity:pe.optional(),role:He.optional(),calculationRepresentation:s.enum(["inline-expression","manual","typed-derived"]).optional(),calculatedFieldOrigin:s.object({id:k,role:He.optional()}).strict().optional(),aggregateOrigin:s.enum(["default","explicit"]).optional(),labelOrigin:s.enum(["semantic","override"]).optional(),formatOrigin:s.enum(["semantic","override"]).optional(),expression:s.string().optional(),derivedField:De.optional(),format:Z.optional(),semanticTemporalPresentation:s.object({granularity:pe,format:Gt}).strict().optional(),aggregate:it.optional(),grainMode:s.literal("automatic").optional(),fieldScope:s.enum(["card","dashboard","domain"]).optional(),calculatedFormula:s.object({operation:s.enum(["sum","difference","product","ratio","change","percentage","scale","custom"]),inputFields:s.array(te),constant:s.number().finite().optional(),computeStage:s.enum(["row","aggregate"]).optional()}).strict().optional()}).strict()),ci=s.union([s.string(),s.number().finite(),s.boolean(),s.date(),s.null()]),mi=s.object({id:k,field:te,operator:s.enum(["=","!=",">",">=","<","<=","contains","startsWith","endsWith","like","not like","in","not in","between","not between","isNull","isNotNull"]),value:s.union([ci,s.array(s.string()),s.array(s.number().finite())]),label:s.string().optional(),temporalBucket:Xt.optional(),rawTemporal:Qt.optional(),relativeMeta:gn.optional(),latestValue:s.literal(!0).optional(),latestValuePolicy:s.literal("snapshot").optional()}).strict().superRefine((e,t)=>{const{operator:n,value:i}=e;if((n==="between"||n==="not between")&&(!Array.isArray(i)||i.length!==2)&&t.addIssue({code:"custom",path:["value"],message:"Between requires two endpoints."}),e.relativeMeta&&!dn(n,F(e.relativeMeta))&&t.addIssue({code:"custom",path:["relativeMeta"],message:"A relative date runs under between, not between, <, <=, > or >=; a window counted from the newest row only under between or not between."}),e.latestValue){const a=[e.field.nativeDataType,e.field.dataType].map(r=>Fe(r)).some(r=>r==="date"||r==="datetime");(n!=="="||!a)&&t.addIssue({code:"custom",path:["latestValue"],message:"Latest value requires = on a date or timestamp field."});}(n==="in"||n==="not in")&&!Array.isArray(i)&&t.addIssue({code:"custom",path:["value"],message:"Membership requires an array."});}),$t=s.lazy(()=>s.object({id:k,logicalOperator:s.enum(["AND","OR"]),negate:s.boolean(),conditions:s.array(mi),groups:s.array($t)}).strict()),pi=s.object({baseEntity:le,joins:s.array(s.object({id:k,source:le,target:le,joinType:s.enum(["INNER","LEFT","RIGHT","FULL"]),sequence:s.number().int().nonnegative(),autoResolved:s.boolean().optional(),relationshipId:s.string().optional(),relationshipName:s.string().optional(),relationshipCardinality:s.enum(["one_to_one","one_to_many","many_to_one","many_to_many"]).optional(),relationshipTraversalDirection:s.enum(["forward","reverse"]).optional(),joinKeyGroups:s.array(s.object({id:k,operator:s.enum(["AND","OR"]),keys:s.array(s.object({id:s.string().optional(),source:te,target:te,operator:s.enum(["=","!=",">",">=","<","<="])}).strict()).min(1)}).strict()).min(1)}).strict())}).strict(),S=s.string().uuid(),fi=s.string().min(1),hi=s.number().int().positive().max(Number.MAX_SAFE_INTEGER),gi=s.enum(["SUM","COUNT","DISTINCT","AVG","MIN","MAX","MEDIAN"]),Dt=Pn.omit({aggregate:!0}),yi={id:S,field:Dt,grain:pe.optional()},be=s.object(yi).strict(),_i=s.object({id:S,kind:s.literal("aggregate"),field:Dt,aggregate:gi}).strict(),bi=s.object({id:S,kind:s.literal("calculated"),definition:De}).strict(),xt=s.discriminatedUnion("kind",[_i,bi]),vi=s.discriminatedUnion("kind",[s.object({kind:s.literal("member")}).strict(),s.object({kind:s.literal("measure"),measureId:S,oppositePath:T}).strict()]),Ii={axis:Te,levelId:S,scope:s.discriminatedUnion("kind",[s.object({kind:s.literal("level")}).strict(),s.object({kind:s.literal("branch"),parent:T}).strict()]),target:vi,direction:s.enum(["asc","desc"]),nulls:s.enum(["first","last"])},Ft=s.object(Ii).strict(),Si=s.object({id:S,axis:Te,levelId:S,direction:s.enum(["top","bottom"]),count:hi,measureId:S,oppositePath:T,others:s.boolean()}).strict(),ue=s.number().finite(),wi=s.object({id:S,axis:Te,levelId:S,measureId:S,operator:s.enum(["=","!=",">",">=","<","<=","between","not between"]),value:s.union([ue,s.tuple([ue,ue]).readonly()])}).strict().superRefine((e,t)=>{const n=e.operator==="between"||e.operator==="not between";n!==Array.isArray(e.value)?_(t,["value"],n?"A range condition needs a low and a high bound.":"A comparison needs one number."):n&&e.value[0]>e.value[1]&&_(t,["value"],"The low bound must not exceed the high bound.");}),Mt=s.object({source:$e,rows:s.array(be).min(1).readonly(),columns:s.array(be).readonly(),measures:s.array(xt).min(1).readonly(),filters:$t.optional(),joinPlan:pi.optional(),relationshipHint:s.object({relationshipIds:s.array(fi).optional()}).strict().optional(),sorts:s.array(Ft).readonly(),rankings:s.array(Si).readonly(),measureFilters:s.array(wi).readonly().optional()}).strict();function Et(e){return JSON.stringify([e.axis,e.levelId,e.scope.kind,e.scope.kind==="branch"?It(e.scope.parent):null]);}function _(e,t,n){e.addIssue({code:"custom",path:t,message:n});}function x(e,t,n){new Set(e).size!==e.length&&_(t,n,"Duplicate identity.");}function ne(e,t,n,i,o,a=!1){n.length>e[t].length&&_(i,o,"Path exceeds axis depth."),n.forEach((r,l)=>{var c;if(r.levelId!==((c=e[t][l])==null?void 0:c.id)&&_(i,[...o,l],"Path must be an ordered axis prefix."),r.member.kind==="others"){const m=r.member.rankingId;(a||l!==n.length-1||!e.rankings.some(u=>u.id===m&&u.others&&u.axis===t&&u.levelId===r.levelId))&&_(i,[...o,l],"Others must terminate a path at its enabled ranking and cannot be a sort/rank target.");}});}function Nt(e,t,n,i){x(t.map(Et),n,i),t.forEach((o,a)=>{const r=[...i,a],l=e[o.axis].findIndex(c=>c.id===o.levelId);if(l<0&&_(n,r,"Sort level is not on its axis."),o.scope.kind==="branch"&&(ne(e,o.axis,o.scope.parent,n,[...r,"scope","parent"],!0),o.scope.parent.length!==l&&_(n,r,"Branch sort must name the immediate parent of its level.")),o.target.kind==="measure"){const c=o.target.measureId;e.measures.some(m=>m.id===c)||_(n,r,"Unknown sort measure."),ne(e,o.axis==="rows"?"columns":"rows",o.target.oppositePath,n,[...r,"target","oppositePath"],!0);}});}function K(e,t,n,i){e&&(e.kind!==t.kind||e.kind==="semantic"&&t.kind==="semantic"&&e.domainId!==t.domainId||e.kind==="physical"&&t.kind==="physical"&&e.connectionId!==t.connectionId)&&_(n,i,"Field source must belong to the same semantic domain or physical connection.");}function ce(e,t,n){(e.aggregationBehavior==="snapshot"||e.aggregationBehavior==="weighted"||e.aggregationStrategy==="weighted")&&_(t,n,"This measure semantic requires a later capability.");}function Tt(e,t){x([...e.rows,...e.columns,...e.measures].map(a=>a.id),t,[]),x(e.rankings.map(a=>a.id),t,["rankings"]),x(e.rankings.map(a=>JSON.stringify([a.axis,a.levelId])),t,["rankings"]);for(const a of["rows","columns"])e[a].forEach((r,l)=>{r.grain&&r.field.dataType!==void 0&&!["date","datetime","unknown"].includes(r.field.dataType)&&_(t,[a,l,"grain"],"Grain requires a temporal field.");});const n=[...e.rows,...e.columns,...e.measures.filter(a=>a.kind==="aggregate")];for(const a of n)if(K(a.field.source,e.source,t,[a.id,"field","source"]),a.field.derivedField){a.field.derivedField.computeStage!=="row"&&_(t,[a.id],"Aggregate-stage calculations cannot be grouped or wrapped in an aggregate."),ce(a.field.derivedField,t,[a.id]);for(const r of Object.values(a.field.derivedField.inputs))K(r.field.source,e.source,t,[a.id,"inputs"]);}for(const a of e.measures)if(a.kind==="calculated"){(a.definition.computeStage!=="aggregate"||a.definition.resultRole!=="measure")&&_(t,[a.id],"Calculated measures require aggregate stage and measure role."),ce(a.definition,t,[a.id]);for(const r of Object.values(a.definition.inputs))K(r.field.source,e.source,t,[a.id,"inputs"]);}const i=a=>{const r=(l,c)=>{var m,u;if((l.aggregate||((m=l.derivedField)==null?void 0:m.computeStage)==="aggregate")&&_(t,c,"Aggregate/HAVING filters are not supported."),l.derivedField){ce(l.derivedField,t,c);for(const p of Object.values(l.derivedField.inputs))K(p.field.source,e.source,t,c);}for(const p of((u=l.calculatedFormula)==null?void 0:u.inputFields)??[])r(p,c);};for(const l of a.conditions)r(l.field,["filters",l.id]);a.groups.forEach(i);};if(e.filters&&i(e.filters),e.joinPlan){const a=[e.joinPlan.baseEntity,...e.joinPlan.joins.flatMap(r=>[r.source,r.target])];(new Set(a.map(r=>r.connectionId)).size>1||e.source.kind==="physical"&&a[0].connectionId!==e.source.connectionId)&&_(t,["joinPlan"],"Joins must stay within the source connection."),x(e.joinPlan.joins.map(r=>r.id),t,["joinPlan","joins"]);}Nt(e,e.sorts,t,["sorts"]);const o=e.measureFilters??[];x(o.map(a=>a.id),t,["measureFilters"]),x(o.map(a=>JSON.stringify([a.axis,a.levelId])),t,["measureFilters"]),o.forEach((a,r)=>{(!e[a.axis].some(l=>l.id===a.levelId)||!e.measures.some(l=>l.id===a.measureId))&&_(t,["measureFilters",r],"Unknown measure filter level or measure.");}),e.rankings.forEach((a,r)=>{(!e[a.axis].some(l=>l.id===a.levelId)||!e.measures.some(l=>l.id===a.measureId))&&_(t,["rankings",r],"Unknown ranking level or measure."),ne(e,a.axis==="rows"?"columns":"rows",a.oppositePath,t,["rankings",r,"oppositePath"],!0);});}const z=Mt.superRefine(Tt),ki=Mt.extend({rows:s.array(be).readonly(),measures:s.array(xt).readonly()}),Ai=ki.superRefine(Tt),$i=z.innerType().extend({kind:s.literal("matrix")}),Di=$i.superRefine(({kind:e,...t},n)=>{const i=z.safeParse(t);i.success||i.error.issues.forEach(o=>n.addIssue(o));}),xi="{member}",ze=s.object({visible:s.boolean(),position:s.enum(["before","after"]),label:s.string().optional()}).strict(),Ge=s.object({grand:ze,levels:s.record(S,ze).readonly(),skipRedundant:s.boolean().optional()}).strict(),Fi={layout:s.discriminatedUnion("kind",[s.object({kind:s.literal("compact")}).strict(),s.object({kind:s.literal("tabular"),repeatLabels:s.boolean()}).strict()]),absence:s.object({emptyText:s.string(),nullText:s.string()}).strict(),levelLabels:s.record(S,s.string()).readonly(),measureLabels:s.record(S,s.string()).readonly(),levelFormats:s.record(S,Z).readonly(),measureFormats:s.record(S,Z).readonly(),totals:s.object({rows:Ge,columns:Ge}).strict()},je=s.object(Fi).strict(),Mi=s.object({depth:s.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),overrides:s.array(s.object({path:T,expanded:s.boolean()}).strict()).readonly()}).strict(),Qe=Mi.superRefine((e,t)=>x(e.overrides.map(n=>It(n.path)),t,["overrides"])),Ei={rows:Qe,columns:Qe},se=s.object(Ei).strict(),Ni=se.extend({sorts:s.array(Ft).readonly()}).strict(),Ti=Ni.superRefine((e,t)=>x(e.sorts.map(Et),t,["sorts"]));function re(e,t){var c,m;const{spec:n,presentation:i,defaults:o,session:a}=e,r=new Set([...n.rows,...n.columns].map(u=>u.id)),l=new Set(n.measures.map(u=>u.id));for(const u of["levelLabels","levelFormats","measureLabels","measureFormats"]){const p=u.startsWith("level")?r:l;for(const f of Object.keys(i[u]))p.has(f)||_(t,["presentation",u,f],"Unknown presentation reference.");}for(const[u,p]of Object.entries(i.measureFormats))p.type==="temporal_bucket"&&_(t,["presentation","measureFormats",u],"Measures cannot own temporal bucket formats.");for(const[u,p]of Object.entries(i.levelFormats))p.type==="temporal_bucket"&&!((c=[...n.rows,...n.columns].find(f=>f.id===u))!=null&&c.grain)&&_(t,["presentation","levelFormats",u],"Temporal bucket formats require a grain.");for(const u of["rows","columns"]){(m=i.totals[u].grand.label)!=null&&m.includes(xi)&&_(t,["presentation","totals",u,"grand","label"],"The grand total has no member, so its label cannot use {member}.");const p=Object.keys(i.totals[u].levels);(p.length!==n[u].length||p.some(f=>!n[u].some(b=>b.id===f)))&&_(t,["presentation","totals",u],"Subtotal map must contain exactly the current axis levels.");for(const f of[o,...(a?[a]:[])])for(const b of f[u].overrides)ne(n,u,b.path,t,[u,"overrides"],!0),b.path.length||_(t,[u,"overrides"],"Use depth to expand/collapse the root.");}a&&Nt(n,a.sorts,t,["session","sorts"]);}const Ri=s.object({spec:z,presentation:je,defaults:se,session:Ti.optional()}).strict(),Ua=Ri.superRefine(re),ji=s.object({version:s.literal(1),spec:z,presentation:je,defaultView:se}).strict(),Ci=ji.superRefine((e,t)=>re({...e,defaults:e.defaultView},t)),Oi=Ci.innerType().extend({spec:Ai}),Va=Oi.superRefine((e,t)=>re({...e,defaults:e.defaultView},t)),Xe=s.object({spec:z,presentation:je}).strict(),Yi=s.union([Xe.extend({mode:s.literal("layout"),format:s.enum(["csv","xlsx","pdf"]),expansion:s.union([se.extend({kind:s.literal("current")}).strict(),s.object({kind:s.literal("all")}).strict()])}).strict(),Xe.extend({mode:s.literal("flat"),format:s.enum(["csv","xlsx"])}).strict()]),Ha=Yi.superRefine((e,t)=>re({...e,defaults:e.mode==="layout"&&e.expansion.kind==="current"?e.expansion:{rows:{depth:0,overrides:[]},columns:{depth:0,overrides:[]}}},t));function za(e){return e&&"id"in e?e.id:void 0;}const Li="SUM";function $(e){return typeof e=="string"&&e.trim().length>0;}function q(e){return $(e)?e.trim().toLowerCase():"";}function Ga(e){const t=$(e.id)?e.id.trim():void 0;if(!t)return;const n=q(t),i=$(e.table)?e.table.trim():void 0;if(!(n===q(e.name)||i&&n===q(i)))return t;}function j(e){const t=$(e.datasetId)?e.datasetId.trim():void 0;if(t)return q(t)===q(e.datasetName)?void 0:t;}function Rt(e){if(e.kind!=="semantic")return e;const t=j(e),{datasetId:n,...i}=e;return{...i,...(t?{datasetId:t}:{})};}function Qa(e){return e?e.kind==="semantic"?!!($(e.domainId)&&($(e.datasetId)||$(e.datasetName))):e.kind==="physical"?$(e.connectionId)&&$(e.tableName):$(e.connectionId):!1;}function ve(e){if(!e)return"";if(e.kind==="semantic"){const t=j(e);return[e.kind,e.domainId,t?`datasetId:${t}`:`datasetName:${e.datasetName}`].join(":");}return e.kind==="physical"?[e.kind,e.connectionId,e.databaseName||"",e.schemaName||"",e.tableName].join(":"):[e.kind,e.connectionId,e.dialect||"",e.label||""].join(":");}function Ce(e,t){if(!e||!t)return e===t;if(e.kind!==t.kind)return!1;if(e.kind==="semantic"&&t.kind==="semantic"){if(e.domainId!==t.domainId)return!1;const n=j(e),i=j(t);return n&&i?n===i:e.datasetName===t.datasetName;}return ve(e)===ve(t);}function jt(e,t){return e.kind!=="semantic"||t.kind!=="semantic"?e:Rt({...e,datasetName:e.datasetName||t.datasetName,datasetId:j(e)||j(t),label:e.label||t.label,connectionId:e.connectionId||t.connectionId});}function Xa(e){const t=[];for(const n of e){const i=Rt(n),o=t.findIndex(a=>Ce(a,i));if(o===-1){t.push(i);continue;}t[o]=jt(t[o],i);}return t;}function Pi(e,t){return e.name===t.name&&Ce(e.source,t.source);}function Ka(e){return[e.source?ve(e.source):"unknown",Ct(e),e.name].filter(Boolean).join(":");}function Ct(e){return qi(e.aggregate||Li);}function qi(e){return e.trim().toUpperCase();}function Za(e,t){return{...e,label:e.label||t.label,role:e.role||t.role,dataType:e.dataType||t.dataType,source:e.source&&t.source?jt(e.source,t.source):e.source||t.source};}function Bi(e){for(let t=0;t<e.length;t+=1){const n=e[t];if(e.some((i,o)=>o!==t&&Yt(i,n)))return!1;}return!0;}function Ot(e,t){return Pi(e,t);}function Yt(e,t){return Ot(e,t)&&H(e)===H(t);}function Wi(e){return`Metric intent has duplicate measure "${e.name}" with the same aggregate (${H(e)}). Use different aggregates to request both, or remove one entry.`;}function Ke(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null;}function Ui(e,t,n){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){n.push(d("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",t));return;}Object.entries(e).forEach(([i,o])=>{if(!i.trim()){n.push(d("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${t}.${i}`));return;}(Array.isArray(o)?o.every(Ke):Ke(o))||n.push(d("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${t}.${i}`));});}}function Vi(e,t){return Oe(e,t).length===1;}function Hi(e,t){return Oe(e,t).length===1;}function Oe(e,t){return t.filter(i=>zi(e,i));}function zi(e,t){return Gi(e,t)?e.source?Ot(t,e):!0:!1;}function Gi(e,t){return!(t.name!==e.name||e.role!==void 0&&t.role!==void 0&&t.role!==e.role||Qi(e,t)&&H(t)!==H(e));}function Qi(e,t){return e.role==="measure"||t.role==="measure"||e.aggregate!==void 0||t.aggregate!==void 0;}function H(e){return Ct(e);}const Xi=/^(\d{4})-(\d{2})-(\d{2})$/,Lt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})$/;function ie(e){if(typeof e!="string")return null;const t=e.trim(),n=Xi.exec(t);if(n){const[,f,b,A]=n;return Ze(f,b,A)?new Date(Date.UTC(Number(f),Number(b)-1,Number(A))):null;}const i=Lt.exec(t);if(!i)return null;const[,o,a,r,l,c,m="00",,u]=i;if(!Ze(o,a,r)||!B(l,0,23)||!B(c,0,59)||!B(m,0,59)||!Ki(u))return null;const p=new Date(t);return Number.isFinite(p.getTime())?p:null;}function Ja(e){return typeof e!="string"||!Lt.test(e.trim())?null:ie(e);}function Ze(e,t,n){const i=Number(e),o=Number(t),a=Number(n);if(!Number.isInteger(i)||!Number.isInteger(o)||!Number.isInteger(a)||o<1||o>12)return!1;const r=new Date(Date.UTC(i,o-1,a));return r.getUTCFullYear()===i&&r.getUTCMonth()===o-1&&r.getUTCDate()===a;}function B(e,t,n){const i=Number(e);return Number.isInteger(i)&&i>=t&&i<=n;}function Ki(e){if(e==="Z")return!0;const t=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(t&&B(t[2],0,23)&&B(t[3],0,59));}function Je(e,t,n){if(e!==void 0){if(!g(e)){n.push(d("invalid_pagination","Pagination must be an object with positive integer page and pageSize.",t));return;}(!Number.isInteger(e.page)||typeof e.page!="number"||e.page<1)&&n.push(d("invalid_pagination_page","Pagination page must be a positive integer.",`${t}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&n.push(d("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${t}.pageSize`));}}function et(e){const t=/* @__PURE__ */new Set();for(const n of e){if(t.has(n))return n;t.add(n);}return null;}function Zi(e,t,n){if(!g(e)){n.push(d("invalid_input_binding","Input bindings must be structured objects.",t));return;}h(e.inputId)||n.push(d("invalid_input_binding","Input bindings need a non-empty inputId.",`${t}.inputId`)),e.kind!==void 0&&e.kind!=="filter"&&e.kind!=="control"&&n.push(d("invalid_input_binding","Input binding kind must be filter or control.",`${t}.kind`)),e.field!==void 0&&I(e.field,`${t}.field`,n),e.relationshipHint!==void 0&&Ye(e.relationshipHint,`${t}.relationshipHint`,n);}function Ye(e,t,n){if(!g(e)){n.push(d("invalid_relationship_hint","Relationship hints must be structured objects.",t));return;}e.relationshipIds!==void 0&&(!Array.isArray(e.relationshipIds)||e.relationshipIds.some(i=>!h(i)))&&n.push(d("invalid_relationship_hint","Relationship hint relationshipIds must be non-empty strings.",`${t}.relationshipIds`));}function Ji(e,t){var i,o;if(((i=e.source)==null?void 0:i.kind)!=="semantic"&&((o=e.source)==null?void 0:o.kind)!=="physical"&&t.push(d("invalid_input_options_source","Input options must use a semantic or physical source.","source")),h(e.inputId)||t.push(d("missing_input_options_input_id","Input options intent needs the inputId it populates.","inputId")),e.search!==void 0&&typeof e.search!="string"&&t.push(d("invalid_input_options_search","Input options search must be a string.","search")),e.matchValues!==void 0){const a=Jt(e.matchValues);a.ok||t.push(d("invalid_input_options_match_values",a.error,"matchValues")),typeof e.search=="string"&&e.search.trim()&&t.push(d("invalid_input_options_match_values","Input options matchValues cannot be combined with search.","matchValues"));}if(e.limit!==void 0&&(typeof e.limit!="number"||!Number.isFinite(e.limit)||!Number.isInteger(e.limit)||e.limit<=0)&&t.push(d("invalid_input_options_limit","Input options limit must be a positive finite number.","limit")),(!e.labelField||!h(e.labelField.name))&&t.push(d("missing_input_options_label_field","Input options intent needs a labelField.","labelField")),I(e.labelField,"labelField",t,{required:!0}),(!e.valueField||!h(e.valueField.name))&&t.push(d("missing_input_options_value_field","Input options intent needs a valueField.","valueField")),I(e.valueField,"valueField",t,{required:!0}),e.searchField!==void 0&&I(e.searchField,"searchField",t,{required:!0}),e.disambiguationFields!==void 0&&(Array.isArray(e.disambiguationFields)?e.disambiguationFields.forEach((a,r)=>{I(a,`disambiguationFields.${r}`,t,{required:!0});}):t.push(d("invalid_input_options_disambiguation_fields","Input options disambiguationFields must be an array of field refs.","disambiguationFields"))),[{field:e.labelField,path:"labelField"},{field:e.valueField,path:"valueField"},...(e.searchField?[{field:e.searchField,path:"searchField"}]:[]),...(Array.isArray(e.disambiguationFields)?e.disambiguationFields.map((a,r)=>({field:a,path:`disambiguationFields.${r}`})):[])].forEach(({field:a,path:r})=>{a!=null&&a.source&&!Ce(a.source,e.source)&&t.push(d("input_options_field_source_mismatch","Input option fields must belong to the declared option source.",`${r}.source`));}),e.dependencies!==void 0){const a=ta(e.dependencies);t.push(...a.errors),a.ok&&ia(e,t);}if(e.population!==void 0){const a=e.population;if(!g(a))t.push(d("invalid_input_options_population","Input options population must be a structured object.","population"));else{const r=a.kind;if(r!=="option_source"&&r!=="related_population"&&t.push(d("invalid_input_options_population","Input options population kind must be option_source or related_population.","population.kind")),r==="option_source"&&a.baseSource!==void 0&&t.push(d("invalid_input_options_population","Input options population baseSource is only valid for related_population.","population.baseSource")),r==="option_source"&&a.relationshipHint!==void 0&&t.push(d("invalid_input_options_population","Input options population relationshipHint is only valid for related_population.","population.relationshipHint")),r==="related_population"){we(a.baseSource,"population.baseSource",t),a.relationshipHint!==void 0&&Ye(a.relationshipHint,"population.relationshipHint",t);const l=a.ifUnreachable;l!==void 0&&l!=="option_source"&&t.push(d("invalid_input_options_population","Input options population ifUnreachable must be option_source.","population.ifUnreachable"));}}}}function ea(e,t){if(!(!("inputs"in e)||e.inputs===void 0)){if(!Array.isArray(e.inputs)){t.push(d("invalid_input_binding","Analytics intent inputs must be an array of input bindings.","inputs"));return;}e.inputs.forEach((n,i)=>Zi(n,`inputs.${i}`,t));}}function ta(e,t="protocol"){const n=[];if(!g(e))return n.push(d("invalid_input_options_dependencies","Input options dependencies must be a structured object.","dependencies")),{ok:!1,errors:n,warnings:[]};const i=e,o=i.mode;if(o!==void 0&&o!=="independent"&&o!=="explicit"&&o!=="all_applicable"&&n.push(d("invalid_input_options_dependencies","Input options dependencies mode must be independent, explicit, or all_applicable.","dependencies.mode")),me(i.includeInputIds,"dependencies.includeInputIds",n,"Input options includeInputIds must be non-empty strings."),me(i.excludeInputIds,"dependencies.excludeInputIds",n,"Input options excludeInputIds must be non-empty strings."),o==="all_applicable"&&i.includeInputIds!==void 0&&n.push(d("invalid_input_options_dependencies","All applicable dependencies cannot specify includeInputIds.","dependencies.includeInputIds")),me(i.omitInputIds,"dependencies.omitInputIds",n,"Input options omitInputIds must be non-empty strings."),Array.isArray(i.omitInputIds)){const a=new Set(Array.isArray(i.includeInputIds)?i.includeInputIds:[]);(o!=="explicit"||new Set(i.omitInputIds).size!==i.omitInputIds.length||i.omitInputIds.some(r=>!a.has(r)))&&n.push(d("invalid_input_options_dependencies","A browse override may only omit unique ids from an explicit includeInputIds list.","dependencies.omitInputIds"));}return t==="dashboard"&&na(i,n),{ok:n.length===0,errors:n,warnings:[]};}function na(e,t){const{mode:n,includeInputIds:i,excludeInputIds:o}=e;n===void 0&&t.push(d("invalid_input_options_dependencies","Dashboard option dependencies must declare a mode.","dependencies.mode"));for(const[a,r]of[["dependencies.includeInputIds",i],["dependencies.excludeInputIds",o]])Array.isArray(r)&&new Set(r).size!==r.length&&t.push(d("invalid_input_options_dependencies","Dashboard option dependency input IDs must be unique.",a));n==="independent"&&(i!==void 0||o!==void 0)&&t.push(d("invalid_input_options_dependencies","Independent dashboard dependencies cannot specify input IDs.","dependencies")),n==="explicit"&&(!Array.isArray(i)||i.length===0||o!==void 0)&&t.push(d("invalid_input_options_dependencies","Explicit dashboard dependencies require included input IDs and cannot specify exclusions.","dependencies"));}function ia(e,t){var o,a,r;const n=new Set(Array.isArray(e.inputs)?e.inputs.map(l=>g(l)?l.inputId:void 0).filter(l=>typeof l=="string"):[]),i=new Set(((o=e.dependencies)==null?void 0:o.omitInputIds)||[]);for(const l of((a=e.dependencies)==null?void 0:a.includeInputIds)||[])!n.has(l)&&!i.has(l)&&t.push(d("invalid_input_options_dependencies",`Input options dependency "${l}" is not declared in inputs.`,"dependencies.includeInputIds"));for(const l of((r=e.dependencies)==null?void 0:r.excludeInputIds)||[])l!==e.inputId&&!n.has(l)&&t.push(d("invalid_input_options_dependencies",`Input options dependency exclusion "${l}" is not the populated inputId and is not declared in inputs.`,"dependencies.excludeInputIds"));}function me(e,t,n,i){e!==void 0&&(!Array.isArray(e)||e.some(o=>!h(o)))&&n.push(d("invalid_input_options_dependencies",i,t));}new Set(Kt);function aa(e,t){if(e.analysis===void 0)return;if(!g(e.analysis)){t.push(d("invalid_measure_analysis","Metric analysis must be a structured object.","analysis"));return;}if(e.analysis.kind!=="period_change"){t.push(d("invalid_measure_analysis","Metric analysis kind is not supported.","analysis.kind"));return;}e.dateField||t.push(d("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||t.push(d("missing_analysis_time_grain","Period-change analysis needs a timeGrain.","timeGrain")),e.analysis.orderBy!==void 0&&e.analysis.orderBy!=="absolute_change"&&e.analysis.orderBy!=="positive_change"&&e.analysis.orderBy!=="negative_change"&&e.analysis.orderBy!=="period"&&t.push(d("invalid_measure_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:n}=e.analysis;n!==void 0&&ae(n,"analysis.timeWindow",t);}function ae(e,t,n){const i=Se(e,{use:"analysis"});i.ok||n.push(d("invalid_time_window",pt(i.refusal),i.refusal.path?`${t}.${i.refusal.path}`:t));}function tt(e,t,n){if(e!==void 0){if(!Array.isArray(e)){n.push(d("invalid_analytics_filters","Analytics filters must be an array.",t));return;}e.forEach((i,o)=>{var c;const a=`${t}.${o}`;if(!g(i)){n.push(d("invalid_analytics_filter","Analytics filter must be a structured object.",a));return;}const r=i;I(r.field,`${a}.field`,n,{required:!0}),r.scope!==void 0&&r.scope!=="row"&&r.scope!=="aggregate"&&n.push(d("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${a}.scope`)),r.scope==="aggregate"&&((c=r.field)==null?void 0:c.role)!==void 0&&r.field.role!=="measure"&&n.push(d("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${a}.scope`));const l=r.operator==="is_null"||r.operator==="is_not_null";if(r.operator!==void 0&&r.operator!=="="&&r.operator!=="!="&&r.operator!=="in"&&r.operator!=="not_in"&&r.operator!=="contains"&&r.operator!=="not_contains"&&r.operator!=="between"&&r.operator!=="not_between"&&r.operator!==">"&&r.operator!==">="&&r.operator!=="<"&&r.operator!=="<="&&r.operator!=="is_null"&&r.operator!=="is_not_null"&&n.push(d("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${a}.operator`)),r.values===void 0&&!l&&n.push(d("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",a)),l&&r.values!==void 0){n.push(d("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${a}.values`));return;}if(r.values!==void 0&&!Array.isArray(r.values)){n.push(d("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${a}.values`));return;}if(r.values!==void 0){const m=r.values.length;if(r.operator==="between"||r.operator==="not_between"){m!==2&&n.push(d("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${a}.values`));return;}(r.operator==="contains"||r.operator==="not_contains"||r.operator==="="||r.operator==="!="||r.operator===">"||r.operator===">="||r.operator==="<"||r.operator==="<="||r.operator===void 0)&&m!==1&&n.push(d("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${a}.values`));}});}}function Pt(e){var i;const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:n,repairHints:[{code:"invalid_analytics_intent",recommendedNextStep:"Send one structured analytics intent object with kind, source, and required fields."}]};if(e.kind==="matrix"){const o=Di.safeParse(e);return o.success||t.push(...o.error.issues.map(a=>d("invalid_matrix_intent",a.message,a.path.join(".")))),{ok:t.length===0,errors:t,warnings:n,repairHints:nt(t)};}if(e.version!==void 0&&e.version!==1&&t.push(d("invalid_version","Analytics intent version must be 1.","version")),we(e.source,"source",t),sa(e,t),ea(e,t),"relationshipHint"in e&&e.relationshipHint!==void 0&&Ye(e.relationshipHint,"relationshipHint",t),e.kind==="metric"){const o=Array.isArray(e.measures)?e.measures.filter(a=>g(a)&&h(a.name)):[];if(!Array.isArray(e.measures)||e.measures.length===0?t.push(d("missing_measure","Metric intent needs at least one measure.","measures")):e.measures.some(a=>!g(a)||!h(a.name))&&t.push(d("invalid_measure_list","Metric intent measures must be an array of field references with names.","measures")),o.forEach((a,r)=>{I(a,`measures.${r}`,t,{required:!0});}),o.length>0&&!Bi(o)){const a=o.find((r,l)=>o.some((c,m)=>m!==l&&Yt(c,r)));a&&t.push(d("duplicate_measure",Wi(a),"measures"));}if(g(e.primaryMeasure)&&h(e.primaryMeasure.name)&&Oe(e.primaryMeasure,o).length>1&&t.push(d("ambiguous_primary_measure","Metric intent primaryMeasure must identify exactly one selected measure.","primaryMeasure")),e.primaryMeasure!==void 0&&(I(e.primaryMeasure,"primaryMeasure",t,{required:!0}),g(e.primaryMeasure)&&h(e.primaryMeasure.name)&&o.length>0&&!Vi(e.primaryMeasure,o)&&t.push(d("invalid_primary_measure","Metric intent primaryMeasure must match one measure field reference.","primaryMeasure"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?t.push(d("invalid_measure_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(a=>!g(a)||!h(a.name))&&t.push(d("invalid_measure_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&I(e.dateField,"dateField",t),e.timeWindow!==void 0&&(ae(e.timeWindow,"timeWindow",t),e.dateField||t.push(d("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),tt(e.filters,"filters",t),Array.isArray(e.dimensions)&&e.dimensions.forEach((a,r)=>{I(a,`dimensions.${r}`,t);}),e.orderBy!==void 0){if(!g(e.orderBy))t.push(d("invalid_measure_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(I(e.orderBy.field,"orderBy.field",t,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&t.push(d("invalid_measure_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),g(e.orderBy.field)&&h(e.orderBy.field.name)){const a=[...o,...(e.timeGrain&&e.dateField&&g(e.dateField)?[e.dateField]:[]),...(Array.isArray(e.dimensions)?e.dimensions.filter(r=>g(r)&&h(r.name)):[])];a.length>0&&!Hi(e.orderBy.field,a)&&t.push(d("invalid_measure_order_by","Metric intent orderBy.field must match one selected measure, grouped dateField, or dimension.","orderBy.field"));}}aa(e,t);}else if(e.kind==="records"){if(!Array.isArray(e.fields)||e.fields.length===0?t.push(d("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(o=>!g(o)||!h(o.name))&&t.push(d("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((o,a)=>{I(o,`fields.${a}`,t);}),e.dateField!==void 0&&I(e.dateField,"dateField",t),Je(e.pagination,"pagination",t),e.timeWindow!==void 0&&(ae(e.timeWindow,"timeWindow",t),e.dateField||t.push(d("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),tt(e.filters,"filters",t),Array.isArray(e.filters)&&e.filters.forEach((o,a)=>{g(o)&&o.scope==="aggregate"&&t.push(d("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${a}.scope`));}),e.orderBy!==void 0&&(g(e.orderBy)?(I(e.orderBy.field,"orderBy.field",t,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&t.push(d("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):t.push(d("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy"))),e.totals!==void 0)if(!g(e.totals))t.push(d("invalid_records_totals","Records totals must be a structured server totals request.","totals"));else{e.totals.mode!=="server"&&t.push(d("invalid_records_totals","Records totals mode must be server.","totals.mode"));const o=e.totals.measures;!Array.isArray(o)||o.length===0?t.push(d("missing_records_totals_measures","Records server totals need at least one measure.","totals.measures")):o.forEach((a,r)=>{I(a,`totals.measures.${r}`,t,{required:!0}),(!g(a)||a.role!=="measure")&&t.push(d("invalid_records_totals_measure","Records server totals measures must be measure field references.",`totals.measures.${r}.role`));});}}else e.kind==="inputOptions"?Ji(e,t):e.kind==="sql"?(((i=e.source)==null?void 0:i.kind)!=="sql"&&t.push(d("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),h(e.sql)||t.push(d("missing_sql","SQL analytics intent needs SQL text.","sql")),Ui(e.defaultParameters,"defaultParameters",t),Array.isArray(e.fields)&&e.fields.forEach((o,a)=>{I(o,`fields.${a}`,t);}),Je(e.pagination,"pagination",t)):t.push(d("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:t.length===0,errors:t,warnings:n,repairHints:nt(t)};}function sa(e,t){if(!(!("derivedFields"in e)||e.derivedFields===void 0)){if(!Array.isArray(e.derivedFields)){t.push(d("invalid_derived_fields","Analytics intent derivedFields must be an array of derived field definitions.","derivedFields"));return;}e.derivedFields.forEach((n,i)=>{Ae(n).errors.forEach(a=>{t.push({...a,path:a.path?`derivedFields.${i}.${a.path}`:`derivedFields.${i}`});});});}}function ra(e){const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_operation_intent","Operation intent must be a structured object.")],warnings:n,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&t.push(d("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?t.push(d("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((i,o)=>{h(i.id)||t.push(d("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${o}.id`)),i.timeWindow!==void 0&&ae(i.timeWindow,`obligations.${o}.timeWindow`,t),h(i.prompt)||t.push(d("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${o}.prompt`));});else if(e.kind==="dashboard_change"){if(h(e.instruction)||t.push(d("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const i=Pt(e.analyticsIntent);t.push(...i.errors),n.push(...i.warnings);}}else t.push(d("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:t.length===0,errors:t,warnings:n,repairHints:qt(t)};}function es(e){const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:n,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&t.push(d("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&t.push(d("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const i=ra(e.operationIntent);return t.push(...i.errors),n.push(...i.warnings),Array.isArray(e.plannedToolCalls)||t.push(d("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:t.length===0,errors:t,warnings:n,repairHints:qt(t)};}function qt(e){return e.map(t=>({code:t.code,recommendedNextStep:t.code==="missing_obligations"?"Normalize the user request into one or more typed analytics obligations before recovery planning.":"Correct the operation/recovery contract shape before planning execution."}));}function nt(e){return e.map(t=>{switch(t.code){case"invalid_matrix_intent":return{code:t.code,recommendedNextStep:`Correct MatrixSpec at ${t.path||"the definition"}: ${t.message} Keep presentation and matrixWindowRequest outside the intent.`};case"missing_source":return{code:t.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_measure":return{code:t.code,fieldRole:"measure",recommendedNextStep:"Choose one exact measure from the grounded schema candidates."};case"missing_record_fields":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_matrix_rows":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Choose at least one row axis level for the matrix table."};case"missing_matrix_values":return{code:t.code,fieldRole:"measure",recommendedNextStep:"Choose at least one value field for the matrix table."};case"unsupported_matrix_sql_source":return{code:t.code,fieldRole:"source",recommendedNextStep:"Use a semantic or explorer-backed source for matrix tables; raw SQL matrix tables are not supported."};case"missing_input_options_input_id":return{code:t.code,fieldRole:"input",recommendedNextStep:"Provide the inputId that these option values populate."};case"missing_input_options_label_field":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Provide the human-readable field used as option labels."};case"missing_input_options_value_field":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Provide the stable field used as option values."};case"missing_sql":return{code:t.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:t.code,fieldRole:"sql",recommendedNextStep:"Use one canonical SQL text location for the intent; prefer top-level sql."};case"missing_semantic_domain":case"missing_dataset_name":case"missing_connection_id":case"missing_table_name":return{code:t.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return;}}).filter(t=>!!t);}function oa(e,t,n,i){if(!e||typeof e!="object"){n.push(d("invalid_view","Dashboard view must be an object.",t));return;}if(h(e.title)||n.push(d("missing_view_title","Dashboard view needs a title.",t)),!e.presentation||typeof e.presentation!="object"){n.push(d("missing_presentation","Dashboard view needs a presentation.",`${t}.presentation`));return;}if(e.presentation.kind==="text"){h(e.text)||i.push(d("missing_text_content","Text views should include text content.",`${t}.text`));return;}if(!e.analytics){n.push(d("missing_view_analytics","Non-text dashboard views need analytics intent.",`${t}.analytics`));return;}e.presentation.kind==="matrixTable"&&e.analytics.kind!=="matrix"&&n.push(d("invalid_matrix_view_analytics","Matrix table views need matrix analytics intent.",`${t}.analytics.kind`));const o=Pt(e.analytics);for(const a of o.errors)n.push(d(a.code,a.message,`${t}.analytics${a.path?`.${a.path}`:""}`));for(const a of o.warnings)i.push(d(a.code,a.message,`${t}.analytics${a.path?`.${a.path}`:""}`));}function ts(e){const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:n};e.version!==1&&t.push(d("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&t.push(d("invalid_kind","Experience intent kind must be dashboard.")),h(e.title)||t.push(d("missing_title","Dashboard intent needs a title.","title"));const i=Array.isArray(e.inputs)?e.inputs:[],o=et(i.filter(g).map(c=>c.id).filter(c=>typeof c=="string"));o&&t.push(d("duplicate_input_id",`Duplicate input id: ${o}.`,"inputs"));for(const[c,m]of i.entries()){const u=`inputs.${c}`;if(!g(m)){t.push(d("invalid_input","Dashboard input must be an object.",u));continue;}h(m.id)||t.push(d("missing_input_id","Input needs an id.",`${u}.id`)),h(m.label)||t.push(d("missing_input_label","Input needs a label.",`${u}.label`)),!m.field||!h(m.field.name)?t.push(d("missing_input_field","Input needs a field.",`${u}.field`)):I(m.field,`${u}.field`,t);}const a=Array.isArray(e.sections)?e.sections:[];a.length===0&&t.push(d("missing_sections","Dashboard intent needs at least one section.","sections"));const r=a.flatMap(c=>c&&typeof c=="object"&&Array.isArray(c.views)?c.views.filter(g).map(m=>m.id).filter(m=>!!m):[]),l=et(r);l&&t.push(d("duplicate_view_id",`Duplicate dashboard view id: ${l}.`,"sections"));for(const[c,m]of a.entries()){const u=`sections.${c}`;if(!m||typeof m!="object"){t.push(d("invalid_section","Dashboard section must be an object.",u));continue;}if(h(m.title)||t.push(d("missing_section_title","Dashboard section needs a title.",u)),!Array.isArray(m.views)||m.views.length===0){t.push(d("missing_section_views","Dashboard section needs at least one view.",`${u}.views`));continue;}for(const[p,f]of m.views.entries())oa(f,`${u}.views.${p}`,t,n);}return{ok:t.length===0,errors:t,warnings:n};}export{ra as $,Zn as A,T as B,ye as C,ti as D,$a as E,vi as F,Ft as G,Si as H,wi as I,Et as J,z as K,Jn as L,ze as M,xi as N,je as O,Qe as P,se as Q,Ti as R,Ua as S,Ci as T,Ha as U,$e as V,Zt as W,Jt as X,ie as Y,ta as Z,Pt as _,xa as a,Di as a$,es as a0,ts as a1,Ae as a2,xe as a3,qn as a4,Bn as a5,Fe as a6,zn as a7,ga as a8,Gn as a9,Xa as aA,Ka as aB,Ct as aC,Za as aD,dn as aE,ua as aF,dt as aG,pn as aH,cn as aI,ca as aJ,E as aK,gn as aL,an as aM,Q as aN,ma as aO,Se as aP,pa as aQ,fa as aR,pt as aS,ha as aT,vt as aU,Xn as aV,Kn as aW,wa as aX,ka as aY,U as aZ,ba as a_,gt as aa,yt as ab,Ue as ac,bt as ad,ya as ae,_a as af,ii as ag,Ra as ah,ja as ai,Ca as aj,wt as ak,Re as al,Oa as am,Ya as an,La as ao,si as ap,Pa as aq,qa as ar,Ba as as,Wa as at,za as au,Ga as av,j as aw,Rt as ax,Ce as ay,jt as az,ni as b,ne as b0,mn as b1,Sa as b2,Ia as b3,Ai as b4,Va as b5,Mn as b6,De as b7,He as b8,va as b9,en as ba,St as c,Ma as d,Ta as e,_e as f,ei as g,Na as h,Da as i,Be as j,F as k,Qa as l,It as m,Fa as n,Pi as o,Ja as p,ve as q,ot as r,Ea as s,$t as t,Aa as u,Te as v,gi as w,Dt as x,be as y,xt as z};
1
+ import{M as Pe,z as Z,y as Bt,E as Wt,F as Ut,H as Vt,J as Ht,x as zt,g as it,h as pe,j as Gt,o as Qt,k as Xt,b as Kt}from"./analytics-base-schemas-DMFrDqn_.js";import{z as s}from"zod";function Zt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";}function Jt(e){return!Array.isArray(e)||e.length===0||e.length>Pe||!e.every(Zt)?{ok:!1,error:`matchValues must be 1 to ${Pe} string, number or boolean values.`}:{ok:!0,values:e};}function en(e,t){const n=e.map((i,o)=>`${t[o]} ${nn(i)}`);return s.union(e,{errorMap:(i,o)=>{if(i.code!==s.ZodIssueCode.invalid_union)return{message:o.defaultError};const a=i.path.length,r=o.data&&typeof o.data=="object"&&!Array.isArray(o.data)?Object.keys(o.data):[],l=i.unionErrors.map((p,f)=>{const b=tn(e[f]);return{index:f,issues:p.issues,overlap:b?r.filter(A=>b.includes(A)).length:0};}).filter(({issues:p})=>!p.every(f=>f.code===s.ZodIssueCode.invalid_type&&f.path.length===a)).filter(({overlap:p})=>!r.length||p>0);if(!l.length){const p=r.length?` Its keys (${r.join(", ")}) belong to none of them.`:"";return{message:`Matches none of: ${n.join("; ")}.${p}`};}const c=l.reduce((p,f)=>f.overlap>p.overlap||f.overlap===p.overlap&&f.issues.length<p.issues.length?f:p),m=c.issues.slice(0,4).map(p=>{const f=p.path.slice(a).join(".");return f?`${p.message} at ${f}`:p.message;}),u=c.issues.length>4?` (and ${c.issues.length-4} more)`:"";return{message:`Matches none of: ${n.join("; ")}. Nearest is the ${t[c.index]}: ${m.join("; ")}${u}`};}});}function tn(e){let t=e;for(;t instanceof s.ZodEffects;)t=t._def.schema;return t instanceof s.ZodObject?Object.keys(t.shape):void 0;}function nn(e){let t=e;for(;t instanceof s.ZodEffects;)t=t._def.schema;return t instanceof s.ZodObject?`{ ${Object.entries(t.shape).map(([i,o])=>o.isOptional()?`${i}?`:i).join(", ")} }`:"";}const an={minute:5256e3,hour:87600,day:3650,week:520,month:120,quarter:40,year:10},N=s.enum(["day","week","month","quarter","year"]),sn=s.enum(["minute","hour"]),rn=s.enum(["minute","hour","day","week","month","quarter","year"]),fe=s.number().int().positive(),J=s.number().int(),D={lastSubDay:s.object({mode:s.literal("last"),n:fe,unit:sn,complete:s.literal(!1).optional(),relativeTo:s.literal("latest_data").optional()}),last:s.object({mode:s.literal("last"),n:fe,unit:N,complete:s.boolean().optional(),relativeTo:s.literal("latest_data").optional()}),this:s.object({mode:s.literal("this"),unit:N,toDate:s.boolean().optional(),boundary:s.enum(["first_day","last_day"]).optional()}),previous:s.object({mode:s.literal("previous"),unit:N}),between:s.object({mode:s.literal("between"),unit:N,from:J,to:J})},he={check:e=>e.boundary===void 0||e.unit==="month",message:'A month boundary requires unit "month".'},at=e=>s.object({kind:s.literal("periods"),unit:N,from:J,to:J,toDate:s.boolean().optional(),anchor:s.union([s.enum(["now","latest_data"]),e])}),st=s.object({lastComplete:N}),rt=at(st.strict()).strict(),W={periods:at(st),rolling:s.object({kind:s.literal("rolling"),unit:rn,n:fe,anchor:s.enum(["now","latest_data"])}),monthDay:s.object({kind:s.literal("monthDay"),day:s.enum(["first","last"])})},on={"<":"start",">=":"start","<=":"end",">":"end"};function ot(e){return on[e];}function ua(e,t){const n=ot(e);return n==="start"?[t[0]]:n==="end"?[t[1]]:[t[0],t[1]];}function dn(e,t){return e==="between"||e==="not between"?!0:ot(e)?!t||t.kind==="monthDay"||t.anchor!=="latest_data":!1;}function F(e,t={}){const n=ln(e);if(!(!n||dt(n,t)))return un(n);}function dt(e,t={}){if(e.kind==="periods")return e.from>e.to?{rule:"W1",message:`from (${e.from}) is after to (${e.to}).`,path:"from"}:e.toDate&&e.to!==0?{rule:"W2",message:`toDate needs to 0, not ${e.to}.`,path:"toDate"}:typeof e.anchor=="object"&&e.to>0?{rule:"W3",message:`A window ending at the last complete ${e.anchor.lastComplete} can't reach past it (to ${e.to}).`,path:"to"}:void 0;if(e.kind!=="rolling")return;if(!Number.isInteger(e.n)||e.n<1)return{rule:"W4",message:`n (${e.n}) must be a whole number of at least 1.`,path:"n"};const n=an[e.unit];if(t.authoring&&e.n>n)return{rule:"limit",message:`At most ${n} ${e.unit}s (ten years).`,path:"n",max:n};}function ln(e){if(!e||typeof e!="object")return;if("kind"in e){for(const r of Object.values(W)){const l=r.safeParse(e);if(l.success)return l.data;}return;}const t=D.lastSubDay.safeParse(e),n=t.success?t:D.last.safeParse(e);if(n.success){const{n:r,unit:l,complete:c,relativeTo:m}=n.data,u=m??"now";return c?{kind:"periods",unit:l,from:-r,to:-1,anchor:u}:{kind:"rolling",unit:l,n:r,anchor:u};}const i=D.this.safeParse(e);if(i.success){const{unit:r,toDate:l,boundary:c}=i.data;return he.check(i.data)?c?{kind:"monthDay",day:c==="first_day"?"first":"last"}:{kind:"periods",unit:r,from:0,to:0,...(l?{toDate:!0}:{}),anchor:"now"}:void 0;}const o=D.previous.safeParse(e);if(o.success)return{kind:"periods",unit:o.data.unit,from:-1,to:-1,anchor:"now"};const a=D.between.safeParse(e);if(a.success){const{unit:r,from:l,to:c}=a.data;return{kind:"periods",unit:r,from:l,to:c,anchor:"now"};}}function un(e){switch(e.kind){case"periods":{const{unit:t,anchor:n}=e;return typeof n=="object"&&n.lastComplete===t?{kind:"periods",unit:t,from:e.from-1,to:e.to-1,anchor:"now"}:{kind:"periods",unit:t,from:e.from,to:e.to,...(e.toDate?{toDate:!0}:{}),anchor:typeof n=="object"?{lastComplete:n.lastComplete}:n};}case"rolling":return{kind:"rolling",unit:e.unit,n:e.n,anchor:e.anchor};case"monthDay":return{kind:"monthDay",day:e.day};}}const y=(e,t,n,i)=>{const o=F(i);if(!o)throw new Error(`The preset ${e} is not a relative date window.`);return{id:e,label:t,category:n,window:o};},v=(e,t,n)=>({kind:"periods",unit:e,from:t,to:n,anchor:"now"}),C=(e,t)=>({kind:"rolling",unit:e,n:t,anchor:"now"}),cn=[y("last_30_minutes","Last 30 minutes","time",C("minute",30)),y("last_1_hour","Last 1 hour","time",C("hour",1)),y("last_4_hours","Last 4 hours","time",C("hour",4)),y("last_12_hours","Last 12 hours","time",C("hour",12)),y("last_24_hours","Last 24 hours","time",C("hour",24)),y("today","Today","day",v("day",0,0)),y("yesterday","Yesterday","day",v("day",-1,-1)),y("first_day_of_month","First day of the month","day",{kind:"monthDay",day:"first"}),y("last_day_of_month","Last day of the month","day",{kind:"monthDay",day:"last"}),y("last_7_days","Last 7 days","day",v("day",-6,0)),y("last_30_days","Last 30 days","day",v("day",-29,0)),y("last_90_days","Last 90 days","day",v("day",-89,0)),y("this_week","This week","week",v("week",0,0)),y("last_week","Last week","week",v("week",-1,-1)),y("last_2_weeks","Last 2 weeks","week",v("week",-2,-1)),y("this_month","This month","month",v("month",0,0)),y("last_month","Last month","month",v("month",-1,-1)),y("last_3_months","Last 3 months","month",v("month",-3,-1)),y("last_6_months","Last 6 months","month",v("month",-6,-1)),y("last_9_months","Last 9 months","month",v("month",-9,-1)),y("last_12_months","Last 12 months","month",v("month",-12,-1)),y("this_quarter","This quarter","quarter",v("quarter",0,0)),y("last_quarter","Last quarter","quarter",v("quarter",-1,-1)),y("last_4_quarters","Last 4 quarters","quarter",v("quarter",-4,-1)),y("this_year","This year","year",v("year",0,0)),y("last_year","Last year","year",v("year",-1,-1)),y("year_to_last_completed_month","Year to last completed month","year",{kind:"periods",unit:"year",from:0,to:0,toDate:!0,anchor:{lastComplete:"month"}})];function mn(e,t){return qe(e)===qe(t);}function qe(e){return JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([i],[o])=>i<o?-1:i>o?1:0)):n);}function Be(e){const t=cn.find(n=>lt(n.window,e));return{label:t?t.label:hn(e),...(t?{presetId:t.id}:{}),definition:ct(e)};}function pn(e,t){const n=F(e),i=F(t);return n&&i?lt(n,i):n||i?!1:mn(e??null,t??null);}function lt(e,t){return JSON.stringify(e)===JSON.stringify(t);}const M=(e,t)=>Math.abs(e)===1?t:`${t}s`;function G(e,t){if(e===0)return t==="day"?"today":`this ${t}`;if(e===-1)return t==="day"?"yesterday":`last ${t}`;if(e===1)return t==="day"?"tomorrow":`next ${t}`;const n=Math.abs(e);return e<0?`${n} ${M(n,t)} ago`:`${n} ${M(n,t)} ahead`;}const oe=e=>e.charAt(0).toUpperCase()+e.slice(1),fn={day:"yesterday",week:"last week",month:"last month",quarter:"last quarter",year:"last year"};function ut(e){return F({kind:"periods",unit:e.unit,from:e.from,to:e.to,anchor:"now"});}function hn(e){if(e.kind==="periods"&&typeof e.anchor=="object")return`${Be(ut(e)).label}, as of end of ${fn[e.anchor.lastComplete]}`;if(e.kind!=="monthDay"&&e.anchor==="latest_data"){const t=F({...e,anchor:"now"});return`${Be(t).label} of data`;}switch(e.kind){case"monthDay":return e.day==="first"?"First day of the month":"Last day of the month";case"rolling":return`Last ${e.n} ${M(e.n,e.unit)}`;case"periods":{const{unit:t,from:n,to:i}=e;if(e.toDate)return n===0?`This ${t} to date`:`${oe(G(n,t))} to date`;if(i===-1&&n<=-2)return`Last ${-n} ${M(-n,t)}`;if(n===i)return oe(G(n,t));const o=t==="day"?"today":`this ${t}`;return i===0&&n<0?`Last ${1-n} ${M(1-n,t)}, including ${o}`:n===1&&i>=2?`Next ${i} ${M(i,t)}`:n===0&&i>0?`Next ${i+1} ${M(i+1,t)}, including ${o}`:`${oe(G(n,t))} to ${G(i,t)}`;}}}const L=(e,t)=>`${e} ${t}${Math.abs(e)===1?"":"s"}`;function O(e,t){return e===0?`the current ${t}`:e<0?`${L(-e,t)} before the current one`:`${L(e,t)} after the current one`;}function ct(e){switch(e.kind){case"monthDay":return e.day==="first"?"the first day of the current month":"the last day of the current month";case"rolling":{const t=L(e.n,e.unit);return e.anchor==="latest_data"?`the last ${t}, up to the latest date in the data`:`the last ${t}, up to now`;}case"periods":{const{unit:t,from:n,to:i}=e;if(typeof e.anchor=="object"){const r=`the end of the last complete ${e.anchor.lastComplete}`;return e.toDate?n===0?`the current ${t} up to ${r}`:`from ${O(n,t)} up to ${r}`:`${ct(ut(e))}, as of ${r}`;}if(e.anchor==="latest_data"&&i===-1)return`the ${L(-n,t)} before the ${t} of the latest date in the data, whole ${t}s only`;const o=e.anchor==="latest_data"?"the latest date in the data":"now";if(e.toDate)return n===0?`the current ${t} up to ${o}`:`from ${O(n,t)} up to ${o}`;const a=e.anchor==="latest_data"?", counted from the latest date in the data":"";return n===0&&i===0?`the whole current ${t}${a}`:n===-1&&i===-1?`the ${t} before the current one`:i===-1?`the ${L(-n,t)} before the current ${t}, whole ${t}s only`:n===i?`${O(n,t)}${a}`:`from ${O(n,t)} through ${O(i,t)}${a}`;}}}const mt="Not a relative date window",gn=s.union([D.lastSubDay.strict(),D.last.strict(),D.this.strict().refine(he.check,{message:he.message,path:["boundary"]}),D.previous.strict(),D.between.strict(),rt,W.rolling.strict(),W.monthDay.strict()]).transform((e,t)=>{const n=F(e);return n||(t.addIssue({code:s.ZodIssueCode.custom,message:mt}),s.NEVER);}),E={periods:rt,rolling:W.rolling.strict(),monthDay:W.monthDay.strict()},ca=s.union([E.periods,E.rolling,E.monthDay]).transform((e,t)=>{const n=F(e,{authoring:!0});return n||(t.addIssue({code:s.ZodIssueCode.custom,message:mt}),s.NEVER);});function Q(e){return e.kind==="absolute";}const X="Use { kind: 'periods', unit, from, to, anchor } for whole periods (the last 3 complete months: from -3, to -1; this month: from 0, to 0) or { kind: 'rolling', unit, n, anchor } for elapsed time.",yn="Ask the user which.",Ie=/* @__PURE__ */new Set(["minute","hour"]);function ma(e,t){if(!e||!t)return e===t;if(Q(e)||Q(t)){if(!Q(e)||!Q(t))return!1;const n=i=>{var o;return(o=ie(i))==null?void 0:o.getTime();};return n(e.start)===n(t.start)&&n(e.end)===n(t.end);}return pn(e,t);}function Se(e,t){const n=ft(e,t);return n.ok?n:{ok:!1,refusal:$n(n.problem,t)};}function pa(e,t,n){const i=Se(e,t);if(!i.ok)return{...i.refusal,message:`${i.refusal.message} It stays while ${n} is left out.`};}const _n=s.object({kind:s.literal("absolute"),start:s.string(),end:s.string()}).strict(),bn={kind:"monthDay",day:"first"};function fa(e){const t=typeof e=="function"?e:()=>e,n=en([E.periods,E.rolling,E.monthDay,_n],["periods window","rolling window","month day window","absolute window"]);return s.preprocess((i,o)=>{const a=Se(i,{use:t(o.path)});return a.ok?a.window:(o.addIssue({code:s.ZodIssueCode.custom,message:pt(a.refusal),...(a.refusal.path?{path:[a.refusal.path]}:{})}),bn);},n);}const ge=" Fix: ";function pt(e){return`${e.message}${ge}${e.fix}`;}function ha(e){const t=e.indexOf(ge);return t>0?{message:e.slice(0,t),fix:e.slice(t+ge.length)}:void 0;}function ft(e,t){if(!e||typeof e!="object"||Array.isArray(e))return w("not_a_window","timeWindow must be an object.",`Send a window. ${X}`,[]);const n=e;if("value"in n||"completeness"in n||"period"in n||n.kind==="relative"||n.kind==="calendar")return w("old_form","timeWindow uses the window form: kind periods or rolling, with an anchor.",X,[]);if(n.kind==="absolute")return vn(n,t);const i=n.kind;if(i!=="periods"&&i!=="rolling"&&i!=="monthDay")return w("not_a_window",`timeWindow kind must be periods, rolling, monthDay or absolute${i===void 0?"":`, not ${JSON.stringify(i)}`}.`,X,[],"kind");if(i!=="monthDay"&&n.anchor===void 0)return In(n,t);if(n.unit==="second")return Sn(n);if(i==="periods"&&typeof n.unit=="string"&&Ie.has(n.unit))return wn(n);const o=E[i].safeParse(n);if(!o.success){const m=o.error.issues[0],u=m.path.join(".");return w("not_a_window",`timeWindow ${u?`${u}: `:""}${m.message}.`,`Send a ${i} window: ${xn(i)}.`,[],u||void 0);}const a=o.data,r=dt(a,{authoring:!0});if(r){if(r.rule==="limit"&&a.kind==="rolling")return w("over_limit",r.message,`Use at most ${r.max}, or the same span in a longer unit.`,[{...a,n:r.max}],"n");const m=r.rule==="W1"&&a.kind==="periods"?[{...a,from:a.to,to:a.from}]:[];return w("not_a_window",r.message,Dn(r.rule),m,r.path);}const l=kn(a,t);if(l)return l;const c=F(a,{authoring:!0});return c?{ok:!0,window:c}:w("not_a_window","timeWindow is not a window.",X,[]);}function vn(e,t){if(t.use==="filterDefault")return w("absolute_default","A filter's default moves with time.","Use a window that moves with time, or leave defaultPeriod out.",[{kind:"periods",unit:"month",from:-1,to:-1,anchor:"now"}]);const n=typeof e.start=="string"?ie(e.start):null,i=typeof e.end=="string"?ie(e.end):null;return!n||!i||n.getTime()>i.getTime()?w("absolute_invalid","start and end must be ISO dates or timestamps, start first.","Send start before end, as YYYY-MM-DD or an ISO timestamp.",[],n?"end":"start"):{ok:!0,window:{kind:"absolute",start:e.start,end:e.end}};}function In(e,t){const n=typeof e.unit=="string"?e.unit:"month",i=[{anchor:"now",words:'"now" counts from the run'},...(t.use==="filterDefault"?[]:[{anchor:"latest_data",words:'"latest_data" from the newest row'}]),...(e.kind==="periods"?[{anchor:{lastComplete:n},words:`{ "lastComplete": "${n}" } ends at the last complete ${n}`}]:[])];return w("missing_anchor","A window needs an anchor: where it counts from.",`Add an anchor: ${i.map(o=>o.words).join(", ")}.`,i.map(o=>({...e,anchor:o.anchor})),"anchor");}function Sn(e){const t=typeof e.n=="number"?e.n:0,n=[.../* @__PURE__ */new Set([Math.floor(t/60),Math.ceil(t/60)])].filter(i=>i>=1);return w("seconds","Windows count minutes, not seconds.","Round to whole minutes.",n.map(i=>({kind:"rolling",unit:"minute",n:i,anchor:e.anchor})),"unit");}function wn(e){const t=typeof e.from=="number"?e.from:0,i=(typeof e.to=="number"?e.to:0)-t+1;return w("sub_day_periods","Minutes and hours count elapsed time; there are no whole-minute or whole-hour periods.",`The nearest is the last ${i} ${String(e.unit)}s up to the anchor.`,i>=1?[{kind:"rolling",unit:e.unit,n:i,anchor:e.anchor}]:[],"unit");}function kn(e,t){if(!(t.use==="analysis"||e.kind==="monthDay")){if(e.kind==="rolling"&&!Ie.has(e.unit))return An(e);if(e.kind==="rolling"&&t.columnHasTime===!1)return w("sub_day_on_date","The date field has dates only, so it can't count minutes or hours.","Use whole days.",[{kind:"periods",unit:"day",from:0,to:0,anchor:e.anchor},{kind:"periods",unit:"day",from:-1,to:0,anchor:e.anchor}],"unit");if(t.use==="filterDefault"&&e.anchor==="latest_data")return w("data_anchor_default","A filter's default counts from the run, not from the latest data.","Count from the run instead.",[{...e,anchor:"now"}],"anchor");}}function An(e){const t=e.unit,n=e.n===1?`Choose the current ${t} so far, or the last complete ${t}.`:`Choose the current ${t} so far and the ${e.n-1} before it, or the last ${e.n} complete ${t}s.`;return w("rolling_days_saved",`A saved card or default counts whole ${t}s.`,n,[{kind:"periods",unit:t,from:1-e.n,to:0,anchor:e.anchor},{kind:"periods",unit:t,from:-e.n,to:-1,anchor:e.anchor}]);}function $n(e,t){const n=[],i=/* @__PURE__ */new Set(),o=[e.sentence],a=(m,u)=>{for(const p of m){const f=ft(p,t);if(f.ok){const b=JSON.stringify(p);i.has(b)||(i.add(b),n.push(p));}else u<4&&f.problem.repairs.length&&(o.includes(f.problem.sentence)||o.push(f.problem.sentence),a(f.problem.repairs,u+1));}};a(e.repairs,0);let r=o.join(" ");const l=n.some(m=>"unit"in m&&Ie.has(String(m.unit)));t.use!=="analysis"&&t.columnHasTime===void 0&&l&&(r=`${r.replace(/\.$/,"")}, if the date field has a time of day.`),n.length>1&&(r=`${r} ${yn}`);const c=n.length?` ${n.length>1?"Send one of":"Send"}: ${n.map(m=>JSON.stringify(m)).join("; ")}.`:"";return{reason:e.reason,message:e.message,fix:`${r}${c}`,suggestions:n,...(e.path?{path:e.path}:{})};}function w(e,t,n,i,o){return{ok:!1,problem:{reason:e,message:t,sentence:n,repairs:i,...(o?{path:o}:{})}};}function Dn(e){switch(e){case"W1":return"from must be at most to; -1 is the period before the anchor's.";case"W2":return"toDate needs to 0: the current period, up to the anchor.";case"W3":return"A window ending at the last complete period ends at or before it: to at most 0.";case"W4":case"limit":return"n is a whole number of at least 1.";}}function xn(e){switch(e){case"periods":return"{ kind: 'periods', unit: day | week | month | quarter | year, from, to, toDate?: true, anchor: 'now' | 'latest_data' | { lastComplete: unit } }";case"rolling":return"{ kind: 'rolling', unit: minute | hour | day | week | month | quarter | year, n, anchor: 'now' | 'latest_data' }";case"monthDay":return"{ kind: 'monthDay', day: 'first' | 'last' }";}}function d(e,t,n){return n?{code:e,message:t,path:n}:{code:e,message:t};}function h(e){return typeof e=="string"&&e.trim().length>0;}function Fn(e){const t=/* @__PURE__ */new Set();return Mn(e,n=>(t.add(n),`{${n}}`)),Array.from(t);}function Mn(e,t){let n="",i=0,o=0;for(;o<e.length;){const a=e[o];if(a==="'"||a==='"'){o=En(e,o);continue;}if(a==="{"){const r=e.indexOf("}",o+1);if(r===-1){o+=1;continue;}const l=e.slice(o+1,r);/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)&&(n+=e.slice(i,o)+t(l),i=r+1),o=r+1;continue;}o+=1;}return n+e.slice(i);}function En(e,t){const n=e[t];let i=t+1;for(;i<e.length;){if(e[i]===n){if(e[i+1]===n){i+=2;continue;}return i+1;}i+=1;}return e.length;}function g(e){return!!(e&&typeof e=="object"&&!Array.isArray(e));}const Nn=/* @__PURE__ */new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function we(e,t,n){if(!e||typeof e!="object"){n.push(d("missing_source","Analytics intent needs a source.",t));return;}if(e.kind==="semantic"){h(e.domainId)||n.push(d("missing_semantic_domain","Semantic source needs a domainId.",`${t}.domainId`)),h(e.datasetName)||n.push(d("missing_dataset_name","Semantic source needs a datasetName.",`${t}.datasetName`));return;}if(e.kind==="physical"){h(e.connectionId)||n.push(d("missing_connection_id","Physical source needs a connectionId.",`${t}.connectionId`)),h(e.tableName)||n.push(d("missing_table_name","Physical source needs a tableName.",`${t}.tableName`));return;}if(e.kind==="sql"){h(e.connectionId)||n.push(d("missing_connection_id","SQL source needs a connectionId.",`${t}.connectionId`));return;}n.push(d("invalid_source_kind","Source kind is not supported.",t));}function I(e,t,n,i={}){if(!e||!g(e)){i.required&&n.push(d("missing_field_ref","Field reference needs a name.",t));return;}h(e.name)||n.push(d("missing_field_ref","Field reference needs a name.",`${t}.name`)),e.source!==void 0&&we(e.source,`${t}.source`,n),ke(e.aggregate,`${t}.aggregate`,n);}function ke(e,t,n){e!==void 0&&(typeof e!="string"||!Nn.has(e))&&n.push(d("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",t));}const Tn=/* @__PURE__ */new Set(["measure","dimension","date","id","unknown"]),Rn=/* @__PURE__ */new Set(["row","aggregate"]),jn=/* @__PURE__ */new Set(["string","number","boolean","date","datetime","unknown"]);function Cn(e,t,n){if(e===void 0)return;if(!g(e)){n.push(d("invalid_value_format","Value format must be a structured object.",t));return;}const i=(e.type==="temporal_bucket"?Z:Bt).safeParse(e);if(i.success)return;const o=e.type==="temporal_bucket"?"invalid_temporal_bucket_format":"invalid_value_format";for(const a of i.error.issues)n.push(d(o,a.message,[t,...a.path.map(String)].filter(Boolean).join(".")));}const On=/* @__PURE__ */new Set(["additive","non_additive","ratio_of_sums","weighted","pre_aggregated","snapshot"]),Yn=/* @__PURE__ */new Set(["default","symmetric_aggregate","aggregate_then_join","weighted"]);function Ln(e,t,n){if(!e||!g(e)){n.push(d("invalid_derived_field_input","Derived field inputs must be structured input references.",t));return;}if(e.kind==="field"){I(e.field,`${t}.field`,n,{required:!0}),ke(e.aggregate,`${t}.aggregate`,n);return;}n.push(d("invalid_derived_field_input","Derived field input kind must be field.",`${t}.kind`));}function Ae(e){const t=[];if(!g(e))return t.push(d("invalid_derived_field","Derived field definition must be a structured object.")),{ok:!1,errors:t,warnings:[]};if(e.kind!=="derived_field"&&t.push(d("invalid_derived_field_kind","Derived field kind must be derived_field.","kind")),h(e.name)||t.push(d("invalid_derived_field_name","Derived field needs a name.","name")),h(e.label)||t.push(d("invalid_derived_field_label","Derived field needs a label.","label")),Tn.has(e.resultRole)||t.push(d("invalid_derived_field_role","Derived field resultRole must be measure, dimension, date, id, or unknown.","resultRole")),jn.has(e.dataType)||t.push(d("invalid_derived_field_data_type","Derived field dataType must be string, number, boolean, date, datetime, or unknown.","dataType")),Rn.has(e.computeStage)||t.push(d("invalid_derived_field_compute_stage","Derived field computeStage must be row or aggregate.","computeStage")),e.computeStage==="aggregate"&&e.resultRole!=="measure"&&t.push(d("invalid_derived_field_compute_stage","Aggregate-stage derived fields must have resultRole measure.","computeStage")),e.resultRole!=="measure"&&e.defaultAggregate!==void 0&&t.push(d("invalid_derived_field_aggregate","Only measure derived fields may declare defaultAggregate.","defaultAggregate")),e.computeStage==="row"&&e.resultRole==="measure"&&e.defaultAggregate===void 0&&t.push(d("missing_derived_field_default_aggregate","Row-stage measure derived fields must declare defaultAggregate so row results have explicit rollup semantics.","defaultAggregate")),ke(e.defaultAggregate,"defaultAggregate",t),e.aggregationBehavior!==void 0&&!On.has(e.aggregationBehavior)&&t.push(d("invalid_derived_field_aggregation_behavior","Derived field aggregationBehavior is not supported.","aggregationBehavior")),e.aggregationStrategy!==void 0&&!Yn.has(e.aggregationStrategy)&&t.push(d("invalid_derived_field_aggregation_strategy","Derived field aggregationStrategy is not supported.","aggregationStrategy")),h(e.expression)||t.push(d("invalid_derived_field_expression","Derived field needs a named-token expression.","expression")),e.expressionLanguage!==void 0&&e.expressionLanguage!=="semaphor_sql_template"&&t.push(d("invalid_derived_field_expression_language","Derived field expressionLanguage must be semaphor_sql_template.","expressionLanguage")),!g(e.inputs)||Object.keys(e.inputs).length===0?t.push(d("invalid_derived_field_inputs","Derived field needs at least one typed input.","inputs")):Object.entries(e.inputs).forEach(([i,o])=>{if(!h(i)){t.push(d("invalid_derived_field_input_name","Derived field input names must be non-empty strings.","inputs"));return;}Ln(o,`inputs.${i}`,t);}),h(e.expression)&&g(e.inputs)){const i=Fn(e.expression),o=new Set(i),a=Object.keys(e.inputs).filter(r=>h(r));i.forEach(r=>{Object.prototype.hasOwnProperty.call(e.inputs,r)||t.push(d("invalid_derived_field_expression_token",`Derived field expression token "{${r}}" needs a matching inputs.${r} entry.`,"expression"));}),a.forEach(r=>{o.has(r)||t.push(d("unused_derived_field_input",`Derived field input "${r}" is not referenced by expression.`,`inputs.${r}`));});}const n=e.format;return g(n)&&n.type==="temporal_bucket"?t.push(d("invalid_derived_field_format","Derived field computation metadata cannot own temporal bucket presentation; declare grain and format on the grouped field.","format")):Cn(n,"format",t),e.tags!==void 0&&(!Array.isArray(e.tags)||e.tags.some(i=>!h(i)))&&t.push(d("invalid_derived_field_tags","Derived field tags must be non-empty strings.","tags")),{ok:t.length===0,errors:t,warnings:[]};}const Y=s.string().min(1).refine(e=>e.trim().length>0,"Must not be blank."),$e=s.union([Wt.extend({domainId:Y,datasetName:Y}).strict(),Ut.extend({connectionId:Y,tableName:Y}).strict()]),ht=Vt.extend({name:Y,source:$e.optional()}).strict(),De=Ht.extend({format:zt.optional(),inputs:s.record(s.object({kind:s.literal("field"),field:ht,aggregate:it.optional()}).strict())}).strict().superRefine((e,t)=>{var n;for(const i of Ae(e).errors)t.addIssue({code:"custom",path:((n=i.path)==null?void 0:n.split("."))??[],message:i.message});}),Pn=ht.extend({derivedField:De.optional()}).strict();function xe(e){return typeof e=="string"?e.trim().toLowerCase():"";}function qn(e){return String(e.column_name||e.name||e.qualifiedFieldName||"");}function Bn(e){return Array.from(new Set([e.column_name,e.name,e.qualifiedFieldName,e.alias].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim())));}function Fe(e){const t=Ee(e);return t?Hn(t)?"number":t.includes("timestamp")||t.includes("datetime")||t.startsWith("time")?"datetime":t.includes("date")?"date":t.includes("bool")?"boolean":"string":"unknown";}const de=/* @__PURE__ */new Map([["int","integer"],["uint","integer"],["integer","integer"],["uinteger","integer"],["bigint","integer"],["ubigint","integer"],["smallint","integer"],["usmallint","integer"],["tinyint","integer"],["utinyint","integer"],["mediumint","integer"],["hugeint","integer"],["uhugeint","integer"],["numeric","decimal"],["decimal","decimal"],["float","float"],["double","float"],["real","float"],["bfloat16","float"],["number",null],["money",null],["currency",null],["percent",null]]),Wn=["int","uint","decimal","float"];function Un(e){return e.length>0&&Array.from(e).every(t=>t>="0"&&t<="9");}function Vn(e){var n;const t=(n=/^number\s*\(\s*\d+\s*,\s*(\d+)\s*\)$/.exec(e))==null?void 0:n[1];return t===void 0?null:Number(t)===0?"integer":"decimal";}function Me(e){const t=e.split(/[\s(]/,1)[0]||"";if(t==="number")return{numeric:!0,kind:Vn(e)};if(de.has(t))return{numeric:!0,kind:de.get(t)??null};const n=Wn.find(i=>t.startsWith(i)&&Un(t.slice(i.length)));return n?{numeric:!0,kind:de.get(n)??null}:{numeric:!1,kind:null};}function Hn(e){return Me(e).numeric;}function zn(e){return Me(Ee(e)).kind;}function ga(e){var o,a;const t=Ee(e),n=Me(t).kind;if(n==="integer")return 0;if(n!=="decimal")return null;const i=((o=/^(?:decimal|numeric|number)\s*\(\s*\d+\s*,\s*(\d+)\s*\)$/.exec(t))==null?void 0:o[1])??((a=/^decimal(?:32|64|128|256)\s*\(\s*(\d+)\s*\)$/.exec(t))==null?void 0:a[1]);return i===void 0?null:Number(i);}function Ee(e){let t=xe(e),n="";for(;t&&t!==n;)n=t,t=We(t,"nullable"),t=We(t,"lowcardinality");return t;}function We(e,t){const n=`${t}(`;return!e.startsWith(n)||!e.endsWith(")")?e:e.slice(n.length,-1).trim();}function Gn(e){const t=Fe(e);return t==="date"||t==="datetime";}function gt(e){return Gn(e.dataType||e.data_type);}function yt(e){const t=_t(e);return t==="id"||t==="row_id";}function Ue(e){const t=_t(e);return yt(e)||t.endsWith("_id")||t.endsWith("_key")||t.endsWith("_number");}function _t(e){return xe(qn(e)||e.name||e.alias).replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");}function bt(e,t={}){const n=xe(e.role);return n==="metric"||n==="measure"?!t.excludeIdentifiers||!Ue(e):n==="groupby"||n==="dimension"||n==="date"||n==="id"?!1:Fe(e.dataType||e.data_type)==="number"&&(!t.excludeIdentifiers||!Ue(e));}function ya(e){return!bt(e)&&!gt(e);}function _a(e){const t=/* @__PURE__ */new Set(),n=/* @__PURE__ */new Set(),i=/* @__PURE__ */new Set();for(const o of e){if(yt(o))continue;const a=Bn(o);if(a.length!==0){if(gt(o)){a.forEach(r=>n.add(r));continue;}if(bt(o,{excludeIdentifiers:!0})){a.forEach(r=>t.add(r));continue;}a.forEach(r=>i.add(r));}}return{validMeasureCandidates:Array.from(t).sort(),validDateCandidates:Array.from(n).sort(),validDimensionCandidates:Array.from(i).sort()};}const P=16*1024;function ee(e){const t=/^([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:[eE]([+-]?\d+))?$/.exec(e);return t?{sign:t[1],whole:t[2]??"",fraction:t[3]??t[4],exponent:Number(t[5]??"0")}:null;}function Ve(e){const{sign:t,whole:n,fraction:i="",exponent:o}=e,a=(n+i).replace(/^0+/,""),r=a.replace(/0+$/,""),l=o-i.length+a.length-r.length;return!Number.isSafeInteger(o)||!Number.isSafeInteger(l)?null:r?`${t==="-"?"-":""}${r}e${l}`:"0";}function ba(e){const t=ee(e);if(!t)return null;const n=t.sign==="+"?e.slice(1):e,i=Number(e);if(!Number.isFinite(i))return n;const o=Ve(t),a=ee(String(i));return o!==null&&a!==null&&o===Ve(a)?i:n;}function va(e){if(e.length>P)throw new RangeError("Exact numeric text exceeds 16 KiB.");const t=ee(e);if(!t)throw new TypeError("Expected finite decimal text.");const{sign:n,whole:i,fraction:o,exponent:a}=t,r=`${n}${i||"0"}${o?`.${o}`:""}`;return U(`${r}e${a}`);}function U(e){if(e.length>P)throw new RangeError("Exact numeric text exceeds 16 KiB.");const t=ee(e);if(!t||t.whole===""||t.fraction==="")throw new TypeError("Expected finite decimal text.");const{sign:n,whole:i,fraction:o="",exponent:a}=t;if(!Number.isSafeInteger(a)||Math.abs(a)>P)throw new RangeError("Exact numeric exponent exceeds the text budget.");const r=i+o,l=i.length+a;if(Math.max(r.length,l)+Math.max(0,-l)+3>P)throw new RangeError("Normalized exact numeric text exceeds 16 KiB.");let m;l<=0?m=`0.${"0".repeat(-l)}${r}`:l>=r.length?m=r+"0".repeat(l-r.length):m=`${r.slice(0,l)}.${r.slice(l)}`;const[u,p=""]=m.split("."),f=u.replace(/^0+(?=\d)/,""),b=p.replace(/0+$/,""),A=f+(b?`.${b}`:"");return n==="-"&&A!=="0"?`-${A}`:A;}function Ia(e,t){const n=e.startsWith("-"),i=t.startsWith("-");if(n!==i)return n?-1:1;const[o,a=""]=(n?e.slice(1):e).split("."),[r,l=""]=(i?t.slice(1):t).split(".");let c=Math.sign(o.length-r.length);if(!c&&o!==r&&(c=o<r?-1:1),!c){const m=Math.max(a.length,l.length),u=a.padEnd(m,"0"),p=l.padEnd(m,"0");c=u===p?0:u<p?-1:1;}return c===0?0:n?-c:c;}function Sa(e,t){if(typeof t=="number"&&!Number.isFinite(t))throw new TypeError("Numeric scale must be finite.");const n=[e,U(String(t))].map(a=>{const[r,l=""]=a.split(".");return{coefficient:BigInt(r+l),digits:l.length};}),i=n[0].coefficient*n[1].coefficient,o=n[0].digits+n[1].digits;return U(`${i}e-${o}`);}function Qn(e){try{return U(e)===e;}catch{return!1;}}const vt=s.object({kind:s.literal("exact_number"),type:s.enum(["integer","decimal"]),value:s.string().max(P).refine(Qn,"Expected canonical decimal text.")}).strict().superRefine((e,t)=>{e.type==="integer"&&e.value.includes(".")&&t.addIssue({code:"custom",path:["value"],message:"An integer cannot have fractional digits."});}),Xn=s.union([s.null(),s.string(),s.boolean(),s.number().finite(),vt]);function Kn(e,t){return vt.parse({kind:"exact_number",type:t,value:U(e)});}function wa(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="exact_number"&&"type"in e&&(e.type==="integer"||e.type==="decimal")&&"value"in e&&typeof e.value=="string";}function ka(e){const t=zn(e.nativeDataType);if(!t)throw new TypeError("Numeric result type is not established.");if(e.value===null)return null;if(t==="float"){if(typeof e.value!="number"||!Number.isFinite(e.value))throw new TypeError("Expected a finite floating-point result.");return e.value;}if(e.exactText===void 0)throw new TypeError("Exact numeric sidecar is required; rounded result values cannot substitute.");return Kn(e.exactText,t);}const Ne=s.string().uuid(),Te=s.enum(["rows","columns"]),Aa=s.enum(["member","subtotal","grand_total","others"]),Zn=s.discriminatedUnion("kind",[s.object({kind:s.literal("value"),value:Xn}).strict(),s.object({kind:s.literal("others"),rankingId:Ne}).strict()]),T=s.array(s.object({levelId:Ne,member:Zn}).strict()).readonly().superRefine((e,t)=>{new Set(e.map(n=>n.levelId)).size!==e.length&&t.addIssue({code:"custom",path:[],message:"Duplicate identity."}),e.some((n,i)=>n.member.kind==="others"&&i!==e.length-1)&&t.addIssue({code:"custom",path:[],message:"Others is terminal."});}),$a=s.object({rowPath:T,columnPath:T,measureId:Ne}).strict();function It(e){return JSON.stringify(e.map(({levelId:t,member:n})=>[t,n.kind==="others"?["others",n.rankingId]:typeof n.value=="object"&&n.value!==null?["exact_number",n.value.value]:[typeof n.value,n.value]]));}const ye="SEMAPHOR_CALCULATED_FIELD",Jn="calculated_fields";function ei(e){return(e==null?void 0:e.sourceField)||(e==null?void 0:e.name)||"";}const ti=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","YYYY-MM-DD HH:mm","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm Z","YYYY-MM-DD HH:mm:ss Z","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function Da(e){return e.role==="metric"&&"expression"in e&&!!e.expression;}function xa(e){return!!e.expression;}function ni(e){return!!(e&&(e.calculationRepresentation||e.expression||e.derivedField||e.calculatedFieldOrigin||e.calculatedFormula||_e(e)));}function St(e){var p,f,b;if(!e)return{representation:"physical",ownership:"local",completeness:"not-calculated",runtimeExecutable:!1,legacyManual:!1};const t=e.fieldScope==="domain"?"domain":"local",n=((p=e.derivedField)==null?void 0:p.computeStage)||((f=e.calculatedFormula)==null?void 0:f.computeStage),i=!e.calculatedFormula||Array.isArray(e.calculatedFormula.inputFields)&&e.calculatedFormula.inputFields.every(A=>{const Le=A&&ei(A);return typeof Le=="string"&&!!Le.trim();}),o=typeof e.expression=="string"&&!!e.expression.trim()&&i,a=e.calculationRepresentation;if(e.derivedField||a==="typed-derived"){const A=e.derivedField!==void 0&&Ae(e.derivedField).ok;return{representation:"typed-derived",ownership:t,completeness:(!a||a==="typed-derived")&&A&&(!e.expression&&!e.calculatedFormula||o)?"complete":"incomplete",computeStage:n,runtimeExecutable:o,legacyManual:!1};}if(!(!!a||ni(e)))return{representation:"physical",ownership:t,completeness:"not-calculated",runtimeExecutable:!1,legacyManual:!1};const l=n||(e.role==="groupby"||((b=e.calculatedFieldOrigin)==null?void 0:b.role)==="groupby"?"row":void 0),c=t==="domain"||_e(e)||e.fieldScope==="card"||e.fieldScope==="dashboard"?"manual":"inline-expression",m=a==="manual"||a==="inline-expression"?a:c,u=(!a||a==="manual"||a==="inline-expression")&&!(a==="inline-expression"&&_e(e));return{representation:m,ownership:t,completeness:o&&u?"complete":"incomplete",computeStage:l,runtimeExecutable:o,legacyManual:m==="manual"&&t==="local"&&!l};}function Fa(e){if(e.calculationRepresentation)return e;const{representation:t}=St(e);return t==="physical"?e:{...e,calculationRepresentation:t};}function Ma(e){return St(e).computeStage;}function Ea(e,t){return e==="aggregate"&&t==="default";}function Na(e){var n,i;const t=e;return!!(t!=null&&t.expression&&(i=(n=t.calculatedFormula)==null?void 0:n.inputFields)!=null&&i.length);}function Ta(e){return!!(e&&(e.entityName===ye||e.entityId===ye));}function _e(e){return e?[e.entityName,e.entityId,e.qualifiedEntityName].some(t=>t===ye||t===Jn):!1;}function ii(e){const t=kt(e);return t.length>0?t.join("."):void 0;}function Ra(e){const t=ii(e.qualifiedName),n=(t==null?void 0:t.split("."))||[];if(n.length===0)return{};const i={};let o=n.length-1;for(let a=e.capabilities.prefixLevels.length-1;a>=0&&o>=0;a-=1,o-=1)ri(i,e.capabilities.prefixLevels[a],n[o]);return i;}function ja(e){return!e.left.tableName||!e.right.tableName?!1:e.capabilities.prefixLevels.every(t=>{const n=R(e.left,t),i=R(e.right,t);return!n||!i||n===i;});}function Ca(e){return e.capabilities.prefixLevels.every(t=>{const n=R(e.requested,t);return n?R(e.allowed,t)===n:!0;});}function wt(e,t={}){const n=V(e),i={connectionId:t.connectionId,connectionType:e,path:["database","schema","table"],labels:{database:"Database",schema:"Schema",table:"Table"},prefixLevels:["database","schema","table"],dialect:"postgres",supportsFilterClause:!0};return n.includes("postgres")?{...i,prefixLevels:["schema","table"],dialect:"postgres"}:n.includes("mysql")?{...i,prefixLevels:["database","table"],dialect:"mysql",supportsFilterClause:!1}:n.includes("mssql")||n.includes("sqlserver")?{...i,dialect:"mssql",supportsFilterClause:!1}:n.includes("redshift")?{...i,prefixLevels:["schema","table"],dialect:"redshift"}:n.includes("snowflake")?{...i,dialect:"snowflake"}:n.includes("clickhouse")?{connectionId:t.connectionId,connectionType:e,path:["database","table"],labels:{database:"Database",table:"Table"},prefixLevels:["database","table"],dialect:"clickhouse",supportsFilterClause:!1}:n==="s3"||n==="api"?{connectionId:t.connectionId,connectionType:e,path:["table"],labels:{table:n==="api"?"API Table":"File Table"},prefixLevels:["table"],dialect:"duckdb",supportsFilterClause:!0}:n==="googlesheets"||n==="fileupload"?{connectionId:t.connectionId,connectionType:e,path:["table"],labels:{table:"Table"},prefixLevels:["table"],dialect:"postgres",supportsFilterClause:!0}:n==="bigquery"?{...i,labels:{database:"Project",schema:"Dataset",table:"Table"},prefixLevels:["schema","table"],dialect:"bigquery",supportsFilterClause:!1}:i;}const Re=["GoogleSheets","FileUpload","MySQL","MSSQL","PostgreSQL","BigQuery","Redshift","Snowflake","S3","clickhouse","API","none"];function Oa(e){if(!e)return;const t=Re.filter(n=>n!=="none"&&wt(n).dialect===e);return t.length===1?t[0]:void 0;}const ai={postgres:"PostgreSQL",sqlserver:"MSSQL"};function Ya(e){const t=V(e);if(t)return Re.find(n=>V(n)===t)??ai[t];}function La(e,t={}){return si(e)?wt(e,t):void 0;}function si(e){const t=V(e);if(t.includes("postgres"))return"postgres";if(t.includes("mysql"))return"mysql";if(t.includes("mssql")||t.includes("sqlserver"))return"mssql";if(t.includes("redshift"))return"redshift";if(t.includes("snowflake"))return"snowflake";if(t.includes("clickhouse"))return"clickhouse";if(t==="s3"||t==="api"||t==="googlesheets"||t==="fileupload"||t==="bigquery")return t;}function Pa(e){const t=V(e);switch(t){case"mysql":case"bigquery":case"redshift":case"snowflake":case"clickhouse":case"duckdb":case"sqlite":return t;case"mssql":case"sqlserver":return"mssql";case"postgres":case"postgresql":return"postgres";default:return"unknown";}}function qa(e){return e.capabilities.prefixLevels.every(t=>!!R(e.source,t));}function Ba(e){const t=e.quoteIdentifier??li;return e.capabilities.prefixLevels.map(n=>R(e.source,n)).filter(n=>!!n).map(n=>t(n,e.capabilities.dialect)).join(".");}function R(e,t){return t==="database"?e.databaseName:t==="schema"?e.schemaName:e.tableName;}function ri(e,t,n){t==="database"?e.databaseName=n:t==="schema"?e.schemaName=n:e.tableName=n;}const oi=[['"','"'],["`","`"],["[","]"]];function di(e){const t=e.trim();for(const[n,i]of oi)if(t.length>=2&&t.startsWith(n)&&t.endsWith(i))return t.slice(1,-1).split(i+i).join(i);return t;}function kt(e){const t=e==null?void 0:e.trim();if(!t)return[];const n=t.split(".").map(di);return n.some(i=>!i)?[]:n;}function Wa(e){const t=kt(e??void 0);return t[t.length-1]||"";}function li(e,t){return t==="mysql"||t==="bigquery"||t==="clickhouse"||t==="duckdb"?`\`${e.replace(/`/g,"``")}\``:t==="mssql"?`[${e.replace(/]/g,"]]")}]`:`"${e.replace(/"/g,'""')}"`;}function V(e){if(typeof e!="string")return"";const t=[];for(const n of e.trim().toLowerCase())ui(n)&&t.push(n);return t.join("");}function ui(e){const t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=122;}const k=s.string().min(1),He=s.enum(["groupby","metric","sortby","pivotby","detail"]),At=s.enum(["table","view","materialized view","model","file","dataset","url","upload"]),le=s.object({connectionId:k,connectionType:s.enum(Re),type:At,name:k,alias:s.string().optional(),id:k.optional(),domainId:k.optional(),datasetType:s.enum(["physical","virtual"]).optional(),label:s.string().optional(),description:s.string().optional(),dbObjectType:s.string().optional(),database:s.string().optional(),schema:s.string().optional(),dialect:s.enum(["mysql","postgres","bigquery","redshift","snowflake","clickhouse","duckdb","mssql"]).optional()}).strict(),te=s.lazy(()=>s.object({id:k,name:k,label:s.string(),derivedLabel:s.string().optional(),qualifiedFieldName:k,dataType:k,entityId:k,entityName:k,entityType:At,alias:s.string().optional(),sourceField:s.string().optional(),source:$e.optional(),nativeDataType:s.string().optional(),description:s.string().optional(),qualifiedEntityName:s.string().optional(),dateFormat:s.enum(ti).optional(),customFormat:s.string().optional(),granularity:pe.optional(),role:He.optional(),calculationRepresentation:s.enum(["inline-expression","manual","typed-derived"]).optional(),calculatedFieldOrigin:s.object({id:k,role:He.optional()}).strict().optional(),aggregateOrigin:s.enum(["default","explicit"]).optional(),labelOrigin:s.enum(["semantic","override"]).optional(),formatOrigin:s.enum(["semantic","override"]).optional(),expression:s.string().optional(),derivedField:De.optional(),format:Z.optional(),semanticTemporalPresentation:s.object({granularity:pe,format:Gt}).strict().optional(),aggregate:it.optional(),grainMode:s.literal("automatic").optional(),fieldScope:s.enum(["card","dashboard","domain"]).optional(),calculatedFormula:s.object({operation:s.enum(["sum","difference","product","ratio","change","percentage","scale","custom"]),inputFields:s.array(te),constant:s.number().finite().optional(),computeStage:s.enum(["row","aggregate"]).optional()}).strict().optional()}).strict()),ci=s.union([s.string(),s.number().finite(),s.boolean(),s.date(),s.null()]),mi=s.object({id:k,field:te,operator:s.enum(["=","!=",">",">=","<","<=","contains","startsWith","endsWith","like","not like","in","not in","between","not between","isNull","isNotNull"]),value:s.union([ci,s.array(s.string()),s.array(s.number().finite())]),label:s.string().optional(),temporalBucket:Xt.optional(),rawTemporal:Qt.optional(),relativeMeta:gn.optional(),latestValue:s.literal(!0).optional(),latestValuePolicy:s.literal("snapshot").optional()}).strict().superRefine((e,t)=>{const{operator:n,value:i}=e;if((n==="between"||n==="not between")&&(!Array.isArray(i)||i.length!==2)&&t.addIssue({code:"custom",path:["value"],message:"Between requires two endpoints."}),e.relativeMeta&&!dn(n,F(e.relativeMeta))&&t.addIssue({code:"custom",path:["relativeMeta"],message:"A relative date runs under between, not between, <, <=, > or >=; a window counted from the newest row only under between or not between."}),e.latestValue){const a=[e.field.nativeDataType,e.field.dataType].map(r=>Fe(r)).some(r=>r==="date"||r==="datetime");(n!=="="||!a)&&t.addIssue({code:"custom",path:["latestValue"],message:"Latest value requires = on a date or timestamp field."});}(n==="in"||n==="not in")&&!Array.isArray(i)&&t.addIssue({code:"custom",path:["value"],message:"Membership requires an array."});}),$t=s.lazy(()=>s.object({id:k,logicalOperator:s.enum(["AND","OR"]),negate:s.boolean(),conditions:s.array(mi),groups:s.array($t)}).strict()),pi=s.object({baseEntity:le,joins:s.array(s.object({id:k,source:le,target:le,joinType:s.enum(["INNER","LEFT","RIGHT","FULL"]),sequence:s.number().int().nonnegative(),autoResolved:s.boolean().optional(),relationshipId:s.string().optional(),relationshipName:s.string().optional(),relationshipCardinality:s.enum(["one_to_one","one_to_many","many_to_one","many_to_many"]).optional(),relationshipTraversalDirection:s.enum(["forward","reverse"]).optional(),joinKeyGroups:s.array(s.object({id:k,operator:s.enum(["AND","OR"]),keys:s.array(s.object({id:s.string().optional(),source:te,target:te,operator:s.enum(["=","!=",">",">=","<","<="])}).strict()).min(1)}).strict()).min(1)}).strict())}).strict(),S=s.string().uuid(),fi=s.string().min(1),hi=s.number().int().positive().max(Number.MAX_SAFE_INTEGER),gi=s.enum(["SUM","COUNT","DISTINCT","AVG","MIN","MAX","MEDIAN"]),Dt=Pn.omit({aggregate:!0}),yi={id:S,field:Dt,grain:pe.optional()},be=s.object(yi).strict(),_i=s.object({id:S,kind:s.literal("aggregate"),field:Dt,aggregate:gi}).strict(),bi=s.object({id:S,kind:s.literal("calculated"),definition:De}).strict(),xt=s.discriminatedUnion("kind",[_i,bi]),vi=s.discriminatedUnion("kind",[s.object({kind:s.literal("member")}).strict(),s.object({kind:s.literal("measure"),measureId:S,oppositePath:T}).strict()]),Ii={axis:Te,levelId:S,scope:s.discriminatedUnion("kind",[s.object({kind:s.literal("level")}).strict(),s.object({kind:s.literal("branch"),parent:T}).strict()]),target:vi,direction:s.enum(["asc","desc"]),nulls:s.enum(["first","last"])},Ft=s.object(Ii).strict(),Si=s.object({id:S,axis:Te,levelId:S,direction:s.enum(["top","bottom"]),count:hi,measureId:S,oppositePath:T,others:s.boolean()}).strict(),ue=s.number().finite(),wi=s.object({id:S,axis:Te,levelId:S,measureId:S,operator:s.enum(["=","!=",">",">=","<","<=","between","not between"]),value:s.union([ue,s.tuple([ue,ue]).readonly()])}).strict().superRefine((e,t)=>{const n=e.operator==="between"||e.operator==="not between";n!==Array.isArray(e.value)?_(t,["value"],n?"A range condition needs a low and a high bound.":"A comparison needs one number."):n&&e.value[0]>e.value[1]&&_(t,["value"],"The low bound must not exceed the high bound.");}),Mt=s.object({source:$e,rows:s.array(be).min(1).readonly(),columns:s.array(be).readonly(),measures:s.array(xt).min(1).readonly(),filters:$t.optional(),joinPlan:pi.optional(),relationshipHint:s.object({relationshipIds:s.array(fi).optional()}).strict().optional(),sorts:s.array(Ft).readonly(),rankings:s.array(Si).readonly(),measureFilters:s.array(wi).readonly().optional()}).strict();function Et(e){return JSON.stringify([e.axis,e.levelId,e.scope.kind,e.scope.kind==="branch"?It(e.scope.parent):null]);}function _(e,t,n){e.addIssue({code:"custom",path:t,message:n});}function x(e,t,n){new Set(e).size!==e.length&&_(t,n,"Duplicate identity.");}function ne(e,t,n,i,o,a=!1){n.length>e[t].length&&_(i,o,"Path exceeds axis depth."),n.forEach((r,l)=>{var c;if(r.levelId!==((c=e[t][l])==null?void 0:c.id)&&_(i,[...o,l],"Path must be an ordered axis prefix."),r.member.kind==="others"){const m=r.member.rankingId;(a||l!==n.length-1||!e.rankings.some(u=>u.id===m&&u.others&&u.axis===t&&u.levelId===r.levelId))&&_(i,[...o,l],"Others must terminate a path at its enabled ranking and cannot be a sort/rank target.");}});}function Nt(e,t,n,i){x(t.map(Et),n,i),t.forEach((o,a)=>{const r=[...i,a],l=e[o.axis].findIndex(c=>c.id===o.levelId);if(l<0&&_(n,r,"Sort level is not on its axis."),o.scope.kind==="branch"&&(ne(e,o.axis,o.scope.parent,n,[...r,"scope","parent"],!0),o.scope.parent.length!==l&&_(n,r,"Branch sort must name the immediate parent of its level.")),o.target.kind==="measure"){const c=o.target.measureId;e.measures.some(m=>m.id===c)||_(n,r,"Unknown sort measure."),ne(e,o.axis==="rows"?"columns":"rows",o.target.oppositePath,n,[...r,"target","oppositePath"],!0);}});}function K(e,t,n,i){e&&(e.kind!==t.kind||e.kind==="semantic"&&t.kind==="semantic"&&e.domainId!==t.domainId||e.kind==="physical"&&t.kind==="physical"&&e.connectionId!==t.connectionId)&&_(n,i,"Field source must belong to the same semantic domain or physical connection.");}function ce(e,t,n){(e.aggregationBehavior==="snapshot"||e.aggregationBehavior==="weighted"||e.aggregationStrategy==="weighted")&&_(t,n,"This measure semantic requires a later capability.");}function Tt(e,t){x([...e.rows,...e.columns,...e.measures].map(a=>a.id),t,[]),x(e.rankings.map(a=>a.id),t,["rankings"]),x(e.rankings.map(a=>JSON.stringify([a.axis,a.levelId])),t,["rankings"]);for(const a of["rows","columns"])e[a].forEach((r,l)=>{r.grain&&r.field.dataType!==void 0&&!["date","datetime","unknown"].includes(r.field.dataType)&&_(t,[a,l,"grain"],"Grain requires a temporal field.");});const n=[...e.rows,...e.columns,...e.measures.filter(a=>a.kind==="aggregate")];for(const a of n)if(K(a.field.source,e.source,t,[a.id,"field","source"]),a.field.derivedField){a.field.derivedField.computeStage!=="row"&&_(t,[a.id],"Aggregate-stage calculations cannot be grouped or wrapped in an aggregate."),ce(a.field.derivedField,t,[a.id]);for(const r of Object.values(a.field.derivedField.inputs))K(r.field.source,e.source,t,[a.id,"inputs"]);}for(const a of e.measures)if(a.kind==="calculated"){(a.definition.computeStage!=="aggregate"||a.definition.resultRole!=="measure")&&_(t,[a.id],"Calculated measures require aggregate stage and measure role."),ce(a.definition,t,[a.id]);for(const r of Object.values(a.definition.inputs))K(r.field.source,e.source,t,[a.id,"inputs"]);}const i=a=>{const r=(l,c)=>{var m,u;if((l.aggregate||((m=l.derivedField)==null?void 0:m.computeStage)==="aggregate")&&_(t,c,"Aggregate/HAVING filters are not supported."),l.derivedField){ce(l.derivedField,t,c);for(const p of Object.values(l.derivedField.inputs))K(p.field.source,e.source,t,c);}for(const p of((u=l.calculatedFormula)==null?void 0:u.inputFields)??[])r(p,c);};for(const l of a.conditions)r(l.field,["filters",l.id]);a.groups.forEach(i);};if(e.filters&&i(e.filters),e.joinPlan){const a=[e.joinPlan.baseEntity,...e.joinPlan.joins.flatMap(r=>[r.source,r.target])];(new Set(a.map(r=>r.connectionId)).size>1||e.source.kind==="physical"&&a[0].connectionId!==e.source.connectionId)&&_(t,["joinPlan"],"Joins must stay within the source connection."),x(e.joinPlan.joins.map(r=>r.id),t,["joinPlan","joins"]);}Nt(e,e.sorts,t,["sorts"]);const o=e.measureFilters??[];x(o.map(a=>a.id),t,["measureFilters"]),x(o.map(a=>JSON.stringify([a.axis,a.levelId])),t,["measureFilters"]),o.forEach((a,r)=>{(!e[a.axis].some(l=>l.id===a.levelId)||!e.measures.some(l=>l.id===a.measureId))&&_(t,["measureFilters",r],"Unknown measure filter level or measure.");}),e.rankings.forEach((a,r)=>{(!e[a.axis].some(l=>l.id===a.levelId)||!e.measures.some(l=>l.id===a.measureId))&&_(t,["rankings",r],"Unknown ranking level or measure."),ne(e,a.axis==="rows"?"columns":"rows",a.oppositePath,t,["rankings",r,"oppositePath"],!0);});}const z=Mt.superRefine(Tt),ki=Mt.extend({rows:s.array(be).readonly(),measures:s.array(xt).readonly()}),Ai=ki.superRefine(Tt),$i=z.innerType().extend({kind:s.literal("matrix")}),Di=$i.superRefine(({kind:e,...t},n)=>{const i=z.safeParse(t);i.success||i.error.issues.forEach(o=>n.addIssue(o));}),xi="{member}",ze=s.object({visible:s.boolean(),position:s.enum(["before","after"]),label:s.string().optional()}).strict(),Ge=s.object({grand:ze,levels:s.record(S,ze).readonly(),skipRedundant:s.boolean().optional()}).strict(),Fi={layout:s.discriminatedUnion("kind",[s.object({kind:s.literal("compact")}).strict(),s.object({kind:s.literal("tabular"),repeatLabels:s.boolean()}).strict()]),absence:s.object({emptyText:s.string(),nullText:s.string()}).strict(),levelLabels:s.record(S,s.string()).readonly(),measureLabels:s.record(S,s.string()).readonly(),levelFormats:s.record(S,Z).readonly(),measureFormats:s.record(S,Z).readonly(),totals:s.object({rows:Ge,columns:Ge}).strict()},je=s.object(Fi).strict(),Mi=s.object({depth:s.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),overrides:s.array(s.object({path:T,expanded:s.boolean()}).strict()).readonly()}).strict(),Qe=Mi.superRefine((e,t)=>x(e.overrides.map(n=>It(n.path)),t,["overrides"])),Ei={rows:Qe,columns:Qe},se=s.object(Ei).strict(),Ni=se.extend({sorts:s.array(Ft).readonly()}).strict(),Ti=Ni.superRefine((e,t)=>x(e.sorts.map(Et),t,["sorts"]));function re(e,t){var c,m;const{spec:n,presentation:i,defaults:o,session:a}=e,r=new Set([...n.rows,...n.columns].map(u=>u.id)),l=new Set(n.measures.map(u=>u.id));for(const u of["levelLabels","levelFormats","measureLabels","measureFormats"]){const p=u.startsWith("level")?r:l;for(const f of Object.keys(i[u]))p.has(f)||_(t,["presentation",u,f],"Unknown presentation reference.");}for(const[u,p]of Object.entries(i.measureFormats))p.type==="temporal_bucket"&&_(t,["presentation","measureFormats",u],"Measures cannot own temporal bucket formats.");for(const[u,p]of Object.entries(i.levelFormats))p.type==="temporal_bucket"&&!((c=[...n.rows,...n.columns].find(f=>f.id===u))!=null&&c.grain)&&_(t,["presentation","levelFormats",u],"Temporal bucket formats require a grain.");for(const u of["rows","columns"]){(m=i.totals[u].grand.label)!=null&&m.includes(xi)&&_(t,["presentation","totals",u,"grand","label"],"The grand total has no member, so its label cannot use {member}.");const p=Object.keys(i.totals[u].levels);(p.length!==n[u].length||p.some(f=>!n[u].some(b=>b.id===f)))&&_(t,["presentation","totals",u],"Subtotal map must contain exactly the current axis levels.");for(const f of[o,...(a?[a]:[])])for(const b of f[u].overrides)ne(n,u,b.path,t,[u,"overrides"],!0),b.path.length||_(t,[u,"overrides"],"Use depth to expand/collapse the root.");}a&&Nt(n,a.sorts,t,["session","sorts"]);}const Ri=s.object({spec:z,presentation:je,defaults:se,session:Ti.optional()}).strict(),Ua=Ri.superRefine(re),ji=s.object({version:s.literal(1),spec:z,presentation:je,defaultView:se}).strict(),Ci=ji.superRefine((e,t)=>re({...e,defaults:e.defaultView},t)),Oi=Ci.innerType().extend({spec:Ai}),Va=Oi.superRefine((e,t)=>re({...e,defaults:e.defaultView},t)),Xe=s.object({spec:z,presentation:je}).strict(),Yi=s.union([Xe.extend({mode:s.literal("layout"),format:s.enum(["csv","xlsx","pdf"]),expansion:s.union([se.extend({kind:s.literal("current")}).strict(),s.object({kind:s.literal("all")}).strict()])}).strict(),Xe.extend({mode:s.literal("flat"),format:s.enum(["csv","xlsx"])}).strict()]),Ha=Yi.superRefine((e,t)=>re({...e,defaults:e.mode==="layout"&&e.expansion.kind==="current"?e.expansion:{rows:{depth:0,overrides:[]},columns:{depth:0,overrides:[]}}},t));function za(e){return e&&"id"in e?e.id:void 0;}const Li="SUM";function $(e){return typeof e=="string"&&e.trim().length>0;}function q(e){return $(e)?e.trim().toLowerCase():"";}function Ga(e){const t=$(e.id)?e.id.trim():void 0;if(!t)return;const n=q(t),i=$(e.table)?e.table.trim():void 0;if(!(n===q(e.name)||i&&n===q(i)))return t;}function j(e){const t=$(e.datasetId)?e.datasetId.trim():void 0;if(t)return q(t)===q(e.datasetName)?void 0:t;}function Rt(e){if(e.kind!=="semantic")return e;const t=j(e),{datasetId:n,...i}=e;return{...i,...(t?{datasetId:t}:{})};}function Qa(e){return e?e.kind==="semantic"?!!($(e.domainId)&&($(e.datasetId)||$(e.datasetName))):e.kind==="physical"?$(e.connectionId)&&$(e.tableName):$(e.connectionId):!1;}function ve(e){if(!e)return"";if(e.kind==="semantic"){const t=j(e);return[e.kind,e.domainId,t?`datasetId:${t}`:`datasetName:${e.datasetName}`].join(":");}return e.kind==="physical"?[e.kind,e.connectionId,e.databaseName||"",e.schemaName||"",e.tableName].join(":"):[e.kind,e.connectionId,e.dialect||"",e.label||""].join(":");}function Ce(e,t){if(!e||!t)return e===t;if(e.kind!==t.kind)return!1;if(e.kind==="semantic"&&t.kind==="semantic"){if(e.domainId!==t.domainId)return!1;const n=j(e),i=j(t);return n&&i?n===i:e.datasetName===t.datasetName;}return ve(e)===ve(t);}function jt(e,t){return e.kind!=="semantic"||t.kind!=="semantic"?e:Rt({...e,datasetName:e.datasetName||t.datasetName,datasetId:j(e)||j(t),label:e.label||t.label,connectionId:e.connectionId||t.connectionId});}function Xa(e){const t=[];for(const n of e){const i=Rt(n),o=t.findIndex(a=>Ce(a,i));if(o===-1){t.push(i);continue;}t[o]=jt(t[o],i);}return t;}function Pi(e,t){return e.name===t.name&&Ce(e.source,t.source);}function Ka(e){return[e.source?ve(e.source):"unknown",Ct(e),e.name].filter(Boolean).join(":");}function Ct(e){return qi(e.aggregate||Li);}function qi(e){return e.trim().toUpperCase();}function Za(e,t){return{...e,label:e.label||t.label,role:e.role||t.role,dataType:e.dataType||t.dataType,source:e.source&&t.source?jt(e.source,t.source):e.source||t.source};}function Bi(e){for(let t=0;t<e.length;t+=1){const n=e[t];if(e.some((i,o)=>o!==t&&Yt(i,n)))return!1;}return!0;}function Ot(e,t){return Pi(e,t);}function Yt(e,t){return Ot(e,t)&&H(e)===H(t);}function Wi(e){return`Metric intent has duplicate measure "${e.name}" with the same aggregate (${H(e)}). Use different aggregates to request both, or remove one entry.`;}function Ke(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null;}function Ui(e,t,n){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){n.push(d("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",t));return;}Object.entries(e).forEach(([i,o])=>{if(!i.trim()){n.push(d("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${t}.${i}`));return;}(Array.isArray(o)?o.every(Ke):Ke(o))||n.push(d("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${t}.${i}`));});}}function Vi(e,t){return Oe(e,t).length===1;}function Hi(e,t){return Oe(e,t).length===1;}function Oe(e,t){return t.filter(i=>zi(e,i));}function zi(e,t){return Gi(e,t)?e.source?Ot(t,e):!0:!1;}function Gi(e,t){return!(t.name!==e.name||e.role!==void 0&&t.role!==void 0&&t.role!==e.role||Qi(e,t)&&H(t)!==H(e));}function Qi(e,t){return e.role==="measure"||t.role==="measure"||e.aggregate!==void 0||t.aggregate!==void 0;}function H(e){return Ct(e);}const Xi=/^(\d{4})-(\d{2})-(\d{2})$/,Lt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})$/;function ie(e){if(typeof e!="string")return null;const t=e.trim(),n=Xi.exec(t);if(n){const[,f,b,A]=n;return Ze(f,b,A)?new Date(Date.UTC(Number(f),Number(b)-1,Number(A))):null;}const i=Lt.exec(t);if(!i)return null;const[,o,a,r,l,c,m="00",,u]=i;if(!Ze(o,a,r)||!B(l,0,23)||!B(c,0,59)||!B(m,0,59)||!Ki(u))return null;const p=new Date(t);return Number.isFinite(p.getTime())?p:null;}function Ja(e){return typeof e!="string"||!Lt.test(e.trim())?null:ie(e);}function Ze(e,t,n){const i=Number(e),o=Number(t),a=Number(n);if(!Number.isInteger(i)||!Number.isInteger(o)||!Number.isInteger(a)||o<1||o>12)return!1;const r=new Date(Date.UTC(i,o-1,a));return r.getUTCFullYear()===i&&r.getUTCMonth()===o-1&&r.getUTCDate()===a;}function B(e,t,n){const i=Number(e);return Number.isInteger(i)&&i>=t&&i<=n;}function Ki(e){if(e==="Z")return!0;const t=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(t&&B(t[2],0,23)&&B(t[3],0,59));}function Je(e,t,n){if(e!==void 0){if(!g(e)){n.push(d("invalid_pagination","Pagination must be an object with positive integer page and pageSize.",t));return;}(!Number.isInteger(e.page)||typeof e.page!="number"||e.page<1)&&n.push(d("invalid_pagination_page","Pagination page must be a positive integer.",`${t}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&n.push(d("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${t}.pageSize`));}}function et(e){const t=/* @__PURE__ */new Set();for(const n of e){if(t.has(n))return n;t.add(n);}return null;}function Zi(e,t,n){if(!g(e)){n.push(d("invalid_input_binding","Input bindings must be structured objects.",t));return;}h(e.inputId)||n.push(d("invalid_input_binding","Input bindings need a non-empty inputId.",`${t}.inputId`)),e.kind!==void 0&&e.kind!=="filter"&&e.kind!=="control"&&n.push(d("invalid_input_binding","Input binding kind must be filter or control.",`${t}.kind`)),e.field!==void 0&&I(e.field,`${t}.field`,n),e.relationshipHint!==void 0&&Ye(e.relationshipHint,`${t}.relationshipHint`,n);}function Ye(e,t,n){if(!g(e)){n.push(d("invalid_relationship_hint","Relationship hints must be structured objects.",t));return;}e.relationshipIds!==void 0&&(!Array.isArray(e.relationshipIds)||e.relationshipIds.some(i=>!h(i)))&&n.push(d("invalid_relationship_hint","Relationship hint relationshipIds must be non-empty strings.",`${t}.relationshipIds`));}function Ji(e,t){var i,o;if(((i=e.source)==null?void 0:i.kind)!=="semantic"&&((o=e.source)==null?void 0:o.kind)!=="physical"&&t.push(d("invalid_input_options_source","Input options must use a semantic or physical source.","source")),h(e.inputId)||t.push(d("missing_input_options_input_id","Input options intent needs the inputId it populates.","inputId")),e.search!==void 0&&typeof e.search!="string"&&t.push(d("invalid_input_options_search","Input options search must be a string.","search")),e.matchValues!==void 0){const a=Jt(e.matchValues);a.ok||t.push(d("invalid_input_options_match_values",a.error,"matchValues")),typeof e.search=="string"&&e.search.trim()&&t.push(d("invalid_input_options_match_values","Input options matchValues cannot be combined with search.","matchValues"));}if(e.limit!==void 0&&(typeof e.limit!="number"||!Number.isFinite(e.limit)||!Number.isInteger(e.limit)||e.limit<=0)&&t.push(d("invalid_input_options_limit","Input options limit must be a positive finite number.","limit")),(!e.labelField||!h(e.labelField.name))&&t.push(d("missing_input_options_label_field","Input options intent needs a labelField.","labelField")),I(e.labelField,"labelField",t,{required:!0}),(!e.valueField||!h(e.valueField.name))&&t.push(d("missing_input_options_value_field","Input options intent needs a valueField.","valueField")),I(e.valueField,"valueField",t,{required:!0}),e.searchField!==void 0&&I(e.searchField,"searchField",t,{required:!0}),e.disambiguationFields!==void 0&&(Array.isArray(e.disambiguationFields)?e.disambiguationFields.forEach((a,r)=>{I(a,`disambiguationFields.${r}`,t,{required:!0});}):t.push(d("invalid_input_options_disambiguation_fields","Input options disambiguationFields must be an array of field refs.","disambiguationFields"))),[{field:e.labelField,path:"labelField"},{field:e.valueField,path:"valueField"},...(e.searchField?[{field:e.searchField,path:"searchField"}]:[]),...(Array.isArray(e.disambiguationFields)?e.disambiguationFields.map((a,r)=>({field:a,path:`disambiguationFields.${r}`})):[])].forEach(({field:a,path:r})=>{a!=null&&a.source&&!Ce(a.source,e.source)&&t.push(d("input_options_field_source_mismatch","Input option fields must belong to the declared option source.",`${r}.source`));}),e.dependencies!==void 0){const a=ta(e.dependencies);t.push(...a.errors),a.ok&&ia(e,t);}if(e.population!==void 0){const a=e.population;if(!g(a))t.push(d("invalid_input_options_population","Input options population must be a structured object.","population"));else{const r=a.kind;if(r!=="option_source"&&r!=="related_population"&&t.push(d("invalid_input_options_population","Input options population kind must be option_source or related_population.","population.kind")),r==="option_source"&&a.baseSource!==void 0&&t.push(d("invalid_input_options_population","Input options population baseSource is only valid for related_population.","population.baseSource")),r==="option_source"&&a.relationshipHint!==void 0&&t.push(d("invalid_input_options_population","Input options population relationshipHint is only valid for related_population.","population.relationshipHint")),r==="related_population"){we(a.baseSource,"population.baseSource",t),a.relationshipHint!==void 0&&Ye(a.relationshipHint,"population.relationshipHint",t);const l=a.ifUnreachable;l!==void 0&&l!=="option_source"&&t.push(d("invalid_input_options_population","Input options population ifUnreachable must be option_source.","population.ifUnreachable"));}}}}function ea(e,t){if(!(!("inputs"in e)||e.inputs===void 0)){if(!Array.isArray(e.inputs)){t.push(d("invalid_input_binding","Analytics intent inputs must be an array of input bindings.","inputs"));return;}e.inputs.forEach((n,i)=>Zi(n,`inputs.${i}`,t));}}function ta(e,t="protocol"){const n=[];if(!g(e))return n.push(d("invalid_input_options_dependencies","Input options dependencies must be a structured object.","dependencies")),{ok:!1,errors:n,warnings:[]};const i=e,o=i.mode;if(o!==void 0&&o!=="independent"&&o!=="explicit"&&o!=="all_applicable"&&n.push(d("invalid_input_options_dependencies","Input options dependencies mode must be independent, explicit, or all_applicable.","dependencies.mode")),me(i.includeInputIds,"dependencies.includeInputIds",n,"Input options includeInputIds must be non-empty strings."),me(i.excludeInputIds,"dependencies.excludeInputIds",n,"Input options excludeInputIds must be non-empty strings."),o==="all_applicable"&&i.includeInputIds!==void 0&&n.push(d("invalid_input_options_dependencies","All applicable dependencies cannot specify includeInputIds.","dependencies.includeInputIds")),me(i.omitInputIds,"dependencies.omitInputIds",n,"Input options omitInputIds must be non-empty strings."),Array.isArray(i.omitInputIds)){const a=new Set(Array.isArray(i.includeInputIds)?i.includeInputIds:[]);(o!=="explicit"||new Set(i.omitInputIds).size!==i.omitInputIds.length||i.omitInputIds.some(r=>!a.has(r)))&&n.push(d("invalid_input_options_dependencies","A browse override may only omit unique ids from an explicit includeInputIds list.","dependencies.omitInputIds"));}return t==="dashboard"&&na(i,n),{ok:n.length===0,errors:n,warnings:[]};}function na(e,t){const{mode:n,includeInputIds:i,excludeInputIds:o}=e;n===void 0&&t.push(d("invalid_input_options_dependencies","Dashboard option dependencies must declare a mode.","dependencies.mode"));for(const[a,r]of[["dependencies.includeInputIds",i],["dependencies.excludeInputIds",o]])Array.isArray(r)&&new Set(r).size!==r.length&&t.push(d("invalid_input_options_dependencies","Dashboard option dependency input IDs must be unique.",a));n==="independent"&&(i!==void 0||o!==void 0)&&t.push(d("invalid_input_options_dependencies","Independent dashboard dependencies cannot specify input IDs.","dependencies")),n==="explicit"&&(!Array.isArray(i)||i.length===0||o!==void 0)&&t.push(d("invalid_input_options_dependencies","Explicit dashboard dependencies require included input IDs and cannot specify exclusions.","dependencies"));}function ia(e,t){var o,a,r;const n=new Set(Array.isArray(e.inputs)?e.inputs.map(l=>g(l)?l.inputId:void 0).filter(l=>typeof l=="string"):[]),i=new Set(((o=e.dependencies)==null?void 0:o.omitInputIds)||[]);for(const l of((a=e.dependencies)==null?void 0:a.includeInputIds)||[])!n.has(l)&&!i.has(l)&&t.push(d("invalid_input_options_dependencies",`Input options dependency "${l}" is not declared in inputs.`,"dependencies.includeInputIds"));for(const l of((r=e.dependencies)==null?void 0:r.excludeInputIds)||[])l!==e.inputId&&!n.has(l)&&t.push(d("invalid_input_options_dependencies",`Input options dependency exclusion "${l}" is not the populated inputId and is not declared in inputs.`,"dependencies.excludeInputIds"));}function me(e,t,n,i){e!==void 0&&(!Array.isArray(e)||e.some(o=>!h(o)))&&n.push(d("invalid_input_options_dependencies",i,t));}new Set(Kt);function aa(e,t){if(e.analysis===void 0)return;if(!g(e.analysis)){t.push(d("invalid_measure_analysis","Metric analysis must be a structured object.","analysis"));return;}if(e.analysis.kind!=="period_change"){t.push(d("invalid_measure_analysis","Metric analysis kind is not supported.","analysis.kind"));return;}e.dateField||t.push(d("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||t.push(d("missing_analysis_time_grain","Period-change analysis needs a timeGrain.","timeGrain")),e.analysis.orderBy!==void 0&&e.analysis.orderBy!=="absolute_change"&&e.analysis.orderBy!=="positive_change"&&e.analysis.orderBy!=="negative_change"&&e.analysis.orderBy!=="period"&&t.push(d("invalid_measure_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:n}=e.analysis;n!==void 0&&ae(n,"analysis.timeWindow",t);}function ae(e,t,n){const i=Se(e,{use:"analysis"});i.ok||n.push(d("invalid_time_window",pt(i.refusal),i.refusal.path?`${t}.${i.refusal.path}`:t));}function tt(e,t,n){if(e!==void 0){if(!Array.isArray(e)){n.push(d("invalid_analytics_filters","Analytics filters must be an array.",t));return;}e.forEach((i,o)=>{var c;const a=`${t}.${o}`;if(!g(i)){n.push(d("invalid_analytics_filter","Analytics filter must be a structured object.",a));return;}const r=i;I(r.field,`${a}.field`,n,{required:!0}),r.scope!==void 0&&r.scope!=="row"&&r.scope!=="aggregate"&&n.push(d("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${a}.scope`)),r.scope==="aggregate"&&((c=r.field)==null?void 0:c.role)!==void 0&&r.field.role!=="measure"&&n.push(d("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${a}.scope`));const l=r.operator==="is_null"||r.operator==="is_not_null";if(r.operator!==void 0&&r.operator!=="="&&r.operator!=="!="&&r.operator!=="in"&&r.operator!=="not_in"&&r.operator!=="contains"&&r.operator!=="not_contains"&&r.operator!=="between"&&r.operator!=="not_between"&&r.operator!==">"&&r.operator!==">="&&r.operator!=="<"&&r.operator!=="<="&&r.operator!=="is_null"&&r.operator!=="is_not_null"&&n.push(d("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${a}.operator`)),r.values===void 0&&!l&&n.push(d("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",a)),l&&r.values!==void 0){n.push(d("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${a}.values`));return;}if(r.values!==void 0&&!Array.isArray(r.values)){n.push(d("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${a}.values`));return;}if(r.values!==void 0){const m=r.values.length;if(r.operator==="between"||r.operator==="not_between"){m!==2&&n.push(d("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${a}.values`));return;}(r.operator==="contains"||r.operator==="not_contains"||r.operator==="="||r.operator==="!="||r.operator===">"||r.operator===">="||r.operator==="<"||r.operator==="<="||r.operator===void 0)&&m!==1&&n.push(d("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${a}.values`));}});}}function Pt(e){var i;const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:n,repairHints:[{code:"invalid_analytics_intent",recommendedNextStep:"Send one structured analytics intent object with kind, source, and required fields."}]};if(e.kind==="matrix"){const o=Di.safeParse(e);return o.success||t.push(...o.error.issues.map(a=>d("invalid_matrix_intent",a.message,a.path.join(".")))),{ok:t.length===0,errors:t,warnings:n,repairHints:nt(t)};}if(e.version!==void 0&&e.version!==1&&t.push(d("invalid_version","Analytics intent version must be 1.","version")),we(e.source,"source",t),sa(e,t),ea(e,t),"relationshipHint"in e&&e.relationshipHint!==void 0&&Ye(e.relationshipHint,"relationshipHint",t),e.kind==="metric"){const o=Array.isArray(e.measures)?e.measures.filter(a=>g(a)&&h(a.name)):[];if(!Array.isArray(e.measures)||e.measures.length===0?t.push(d("missing_measure","Metric intent needs at least one measure.","measures")):e.measures.some(a=>!g(a)||!h(a.name))&&t.push(d("invalid_measure_list","Metric intent measures must be an array of field references with names.","measures")),o.forEach((a,r)=>{I(a,`measures.${r}`,t,{required:!0});}),o.length>0&&!Bi(o)){const a=o.find((r,l)=>o.some((c,m)=>m!==l&&Yt(c,r)));a&&t.push(d("duplicate_measure",Wi(a),"measures"));}if(g(e.primaryMeasure)&&h(e.primaryMeasure.name)&&Oe(e.primaryMeasure,o).length>1&&t.push(d("ambiguous_primary_measure","Metric intent primaryMeasure must identify exactly one selected measure.","primaryMeasure")),e.primaryMeasure!==void 0&&(I(e.primaryMeasure,"primaryMeasure",t,{required:!0}),g(e.primaryMeasure)&&h(e.primaryMeasure.name)&&o.length>0&&!Vi(e.primaryMeasure,o)&&t.push(d("invalid_primary_measure","Metric intent primaryMeasure must match one measure field reference.","primaryMeasure"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?t.push(d("invalid_measure_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(a=>!g(a)||!h(a.name))&&t.push(d("invalid_measure_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&I(e.dateField,"dateField",t),e.timeWindow!==void 0&&(ae(e.timeWindow,"timeWindow",t),e.dateField||t.push(d("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),tt(e.filters,"filters",t),Array.isArray(e.dimensions)&&e.dimensions.forEach((a,r)=>{I(a,`dimensions.${r}`,t);}),e.orderBy!==void 0){if(!g(e.orderBy))t.push(d("invalid_measure_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(I(e.orderBy.field,"orderBy.field",t,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&t.push(d("invalid_measure_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),g(e.orderBy.field)&&h(e.orderBy.field.name)){const a=[...o,...(e.timeGrain&&e.dateField&&g(e.dateField)?[e.dateField]:[]),...(Array.isArray(e.dimensions)?e.dimensions.filter(r=>g(r)&&h(r.name)):[])];a.length>0&&!Hi(e.orderBy.field,a)&&t.push(d("invalid_measure_order_by","Metric intent orderBy.field must match one selected measure, grouped dateField, or dimension.","orderBy.field"));}}aa(e,t);}else if(e.kind==="records"){if(!Array.isArray(e.fields)||e.fields.length===0?t.push(d("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(o=>!g(o)||!h(o.name))&&t.push(d("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((o,a)=>{I(o,`fields.${a}`,t);}),e.dateField!==void 0&&I(e.dateField,"dateField",t),Je(e.pagination,"pagination",t),e.timeWindow!==void 0&&(ae(e.timeWindow,"timeWindow",t),e.dateField||t.push(d("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),tt(e.filters,"filters",t),Array.isArray(e.filters)&&e.filters.forEach((o,a)=>{g(o)&&o.scope==="aggregate"&&t.push(d("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${a}.scope`));}),e.orderBy!==void 0&&(g(e.orderBy)?(I(e.orderBy.field,"orderBy.field",t,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&t.push(d("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):t.push(d("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy"))),e.totals!==void 0)if(!g(e.totals))t.push(d("invalid_records_totals","Records totals must be a structured server totals request.","totals"));else{e.totals.mode!=="server"&&t.push(d("invalid_records_totals","Records totals mode must be server.","totals.mode"));const o=e.totals.measures;!Array.isArray(o)||o.length===0?t.push(d("missing_records_totals_measures","Records server totals need at least one measure.","totals.measures")):o.forEach((a,r)=>{I(a,`totals.measures.${r}`,t,{required:!0}),(!g(a)||a.role!=="measure")&&t.push(d("invalid_records_totals_measure","Records server totals measures must be measure field references.",`totals.measures.${r}.role`));});}}else e.kind==="inputOptions"?Ji(e,t):e.kind==="sql"?(((i=e.source)==null?void 0:i.kind)!=="sql"&&t.push(d("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),h(e.sql)||t.push(d("missing_sql","SQL analytics intent needs SQL text.","sql")),Ui(e.defaultParameters,"defaultParameters",t),Array.isArray(e.fields)&&e.fields.forEach((o,a)=>{I(o,`fields.${a}`,t);}),Je(e.pagination,"pagination",t)):t.push(d("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:t.length===0,errors:t,warnings:n,repairHints:nt(t)};}function sa(e,t){if(!(!("derivedFields"in e)||e.derivedFields===void 0)){if(!Array.isArray(e.derivedFields)){t.push(d("invalid_derived_fields","Analytics intent derivedFields must be an array of derived field definitions.","derivedFields"));return;}e.derivedFields.forEach((n,i)=>{Ae(n).errors.forEach(a=>{t.push({...a,path:a.path?`derivedFields.${i}.${a.path}`:`derivedFields.${i}`});});});}}function ra(e){const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_operation_intent","Operation intent must be a structured object.")],warnings:n,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&t.push(d("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?t.push(d("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((i,o)=>{h(i.id)||t.push(d("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${o}.id`)),i.timeWindow!==void 0&&ae(i.timeWindow,`obligations.${o}.timeWindow`,t),h(i.prompt)||t.push(d("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${o}.prompt`));});else if(e.kind==="dashboard_change"){if(h(e.instruction)||t.push(d("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const i=Pt(e.analyticsIntent);t.push(...i.errors),n.push(...i.warnings);}}else t.push(d("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:t.length===0,errors:t,warnings:n,repairHints:qt(t)};}function es(e){const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:n,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&t.push(d("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&t.push(d("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const i=ra(e.operationIntent);return t.push(...i.errors),n.push(...i.warnings),Array.isArray(e.plannedToolCalls)||t.push(d("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:t.length===0,errors:t,warnings:n,repairHints:qt(t)};}function qt(e){return e.map(t=>({code:t.code,recommendedNextStep:t.code==="missing_obligations"?"Normalize the user request into one or more typed analytics obligations before recovery planning.":"Correct the operation/recovery contract shape before planning execution."}));}function nt(e){return e.map(t=>{switch(t.code){case"invalid_matrix_intent":return{code:t.code,recommendedNextStep:`Correct MatrixSpec at ${t.path||"the definition"}: ${t.message} Keep presentation and matrixWindowRequest outside the intent.`};case"missing_source":return{code:t.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_measure":return{code:t.code,fieldRole:"measure",recommendedNextStep:"Choose one exact measure from the grounded schema candidates."};case"missing_record_fields":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_matrix_rows":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Choose at least one row axis level for the matrix table."};case"missing_matrix_values":return{code:t.code,fieldRole:"measure",recommendedNextStep:"Choose at least one value field for the matrix table."};case"unsupported_matrix_sql_source":return{code:t.code,fieldRole:"source",recommendedNextStep:"Use a semantic or explorer-backed source for matrix tables; raw SQL matrix tables are not supported."};case"missing_input_options_input_id":return{code:t.code,fieldRole:"input",recommendedNextStep:"Provide the inputId that these option values populate."};case"missing_input_options_label_field":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Provide the human-readable field used as option labels."};case"missing_input_options_value_field":return{code:t.code,fieldRole:"dimension",recommendedNextStep:"Provide the stable field used as option values."};case"missing_sql":return{code:t.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:t.code,fieldRole:"sql",recommendedNextStep:"Use one canonical SQL text location for the intent; prefer top-level sql."};case"missing_semantic_domain":case"missing_dataset_name":case"missing_connection_id":case"missing_table_name":return{code:t.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return;}}).filter(t=>!!t);}function oa(e,t,n,i){if(!e||typeof e!="object"){n.push(d("invalid_view","Dashboard view must be an object.",t));return;}if(h(e.title)||n.push(d("missing_view_title","Dashboard view needs a title.",t)),!e.presentation||typeof e.presentation!="object"){n.push(d("missing_presentation","Dashboard view needs a presentation.",`${t}.presentation`));return;}if(e.presentation.kind==="text"){h(e.text)||i.push(d("missing_text_content","Text views should include text content.",`${t}.text`));return;}if(!e.analytics){n.push(d("missing_view_analytics","Non-text dashboard views need analytics intent.",`${t}.analytics`));return;}e.presentation.kind==="matrixTable"&&e.analytics.kind!=="matrix"&&n.push(d("invalid_matrix_view_analytics","Matrix table views need matrix analytics intent.",`${t}.analytics.kind`));const o=Pt(e.analytics);for(const a of o.errors)n.push(d(a.code,a.message,`${t}.analytics${a.path?`.${a.path}`:""}`));for(const a of o.warnings)i.push(d(a.code,a.message,`${t}.analytics${a.path?`.${a.path}`:""}`));}function ts(e){const t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[d("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:n};e.version!==1&&t.push(d("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&t.push(d("invalid_kind","Experience intent kind must be dashboard.")),h(e.title)||t.push(d("missing_title","Dashboard intent needs a title.","title"));const i=Array.isArray(e.inputs)?e.inputs:[],o=et(i.filter(g).map(c=>c.id).filter(c=>typeof c=="string"));o&&t.push(d("duplicate_input_id",`Duplicate input id: ${o}.`,"inputs"));for(const[c,m]of i.entries()){const u=`inputs.${c}`;if(!g(m)){t.push(d("invalid_input","Dashboard input must be an object.",u));continue;}h(m.id)||t.push(d("missing_input_id","Input needs an id.",`${u}.id`)),h(m.label)||t.push(d("missing_input_label","Input needs a label.",`${u}.label`)),!m.field||!h(m.field.name)?t.push(d("missing_input_field","Input needs a field.",`${u}.field`)):I(m.field,`${u}.field`,t);}const a=Array.isArray(e.sections)?e.sections:[];a.length===0&&t.push(d("missing_sections","Dashboard intent needs at least one section.","sections"));const r=a.flatMap(c=>c&&typeof c=="object"&&Array.isArray(c.views)?c.views.filter(g).map(m=>m.id).filter(m=>!!m):[]),l=et(r);l&&t.push(d("duplicate_view_id",`Duplicate dashboard view id: ${l}.`,"sections"));for(const[c,m]of a.entries()){const u=`sections.${c}`;if(!m||typeof m!="object"){t.push(d("invalid_section","Dashboard section must be an object.",u));continue;}if(h(m.title)||t.push(d("missing_section_title","Dashboard section needs a title.",u)),!Array.isArray(m.views)||m.views.length===0){t.push(d("missing_section_views","Dashboard section needs at least one view.",`${u}.views`));continue;}for(const[p,f]of m.views.entries())oa(f,`${u}.views.${p}`,t,n);}return{ok:t.length===0,errors:t,warnings:n};}export{Pt as $,xt as A,Zn as B,ye as C,ti as D,T as E,$a as F,vi as G,Ft as H,Si as I,wi as J,Et as K,Jn as L,z as M,ze as N,xi as O,je as P,Qe as Q,se as R,Ti as S,Ua as T,Ci as U,Ha as V,$e as W,Zt as X,Jt as Y,ie as Z,ta as _,xa as a,Di as a$,ra as a0,es as a1,ts as a2,Ae as a3,xe as a4,qn as a5,Bn as a6,zn as a7,ga as a8,Gn as a9,Xa as aA,Ka as aB,Ct as aC,Za as aD,dn as aE,ua as aF,dt as aG,pn as aH,cn as aI,ca as aJ,E as aK,gn as aL,an as aM,Q as aN,ma as aO,Se as aP,pa as aQ,fa as aR,pt as aS,ha as aT,vt as aU,Xn as aV,Kn as aW,wa as aX,ka as aY,U as aZ,ba as a_,gt as aa,yt as ab,Ue as ac,bt as ad,ya as ae,_a as af,ii as ag,Ra as ah,ja as ai,Ca as aj,wt as ak,Re as al,Oa as am,Ya as an,La as ao,si as ap,Pa as aq,qa as ar,Ba as as,Wa as at,za as au,Ga as av,j as aw,Rt as ax,Ce as ay,jt as az,ni as b,ne as b0,mn as b1,Ai as b2,Va as b3,Sa as b4,Ia as b5,Mn as b6,De as b7,He as b8,va as b9,en as ba,St as c,Ma as d,Ta as e,_e as f,ei as g,Na as h,Da as i,Fe as j,Be as k,F as l,It as m,Fa as n,Qa as o,Ja as p,Pi as q,ot as r,Ea as s,ve as t,$t as u,Aa as v,Te as w,gi as x,Dt as y,be as z};
@@ -1 +1 @@
1
- import{c as v,g as M,a as A,b as q,d as N,e as y,h as D,j as w}from"./resolve-dashboard-input-context-BDY7KwRe.js";import{d as E}from"./validators-Dg2kyF4_.js";import{g as L,m as x}from"./matrix-analytical-definition-5T-2euHZ.js";const O=[{value:"only",label:"The only value",hint:"Shows the value when exactly one matches. When more than one matches, readers see nothing."},{value:"first",label:"First by…",hint:"Shows the first value by the order you choose."},{value:"list",label:"List",hint:"Shows the distinct values in order, joined with a separator."}],k={SUM:{number:"Total",date:"Total",other:"Total"},AVG:{number:"Average",date:"Average",other:"Average"},MIN:{number:"Lowest",date:"Earliest",other:"Min"},MAX:{number:"Highest",date:"Latest",other:"Max"},MEDIAN:{number:"Median",date:"Median",other:"Median"},COUNT:{number:"Count",date:"Count",other:"Count"},DISTINCT:{number:"Count distinct",date:"Count distinct",other:"Count distinct"}};function h(e){return E(e)==="aggregate";}function X(e){const t=e==null?void 0:e.dataType;if(h(e))return[{value:"calculation",label:"The calculation’s value",hint:"Shows the calculation over the rows the filters keep; it aggregates itself."}];const a=y(t),i=a==="number"?"number":a==="date"?"date":"other",o=[...D(t)];return i==="date"&&o.push({value:"MIN",label:"Min"},{value:"MAX",label:"Max"}),[...O,...o.map(({value:l})=>{var n,r;return{value:l,label:((n=k[l])==null?void 0:n[i])??l,hint:`Shows the ${(((r=k[l])==null?void 0:r[i])??l).toLowerCase()} of the rows the filters keep.`};})];}function H(e){return h(e)?"calculation":y(e.dataType)==="number"?w(y(e.dataType)):"only";}function b(e){return e!=="only"&&e!=="first"&&e!=="list";}function B(e){return e.mode!=="data"||!e.field||!b(e.get)?!1:e.get==="COUNT"||e.get==="DISTINCT"?!0:y(e.field.dataType)==="number";}function G(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e).replace(/-/g,"").slice(0,10))??Math.random().toString(36).slice(2,12);}function V(){return`var_${G()}`;}function z(){return{id:V(),name:"",mode:"data",sql:"",get:"only",sortDirection:"asc"};}const _={id:"catalog",name:"catalog",label:"catalog",derivedLabel:"catalog",alias:"catalog",sourceField:"catalog",source:"catalog",qualifiedFieldName:"catalog",dataType:"catalog",nativeDataType:"catalog",description:"catalog",qualifiedEntityName:"catalog",dateFormat:"catalog",customFormat:"catalog",granularity:"catalog",entityId:"catalog",entityName:"catalog",entityType:"catalog",expression:"catalog",calculatedFormula:"catalog",derivedField:"catalog",format:"catalog",semanticTemporalPresentation:"catalog",calculationRepresentation:"catalog",calculatedFieldOrigin:"catalog",labelOrigin:"catalog",formatOrigin:"catalog",fieldScope:"catalog",timeDrillPath:"catalog",aliasTemplate:"catalog",valueAliases:"catalog",isPreAggregated:"catalog",role:"shelf",aggregate:"shelf",aggregateOrigin:"shelf",semanticAggregate:"shelf",effectiveAggregate:"shelf",aggregateSource:"shelf",comparison:"shelf",comparisonPolarity:"shelf",semanticComparisonPolarity:"shelf",parameters:"shelf",direction:"shelf",grainMode:"shelf"};function T(e){return Object.fromEntries(Object.entries(e).filter(([t])=>_[t]!=="shelf"));}function K(e){var g,u,m,d,p;const{query:t,get:a}=e,i=t.config??{},o=(g=i.metricColumns)==null?void 0:g[0],l=(u=i.groupByColumns)==null?void 0:u[0],n=(m=i.sortByColumns)==null?void 0:m[0],r=n?T(o&&n.id===o.id?o:n):void 0,s=(d=t.sql)!=null&&d.trim()?t.sql:"";return{id:e.id,name:e.name,...(e.label?{label:e.label}:{}),mode:s?"sql":"data",dataSource:t.dataSource,connectionId:t.connectionId,sql:s,field:o&&a.kind==="aggregate"?T(o):l?T(l):void 0,get:a.kind==="aggregate"?h(o)?"calculation":(o==null?void 0:o.aggregate)??"SUM":a.kind,sortField:r,sortDirection:(n==null?void 0:n.direction)??"asc",...(a.kind==="list"?{listLimit:a.limit,listSeparator:a.separator}:{}),conditions:i.filters??null,calculatedFields:t.calculatedFields,presentation:e.presentation,emptyText:e.emptyText,...(a.kind==="aggregate"&&((p=o==null?void 0:o.comparison)==null?void 0:p.mode)==="explicit"?{comparison:o.comparison}:{})};}function P(e,t){var n;const a=t.name.trim();if(a)return a;const i=(n=t.label)!=null&&n.trim()?v(t.label):t.field?v(t.field.name||t.field.label):t.mode==="sql"?"sql_value":"variable",o=new Set(M(e,{source:"dataVariable",variableId:t.id},{cardInputs:"taken"}));let l=i;for(let r=2;o.has(l);r+=1)l=`${i}_${r}`;return l;}function Q(e,t){var g,u,m,d,p,f,F,I;const a=P(t,e),i={id:e.id,name:a,...((g=e.label)!=null&&g.trim()?{label:e.label.trim()}:{}),...(e.presentation?{presentation:e.presentation}:{}),...((u=e.emptyText)!=null&&u.trim()?{emptyText:e.emptyText}:{})};if(e.mode==="sql")return{...i,query:{...(e.connectionId?{connectionId:e.connectionId}:{}),...(e.dataSource?{dataSource:e.dataSource}:{}),sql:e.sql},get:e.get==="first"?{kind:"first"}:{kind:"only"}};const o=((m=e.dataSource)==null?void 0:m.connectionId)||((f=(p=(d=e.dataSource)==null?void 0:d.selectedEntities)==null?void 0:p[0])==null?void 0:f.connectionId),l={...(o?{connectionId:o}:{}),...(e.dataSource?{dataSource:e.dataSource}:{}),...((F=e.calculatedFields)!=null&&F.length?{calculatedFields:e.calculatedFields}:{}),config:{...(e.conditions?{filters:e.conditions}:{})}},n=l.config,r=e.field;let s;if(!r)s=b(e.get)?{kind:"aggregate"}:{kind:e.get};else if(b(e.get)){const{comparison:S,...c}=C(r,e.get);n.metricColumns=[((I=e.comparison)==null?void 0:I.mode)==="explicit"&&e.comparison.spec.kind!=="target"&&B(e)?{...c,comparison:e.comparison}:c],s={kind:"aggregate"};}else if(h(r))n.metricColumns=[C(r,"calculation")],s={kind:"aggregate"};else if(n.groupByColumns=[U(r)],e.get==="list"?s={kind:"list",...(e.listLimit?{limit:e.listLimit}:{}),...(e.listSeparator!==void 0&&e.listSeparator!==", "?{separator:e.listSeparator}:{})}:s={kind:e.get},e.get!=="only"){const S=e.sortField??r;if(j(S,r)){const c=n.groupByColumns[0];n.sortByColumns=[{...c,role:"sortby",direction:e.sortDirection}];}else{const c=C(S,e.sortDirection==="desc"?"MAX":"MIN");n.metricColumns=[c],n.sortByColumns=[{...c,role:"sortby",direction:e.sortDirection}];}}return{...i,query:l,get:s};}function C(e,t){const a=A(e,"metrics",[],q("metrics",e));return h(e)||t==="calculation"||!b(t)?a:{...a,...x(a,t,"explicit"),...L(a,N(e.name,t))};}function U(e){const t=A(e,"groupBy",[],q("groupBy",e));if(e.granularity||!("granularity"in t))return t;const{granularity:a,...i}=t;return i;}function j(e,t){return e.name===t.name&&(e.qualifiedEntityName??e.entityName??"")===(t.qualifiedEntityName??t.entityName??"");}function Y(e){var t,a;if(e.mode==="sql")return e.connectionId?e.sql.trim()?void 0:"Write the SQL that returns the value.":"Choose a connection.";if(!((a=(t=e.dataSource)==null?void 0:t.selectedEntities)!=null&&a.length))return"Choose a source.";if(!e.field)return"Choose a field.";}export{_ as S,X as a,K as b,B as c,H as d,z as e,P as f,Y as g,b as i,V as n,h as o,Q as v};
1
+ import{c as v,g as M,a as A,b as q,d as N,e as y,h as D,j as w}from"./resolve-dashboard-input-context-B-0tONJg.js";import{d as E}from"./validators-BPGmPz8-.js";import{g as L,m as x}from"./matrix-analytical-definition-Bd-dXB8q.js";const O=[{value:"only",label:"The only value",hint:"Shows the value when exactly one matches. When more than one matches, readers see nothing."},{value:"first",label:"First by…",hint:"Shows the first value by the order you choose."},{value:"list",label:"List",hint:"Shows the distinct values in order, joined with a separator."}],k={SUM:{number:"Total",date:"Total",other:"Total"},AVG:{number:"Average",date:"Average",other:"Average"},MIN:{number:"Lowest",date:"Earliest",other:"Min"},MAX:{number:"Highest",date:"Latest",other:"Max"},MEDIAN:{number:"Median",date:"Median",other:"Median"},COUNT:{number:"Count",date:"Count",other:"Count"},DISTINCT:{number:"Count distinct",date:"Count distinct",other:"Count distinct"}};function h(e){return E(e)==="aggregate";}function X(e){const t=e==null?void 0:e.dataType;if(h(e))return[{value:"calculation",label:"The calculation’s value",hint:"Shows the calculation over the rows the filters keep; it aggregates itself."}];const a=y(t),i=a==="number"?"number":a==="date"?"date":"other",o=[...D(t)];return i==="date"&&o.push({value:"MIN",label:"Min"},{value:"MAX",label:"Max"}),[...O,...o.map(({value:l})=>{var n,r;return{value:l,label:((n=k[l])==null?void 0:n[i])??l,hint:`Shows the ${(((r=k[l])==null?void 0:r[i])??l).toLowerCase()} of the rows the filters keep.`};})];}function H(e){return h(e)?"calculation":y(e.dataType)==="number"?w(y(e.dataType)):"only";}function b(e){return e!=="only"&&e!=="first"&&e!=="list";}function B(e){return e.mode!=="data"||!e.field||!b(e.get)?!1:e.get==="COUNT"||e.get==="DISTINCT"?!0:y(e.field.dataType)==="number";}function G(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e).replace(/-/g,"").slice(0,10))??Math.random().toString(36).slice(2,12);}function V(){return`var_${G()}`;}function z(){return{id:V(),name:"",mode:"data",sql:"",get:"only",sortDirection:"asc"};}const _={id:"catalog",name:"catalog",label:"catalog",derivedLabel:"catalog",alias:"catalog",sourceField:"catalog",source:"catalog",qualifiedFieldName:"catalog",dataType:"catalog",nativeDataType:"catalog",description:"catalog",qualifiedEntityName:"catalog",dateFormat:"catalog",customFormat:"catalog",granularity:"catalog",entityId:"catalog",entityName:"catalog",entityType:"catalog",expression:"catalog",calculatedFormula:"catalog",derivedField:"catalog",format:"catalog",semanticTemporalPresentation:"catalog",calculationRepresentation:"catalog",calculatedFieldOrigin:"catalog",labelOrigin:"catalog",formatOrigin:"catalog",fieldScope:"catalog",timeDrillPath:"catalog",aliasTemplate:"catalog",valueAliases:"catalog",isPreAggregated:"catalog",role:"shelf",aggregate:"shelf",aggregateOrigin:"shelf",semanticAggregate:"shelf",effectiveAggregate:"shelf",aggregateSource:"shelf",comparison:"shelf",comparisonPolarity:"shelf",semanticComparisonPolarity:"shelf",parameters:"shelf",direction:"shelf",grainMode:"shelf"};function T(e){return Object.fromEntries(Object.entries(e).filter(([t])=>_[t]!=="shelf"));}function K(e){var g,u,m,d,p;const{query:t,get:a}=e,i=t.config??{},o=(g=i.metricColumns)==null?void 0:g[0],l=(u=i.groupByColumns)==null?void 0:u[0],n=(m=i.sortByColumns)==null?void 0:m[0],r=n?T(o&&n.id===o.id?o:n):void 0,s=(d=t.sql)!=null&&d.trim()?t.sql:"";return{id:e.id,name:e.name,...(e.label?{label:e.label}:{}),mode:s?"sql":"data",dataSource:t.dataSource,connectionId:t.connectionId,sql:s,field:o&&a.kind==="aggregate"?T(o):l?T(l):void 0,get:a.kind==="aggregate"?h(o)?"calculation":(o==null?void 0:o.aggregate)??"SUM":a.kind,sortField:r,sortDirection:(n==null?void 0:n.direction)??"asc",...(a.kind==="list"?{listLimit:a.limit,listSeparator:a.separator}:{}),conditions:i.filters??null,calculatedFields:t.calculatedFields,presentation:e.presentation,emptyText:e.emptyText,...(a.kind==="aggregate"&&((p=o==null?void 0:o.comparison)==null?void 0:p.mode)==="explicit"?{comparison:o.comparison}:{})};}function P(e,t){var n;const a=t.name.trim();if(a)return a;const i=(n=t.label)!=null&&n.trim()?v(t.label):t.field?v(t.field.name||t.field.label):t.mode==="sql"?"sql_value":"variable",o=new Set(M(e,{source:"dataVariable",variableId:t.id},{cardInputs:"taken"}));let l=i;for(let r=2;o.has(l);r+=1)l=`${i}_${r}`;return l;}function Q(e,t){var g,u,m,d,p,f,F,I;const a=P(t,e),i={id:e.id,name:a,...((g=e.label)!=null&&g.trim()?{label:e.label.trim()}:{}),...(e.presentation?{presentation:e.presentation}:{}),...((u=e.emptyText)!=null&&u.trim()?{emptyText:e.emptyText}:{})};if(e.mode==="sql")return{...i,query:{...(e.connectionId?{connectionId:e.connectionId}:{}),...(e.dataSource?{dataSource:e.dataSource}:{}),sql:e.sql},get:e.get==="first"?{kind:"first"}:{kind:"only"}};const o=((m=e.dataSource)==null?void 0:m.connectionId)||((f=(p=(d=e.dataSource)==null?void 0:d.selectedEntities)==null?void 0:p[0])==null?void 0:f.connectionId),l={...(o?{connectionId:o}:{}),...(e.dataSource?{dataSource:e.dataSource}:{}),...((F=e.calculatedFields)!=null&&F.length?{calculatedFields:e.calculatedFields}:{}),config:{...(e.conditions?{filters:e.conditions}:{})}},n=l.config,r=e.field;let s;if(!r)s=b(e.get)?{kind:"aggregate"}:{kind:e.get};else if(b(e.get)){const{comparison:S,...c}=C(r,e.get);n.metricColumns=[((I=e.comparison)==null?void 0:I.mode)==="explicit"&&e.comparison.spec.kind!=="target"&&B(e)?{...c,comparison:e.comparison}:c],s={kind:"aggregate"};}else if(h(r))n.metricColumns=[C(r,"calculation")],s={kind:"aggregate"};else if(n.groupByColumns=[U(r)],e.get==="list"?s={kind:"list",...(e.listLimit?{limit:e.listLimit}:{}),...(e.listSeparator!==void 0&&e.listSeparator!==", "?{separator:e.listSeparator}:{})}:s={kind:e.get},e.get!=="only"){const S=e.sortField??r;if(j(S,r)){const c=n.groupByColumns[0];n.sortByColumns=[{...c,role:"sortby",direction:e.sortDirection}];}else{const c=C(S,e.sortDirection==="desc"?"MAX":"MIN");n.metricColumns=[c],n.sortByColumns=[{...c,role:"sortby",direction:e.sortDirection}];}}return{...i,query:l,get:s};}function C(e,t){const a=A(e,"metrics",[],q("metrics",e));return h(e)||t==="calculation"||!b(t)?a:{...a,...x(a,t,"explicit"),...L(a,N(e.name,t))};}function U(e){const t=A(e,"groupBy",[],q("groupBy",e));if(e.granularity||!("granularity"in t))return t;const{granularity:a,...i}=t;return i;}function j(e,t){return e.name===t.name&&(e.qualifiedEntityName??e.entityName??"")===(t.qualifiedEntityName??t.entityName??"");}function Y(e){var t,a;if(e.mode==="sql")return e.connectionId?e.sql.trim()?void 0:"Write the SQL that returns the value.":"Choose a connection.";if(!((a=(t=e.dataSource)==null?void 0:t.selectedEntities)!=null&&a.length))return"Choose a source.";if(!e.field)return"Choose a field.";}export{_ as S,X as a,K as b,B as c,H as d,z as e,P as f,Y as g,b as i,V as n,h as o,Q as v};