react-semaphor 0.1.415 → 0.1.416

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.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../data-app-sdk-adapters/index.cjs"),i=require("react/jsx-runtime"),c=require("react"),Be=require("../chunks/source-identity-BM2FvJDP.js");require("../chunks/analyze-result-contract-8nxUOWp8.js");const se=require("../chunks/search-DNCejM7Z.js"),Ke=require("../chunks/x-B6ghREd2.js"),$r=require("../chunks/validators-CB9BFarT.js");function de(e,r,t={}){return{...t,name:e,role:r}}function Or(e){return e}function Br(e){return e}const Kr={source:{semantic(e){return{...e,kind:"semantic"}},sql(e){return{...e,kind:"sql"}}},field:{measure(e,r){return de(e,"measure",r)},dimension(e,r){return de(e,"dimension",r)},date(e,r){return de(e,"date",r)},id(e,r){return de(e,"id",r)}},filter(e){return{...e,kind:"filter"}},bindInput(e,r){return{toAnalyticsInput(){const[t]=w.toSemaphorInputSnapshots([e]),n=w.toSemaphorInputBinding({...r,inputId:r.inputId||t.inputId});return{...t,inputId:n.inputId,...n.kind?{kind:n.kind}:{},...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}}},control(e){return{...e,kind:"control"}},sqlParam(e){return{...e,kind:"control",role:"sqlParam"}},derivedField(e){return{...e,kind:"derived_field",expressionLanguage:e.expressionLanguage||"semaphor_sql_template"}},metric(e){return{...e,queryKind:"metric"}},analysis(e){return{...e,queryKind:"analysis"}},records(e){return{...e,queryKind:"records"}},inputOptions(e){return{...e,queryKind:"inputOptions"}},sql(e){return{...e,queryKind:"sql"}},matrix(e){return{...e,queryKind:"matrix"}}},ie=10,Re=8;function Wr(e){const r=e==null?void 0:e.result;if(r)switch(r.kind){case"records":return te({title:"Records",rowNoun:"rows",records:r.records,columns:r.columns,rowCount:r.rowCount});case"sql":return te({title:"SQL Rows",rowNoun:"rows",records:r.records,columns:r.columns,rowCount:r.rowCount});case"inputOptions":return te({title:"Options",rowNoun:"options",records:r.options.slice(0,ie).map(t=>{var n;return{label:t.label,value:t.value,count:t.count,disambiguation:(n=t.disambiguation)==null?void 0:n.join(" / ")}}),columns:[{key:"label",label:"Label"},{key:"value",label:"Value"},{key:"count",label:"Count"},{key:"disambiguation",label:"Disambiguation"}],rowCount:r.rowCount??r.options.length});case"metric":{const t=[{metric:"value",value:r.value}];return r.comparison&&t.push({metric:`${r.comparison.kind} value`,value:r.comparison.value},{metric:"delta",value:r.comparison.delta},{metric:"deltaPercent",value:r.comparison.deltaPercent}),te({title:"Metric",rowNoun:"values",records:t,columns:[{key:"metric",label:"Metric"},{key:"value",label:"Value"}],rowCount:t.length})}case"matrix":return te({title:"Matrix Cells",rowNoun:"cells",records:r.cells.slice(0,ie).map(t=>{const n=r.nodesById[t.rowId],s=t.columnId?r.nodesById[t.columnId]:void 0,o=r.measuresById[t.measureId];return{row:(n==null?void 0:n.label)||t.rowId,column:(s==null?void 0:s.label)||t.columnId||"Total",measure:(o==null?void 0:o.label)||t.measureId,value:t.formattedValue??t.value,role:t.role}}),columns:[{key:"row",label:"Row"},{key:"column",label:"Column"},{key:"measure",label:"Measure"},{key:"value",label:"Value"},{key:"role",label:"Role"}],rowCount:r.rowCount??r.cells.length});default:return _r(r)}}function te({title:e,rowNoun:r,records:t,columns:n,rowCount:s}){const o=Mr(n,t);if(!o.length)return;const u=s??t.length,p=t.slice(0,ie);return{title:e,summary:`${Pr(u)} ${r}`,columns:o.slice(0,Re),rows:p,truncatedRows:u>p.length,truncatedColumns:o.length>Re}}function Mr(e,r){if(e!=null&&e.length)return e.filter(n=>n.key).map(n=>({key:n.key,label:n.label||n.key}));const t=new Set;return r.slice(0,ie).forEach(n=>{Object.keys(n).forEach(s=>t.add(s))}),[...t].map(n=>({key:n,label:n}))}function _r(e){throw new Error(`Unhandled Semaphor result kind: ${ur(e)}`)}function Nr(e){return e===null?"null":e===void 0?"":typeof e=="string"?Xe(e):typeof e=="number"||typeof e=="boolean"?String(e):Xe(ur(e))}function Pr(e){return typeof e=="number"?e.toLocaleString():"-"}function ur(e){return JSON.stringify(e,null,2)??"undefined"}function Xe(e){return e.length>80?`${e.slice(0,77)}...`:e}function ye(e){return e.viewTitle||e.queryLabel||e.viewId||e.queryId}function zr(e){if(e.label)return e.label;if(e.queryKind!=="inputOptions")return;const t=e.labelField.label||e.valueField.label||e.labelField.name||e.valueField.name||e.inputId;return`${Fr(t)} Options`}function Fr(e){return(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\bfilter\b/gi," ").replace(/\boptions?\b/gi," ").replace(/\bid\b/gi," ").replace(/\s+/g," ").trim()||e).split(" ").filter(Boolean).map(n=>n===n.toUpperCase()&&n.length>1?n:`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function We(e){return e.flatMap(r=>{var y,m,v,g;const t=r.latestAttempt,n=t==null?void 0:t.executionResult,s=xe((y=n==null?void 0:n.validation)==null?void 0:y.warnings),o=xe((m=n==null?void 0:n.validation)==null?void 0:m.errors),u=Ur((v=n==null?void 0:n.coverage)==null?void 0:v.missingObligations),p=xe((g=n==null?void 0:n.coverage)==null?void 0:g.warnings),d=[],f=ye(r);(t==null?void 0:t.status)==="error"&&d.push({trace:r,tone:"error",title:f,message:t.errorMessage||"Query attempt failed."});for(const h of r.clientWarnings)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of s)d.push({trace:r,tone:"warning",title:f,...h});for(const h of o)d.push({trace:r,tone:"error",title:f,...h});for(const h of u)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of p)d.push({trace:r,tone:"warning",title:f,...h});return d})}function Hr(e){return{traceId:e.trace.traceId,queryId:e.trace.queryId,viewId:e.trace.viewId,viewTitle:e.trace.viewTitle,queryLabel:e.trace.queryLabel,severity:e.tone,title:e.title,message:e.message,code:e.code,path:e.path}}function Vr(e,r){return e.filter(t=>t.trace.traceId===r.traceId).length}function Qr(e){const r=We(e),t=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="error"}).length,n=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="loading"}).length,s=r.filter(u=>u.tone==="error").length,o=r.filter(u=>u.tone==="warning").length;return{total:e.length,failed:t,loading:n,errorCount:s,warningCount:o,issueCount:r.length,severity:t||s?"error":o?"warning":n?"loading":"ok"}}function Ur(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function xe(e){return Array.isArray(e)?e.map(Gr).filter(r=>!!r):[]}function Gr(e){if(typeof e=="string")return{message:e};if(!e||typeof e!="object"||Array.isArray(e))return;const r=e,t=typeof r.message=="string"?r.message:"",n=typeof r.code=="string"?r.code:"",s=typeof r.path=="string"?r.path:"";return t&&n?{message:s?`${t} (${n}, ${s})`:`${t} (${n})`,code:n,...s?{path:s}:{}}:t?{message:t,...s?{path:s}:{}}:n?{message:n,code:n}:void 0}function Jr(e){if(!e.enabled)return e;const r=e.queries.map(cr);return{enabled:e.enabled,queries:r,issues:e.issues,getQuery:t=>r.find(n=>n.queryId===t),getQueries:t=>r.filter(n=>n.queryId===t)}}function Ze(e){return e?cr(e):void 0}function cr(e){var r;return(r=e==null?void 0:e.latestAttempt)!=null&&r.executionResult?{...e,latestAttempt:{...e.latestAttempt,executionResult:Yr(e.latestAttempt.executionResult)}}:e}function Yr(e){const{compiledQuery:r,intent:t,result:n,...s}=e,o=Xr(s.metadata);return{...s,...o?{metadata:o}:{}}}function Xr(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e.dataAppDebug;if(!r||typeof r!="object"||Array.isArray(r))return e;const{compiledSql:t,...n}=r;return{...e,dataAppDebug:n}}function Zr(e){return e==="relative"?{position:"relative",top:"auto",right:"auto",bottom:"auto",left:"auto"}:{top:e.startsWith("top")?20:"auto",right:e.endsWith("right")?20:"auto",bottom:e.startsWith("bottom")?20:"auto",left:e.endsWith("left")?20:"auto"}}function et(e){return e==="error"?{borderColor:"var(--sd-error-border)",background:"var(--sd-error-bg)",color:"var(--sd-error-fg)"}:e==="warning"?{borderColor:"var(--sd-warning-border)",background:"var(--sd-warning-bg)",color:"var(--sd-warning-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",background:"var(--sd-loading-bg)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-success-border)",background:"var(--sd-success-bg)",color:"var(--sd-success-fg)"}}function rt(e){return e==="right"?{top:16,right:16,bottom:16,left:"auto",width:"min(720px, calc(100vw - 32px))",height:"auto",borderRadius:6}:{top:"auto",right:16,bottom:16,left:16,width:"auto",height:"min(420px, 45vh)",borderRadius:6}}function tt(e){return e==="right"?{gridTemplateColumns:"minmax(210px, 280px) minmax(0, 1fr)"}:{gridTemplateColumns:"minmax(260px, 340px) minmax(0, 1fr)"}}function nt(e){return{borderRight:"1px solid var(--sd-border)",borderBottom:0}}function fr(e){return e==="error"?{background:"var(--sd-error-dot)"}:e==="success"?{background:"var(--sd-success-dot)"}:e==="loading"?{background:"var(--sd-loading-dot)"}:{background:"var(--sd-idle-dot)"}}function st(e){return e==="error"?{borderColor:"var(--sd-error-border)",color:"var(--sd-error-fg)"}:e==="success"?{borderColor:"var(--sd-success-border)",color:"var(--sd-success-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-border)",color:"var(--sd-fg-muted)"}}const er="semaphor-devtools-stylesheet",T="semaphor-devtools",it=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../data-app-sdk-adapters/index.cjs"),i=require("react/jsx-runtime"),c=require("react"),Be=require("../chunks/source-identity-BM2FvJDP.js");require("../chunks/analyze-result-contract-8nxUOWp8.js");const se=require("../chunks/search-DNCejM7Z.js"),Ke=require("../chunks/x-B6ghREd2.js"),$r=require("../chunks/validators-JzI7olk4.js");function de(e,r,t={}){return{...t,name:e,role:r}}function Or(e){return e}function Br(e){return e}const Kr={source:{semantic(e){return{...e,kind:"semantic"}},sql(e){return{...e,kind:"sql"}}},field:{measure(e,r){return de(e,"measure",r)},dimension(e,r){return de(e,"dimension",r)},date(e,r){return de(e,"date",r)},id(e,r){return de(e,"id",r)}},filter(e){return{...e,kind:"filter"}},bindInput(e,r){return{toAnalyticsInput(){const[t]=w.toSemaphorInputSnapshots([e]),n=w.toSemaphorInputBinding({...r,inputId:r.inputId||t.inputId});return{...t,inputId:n.inputId,...n.kind?{kind:n.kind}:{},...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}}},control(e){return{...e,kind:"control"}},sqlParam(e){return{...e,kind:"control",role:"sqlParam"}},derivedField(e){return{...e,kind:"derived_field",expressionLanguage:e.expressionLanguage||"semaphor_sql_template"}},metric(e){return{...e,queryKind:"metric"}},analysis(e){return{...e,queryKind:"analysis"}},records(e){return{...e,queryKind:"records"}},inputOptions(e){return{...e,queryKind:"inputOptions"}},sql(e){return{...e,queryKind:"sql"}},matrix(e){return{...e,queryKind:"matrix"}}},ie=10,Re=8;function Wr(e){const r=e==null?void 0:e.result;if(r)switch(r.kind){case"records":return te({title:"Records",rowNoun:"rows",records:r.records,columns:r.columns,rowCount:r.rowCount});case"sql":return te({title:"SQL Rows",rowNoun:"rows",records:r.records,columns:r.columns,rowCount:r.rowCount});case"inputOptions":return te({title:"Options",rowNoun:"options",records:r.options.slice(0,ie).map(t=>{var n;return{label:t.label,value:t.value,count:t.count,disambiguation:(n=t.disambiguation)==null?void 0:n.join(" / ")}}),columns:[{key:"label",label:"Label"},{key:"value",label:"Value"},{key:"count",label:"Count"},{key:"disambiguation",label:"Disambiguation"}],rowCount:r.rowCount??r.options.length});case"metric":{const t=[{metric:"value",value:r.value}];return r.comparison&&t.push({metric:`${r.comparison.kind} value`,value:r.comparison.value},{metric:"delta",value:r.comparison.delta},{metric:"deltaPercent",value:r.comparison.deltaPercent}),te({title:"Metric",rowNoun:"values",records:t,columns:[{key:"metric",label:"Metric"},{key:"value",label:"Value"}],rowCount:t.length})}case"matrix":return te({title:"Matrix Cells",rowNoun:"cells",records:r.cells.slice(0,ie).map(t=>{const n=r.nodesById[t.rowId],s=t.columnId?r.nodesById[t.columnId]:void 0,o=r.measuresById[t.measureId];return{row:(n==null?void 0:n.label)||t.rowId,column:(s==null?void 0:s.label)||t.columnId||"Total",measure:(o==null?void 0:o.label)||t.measureId,value:t.formattedValue??t.value,role:t.role}}),columns:[{key:"row",label:"Row"},{key:"column",label:"Column"},{key:"measure",label:"Measure"},{key:"value",label:"Value"},{key:"role",label:"Role"}],rowCount:r.rowCount??r.cells.length});default:return _r(r)}}function te({title:e,rowNoun:r,records:t,columns:n,rowCount:s}){const o=Mr(n,t);if(!o.length)return;const u=s??t.length,p=t.slice(0,ie);return{title:e,summary:`${Pr(u)} ${r}`,columns:o.slice(0,Re),rows:p,truncatedRows:u>p.length,truncatedColumns:o.length>Re}}function Mr(e,r){if(e!=null&&e.length)return e.filter(n=>n.key).map(n=>({key:n.key,label:n.label||n.key}));const t=new Set;return r.slice(0,ie).forEach(n=>{Object.keys(n).forEach(s=>t.add(s))}),[...t].map(n=>({key:n,label:n}))}function _r(e){throw new Error(`Unhandled Semaphor result kind: ${ur(e)}`)}function Nr(e){return e===null?"null":e===void 0?"":typeof e=="string"?Xe(e):typeof e=="number"||typeof e=="boolean"?String(e):Xe(ur(e))}function Pr(e){return typeof e=="number"?e.toLocaleString():"-"}function ur(e){return JSON.stringify(e,null,2)??"undefined"}function Xe(e){return e.length>80?`${e.slice(0,77)}...`:e}function ye(e){return e.viewTitle||e.queryLabel||e.viewId||e.queryId}function zr(e){if(e.label)return e.label;if(e.queryKind!=="inputOptions")return;const t=e.labelField.label||e.valueField.label||e.labelField.name||e.valueField.name||e.inputId;return`${Fr(t)} Options`}function Fr(e){return(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\bfilter\b/gi," ").replace(/\boptions?\b/gi," ").replace(/\bid\b/gi," ").replace(/\s+/g," ").trim()||e).split(" ").filter(Boolean).map(n=>n===n.toUpperCase()&&n.length>1?n:`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function We(e){return e.flatMap(r=>{var y,m,v,g;const t=r.latestAttempt,n=t==null?void 0:t.executionResult,s=xe((y=n==null?void 0:n.validation)==null?void 0:y.warnings),o=xe((m=n==null?void 0:n.validation)==null?void 0:m.errors),u=Ur((v=n==null?void 0:n.coverage)==null?void 0:v.missingObligations),p=xe((g=n==null?void 0:n.coverage)==null?void 0:g.warnings),d=[],f=ye(r);(t==null?void 0:t.status)==="error"&&d.push({trace:r,tone:"error",title:f,message:t.errorMessage||"Query attempt failed."});for(const h of r.clientWarnings)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of s)d.push({trace:r,tone:"warning",title:f,...h});for(const h of o)d.push({trace:r,tone:"error",title:f,...h});for(const h of u)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of p)d.push({trace:r,tone:"warning",title:f,...h});return d})}function Hr(e){return{traceId:e.trace.traceId,queryId:e.trace.queryId,viewId:e.trace.viewId,viewTitle:e.trace.viewTitle,queryLabel:e.trace.queryLabel,severity:e.tone,title:e.title,message:e.message,code:e.code,path:e.path}}function Vr(e,r){return e.filter(t=>t.trace.traceId===r.traceId).length}function Qr(e){const r=We(e),t=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="error"}).length,n=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="loading"}).length,s=r.filter(u=>u.tone==="error").length,o=r.filter(u=>u.tone==="warning").length;return{total:e.length,failed:t,loading:n,errorCount:s,warningCount:o,issueCount:r.length,severity:t||s?"error":o?"warning":n?"loading":"ok"}}function Ur(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function xe(e){return Array.isArray(e)?e.map(Gr).filter(r=>!!r):[]}function Gr(e){if(typeof e=="string")return{message:e};if(!e||typeof e!="object"||Array.isArray(e))return;const r=e,t=typeof r.message=="string"?r.message:"",n=typeof r.code=="string"?r.code:"",s=typeof r.path=="string"?r.path:"";return t&&n?{message:s?`${t} (${n}, ${s})`:`${t} (${n})`,code:n,...s?{path:s}:{}}:t?{message:t,...s?{path:s}:{}}:n?{message:n,code:n}:void 0}function Jr(e){if(!e.enabled)return e;const r=e.queries.map(cr);return{enabled:e.enabled,queries:r,issues:e.issues,getQuery:t=>r.find(n=>n.queryId===t),getQueries:t=>r.filter(n=>n.queryId===t)}}function Ze(e){return e?cr(e):void 0}function cr(e){var r;return(r=e==null?void 0:e.latestAttempt)!=null&&r.executionResult?{...e,latestAttempt:{...e.latestAttempt,executionResult:Yr(e.latestAttempt.executionResult)}}:e}function Yr(e){const{compiledQuery:r,intent:t,result:n,...s}=e,o=Xr(s.metadata);return{...s,...o?{metadata:o}:{}}}function Xr(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e.dataAppDebug;if(!r||typeof r!="object"||Array.isArray(r))return e;const{compiledSql:t,...n}=r;return{...e,dataAppDebug:n}}function Zr(e){return e==="relative"?{position:"relative",top:"auto",right:"auto",bottom:"auto",left:"auto"}:{top:e.startsWith("top")?20:"auto",right:e.endsWith("right")?20:"auto",bottom:e.startsWith("bottom")?20:"auto",left:e.endsWith("left")?20:"auto"}}function et(e){return e==="error"?{borderColor:"var(--sd-error-border)",background:"var(--sd-error-bg)",color:"var(--sd-error-fg)"}:e==="warning"?{borderColor:"var(--sd-warning-border)",background:"var(--sd-warning-bg)",color:"var(--sd-warning-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",background:"var(--sd-loading-bg)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-success-border)",background:"var(--sd-success-bg)",color:"var(--sd-success-fg)"}}function rt(e){return e==="right"?{top:16,right:16,bottom:16,left:"auto",width:"min(720px, calc(100vw - 32px))",height:"auto",borderRadius:6}:{top:"auto",right:16,bottom:16,left:16,width:"auto",height:"min(420px, 45vh)",borderRadius:6}}function tt(e){return e==="right"?{gridTemplateColumns:"minmax(210px, 280px) minmax(0, 1fr)"}:{gridTemplateColumns:"minmax(260px, 340px) minmax(0, 1fr)"}}function nt(e){return{borderRight:"1px solid var(--sd-border)",borderBottom:0}}function fr(e){return e==="error"?{background:"var(--sd-error-dot)"}:e==="success"?{background:"var(--sd-success-dot)"}:e==="loading"?{background:"var(--sd-loading-dot)"}:{background:"var(--sd-idle-dot)"}}function st(e){return e==="error"?{borderColor:"var(--sd-error-border)",color:"var(--sd-error-fg)"}:e==="success"?{borderColor:"var(--sd-success-border)",color:"var(--sd-success-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-border)",color:"var(--sd-fg-muted)"}}const er="semaphor-devtools-stylesheet",T="semaphor-devtools",it=`
2
2
  .${T} {
3
3
  --sd-bg: #ffffff;
4
4
  --sd-bg-muted: #fafafa;
@@ -6,7 +6,7 @@ import { d as ro } from "../chunks/source-identity-Cv4Nm3TM.js";
6
6
  import "../chunks/analyze-result-contract-DPjm6btg.js";
7
7
  import { M as Zr, a as et, S as rt, E as tt, C as nt } from "../chunks/search-BHsQIWBV.js";
8
8
  import { X as it, C as ot, j as st } from "../chunks/x-CXDkqdur.js";
9
- import { b as at } from "../chunks/validators-C-_9Ew5G.js";
9
+ import { b as at } from "../chunks/validators-UqQI3Cg_.js";
10
10
  function me(e, r, t = {}) {
11
11
  return {
12
12
  ...t,
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("../chunks/validators-CB9BFarT.js");require("../chunks/analyze-result-contract-8nxUOWp8.js");const q=require("../chunks/source-identity-BM2FvJDP.js"),y=require("../data-app-sdk-adapters/index.cjs"),R=require("../chunks/catalog-field-grounding-Bnx-3tE0.js");function W({intent:e,field:r,catalogField:o,relativePath:t}){const i=U({intent:e,field:r,relativePath:t});if(!i||i.allowedRelatedRoles.length===0)return!1;const a=f(r,i.selectedField),s=w(o),n=p(a);return M(s,i.allowedRelatedRoles)?n===s:!1}function J(e){return e.kind==="records"?X(e):e.kind==="metric"?Y(e):Z(e)}function w(e){const r=R.normalizeAnalyticsCatalogName(e.role);if(r==="measure")return"measure";if(r==="id")return"id";const o=R.normalizeAnalyticsCatalogDataType(e.dataType);if(r==="date"||o==="date"||o==="datetime")return"date";if(r==="dimension")return"dimension"}function M(e,r){return!!(e&&r.includes(e))}function f(e,r){const o=p(e);if(o)return e.role===o?e:{...e,role:o};const t=r?p(r):void 0;return t?{...e,role:t}:e}function u(e,r){return e.find(o=>D(o,r))}function S(e){return[...e.rows.map(r=>r.field),...(e.columns||[]).map(r=>r.field)]}function U({intent:e,field:r,relativePath:o}){if(e.kind==="records")return L(e,r,o);if(e.kind==="metric")return V(e,r,o);if(e.kind==="matrix")return G(e,r,o)}function L(e,r,o){if(o.startsWith("spec.fields."))return{allowedRelatedRoles:["dimension","date","id"]};if(o==="spec.dateField"&&!e.timeWindow)return{allowedRelatedRoles:["date"]};if(o==="spec.orderBy.field"){const t=u(B(e),r);return{selectedField:t,allowedRelatedRoles:t?x(t):[]}}}function V(e,r,o){if(o.startsWith("spec.dimensions."))return{allowedRelatedRoles:["dimension"]};if(o==="spec.orderBy.field"){const t=u(e.dimensions||[],r);return{selectedField:t,allowedRelatedRoles:t?["dimension"]:[]}}}function G(e,r,o){if(oe(o))return{allowedRelatedRoles:["dimension","date"]};if(te(o)){const t=u(S(e),r);return{selectedField:t,allowedRelatedRoles:v(t)}}}function X(e){var t,i;const r=B(e),o=(t=e.orderBy)!=null&&t.field?u(r,e.orderBy.field):void 0;return _([...r.map(a=>l(a,x(a))),...(i=e.orderBy)!=null&&i.field?[l(f(e.orderBy.field,o),o?x(o):[],{unsupportedRelatedRoleMessage:"Joined records projections support related sort fields only when the same related field is included in spec.fields.",recommendedNextStep:"Add the related sort field to spec.fields, or keep orderBy fields on the base source."})]:[]])}function Y(e){var o,t;const r=(o=e.orderBy)!=null&&o.field?u(e.dimensions||[],e.orderBy.field):void 0;return _([...e.measures.map(i=>l(i,[])),...e.primaryMeasure?[l(e.primaryMeasure,[])]:[],...(e.dimensions||[]).map(i=>l(i,["dimension"])),...e.dateField?[l({...e.dateField,role:"date"},[])]:[],...(t=e.orderBy)!=null&&t.field?[l(f(e.orderBy.field,r),r?["dimension"]:[],{unsupportedRelatedRoleMessage:"Joined metric projections support related orderBy fields only when the same related field is declared in spec.dimensions.",recommendedNextStep:"Add the related field as a metric dimension when it should participate in the grouped result, or keep orderBy fields on the base source."})]:[]])}function Z(e){const r=[...e.rows,...e.columns||[]];return _([...r.map(o=>l(o.field,v(o.field))),...r.flatMap(o=>{var a;if(((a=o.sortBy)==null?void 0:a.by.kind)!=="field")return[];const t=o.sortBy.by.field,i=u(S(e),t);return[l(f(t,i),v(i),{unsupportedRelatedRoleMessage:"Joined matrix projections support related axis sort fields only when the same related field is used as a row/column axis.",recommendedNextStep:"Use a related field as a row or column axis, or keep axis sort fields on the base source."})]}),...e.values.map(o=>l(o.field,[],{unsupportedRelatedRoleMessage:"Joined matrix projections support related row/column dimensions or dates only. Related value fields are not supported in this phase.",recommendedNextStep:"Keep matrix values on the base source, or use governed SQL for unsupported aggregate-safe joined values."})),...(e.sort||[]).flatMap(o=>{if(o.by.kind!=="field")return[];const t=o.by.field,i=u(S(e),t);return[l(f(t,i),v(i),{unsupportedRelatedRoleMessage:"Joined matrix projections support related top-level sort fields only when the same related field is used as a row/column axis.",recommendedNextStep:"Use a related field as a row or column axis, or keep matrix sort fields on the base source."})]})])}function x(e){const r=e?p(e):void 0;return r==="dimension"?["dimension"]:r==="date"?["date"]:r==="id"?["id"]:["dimension","date","id"]}function v(e){const r=e?p(e):void 0;return r==="date"?["date"]:r==="dimension"?["dimension"]:[]}function l(e,r,o={}){return{field:f(e),allowedRelatedRoles:r,...o}}function _(e){const r=[];return e.forEach(o=>{r.some(t=>ee(t,o))||r.push(o)}),r}function B(e){const r=[...e.fields];return e.dateField&&!r.some(o=>T(o,e.dateField))&&r.push({...e.dateField,role:"date"}),r}function ee(e,r){return D(e.field,r.field)&&e.allowedRelatedRoles.join("|")===r.allowedRelatedRoles.join("|")&&(e.unsupportedRelatedRoleMessage||"")===(r.unsupportedRelatedRoleMessage||"")&&(e.recommendedNextStep||"")===(r.recommendedNextStep||"")}function T(e,r){return q.semaphorFieldRefsMatch(e,r)}function D(e,r){return T(e,r)&&re(p(e),p(r))}function re(e,r){return!!(e&&(!r||e===r))}function p(e){return w(e)}function oe(e){const r=e.split(".");return r.length===4&&r[0]==="spec"&&(r[1]==="rows"||r[1]==="columns")&&b(r[2])&&r[3]==="field"}function te(e){const r=e.split(".");return r.length===6&&r[0]==="spec"&&(r[1]==="rows"||r[1]==="columns")&&b(r[2])&&r[3]==="sortBy"&&r[4]==="by"&&r[5]==="field"||r.length===5&&r[0]==="spec"&&r[1]==="sort"&&b(r[2])&&r[3]==="by"&&r[4]==="field"}function b(e){return e===void 0||e.trim()===""?!1:Number.isInteger(Number(e))&&Number(e)>=0}function ie({intent:e,field:r,relativePath:o,baseCatalog:t,fieldCatalogs:i}){const a=g(r,e.source),s=q.semaphorSourcesReferToSameDataset(a,e.source);if(!s&&!se(e.source,a))return{ok:!1,code:"invalid_source_ref",message:`Field "${r.name}" references a related Semaphor source outside the query's semantic domain.`,pathSuffix:".source",source:a};const n=s?t:k(i,a);if(!n)return{ok:!1,code:"invalid_source_ref",message:`Field "${r.name}" references a Semaphor source that is not present in the visible field catalog.`,pathSuffix:".source",source:a};const d=I(n,r,e.source);return d?!s&&!ae({intent:e,field:r,catalogField:d,relativePath:o})?{ok:!1,code:"unsupported_joined_projection",message:`Field "${r.name}" references a related Semaphor source, but this query kind does not support joined projections for that field yet.`,pathSuffix:".source",source:a}:{ok:!0,source:a,catalogField:d,usesBaseSource:s}:{ok:!1,code:"missing_field",message:`Field "${r.name}" is not visible on the selected Semaphor source.`,source:a}}function ae({intent:e,field:r,catalogField:o,relativePath:t}){return W({intent:e,field:r,catalogField:o,relativePath:t})}function se(e,r){return e.kind==="semantic"&&r.kind==="semantic"&&e.domainId===r.domainId}function k(e,r){return e.find(o=>$(o,r))}function I(e,r,o){const t=g(r,o);if($(e,t))return e.fields.find(i=>ne(i,r)&&$(e,g(i,e.source)))}function P(e){return R.normalizeAnalyticsCatalogName(e)}function g(e,r){return e.source||r}function $(e,r){return[e.source,...e.sourceAliases||[]].some(o=>q.semaphorSourcesReferToSameDataset(o,r))}function ne(e,r){return!!(e.name&&r.name&&e.name===r.name)}function z(e,r={}){const o=r.pathPrefix||"analysisOptions";if(e===void 0)return{ok:!0};if(!e||typeof e!="object"||Array.isArray(e))return c(o,"Data App analysis options must be an object.");const t=e,i={};if(t.chartTitle!==void 0){if(typeof t.chartTitle!="string")return c(`${o}.chartTitle`,'Data App analysis option "chartTitle" must be a string.');i.chartTitle=t.chartTitle}if(t.chartType!==void 0){if(typeof t.chartType!="string")return c(`${o}.chartType`,'Data App analysis option "chartType" must be a string.');i.chartType=t.chartType}if(t.driverMode!==void 0){if(!ce(t.driverMode))return c(`${o}.driverMode`,'Data App analysis option "driverMode" must be absolute_delta, largest_negative, largest_positive, positive_and_negative, or all.');i.driverMode=t.driverMode}if(t.includePopulation!==void 0){if(typeof t.includePopulation!="boolean")return c(`${o}.includePopulation`,'Data App analysis option "includePopulation" must be a boolean.');i.includePopulation=t.includePopulation}if(t.calendarContext!==void 0){const a=fe(t.calendarContext,{pathPrefix:`${o}.calendarContext`,validateTimezone:r.validateTimezone});if(!a.ok)return a;i.calendarContext=a.calendarContext}return{ok:!0,analysisOptions:i}}function de(e){const r=e.queries.map((i,a)=>le(i,a,{fieldCatalogs:e.fieldCatalogs||[],requireFieldCatalog:!!e.requireFieldCatalog,validateTimezone:e.validateTimezone})),o=r.flatMap(i=>i.diagnostics),t=r.map(i=>i.executionResult);return{ok:o.every(i=>i.severity!=="error"),diagnostics:o,queries:r,intents:r.flatMap(i=>i.intent?[i.intent]:[]),executionResults:t}}function le(e,r,o){const t=`queries.${r}`;try{const i=pe(e),a=$e(e,i),s=E.validateSemaphorAnalyticsIntent(i),n=[...ke({querySpec:e,queryId:a,intent:i,pathPrefix:t}),...s.errors.map(h=>C(h,{queryHook:e.queryHook,queryId:a,pathPrefix:t,severity:"error",intent:i})),...s.warnings.map(h=>C(h,{queryHook:e.queryHook,queryId:a,pathPrefix:t,severity:"warning",intent:i})),...ye({querySpec:e,queryId:a,intent:i,pathPrefix:t,fieldCatalogs:o.fieldCatalogs,requireFieldCatalog:o.requireFieldCatalog}),...Ie({querySpec:e,queryId:a,intent:i,pathPrefix:t,validateTimezone:o.validateTimezone})],d=be(s,n);return{queryHook:e.queryHook,queryId:a,intent:i,diagnostics:n,executionResult:j({intent:i,validation:d,diagnostics:n})}}catch(i){const a={severity:"error",code:"invalid_query_spec",message:i instanceof Error?i.message:String(i),path:t,queryHook:e.queryHook,queryId:Q(e.spec)},s=K([a]);return{queryHook:e.queryHook,queryId:a.queryId,diagnostics:[a],executionResult:j({validation:s,diagnostics:[a]})}}}function c(e,r){return{ok:!1,issues:[{code:"invalid_analysis_option",message:r,path:e}]}}function N(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function ce(e){return e==="absolute_delta"||e==="largest_negative"||e==="largest_positive"||e==="positive_and_negative"||e==="all"}function ue(e){return e.trim().length>0&&!Number.isNaN(Date.parse(e))}function fe(e,r){var d;if(!e||typeof e!="object"||Array.isArray(e))return c(r.pathPrefix,'Data App analysis option "calendarContext" must be an object.');const o=e,t=o.tz,i=o.weekStart,a=o.anchor,s=a&&typeof a=="object"&&!Array.isArray(a)?a.iso:void 0,n=typeof t=="string"?((d=r.validateTimezone)==null?void 0:d.call(r,t))??t:null;return n?typeof i!="number"||!Number.isInteger(i)||i<0||i>6?c(`${r.pathPrefix}.weekStart`,'Data App analysis option "calendarContext.weekStart" must be an integer from 0 to 6.'):a!=="now"&&!(typeof s=="string"&&ue(s))?c(`${r.pathPrefix}.anchor`,'Data App analysis option "calendarContext.anchor" must be "now" or an object with a valid iso string.'):{ok:!0,calendarContext:{tz:n,weekStart:i,anchor:a}}:c(`${r.pathPrefix}.tz`,'Data App analysis option "calendarContext.tz" must be a valid timezone string.')}function pe(e){return me(e.spec)}function me(e){if(!N(e))throw new Error("useSemaphorQuery spec must be an object.");if(e.queryKind==="metric")return y.toSemaphorMetricIntent(e);if(e.queryKind==="analysis")return y.toSemaphorAnalysisIntent(e);if(e.queryKind==="records")return y.toSemaphorRecordsIntent(e);if(e.queryKind==="sql")return y.toSemaphorSqlIntent(e);if(e.queryKind==="matrix")return y.toSemaphorMatrixIntent(e);if(e.queryKind==="inputOptions")return y.toSemaphorInputOptionsIntent(e);throw new Error("useSemaphorQuery spec.queryKind must be metric, analysis, records, inputOptions, sql, or matrix.")}function ye(e){if(e.intent.kind==="sql")return[];if(e.fieldCatalogs.length===0&&!e.requireFieldCatalog)return[];const r=k(e.fieldCatalogs,e.intent.source);if(!r)return[{severity:"error",code:"invalid_source_ref",message:`Source ref for ${e.querySpec.queryHook} does not match a visible Semaphor source.`,path:`${e.pathPrefix}.spec.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}];const o=ge({...e,catalog:r}),t={...r,fields:[...r.fields,...Re(e.intent,r,e.intent.source)]};return[...o,...he({...e,fieldCatalogs:e.fieldCatalogs}),...qe({...e,catalog:t,fieldCatalogs:e.fieldCatalogs}),...ve({...e,catalog:t,fieldCatalogs:e.fieldCatalogs})]}function he(e){var o;if(e.intent.kind!=="inputOptions"||((o=e.intent.population)==null?void 0:o.kind)!=="related_population")return[];const r=e.intent.population.baseSource;return k(e.fieldCatalogs,r)?[]:[{severity:"error",code:"invalid_source_ref",message:"Input options related population baseSource does not match a visible Semaphor source.",path:`${e.pathPrefix}.spec.population.baseSource`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:r}]}function ge(e){const r=O(e.intent);if(r.length===0)return[];const o=[],t=new Set;return r.forEach((i,a)=>{const s=`${e.pathPrefix}.spec.derivedFields.${a}`,n=P(i.name);n&&(t.has(n)&&o.push({severity:"error",code:"duplicate_derived_field",message:`Derived field "${i.name}" is declared more than once.`,path:`${s}.name`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}),t.add(n),e.catalog.fields.some(d=>P(d.name)===n)&&o.push({severity:"error",code:"derived_field_name_collision",message:`Derived field "${i.name}" conflicts with a field already visible on the selected Semaphor source.`,path:`${s}.name`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source})),Object.entries(i.inputs||{}).forEach(([d,h])=>{const m=xe(h);if(!m)return;const F=g(m,e.intent.source);if(!q.semaphorSourcesReferToSameDataset(F,e.intent.source)){o.push({severity:"error",code:"unsupported_derived_field_source",message:`Derived field "${i.name}" input "${d}" references a different Semaphor source. App-local derived fields must use fields from the query source.`,path:`${s}.inputs.${d}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:F,field:m});return}I(e.catalog,m,e.intent.source)||o.push({severity:"error",code:"missing_field",message:`Derived field "${i.name}" input "${d}" references field "${m.name}", which is not visible on the selected Semaphor source.`,path:`${s}.inputs.${d}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:F,field:m})})}),o}function qe(e){return Fe(e.intent).flatMap(({field:r,path:o})=>{const t=ie({intent:e.intent,field:r,relativePath:o,baseCatalog:e.catalog,fieldCatalogs:e.fieldCatalogs});return t.ok?[]:[{severity:"error",code:t.code,message:t.message,path:`${e.pathPrefix}.${o}${t.pathSuffix||""}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:t.source,field:r}]})}function ve(e){return("inputs"in e.intent?e.intent.inputs||[]:[]).flatMap((o,t)=>{if(!o.field)return[];const i=g(o.field,e.intent.source);if(!q.semaphorSourcesReferToSameDataset(i,e.intent.source)){if(Se(e.intent,i)){const a=k(e.fieldCatalogs,i);return a?I(a,o.field,i)?[]:[{severity:"error",code:"missing_field",message:`Input "${o.inputId}" references field "${o.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${t}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]:[{severity:"error",code:"invalid_source_ref",message:`Input "${o.inputId}" references a Semaphor source that is not present in the visible field catalog.`,path:`${e.pathPrefix}.spec.inputs.${t}.field.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]}return[{severity:"error",code:"unsupported_input_filter_composition",message:`Input "${o.inputId}" filters a different Semaphor source than the query, and no relationship-aware semantic validation path is available for this query kind.`,path:`${e.pathPrefix}.spec.inputs.${t}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]}return I(e.catalog,o.field,e.intent.source)?[]:[{severity:"error",code:"missing_field",message:`Input "${o.inputId}" references field "${o.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${t}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]})}function Se(e,r){return e.source.kind==="semantic"&&r.kind==="semantic"&&r.domainId===e.source.domainId}function Ie(e){if(e.querySpec.spec.queryKind!=="analysis")return[];const r=z(e.querySpec.spec,{pathPrefix:`${e.pathPrefix}.spec`,validateTimezone:e.validateTimezone});return r.ok?[]:r.issues.map(o=>({severity:"error",code:o.code,message:o.message,path:o.path,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}))}function ke(e){return e.querySpec.spec.queryKind!=="sql"?[]:N(e.querySpec.spec)?Object.prototype.hasOwnProperty.call(e.querySpec.spec,"parameters")?[{severity:"error",code:"deprecated_sql_parameters",message:"semaphor.sql uses defaultParameters for static SQL param(...) fallback values. The legacy parameters field is not supported.",path:`${e.pathPrefix}.spec.parameters`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id}]:[]:[]}function Fe(e){return e.kind==="metric"?[...e.measures.map((r,o)=>({field:r,path:`spec.measures.${o}`})),...e.primaryMeasure?[{field:e.primaryMeasure,path:"spec.primaryMeasure"}]:[],...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...(e.dimensions||[]).map((r,o)=>({field:r,path:`spec.dimensions.${o}`})),...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,o)=>({field:r.field,path:`spec.filters.${o}.field`}))]:e.kind==="records"?[...e.fields.map((r,o)=>({field:r,path:`spec.fields.${o}`})),...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,o)=>({field:r.field,path:`spec.filters.${o}.field`}))]:e.kind==="inputOptions"?[{field:e.labelField,path:"spec.labelField"},{field:e.valueField,path:"spec.valueField"},...e.searchField?[{field:e.searchField,path:"spec.searchField"}]:[],...(e.disambiguationFields||[]).map((r,o)=>({field:r,path:`spec.disambiguationFields.${o}`}))]:e.kind==="matrix"?[...e.rows.map((r,o)=>({field:r.field,path:`spec.rows.${o}.field`})),...e.rows.flatMap((r,o)=>{var t;return((t=r.sortBy)==null?void 0:t.by.kind)==="field"?[{field:r.sortBy.by.field,path:`spec.rows.${o}.sortBy.by.field`}]:[]}),...(e.columns||[]).map((r,o)=>({field:r.field,path:`spec.columns.${o}.field`})),...(e.columns||[]).flatMap((r,o)=>{var t;return((t=r.sortBy)==null?void 0:t.by.kind)==="field"?[{field:r.sortBy.by.field,path:`spec.columns.${o}.sortBy.by.field`}]:[]}),...e.values.map((r,o)=>({field:r.field,path:`spec.values.${o}.field`})),...(e.sort||[]).flatMap((r,o)=>r.by.kind==="field"?[{field:r.by.field,path:`spec.sort.${o}.by.field`}]:[]),...(e.filters||[]).map((r,o)=>({field:r.field,path:`spec.filters.${o}.field`}))]:[]}function O(e){return!("derivedFields"in e)||!Array.isArray(e.derivedFields)?[]:e.derivedFields}function Re(e,r,o){return O(e).map(t=>({name:t.name,label:t.label,role:t.resultRole,dataType:t.dataType,source:r.source||o,...t.defaultAggregate?{aggregate:t.defaultAggregate}:{}}))}function xe(e){if(!(!e||typeof e!="object"))return e.field}function C(e,r){return{severity:r.severity,code:e.code||"invalid_analytics_intent",message:e.message,path:e.path?`${r.pathPrefix}.spec.${e.path}`:r.pathPrefix,queryHook:r.queryHook,queryId:r.queryId,intentId:r.intent.id,source:r.intent.source}}function be(e,r){const o=K(r);return{ok:o.ok&&e.ok,errors:H([...e.errors,...o.errors]),warnings:H([...e.warnings,...o.warnings]),repairHints:[...e.repairHints,...o.repairHints]}}function K(e){const r=e.filter(t=>t.severity==="error").map(A),o=e.filter(t=>t.severity==="warning").map(A);return{ok:r.length===0,errors:r,warnings:o,repairHints:r.map(t=>{var i,a;return{code:t.code,message:t.message,fieldRole:t.fieldRole,invalidField:(i=t.repairHint)==null?void 0:i.invalidField,recommendedNextStep:((a=t.repairHint)==null?void 0:a.recommendedNextStep)||"Update the Data App SDK query spec to use visible Semaphor source and field refs."}})}}function A(e){var r;return{code:e.code,message:e.message,path:e.path,fieldRole:e.code==="invalid_source_ref"?"source":void 0,repairHint:{code:e.code,message:e.message,invalidField:(r=e.field)==null?void 0:r.name,fieldRole:e.code==="invalid_source_ref"?"source":void 0,recommendedNextStep:e.code==="unsupported_input_filter_composition"?"Use an input field from the same Semaphor source as the query, or split the query into separate source-scoped queries.":"Update the query spec to use a visible Semaphor source and field ref."}}}function H(e){const r=new Set;return e.filter(o=>{const t=`${o.code}:${o.path||""}:${o.message}`;return r.has(t)?!1:(r.add(t),!0)})}function j(e){var o,t;const r=e.diagnostics.filter(i=>i.severity==="error");return{intentId:(o=e.intent)==null?void 0:o.id,status:r.length?"failed":"answered",resultShape:(t=e.intent)==null?void 0:t.kind,intent:e.intent,validation:e.validation,coverage:{answeredObligations:r.length?[]:["query_spec_validation"],missingObligations:r.length?["query_spec_validation"]:[],warnings:e.validation.warnings},missingFields:r.filter(i=>i.code==="missing_field").flatMap(i=>{var a;return(a=i.field)!=null&&a.name?[i.field.name]:[]}),warnings:e.diagnostics.filter(i=>i.severity==="warning").map(i=>i.message),metadata:{validationKind:"data_app_sdk_query_spec"}}}function $e(e,r){return r.id||Q(e.spec)}function Q(e){if(!e||typeof e!="object"||!("id"in e))return;const r=e.id;return typeof r=="string"&&r.trim()?r:void 0}exports.fieldWithSelectedProjectionRole=f;exports.findMatchingRelatedProjectionField=u;exports.isAllowedRelatedProjectionRole=M;exports.matrixAxisFieldsForPolicy=S;exports.normalizeSemaphorAnalysisQueryOptions=z;exports.normalizeSemaphorFieldRole=w;exports.relatedProjectionFieldCandidatesForIntent=J;exports.validateSemaphorDataAppQuerySpecs=de;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("../chunks/validators-JzI7olk4.js");require("../chunks/analyze-result-contract-8nxUOWp8.js");const q=require("../chunks/source-identity-BM2FvJDP.js"),y=require("../data-app-sdk-adapters/index.cjs"),R=require("../chunks/catalog-field-grounding-Bnx-3tE0.js");function W({intent:e,field:r,catalogField:o,relativePath:t}){const i=U({intent:e,field:r,relativePath:t});if(!i||i.allowedRelatedRoles.length===0)return!1;const a=f(r,i.selectedField),s=w(o),n=p(a);return M(s,i.allowedRelatedRoles)?n===s:!1}function J(e){return e.kind==="records"?X(e):e.kind==="metric"?Y(e):Z(e)}function w(e){const r=R.normalizeAnalyticsCatalogName(e.role);if(r==="measure")return"measure";if(r==="id")return"id";const o=R.normalizeAnalyticsCatalogDataType(e.dataType);if(r==="date"||o==="date"||o==="datetime")return"date";if(r==="dimension")return"dimension"}function M(e,r){return!!(e&&r.includes(e))}function f(e,r){const o=p(e);if(o)return e.role===o?e:{...e,role:o};const t=r?p(r):void 0;return t?{...e,role:t}:e}function u(e,r){return e.find(o=>D(o,r))}function S(e){return[...e.rows.map(r=>r.field),...(e.columns||[]).map(r=>r.field)]}function U({intent:e,field:r,relativePath:o}){if(e.kind==="records")return L(e,r,o);if(e.kind==="metric")return V(e,r,o);if(e.kind==="matrix")return G(e,r,o)}function L(e,r,o){if(o.startsWith("spec.fields."))return{allowedRelatedRoles:["dimension","date","id"]};if(o==="spec.dateField"&&!e.timeWindow)return{allowedRelatedRoles:["date"]};if(o==="spec.orderBy.field"){const t=u(B(e),r);return{selectedField:t,allowedRelatedRoles:t?x(t):[]}}}function V(e,r,o){if(o.startsWith("spec.dimensions."))return{allowedRelatedRoles:["dimension"]};if(o==="spec.orderBy.field"){const t=u(e.dimensions||[],r);return{selectedField:t,allowedRelatedRoles:t?["dimension"]:[]}}}function G(e,r,o){if(oe(o))return{allowedRelatedRoles:["dimension","date"]};if(te(o)){const t=u(S(e),r);return{selectedField:t,allowedRelatedRoles:v(t)}}}function X(e){var t,i;const r=B(e),o=(t=e.orderBy)!=null&&t.field?u(r,e.orderBy.field):void 0;return _([...r.map(a=>l(a,x(a))),...(i=e.orderBy)!=null&&i.field?[l(f(e.orderBy.field,o),o?x(o):[],{unsupportedRelatedRoleMessage:"Joined records projections support related sort fields only when the same related field is included in spec.fields.",recommendedNextStep:"Add the related sort field to spec.fields, or keep orderBy fields on the base source."})]:[]])}function Y(e){var o,t;const r=(o=e.orderBy)!=null&&o.field?u(e.dimensions||[],e.orderBy.field):void 0;return _([...e.measures.map(i=>l(i,[])),...e.primaryMeasure?[l(e.primaryMeasure,[])]:[],...(e.dimensions||[]).map(i=>l(i,["dimension"])),...e.dateField?[l({...e.dateField,role:"date"},[])]:[],...(t=e.orderBy)!=null&&t.field?[l(f(e.orderBy.field,r),r?["dimension"]:[],{unsupportedRelatedRoleMessage:"Joined metric projections support related orderBy fields only when the same related field is declared in spec.dimensions.",recommendedNextStep:"Add the related field as a metric dimension when it should participate in the grouped result, or keep orderBy fields on the base source."})]:[]])}function Z(e){const r=[...e.rows,...e.columns||[]];return _([...r.map(o=>l(o.field,v(o.field))),...r.flatMap(o=>{var a;if(((a=o.sortBy)==null?void 0:a.by.kind)!=="field")return[];const t=o.sortBy.by.field,i=u(S(e),t);return[l(f(t,i),v(i),{unsupportedRelatedRoleMessage:"Joined matrix projections support related axis sort fields only when the same related field is used as a row/column axis.",recommendedNextStep:"Use a related field as a row or column axis, or keep axis sort fields on the base source."})]}),...e.values.map(o=>l(o.field,[],{unsupportedRelatedRoleMessage:"Joined matrix projections support related row/column dimensions or dates only. Related value fields are not supported in this phase.",recommendedNextStep:"Keep matrix values on the base source, or use governed SQL for unsupported aggregate-safe joined values."})),...(e.sort||[]).flatMap(o=>{if(o.by.kind!=="field")return[];const t=o.by.field,i=u(S(e),t);return[l(f(t,i),v(i),{unsupportedRelatedRoleMessage:"Joined matrix projections support related top-level sort fields only when the same related field is used as a row/column axis.",recommendedNextStep:"Use a related field as a row or column axis, or keep matrix sort fields on the base source."})]})])}function x(e){const r=e?p(e):void 0;return r==="dimension"?["dimension"]:r==="date"?["date"]:r==="id"?["id"]:["dimension","date","id"]}function v(e){const r=e?p(e):void 0;return r==="date"?["date"]:r==="dimension"?["dimension"]:[]}function l(e,r,o={}){return{field:f(e),allowedRelatedRoles:r,...o}}function _(e){const r=[];return e.forEach(o=>{r.some(t=>ee(t,o))||r.push(o)}),r}function B(e){const r=[...e.fields];return e.dateField&&!r.some(o=>T(o,e.dateField))&&r.push({...e.dateField,role:"date"}),r}function ee(e,r){return D(e.field,r.field)&&e.allowedRelatedRoles.join("|")===r.allowedRelatedRoles.join("|")&&(e.unsupportedRelatedRoleMessage||"")===(r.unsupportedRelatedRoleMessage||"")&&(e.recommendedNextStep||"")===(r.recommendedNextStep||"")}function T(e,r){return q.semaphorFieldRefsMatch(e,r)}function D(e,r){return T(e,r)&&re(p(e),p(r))}function re(e,r){return!!(e&&(!r||e===r))}function p(e){return w(e)}function oe(e){const r=e.split(".");return r.length===4&&r[0]==="spec"&&(r[1]==="rows"||r[1]==="columns")&&b(r[2])&&r[3]==="field"}function te(e){const r=e.split(".");return r.length===6&&r[0]==="spec"&&(r[1]==="rows"||r[1]==="columns")&&b(r[2])&&r[3]==="sortBy"&&r[4]==="by"&&r[5]==="field"||r.length===5&&r[0]==="spec"&&r[1]==="sort"&&b(r[2])&&r[3]==="by"&&r[4]==="field"}function b(e){return e===void 0||e.trim()===""?!1:Number.isInteger(Number(e))&&Number(e)>=0}function ie({intent:e,field:r,relativePath:o,baseCatalog:t,fieldCatalogs:i}){const a=g(r,e.source),s=q.semaphorSourcesReferToSameDataset(a,e.source);if(!s&&!se(e.source,a))return{ok:!1,code:"invalid_source_ref",message:`Field "${r.name}" references a related Semaphor source outside the query's semantic domain.`,pathSuffix:".source",source:a};const n=s?t:k(i,a);if(!n)return{ok:!1,code:"invalid_source_ref",message:`Field "${r.name}" references a Semaphor source that is not present in the visible field catalog.`,pathSuffix:".source",source:a};const d=I(n,r,e.source);return d?!s&&!ae({intent:e,field:r,catalogField:d,relativePath:o})?{ok:!1,code:"unsupported_joined_projection",message:`Field "${r.name}" references a related Semaphor source, but this query kind does not support joined projections for that field yet.`,pathSuffix:".source",source:a}:{ok:!0,source:a,catalogField:d,usesBaseSource:s}:{ok:!1,code:"missing_field",message:`Field "${r.name}" is not visible on the selected Semaphor source.`,source:a}}function ae({intent:e,field:r,catalogField:o,relativePath:t}){return W({intent:e,field:r,catalogField:o,relativePath:t})}function se(e,r){return e.kind==="semantic"&&r.kind==="semantic"&&e.domainId===r.domainId}function k(e,r){return e.find(o=>$(o,r))}function I(e,r,o){const t=g(r,o);if($(e,t))return e.fields.find(i=>ne(i,r)&&$(e,g(i,e.source)))}function P(e){return R.normalizeAnalyticsCatalogName(e)}function g(e,r){return e.source||r}function $(e,r){return[e.source,...e.sourceAliases||[]].some(o=>q.semaphorSourcesReferToSameDataset(o,r))}function ne(e,r){return!!(e.name&&r.name&&e.name===r.name)}function z(e,r={}){const o=r.pathPrefix||"analysisOptions";if(e===void 0)return{ok:!0};if(!e||typeof e!="object"||Array.isArray(e))return c(o,"Data App analysis options must be an object.");const t=e,i={};if(t.chartTitle!==void 0){if(typeof t.chartTitle!="string")return c(`${o}.chartTitle`,'Data App analysis option "chartTitle" must be a string.');i.chartTitle=t.chartTitle}if(t.chartType!==void 0){if(typeof t.chartType!="string")return c(`${o}.chartType`,'Data App analysis option "chartType" must be a string.');i.chartType=t.chartType}if(t.driverMode!==void 0){if(!ce(t.driverMode))return c(`${o}.driverMode`,'Data App analysis option "driverMode" must be absolute_delta, largest_negative, largest_positive, positive_and_negative, or all.');i.driverMode=t.driverMode}if(t.includePopulation!==void 0){if(typeof t.includePopulation!="boolean")return c(`${o}.includePopulation`,'Data App analysis option "includePopulation" must be a boolean.');i.includePopulation=t.includePopulation}if(t.calendarContext!==void 0){const a=fe(t.calendarContext,{pathPrefix:`${o}.calendarContext`,validateTimezone:r.validateTimezone});if(!a.ok)return a;i.calendarContext=a.calendarContext}return{ok:!0,analysisOptions:i}}function de(e){const r=e.queries.map((i,a)=>le(i,a,{fieldCatalogs:e.fieldCatalogs||[],requireFieldCatalog:!!e.requireFieldCatalog,validateTimezone:e.validateTimezone})),o=r.flatMap(i=>i.diagnostics),t=r.map(i=>i.executionResult);return{ok:o.every(i=>i.severity!=="error"),diagnostics:o,queries:r,intents:r.flatMap(i=>i.intent?[i.intent]:[]),executionResults:t}}function le(e,r,o){const t=`queries.${r}`;try{const i=pe(e),a=$e(e,i),s=E.validateSemaphorAnalyticsIntent(i),n=[...ke({querySpec:e,queryId:a,intent:i,pathPrefix:t}),...s.errors.map(h=>C(h,{queryHook:e.queryHook,queryId:a,pathPrefix:t,severity:"error",intent:i})),...s.warnings.map(h=>C(h,{queryHook:e.queryHook,queryId:a,pathPrefix:t,severity:"warning",intent:i})),...ye({querySpec:e,queryId:a,intent:i,pathPrefix:t,fieldCatalogs:o.fieldCatalogs,requireFieldCatalog:o.requireFieldCatalog}),...Ie({querySpec:e,queryId:a,intent:i,pathPrefix:t,validateTimezone:o.validateTimezone})],d=be(s,n);return{queryHook:e.queryHook,queryId:a,intent:i,diagnostics:n,executionResult:j({intent:i,validation:d,diagnostics:n})}}catch(i){const a={severity:"error",code:"invalid_query_spec",message:i instanceof Error?i.message:String(i),path:t,queryHook:e.queryHook,queryId:Q(e.spec)},s=K([a]);return{queryHook:e.queryHook,queryId:a.queryId,diagnostics:[a],executionResult:j({validation:s,diagnostics:[a]})}}}function c(e,r){return{ok:!1,issues:[{code:"invalid_analysis_option",message:r,path:e}]}}function N(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function ce(e){return e==="absolute_delta"||e==="largest_negative"||e==="largest_positive"||e==="positive_and_negative"||e==="all"}function ue(e){return e.trim().length>0&&!Number.isNaN(Date.parse(e))}function fe(e,r){var d;if(!e||typeof e!="object"||Array.isArray(e))return c(r.pathPrefix,'Data App analysis option "calendarContext" must be an object.');const o=e,t=o.tz,i=o.weekStart,a=o.anchor,s=a&&typeof a=="object"&&!Array.isArray(a)?a.iso:void 0,n=typeof t=="string"?((d=r.validateTimezone)==null?void 0:d.call(r,t))??t:null;return n?typeof i!="number"||!Number.isInteger(i)||i<0||i>6?c(`${r.pathPrefix}.weekStart`,'Data App analysis option "calendarContext.weekStart" must be an integer from 0 to 6.'):a!=="now"&&!(typeof s=="string"&&ue(s))?c(`${r.pathPrefix}.anchor`,'Data App analysis option "calendarContext.anchor" must be "now" or an object with a valid iso string.'):{ok:!0,calendarContext:{tz:n,weekStart:i,anchor:a}}:c(`${r.pathPrefix}.tz`,'Data App analysis option "calendarContext.tz" must be a valid timezone string.')}function pe(e){return me(e.spec)}function me(e){if(!N(e))throw new Error("useSemaphorQuery spec must be an object.");if(e.queryKind==="metric")return y.toSemaphorMetricIntent(e);if(e.queryKind==="analysis")return y.toSemaphorAnalysisIntent(e);if(e.queryKind==="records")return y.toSemaphorRecordsIntent(e);if(e.queryKind==="sql")return y.toSemaphorSqlIntent(e);if(e.queryKind==="matrix")return y.toSemaphorMatrixIntent(e);if(e.queryKind==="inputOptions")return y.toSemaphorInputOptionsIntent(e);throw new Error("useSemaphorQuery spec.queryKind must be metric, analysis, records, inputOptions, sql, or matrix.")}function ye(e){if(e.intent.kind==="sql")return[];if(e.fieldCatalogs.length===0&&!e.requireFieldCatalog)return[];const r=k(e.fieldCatalogs,e.intent.source);if(!r)return[{severity:"error",code:"invalid_source_ref",message:`Source ref for ${e.querySpec.queryHook} does not match a visible Semaphor source.`,path:`${e.pathPrefix}.spec.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}];const o=ge({...e,catalog:r}),t={...r,fields:[...r.fields,...Re(e.intent,r,e.intent.source)]};return[...o,...he({...e,fieldCatalogs:e.fieldCatalogs}),...qe({...e,catalog:t,fieldCatalogs:e.fieldCatalogs}),...ve({...e,catalog:t,fieldCatalogs:e.fieldCatalogs})]}function he(e){var o;if(e.intent.kind!=="inputOptions"||((o=e.intent.population)==null?void 0:o.kind)!=="related_population")return[];const r=e.intent.population.baseSource;return k(e.fieldCatalogs,r)?[]:[{severity:"error",code:"invalid_source_ref",message:"Input options related population baseSource does not match a visible Semaphor source.",path:`${e.pathPrefix}.spec.population.baseSource`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:r}]}function ge(e){const r=O(e.intent);if(r.length===0)return[];const o=[],t=new Set;return r.forEach((i,a)=>{const s=`${e.pathPrefix}.spec.derivedFields.${a}`,n=P(i.name);n&&(t.has(n)&&o.push({severity:"error",code:"duplicate_derived_field",message:`Derived field "${i.name}" is declared more than once.`,path:`${s}.name`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}),t.add(n),e.catalog.fields.some(d=>P(d.name)===n)&&o.push({severity:"error",code:"derived_field_name_collision",message:`Derived field "${i.name}" conflicts with a field already visible on the selected Semaphor source.`,path:`${s}.name`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source})),Object.entries(i.inputs||{}).forEach(([d,h])=>{const m=xe(h);if(!m)return;const F=g(m,e.intent.source);if(!q.semaphorSourcesReferToSameDataset(F,e.intent.source)){o.push({severity:"error",code:"unsupported_derived_field_source",message:`Derived field "${i.name}" input "${d}" references a different Semaphor source. App-local derived fields must use fields from the query source.`,path:`${s}.inputs.${d}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:F,field:m});return}I(e.catalog,m,e.intent.source)||o.push({severity:"error",code:"missing_field",message:`Derived field "${i.name}" input "${d}" references field "${m.name}", which is not visible on the selected Semaphor source.`,path:`${s}.inputs.${d}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:F,field:m})})}),o}function qe(e){return Fe(e.intent).flatMap(({field:r,path:o})=>{const t=ie({intent:e.intent,field:r,relativePath:o,baseCatalog:e.catalog,fieldCatalogs:e.fieldCatalogs});return t.ok?[]:[{severity:"error",code:t.code,message:t.message,path:`${e.pathPrefix}.${o}${t.pathSuffix||""}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:t.source,field:r}]})}function ve(e){return("inputs"in e.intent?e.intent.inputs||[]:[]).flatMap((o,t)=>{if(!o.field)return[];const i=g(o.field,e.intent.source);if(!q.semaphorSourcesReferToSameDataset(i,e.intent.source)){if(Se(e.intent,i)){const a=k(e.fieldCatalogs,i);return a?I(a,o.field,i)?[]:[{severity:"error",code:"missing_field",message:`Input "${o.inputId}" references field "${o.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${t}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]:[{severity:"error",code:"invalid_source_ref",message:`Input "${o.inputId}" references a Semaphor source that is not present in the visible field catalog.`,path:`${e.pathPrefix}.spec.inputs.${t}.field.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]}return[{severity:"error",code:"unsupported_input_filter_composition",message:`Input "${o.inputId}" filters a different Semaphor source than the query, and no relationship-aware semantic validation path is available for this query kind.`,path:`${e.pathPrefix}.spec.inputs.${t}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]}return I(e.catalog,o.field,e.intent.source)?[]:[{severity:"error",code:"missing_field",message:`Input "${o.inputId}" references field "${o.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${t}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:i,field:o.field}]})}function Se(e,r){return e.source.kind==="semantic"&&r.kind==="semantic"&&r.domainId===e.source.domainId}function Ie(e){if(e.querySpec.spec.queryKind!=="analysis")return[];const r=z(e.querySpec.spec,{pathPrefix:`${e.pathPrefix}.spec`,validateTimezone:e.validateTimezone});return r.ok?[]:r.issues.map(o=>({severity:"error",code:o.code,message:o.message,path:o.path,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}))}function ke(e){return e.querySpec.spec.queryKind!=="sql"?[]:N(e.querySpec.spec)?Object.prototype.hasOwnProperty.call(e.querySpec.spec,"parameters")?[{severity:"error",code:"deprecated_sql_parameters",message:"semaphor.sql uses defaultParameters for static SQL param(...) fallback values. The legacy parameters field is not supported.",path:`${e.pathPrefix}.spec.parameters`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id}]:[]:[]}function Fe(e){return e.kind==="metric"?[...e.measures.map((r,o)=>({field:r,path:`spec.measures.${o}`})),...e.primaryMeasure?[{field:e.primaryMeasure,path:"spec.primaryMeasure"}]:[],...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...(e.dimensions||[]).map((r,o)=>({field:r,path:`spec.dimensions.${o}`})),...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,o)=>({field:r.field,path:`spec.filters.${o}.field`}))]:e.kind==="records"?[...e.fields.map((r,o)=>({field:r,path:`spec.fields.${o}`})),...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,o)=>({field:r.field,path:`spec.filters.${o}.field`}))]:e.kind==="inputOptions"?[{field:e.labelField,path:"spec.labelField"},{field:e.valueField,path:"spec.valueField"},...e.searchField?[{field:e.searchField,path:"spec.searchField"}]:[],...(e.disambiguationFields||[]).map((r,o)=>({field:r,path:`spec.disambiguationFields.${o}`}))]:e.kind==="matrix"?[...e.rows.map((r,o)=>({field:r.field,path:`spec.rows.${o}.field`})),...e.rows.flatMap((r,o)=>{var t;return((t=r.sortBy)==null?void 0:t.by.kind)==="field"?[{field:r.sortBy.by.field,path:`spec.rows.${o}.sortBy.by.field`}]:[]}),...(e.columns||[]).map((r,o)=>({field:r.field,path:`spec.columns.${o}.field`})),...(e.columns||[]).flatMap((r,o)=>{var t;return((t=r.sortBy)==null?void 0:t.by.kind)==="field"?[{field:r.sortBy.by.field,path:`spec.columns.${o}.sortBy.by.field`}]:[]}),...e.values.map((r,o)=>({field:r.field,path:`spec.values.${o}.field`})),...(e.sort||[]).flatMap((r,o)=>r.by.kind==="field"?[{field:r.by.field,path:`spec.sort.${o}.by.field`}]:[]),...(e.filters||[]).map((r,o)=>({field:r.field,path:`spec.filters.${o}.field`}))]:[]}function O(e){return!("derivedFields"in e)||!Array.isArray(e.derivedFields)?[]:e.derivedFields}function Re(e,r,o){return O(e).map(t=>({name:t.name,label:t.label,role:t.resultRole,dataType:t.dataType,source:r.source||o,...t.defaultAggregate?{aggregate:t.defaultAggregate}:{}}))}function xe(e){if(!(!e||typeof e!="object"))return e.field}function C(e,r){return{severity:r.severity,code:e.code||"invalid_analytics_intent",message:e.message,path:e.path?`${r.pathPrefix}.spec.${e.path}`:r.pathPrefix,queryHook:r.queryHook,queryId:r.queryId,intentId:r.intent.id,source:r.intent.source}}function be(e,r){const o=K(r);return{ok:o.ok&&e.ok,errors:H([...e.errors,...o.errors]),warnings:H([...e.warnings,...o.warnings]),repairHints:[...e.repairHints,...o.repairHints]}}function K(e){const r=e.filter(t=>t.severity==="error").map(A),o=e.filter(t=>t.severity==="warning").map(A);return{ok:r.length===0,errors:r,warnings:o,repairHints:r.map(t=>{var i,a;return{code:t.code,message:t.message,fieldRole:t.fieldRole,invalidField:(i=t.repairHint)==null?void 0:i.invalidField,recommendedNextStep:((a=t.repairHint)==null?void 0:a.recommendedNextStep)||"Update the Data App SDK query spec to use visible Semaphor source and field refs."}})}}function A(e){var r;return{code:e.code,message:e.message,path:e.path,fieldRole:e.code==="invalid_source_ref"?"source":void 0,repairHint:{code:e.code,message:e.message,invalidField:(r=e.field)==null?void 0:r.name,fieldRole:e.code==="invalid_source_ref"?"source":void 0,recommendedNextStep:e.code==="unsupported_input_filter_composition"?"Use an input field from the same Semaphor source as the query, or split the query into separate source-scoped queries.":"Update the query spec to use a visible Semaphor source and field ref."}}}function H(e){const r=new Set;return e.filter(o=>{const t=`${o.code}:${o.path||""}:${o.message}`;return r.has(t)?!1:(r.add(t),!0)})}function j(e){var o,t;const r=e.diagnostics.filter(i=>i.severity==="error");return{intentId:(o=e.intent)==null?void 0:o.id,status:r.length?"failed":"answered",resultShape:(t=e.intent)==null?void 0:t.kind,intent:e.intent,validation:e.validation,coverage:{answeredObligations:r.length?[]:["query_spec_validation"],missingObligations:r.length?["query_spec_validation"]:[],warnings:e.validation.warnings},missingFields:r.filter(i=>i.code==="missing_field").flatMap(i=>{var a;return(a=i.field)!=null&&a.name?[i.field.name]:[]}),warnings:e.diagnostics.filter(i=>i.severity==="warning").map(i=>i.message),metadata:{validationKind:"data_app_sdk_query_spec"}}}function $e(e,r){return r.id||Q(e.spec)}function Q(e){if(!e||typeof e!="object"||!("id"in e))return;const r=e.id;return typeof r=="string"&&r.trim()?r:void 0}exports.fieldWithSelectedProjectionRole=f;exports.findMatchingRelatedProjectionField=u;exports.isAllowedRelatedProjectionRole=M;exports.matrixAxisFieldsForPolicy=S;exports.normalizeSemaphorAnalysisQueryOptions=z;exports.normalizeSemaphorFieldRole=w;exports.relatedProjectionFieldCandidatesForIntent=J;exports.validateSemaphorDataAppQuerySpecs=de;
@@ -1,4 +1,4 @@
1
- import { b as O } from "../chunks/validators-C-_9Ew5G.js";
1
+ import { b as O } from "../chunks/validators-UqQI3Cg_.js";
2
2
  import "../chunks/analyze-result-contract-DPjm6btg.js";
3
3
  import { s as K, b as q } from "../chunks/source-identity-Cv4Nm3TM.js";
4
4
  import { toSemaphorMetricIntent as Q, toSemaphorAnalysisIntent as E, toSemaphorRecordsIntent as J, toSemaphorSqlIntent as U, toSemaphorMatrixIntent as W, toSemaphorInputOptionsIntent as L } from "../data-app-sdk-adapters/index.js";
@@ -3231,7 +3231,7 @@ export declare type SemaphorOperationIntent = {
3231
3231
  };
3232
3232
 
3233
3233
  export declare type SemaphorOptionDependencies = {
3234
- mode?: 'auto' | 'independent' | 'explicit';
3234
+ mode?: 'independent' | 'explicit';
3235
3235
  includeInputIds?: string[];
3236
3236
  excludeInputIds?: string[];
3237
3237
  };
@@ -1346,7 +1346,7 @@ declare type SemaphorMetricResult = SemaphorAnalyticsResultBase & {
1346
1346
  };
1347
1347
 
1348
1348
  declare type SemaphorOptionDependencies = {
1349
- mode?: 'auto' | 'independent' | 'explicit';
1349
+ mode?: 'independent' | 'explicit';
1350
1350
  includeInputIds?: string[];
1351
1351
  excludeInputIds?: string[];
1352
1352
  };
@@ -2192,7 +2192,7 @@ declare type SemaphorMetricIntent = {
2192
2192
  };
2193
2193
 
2194
2194
  declare type SemaphorOptionDependencies = {
2195
- mode?: 'auto' | 'independent' | 'explicit';
2195
+ mode?: 'independent' | 'explicit';
2196
2196
  includeInputIds?: string[];
2197
2197
  excludeInputIds?: string[];
2198
2198
  };
@@ -837,7 +837,7 @@ declare type SemaphorMetricIntent = {
837
837
  };
838
838
 
839
839
  declare type SemaphorOptionDependencies = {
840
- mode?: 'auto' | 'independent' | 'explicit';
840
+ mode?: 'independent' | 'explicit';
841
841
  includeInputIds?: string[];
842
842
  excludeInputIds?: string[];
843
843
  };
@@ -990,7 +990,7 @@ declare type SemaphorMetricIntent = {
990
990
  };
991
991
 
992
992
  declare type SemaphorOptionDependencies = {
993
- mode?: 'auto' | 'independent' | 'explicit';
993
+ mode?: 'independent' | 'explicit';
994
994
  includeInputIds?: string[];
995
995
  excludeInputIds?: string[];
996
996
  };
@@ -962,7 +962,7 @@ declare type SemaphorMetricIntent = {
962
962
  };
963
963
 
964
964
  declare type SemaphorOptionDependencies = {
965
- mode?: 'auto' | 'independent' | 'explicit';
965
+ mode?: 'independent' | 'explicit';
966
966
  includeInputIds?: string[];
967
967
  excludeInputIds?: string[];
968
968
  };
@@ -481,7 +481,7 @@ declare type SemaphorMetricQuerySpec = SemaphorQuerySourceSpec & SemaphorAppDeri
481
481
  declare type SemaphorNonEmptyArray<T> = [T, ...T[]];
482
482
 
483
483
  declare type SemaphorOptionDependencies = {
484
- mode?: 'auto' | 'independent' | 'explicit';
484
+ mode?: 'independent' | 'explicit';
485
485
  includeInputIds?: string[];
486
486
  excludeInputIds?: string[];
487
487
  };
@@ -971,7 +971,7 @@ declare type SemaphorMetricResult = SemaphorAnalyticsResultBase & {
971
971
  declare type SemaphorNonEmptyArray<T> = [T, ...T[]];
972
972
 
973
973
  declare type SemaphorOptionDependencies = {
974
- mode?: 'auto' | 'independent' | 'explicit';
974
+ mode?: 'independent' | 'explicit';
975
975
  includeInputIds?: string[];
976
976
  excludeInputIds?: string[];
977
977
  };
@@ -1342,7 +1342,7 @@ declare type SemaphorMetricResult = SemaphorAnalyticsResultBase & {
1342
1342
  export declare type SemaphorNonEmptyArray<T> = [T, ...T[]];
1343
1343
 
1344
1344
  export declare type SemaphorOptionDependencies = {
1345
- mode?: 'auto' | 'independent' | 'explicit';
1345
+ mode?: 'independent' | 'explicit';
1346
1346
  includeInputIds?: string[];
1347
1347
  excludeInputIds?: string[];
1348
1348
  };
@@ -5139,7 +5139,7 @@ declare type SemaphorMetricIntent = {
5139
5139
  };
5140
5140
 
5141
5141
  declare type SemaphorOptionDependencies = {
5142
- mode?: 'auto' | 'independent' | 'explicit';
5142
+ mode?: 'independent' | 'explicit';
5143
5143
  includeInputIds?: string[];
5144
5144
  excludeInputIds?: string[];
5145
5145
  };
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "email": "support@semaphor.cloud"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "0.1.415",
8
+ "version": "0.1.416",
9
9
  "description": "Fully interactive and customizable dashboards for your apps.",
10
10
  "keywords": [
11
11
  "react",
@@ -242,15 +242,12 @@ const segmentOptions = semaphor.inputOptions({
242
242
  source,
243
243
  labelField: segment,
244
244
  valueField: segment,
245
- dependencies: { mode: "auto" },
246
245
  limit: 100,
247
246
  });
248
247
 
249
248
  function SegmentFilter() {
250
249
  const [segmentHandle] = useSemaphorInputs([segmentFilter]);
251
- const optionsResult = useSemaphorQuery(segmentOptions, {
252
- inputs: [segmentHandle],
253
- });
250
+ const optionsResult = useSemaphorQuery(segmentOptions);
254
251
 
255
252
  useClearInvalidSemaphorInputValue(segmentHandle, optionsResult);
256
253
 
@@ -1 +0,0 @@
1
- "use strict";const Z=require("./source-identity-BM2FvJDP.js");function a(e,i,t){return t?{code:e,message:i,path:t}:{code:e,message:i}}function J(e){for(let i=0;i<e.length;i+=1){const t=e[i];if(e.some((n,o)=>o!==i&&U(n,t)))return!1}return!0}function L(e,i){return Z.semaphorFieldRefsMatch(e,i)}function U(e,i){return L(e,i)&&g(e)===g(i)}function W(e){return`Metric intent has duplicate measure "${e.name}" with the same aggregate (${g(e)}). Use different aggregates to request both, or remove one entry.`}function E(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function ee(e,i,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){t.push(a("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",i));return}Object.entries(e).forEach(([n,o])=>{if(!n.trim()){t.push(a("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${i}.${n}`));return}(Array.isArray(o)?o.every(E):E(o))||t.push(a("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${i}.${n}`))})}}function ie(e,i){return M(e,i).length===1}function te(e,i){return M(e,i).length===1}function M(e,i){return i.filter(n=>ae(e,n))}function ae(e,i){return ne(e,i)?e.source?L(i,e):!0:!1}function ne(e,i){return!(i.name!==e.name||e.role!==void 0&&i.role!==void 0&&i.role!==e.role||se(e,i)&&g(i)!==g(e))}function se(e,i){return e.role==="measure"||i.role==="measure"||e.aggregate!==void 0||i.aggregate!==void 0}function g(e){return(e.aggregate||"SUM").toUpperCase()}const oe=/^(\d{4})-(\d{2})-(\d{2})$/,re=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})$/;function $(e){if(typeof e!="string")return null;const i=e.trim(),t=oe.exec(i);if(t){const[,y,P,T]=t;return N(y,P,T)?new Date(Date.UTC(Number(y),Number(P)-1,Number(T))):null}const n=re.exec(i);if(!n)return null;const[,o,s,r,c,d,p="00",,f]=n;if(!N(o,s,r)||!v(c,0,23)||!v(d,0,59)||!v(p,0,59)||!de(f))return null;const b=new Date(i);return Number.isFinite(b.getTime())?b:null}function N(e,i,t){const n=Number(e),o=Number(i),s=Number(t);if(!Number.isInteger(n)||!Number.isInteger(o)||!Number.isInteger(s)||o<1||o>12)return!1;const r=new Date(Date.UTC(n,o-1,s));return r.getUTCFullYear()===n&&r.getUTCMonth()===o-1&&r.getUTCDate()===s}function v(e,i,t){const n=Number(e);return Number.isInteger(n)&&n>=i&&n<=t}function de(e){if(e==="Z")return!0;const i=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(i&&v(i[2],0,23)&&v(i[3],0,59))}function l(e){return typeof e=="string"&&e.trim().length>0}function le(e){const i=new Set;let t=0;for(;t<e.length;){const n=e[t];if(n==="'"||n==='"'){t=ue(e,t);continue}if(n==="{"){const o=e.indexOf("}",t+1);if(o===-1){t+=1;continue}const s=e.slice(t+1,o);/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&i.add(s),t=o+1;continue}t+=1}return Array.from(i)}function ue(e,i){const t=e[i];let n=i+1;for(;n<e.length;){if(e[n]===t){if(e[n+1]===t){n+=2;continue}return n+1}n+=1}return e.length}function u(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function O(e,i,t){if(e!==void 0){if(!u(e)){t.push(a("invalid_pagination","Pagination must be an object with positive integer page and pageSize.",i));return}(!Number.isInteger(e.page)||typeof e.page!="number"||e.page<1)&&t.push(a("invalid_pagination_page","Pagination page must be a positive integer.",`${i}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&t.push(a("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${i}.pageSize`))}}function I(e){const i=new Set;for(const t of e){if(i.has(t))return t;i.add(t)}return null}function w(e,i,t,n){I(e.filter(s=>l(s)))&&n.push(a("duplicate_matrix_public_id",`Matrix ${t} ids must be unique so sort and expansion references are unambiguous.`,i))}const ce=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function k(e,i,t){if(!e||typeof e!="object"){t.push(a("missing_source","Analytics intent needs a source.",i));return}if(e.kind==="semantic"){l(e.domainId)||t.push(a("missing_semantic_domain","Semantic source needs a domainId.",`${i}.domainId`)),l(e.datasetName)||t.push(a("missing_dataset_name","Semantic source needs a datasetName.",`${i}.datasetName`));return}if(e.kind==="physical"){l(e.connectionId)||t.push(a("missing_connection_id","Physical source needs a connectionId.",`${i}.connectionId`)),l(e.tableName)||t.push(a("missing_table_name","Physical source needs a tableName.",`${i}.tableName`));return}if(e.kind==="sql"){l(e.connectionId)||t.push(a("missing_connection_id","SQL source needs a connectionId.",`${i}.connectionId`));return}t.push(a("invalid_source_kind","Source kind is not supported.",i))}function m(e,i,t,n={}){if(!e||!u(e)){n.required&&t.push(a("missing_field_ref","Field reference needs a name.",i));return}l(e.name)||t.push(a("missing_field_ref","Field reference needs a name.",`${i}.name`)),e.source!==void 0&&k(e.source,`${i}.source`,t),_(e.aggregate,`${i}.aggregate`,t)}function pe(e,i,t){if(!u(e)){t.push(a("invalid_input_binding","Input bindings must be structured objects.",i));return}l(e.inputId)||t.push(a("invalid_input_binding","Input bindings need a non-empty inputId.",`${i}.inputId`)),e.kind!==void 0&&e.kind!=="filter"&&e.kind!=="control"&&t.push(a("invalid_input_binding","Input binding kind must be filter or control.",`${i}.kind`)),e.field!==void 0&&m(e.field,`${i}.field`,t),e.relationshipHint!==void 0&&R(e.relationshipHint,`${i}.relationshipHint`,t)}function R(e,i,t){if(!u(e)){t.push(a("invalid_relationship_hint","Relationship hints must be structured objects.",i));return}e.relationshipIds!==void 0&&(!Array.isArray(e.relationshipIds)||e.relationshipIds.some(n=>!l(n)))&&t.push(a("invalid_relationship_hint","Relationship hint relationshipIds must be non-empty strings.",`${i}.relationshipIds`))}function me(e,i){if(l(e.inputId)||i.push(a("missing_input_options_input_id","Input options intent needs the inputId it populates.","inputId")),(!e.labelField||!l(e.labelField.name))&&i.push(a("missing_input_options_label_field","Input options intent needs a labelField.","labelField")),m(e.labelField,"labelField",i,{required:!0}),(!e.valueField||!l(e.valueField.name))&&i.push(a("missing_input_options_value_field","Input options intent needs a valueField.","valueField")),m(e.valueField,"valueField",i,{required:!0}),e.searchField!==void 0&&m(e.searchField,"searchField",i,{required:!0}),e.disambiguationFields!==void 0&&(Array.isArray(e.disambiguationFields)?e.disambiguationFields.forEach((t,n)=>{m(t,`disambiguationFields.${n}`,i,{required:!0})}):i.push(a("invalid_input_options_disambiguation_fields","Input options disambiguationFields must be an array of field refs.","disambiguationFields"))),e.dependencies!==void 0){const t=e.dependencies;if(!u(t))i.push(a("invalid_input_options_dependencies","Input options dependencies must be a structured object.","dependencies"));else{const n=t.mode;n!==void 0&&n!=="auto"&&n!=="independent"&&n!=="explicit"&&i.push(a("invalid_input_options_dependencies","Input options dependencies mode must be auto, independent, or explicit.","dependencies.mode")),j(t.includeInputIds,"dependencies.includeInputIds",i,"Input options includeInputIds must be non-empty strings."),j(t.excludeInputIds,"dependencies.excludeInputIds",i,"Input options excludeInputIds must be non-empty strings."),_e(e,i)}}if(e.population!==void 0){const t=e.population;if(!u(t))i.push(a("invalid_input_options_population","Input options population must be a structured object.","population"));else{const n=t.kind;n!=="option_source"&&n!=="related_population"&&i.push(a("invalid_input_options_population","Input options population kind must be option_source or related_population.","population.kind")),n==="option_source"&&t.baseSource!==void 0&&i.push(a("invalid_input_options_population","Input options population baseSource is only valid for related_population.","population.baseSource")),n==="option_source"&&t.relationshipHint!==void 0&&i.push(a("invalid_input_options_population","Input options population relationshipHint is only valid for related_population.","population.relationshipHint")),n==="related_population"&&(k(t.baseSource,"population.baseSource",i),t.relationshipHint!==void 0&&R(t.relationshipHint,"population.relationshipHint",i))}}}function fe(e,i){if(!(!("inputs"in e)||e.inputs===void 0)){if(!Array.isArray(e.inputs)){i.push(a("invalid_input_binding","Analytics intent inputs must be an array of input bindings.","inputs"));return}e.inputs.forEach((t,n)=>pe(t,`inputs.${n}`,i))}}function _e(e,i){var n,o;const t=new Set(Array.isArray(e.inputs)?e.inputs.map(s=>u(s)?s.inputId:void 0).filter(s=>typeof s=="string"):[]);for(const s of((n=e.dependencies)==null?void 0:n.includeInputIds)||[])t.has(s)||i.push(a("invalid_input_options_dependencies",`Input options dependency "${s}" is not declared in inputs.`,"dependencies.includeInputIds"));for(const s of((o=e.dependencies)==null?void 0:o.excludeInputIds)||[])s!==e.inputId&&!t.has(s)&&i.push(a("invalid_input_options_dependencies",`Input options dependency exclusion "${s}" is not the populated inputId and is not declared in inputs.`,"dependencies.excludeInputIds"))}function j(e,i,t,n){e!==void 0&&(!Array.isArray(e)||e.some(o=>!l(o)))&&t.push(a("invalid_input_options_dependencies",n,i))}function _(e,i,t){e!==void 0&&(typeof e!="string"||!ce.has(e))&&t.push(a("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",i))}const ve=new Set(["measure","dimension","date","id","unknown"]),ge=new Set(["row","aggregate"]),V=new Set(["string","number","boolean","date","datetime","unknown"]),be=new Set(["number","currency","percent","percentage","scientific","date","datetime","duration","string"]),ye=new Set(["millisecond","second","minute","hour","day"]),he=new Set(["compact","digital","long"]);function D(e,i,t){if(e===void 0)return;if(!u(e)){t.push(a("invalid_value_format","Value format must be a structured object.",i));return}const n=e;(typeof n.type!="string"||!be.has(n.type))&&t.push(a("invalid_value_format_type","Value format type must be number, currency, percent, scientific, date, datetime, duration, or string.",`${i}.type`)),h(e.minimumFractionDigits,`${i}.minimumFractionDigits`,t),h(e.maximumFractionDigits,`${i}.maximumFractionDigits`,t),h(e.scale,`${i}.scale`,t),h(e.maxUnits,`${i}.maxUnits`,t),e.useGrouping!==void 0&&typeof e.useGrouping!="boolean"&&t.push(a("invalid_value_format_use_grouping","Value format useGrouping must be boolean.",`${i}.useGrouping`)),e.negativeStyle!==void 0&&e.negativeStyle!=="minus"&&e.negativeStyle!=="parentheses"&&t.push(a("invalid_value_format_negative_style","Value format negativeStyle must be minus or parentheses.",`${i}.negativeStyle`)),e.percentValueMode!==void 0&&e.percentValueMode!=="fraction"&&e.percentValueMode!=="whole"&&t.push(a("invalid_value_format_percent_mode","Value format percentValueMode must be fraction or whole.",`${i}.percentValueMode`));for(const o of["inputUnit","largestUnit","smallestUnit"]){const s=e[o];s!==void 0&&(typeof s!="string"||!ye.has(s))&&t.push(a("invalid_value_format_duration_unit","Duration format units must be millisecond, second, minute, hour, or day.",`${i}.${o}`))}e.outputStyle!==void 0&&(typeof e.outputStyle!="string"||!he.has(e.outputStyle))&&t.push(a("invalid_value_format_duration_style","Duration format outputStyle must be compact, digital, or long.",`${i}.outputStyle`))}function h(e,i,t){e!==void 0&&(typeof e!="number"||!Number.isFinite(e))&&t.push(a("invalid_value_format_number","Value format numeric options must be finite numbers.",i))}const xe=new Set(["additive","non_additive","ratio_of_sums","weighted","pre_aggregated","snapshot"]),we=new Set(["default","symmetric_aggregate","aggregate_then_join","weighted"]);function $e(e,i,t){if(!e||!u(e)){t.push(a("invalid_derived_field_input","Derived field inputs must be structured input references.",i));return}if(e.kind==="field"){m(e.field,`${i}.field`,t,{required:!0}),_(e.aggregate,`${i}.aggregate`,t);return}t.push(a("invalid_derived_field_input","Derived field input kind must be field.",`${i}.kind`))}function B(e,i,t){if(!u(e)){t.push(a("invalid_result_column_ref","Result calculation references must use columnKey or field.",i));return}const n=l(e.columnKey),o=u(e.field);if(n===o){t.push(a("invalid_result_column_ref","Result calculation references must identify exactly one of columnKey or field.",i));return}o&&m(e.field,`${i}.field`,t,{required:!0})}function Ie(e,i,t){if(!u(e)){t.push(a("invalid_result_calculation_output","Result calculation output must be a structured object.",i));return}l(e.key)||t.push(a("invalid_result_calculation_output","Result calculation output needs a stable key.",`${i}.key`)),e.dataType!==void 0&&(typeof e.dataType!="string"||!V.has(e.dataType))&&t.push(a("invalid_result_calculation_output","Result calculation output dataType must be string, number, boolean, date, datetime, or unknown.",`${i}.dataType`)),D(e.format,`${i}.format`,t)}function Ae(e,i,t){e!==void 0&&e!=="hour"&&e!=="day"&&e!=="week"&&e!=="month"&&e!=="quarter"&&e!=="year"&&t.push(a("invalid_time_grain","Time grain must be hour, day, week, month, quarter, or year.",i))}function G(e,i,t,n){e!=="asc"&&e!=="desc"&&t.push(a(n,"Sort direction must be asc or desc.",i))}function z(e,i,t,n){e!==void 0&&e!=="warehouseDefault"&&e!=="first"&&e!=="last"&&t.push(a(n,"Null ordering must be warehouseDefault, first, or last.",i))}function Q(e,i,t,n){e!==void 0&&e!=="global"&&e!=="withinParent"&&t.push(a(n,"Sort scope must be global or withinParent.",i))}function Se(e,i,t){e.enabled!==void 0&&typeof e.enabled!="boolean"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal enabled must be a boolean.",`${i}.enabled`)),e.position!==void 0&&e.position!=="before"&&e.position!=="after"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal position must be before or after.",`${i}.position`)),e.label!==void 0&&typeof e.label!="string"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal label must be a string.",`${i}.label`))}function Me(e,i,t){if(G(e.direction,`${i}.direction`,t,"invalid_matrix_sort_direction"),z(e.nulls,`${i}.nulls`,t,"invalid_matrix_sort_nulls"),Q(e.scope,`${i}.scope`,t,"invalid_matrix_sort_scope"),!u(e.by)){t.push(a("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${i}.by`));return}if(e.by.kind!=="label"){if(e.by.kind==="field"){m(e.by.field,`${i}.by.field`,t,{required:!0}),_(e.by.aggregate,`${i}.by.aggregate`,t);return}t.push(a("invalid_matrix_sort_by","Matrix axis sort by must be label or field.",`${i}.by.kind`))}}function q(e,i,t,n){if(!Array.isArray(e))return n.required?t.push(a("missing_matrix_rows","Matrix intent needs at least one row axis level.",i)):e!==void 0&&t.push(a("invalid_matrix_columns","Matrix columns must be an array of axis levels.",i)),[];n.required&&e.length===0&&t.push(a("missing_matrix_rows","Matrix intent needs at least one row axis level.",i));const o=[];return e.forEach((s,r)=>{const c=`${i}.${r}`;if(!u(s)){t.push(a("invalid_matrix_axis_level","Matrix axis levels must be structured objects.",c));return}const d=s;o.push(d),d.id!==void 0&&!l(d.id)&&t.push(a("invalid_matrix_axis_level_id","Matrix axis level id must be a non-empty string.",`${c}.id`)),m(d.field,`${c}.field`,t,{required:!0}),Ae(d.grain,`${c}.grain`,t),d.label!==void 0&&typeof d.label!="string"&&t.push(a("invalid_matrix_axis_label","Matrix axis level label must be a string.",`${c}.label`)),d.subtotal!==void 0&&typeof d.subtotal!="boolean"&&(u(d.subtotal)?Se(d.subtotal,`${c}.subtotal`,t):t.push(a("invalid_matrix_subtotal","Matrix subtotal must be a boolean or structured options object.",`${c}.subtotal`))),d.sortBy!==void 0&&(u(d.sortBy)?Me(d.sortBy,`${c}.sortBy`,t):t.push(a("invalid_matrix_sort_by","Matrix axis sortBy must be a structured object.",`${c}.sortBy`)))}),o}function ke(e,i,t){if(!u(e)){t.push(a("invalid_matrix_total_behavior","Matrix total behavior must be a structured object.",i));return}if(e.kind!=="defaultAggregate"&&e.kind!=="blank"&&e.kind!=="labelOnly"&&e.kind!=="customAggregate"&&e.kind!=="percentOfParent"&&e.kind!=="percentOfGrandTotal"&&e.kind!=="customExpression"){t.push(a("invalid_matrix_total_behavior","Matrix total behavior kind is not supported.",`${i}.kind`));return}e.kind==="customAggregate"&&(Object.prototype.hasOwnProperty.call(e,"aggregate")?_(e.aggregate,`${i}.aggregate`,t):t.push(a("invalid_matrix_total_behavior","Custom matrix total behavior needs an aggregate.",`${i}.aggregate`))),e.kind==="customExpression"&&!l(e.expressionId)&&t.push(a("invalid_matrix_total_behavior","Custom matrix total behavior needs an expressionId.",`${i}.expressionId`)),e.kind==="labelOnly"&&e.label!==void 0&&typeof e.label!="string"&&t.push(a("invalid_matrix_total_behavior","Matrix label-only total behavior label must be a string.",`${i}.label`))}function Re(e,i,t){if(!Array.isArray(e)||e.length===0)return t.push(a("missing_matrix_values","Matrix intent needs at least one value field.",i)),[];const n=[];return e.forEach((o,s)=>{const r=`${i}.${s}`;if(!u(o)){t.push(a("invalid_matrix_value","Matrix values must be structured objects.",r));return}const c=o;n.push(c),c.id!==void 0&&!l(c.id)&&t.push(a("invalid_matrix_value_id","Matrix value id must be a non-empty string.",`${r}.id`)),m(c.field,`${r}.field`,t,{required:!0}),_(c.aggregate,`${r}.aggregate`,t),D(c.format,`${r}.format`,t),c.label!==void 0&&typeof c.label!="string"&&t.push(a("invalid_matrix_value_label","Matrix value label must be a string.",`${r}.label`)),c.totalBehavior!==void 0&&ke(c.totalBehavior,`${r}.totalBehavior`,t)}),n}function De(e,i,t){if(!u(e)){t.push(a("invalid_matrix_totals","Matrix totals must be a structured object.",i));return}for(const n of["rows","columns"]){const o=e[n];o!==void 0&&o!==!0&&o!==!1&&o!=="perLevel"&&t.push(a("invalid_matrix_totals","Matrix total axis setting must be a boolean or perLevel.",`${i}.${n}`))}if(e.grandTotal!==void 0&&typeof e.grandTotal!="boolean")if(!u(e.grandTotal))t.push(a("invalid_matrix_totals","Matrix grandTotal must be a boolean or structured object.",`${i}.grandTotal`));else for(const n of["rows","columns"]){const o=e.grandTotal[n];o!==void 0&&typeof o!="boolean"&&t.push(a("invalid_matrix_totals","Matrix grandTotal rows/columns must be booleans.",`${i}.grandTotal.${n}`))}e.rowPosition!==void 0&&e.rowPosition!=="top"&&e.rowPosition!=="bottom"&&t.push(a("invalid_matrix_totals","Matrix row total position must be top or bottom.",`${i}.rowPosition`)),e.columnPosition!==void 0&&e.columnPosition!=="left"&&e.columnPosition!=="right"&&t.push(a("invalid_matrix_totals","Matrix column total position must be left or right.",`${i}.columnPosition`))}function A(e,i,t,n){if(!Array.isArray(e)){n.push(a("invalid_matrix_path","Matrix member path must be an array of path segments.",i));return}e.forEach((o,s)=>{const r=`${i}.${s}`;if(!u(o)){n.push(a("invalid_matrix_path","Matrix path segment must be a structured object.",r));return}const c=o;if(!l(c.levelId)){n.push(a("stable_id_required","Matrix path segments must reference an explicit public axis level id.",`${r}.levelId`));return}Object.prototype.hasOwnProperty.call(o,"value")||n.push(a("invalid_matrix_path","Matrix path segments must include a value property; use explicit null for null members.",`${r}.value`)),t.has(c.levelId)||n.push(a("stable_id_required","Matrix path segment levelId must match an explicit public axis level id.",`${r}.levelId`))})}function H(e,i,t,n){if(!u(e)){n.push(a("invalid_matrix_expansion","Matrix expansion axis options must be structured objects.",i));return}e.defaultDepth!==void 0&&(typeof e.defaultDepth!="number"||!Number.isInteger(e.defaultDepth)||e.defaultDepth<0)&&n.push(a("invalid_matrix_expansion","Matrix expansion defaultDepth must be a non-negative integer.",`${i}.defaultDepth`)),e.lazy!==void 0&&typeof e.lazy!="boolean"&&n.push(a("invalid_matrix_expansion","Matrix expansion lazy must be a boolean.",`${i}.lazy`)),e.expandedPaths!==void 0&&(Array.isArray(e.expandedPaths)?e.expandedPaths.forEach((o,s)=>{A(o,`${i}.expandedPaths.${s}`,t,n)}):n.push(a("invalid_matrix_expansion","Matrix expandedPaths must be an array of member paths.",`${i}.expandedPaths`)))}function Fe(e,i,t,n){if(e!==void 0){if(!u(e)){n.push(a("invalid_matrix_expansion","Matrix expansion must be a structured object.","expansion"));return}e.rows!==void 0&&H(e.rows,"expansion.rows",i,n),e.columns!==void 0&&H(e.columns,"expansion.columns",t,n)}}function Pe(e,i,t,n,o){if(e!==void 0){if(!Array.isArray(e)){o.push(a("invalid_matrix_sort","Matrix sort must be an array of sort rules.","sort"));return}e.forEach((s,r)=>{const c=`sort.${r}`;if(!u(s)){o.push(a("invalid_matrix_sort","Matrix sort rule must be a structured object.",c));return}const d=s;d.axis!=="row"&&d.axis!=="column"&&o.push(a("invalid_matrix_sort","Matrix sort axis must be row or column.",`${c}.axis`));const p=d.axis==="column"?t:i;if(d.targetId!==void 0&&!p.has(d.targetId)&&o.push(a("stable_id_required","Matrix sort targetId must reference an explicit public axis level id.",`${c}.targetId`)),G(d.direction,`${c}.direction`,o,"invalid_matrix_sort_direction"),z(d.nulls,`${c}.nulls`,o,"invalid_matrix_sort_nulls"),Q(d.scope,`${c}.scope`,o,"invalid_matrix_sort_scope"),!u(d.by)){o.push(a("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${c}.by`));return}if(d.by.kind!=="label"){if(d.by.kind==="field"){m(d.by.field,`${c}.by.field`,o,{required:!0}),_(d.by.aggregate,`${c}.by.aggregate`,o);return}if(d.by.kind==="value"){(!l(d.by.valueId)||!n.has(d.by.valueId))&&o.push(a("stable_id_required","Matrix value sort must reference an explicit public value id.",`${c}.by.valueId`)),d.by.rowPath!==void 0&&A(d.by.rowPath,`${c}.by.rowPath`,i,o),d.by.columnPath!==void 0&&A(d.by.columnPath,`${c}.by.columnPath`,t,o);return}o.push(a("invalid_matrix_sort_by","Matrix sort by must be label, field, or value.",`${c}.by.kind`))}})}}function Te(e,i){if(e!==void 0){if(!u(e)){i.push(a("invalid_matrix_layout","Matrix layout must be a structured object.","layout"));return}e.hierarchy!==void 0&&e.hierarchy!=="compact"&&e.hierarchy!=="tabular"&&e.hierarchy!=="outline"&&i.push(a("invalid_matrix_layout","Matrix hierarchy layout must be compact, tabular, or outline.","layout.hierarchy")),e.valuesPlacement!==void 0&&e.valuesPlacement!=="columns"&&e.valuesPlacement!=="rows"&&i.push(a("invalid_matrix_layout","Matrix valuesPlacement must be columns or rows.","layout.valuesPlacement")),e.stickyRowHeaders!==void 0&&typeof e.stickyRowHeaders!="boolean"&&i.push(a("invalid_matrix_layout","Matrix stickyRowHeaders must be a boolean.","layout.stickyRowHeaders")),e.stickyColumnHeaders!==void 0&&typeof e.stickyColumnHeaders!="boolean"&&i.push(a("invalid_matrix_layout","Matrix stickyColumnHeaders must be a boolean.","layout.stickyColumnHeaders"))}}function C(e,i,t){if(!u(e)){t.push(a("invalid_matrix_display_limits","Matrix display limit must be a structured object.",i));return}(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<1)&&t.push(a("invalid_matrix_display_limits","Matrix display limit must be a positive integer.",`${i}.limit`));for(const n of Object.keys(e))n!=="limit"&&t.push(a("invalid_matrix_display_limits",`Matrix display limit ${n} is not supported in v1; use count-only { limit } display limits.`,`${i}.${n}`))}function Ee(e,i){if(e!==void 0){if(!u(e)){i.push(a("invalid_matrix_display_limits","Matrix displayLimits must be a structured object.","displayLimits"));return}e.rows!==void 0&&C(e.rows,"displayLimits.rows",i),e.columns!==void 0&&C(e.columns,"displayLimits.columns",i);for(const t of Object.keys(e))t==="rows"||t==="columns"||i.push(a("invalid_matrix_display_limits",`Matrix displayLimits ${t} is not supported in v1; use rows and columns count limits only.`,`displayLimits.${t}`))}}function Ne(e,i){var d;((d=e.source)==null?void 0:d.kind)==="sql"&&i.push(a("unsupported_matrix_sql_source","Matrix analytics intent does not support raw SQL sources.","source.kind"));const t=q(e.rows,"rows",i,{required:!0}),n=q(e.columns,"columns",i,{required:!1}),o=Re(e.values,"values",i);x(e.filters,"filters",i),e.totals!==void 0&&De(e.totals,"totals",i),w(t.map(p=>p.id),"rows","row axis level",i),w(n.map(p=>p.id),"columns","column axis level",i),w(o.map(p=>p.id),"values","value",i);const s=new Set(t.map(p=>p.id).filter(p=>l(p))),r=new Set(n.map(p=>p.id).filter(p=>l(p))),c=new Set(o.map(p=>p.id).filter(p=>l(p)));Pe(e.sort,s,r,c,i),Fe(e.expansion,s,r,i),Te(e.layout,i),Ee(e.displayLimits,i)}function Oe(e,i){if(e.analysis===void 0)return;if(!u(e.analysis)){i.push(a("invalid_measure_analysis","Metric analysis must be a structured object.","analysis"));return}if(e.analysis.kind!=="period_change"){i.push(a("invalid_measure_analysis","Metric analysis kind is not supported.","analysis.kind"));return}e.dateField||i.push(a("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||i.push(a("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"&&i.push(a("invalid_measure_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:t}=e.analysis;t!==void 0&&S(t,"analysis.timeWindow",i)}function S(e,i,t){if(!u(e)){t.push(a("invalid_time_window","Time window must be a structured object.",i));return}if(e.kind!==void 0&&e.kind!=="relative"&&e.kind!=="absolute"&&t.push(a("invalid_time_window","Time window kind must be relative or absolute.",`${i}.kind`)),e.kind==="absolute"){if(l(e.start)||t.push(a("invalid_time_window","Absolute time window start must be a non-empty ISO date or timestamp string.",`${i}.start`)),l(e.end)||t.push(a("invalid_time_window","Absolute time window end must be a non-empty ISO date or timestamp string.",`${i}.end`)),l(e.start)&&l(e.end)){const n=$(e.start),o=$(e.end);n||t.push(a("invalid_time_window","Absolute time window start must be a valid ISO date or timestamp.",`${i}.start`)),o||t.push(a("invalid_time_window","Absolute time window end must be a valid ISO date or timestamp.",`${i}.end`)),n&&o&&n.getTime()>o.getTime()&&t.push(a("invalid_time_window","Absolute time window start must be before or equal to end.",i))}return}e.unit!=="second"&&e.unit!=="minute"&&e.unit!=="hour"&&e.unit!=="day"&&e.unit!=="week"&&e.unit!=="month"&&e.unit!=="quarter"&&e.unit!=="year"&&t.push(a("invalid_time_window","Time window unit must be second, minute, hour, day, week, month, quarter, or year.",`${i}.unit`)),(typeof e.value!="number"||!Number.isFinite(e.value)||e.value<=0)&&t.push(a("invalid_time_window","Time window value must be a positive number.",`${i}.value`)),e.anchor!==void 0&&e.anchor!=="now"&&e.anchor!=="latest_available"&&t.push(a("invalid_time_window","Time window anchor must be now or latest_available.",`${i}.anchor`)),e.completeness!==void 0&&e.completeness!=="include_partial"&&e.completeness!=="complete_periods"&&t.push(a("invalid_time_window","Time window completeness must be include_partial or complete_periods.",`${i}.completeness`))}function x(e,i,t){if(e!==void 0){if(!Array.isArray(e)){t.push(a("invalid_analytics_filters","Analytics filters must be an array.",i));return}e.forEach((n,o)=>{var d;const s=`${i}.${o}`;if(!u(n)){t.push(a("invalid_analytics_filter","Analytics filter must be a structured object.",s));return}const r=n;m(r.field,`${s}.field`,t,{required:!0}),r.scope!==void 0&&r.scope!=="row"&&r.scope!=="aggregate"&&t.push(a("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${s}.scope`)),r.scope==="aggregate"&&((d=r.field)==null?void 0:d.role)!==void 0&&r.field.role!=="measure"&&t.push(a("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${s}.scope`));const c=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"&&t.push(a("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${s}.operator`)),r.values===void 0&&!c&&t.push(a("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",s)),c&&r.values!==void 0){t.push(a("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${s}.values`));return}if(r.values!==void 0&&!Array.isArray(r.values)){t.push(a("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${s}.values`));return}if(r.values!==void 0){const p=r.values.length;if(r.operator==="between"||r.operator==="not_between"){p!==2&&t.push(a("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${s}.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)&&p!==1&&t.push(a("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${s}.values`))}})}}function Y(e){const i=[];if(!u(e))return i.push(a("invalid_derived_field","Derived field definition must be a structured object.")),{ok:!1,errors:i,warnings:[]};if(e.kind!=="derived_field"&&i.push(a("invalid_derived_field_kind","Derived field kind must be derived_field.","kind")),l(e.name)||i.push(a("invalid_derived_field_name","Derived field needs a name.","name")),l(e.label)||i.push(a("invalid_derived_field_label","Derived field needs a label.","label")),ve.has(e.resultRole)||i.push(a("invalid_derived_field_role","Derived field resultRole must be measure, dimension, date, id, or unknown.","resultRole")),V.has(e.dataType)||i.push(a("invalid_derived_field_data_type","Derived field dataType must be string, number, boolean, date, datetime, or unknown.","dataType")),ge.has(e.computeStage)||i.push(a("invalid_derived_field_compute_stage","Derived field computeStage must be row or aggregate.","computeStage")),e.computeStage==="aggregate"&&e.resultRole!=="measure"&&i.push(a("invalid_derived_field_compute_stage","Aggregate-stage derived fields must have resultRole measure.","computeStage")),e.resultRole!=="measure"&&e.defaultAggregate!==void 0&&i.push(a("invalid_derived_field_aggregate","Only measure derived fields may declare defaultAggregate.","defaultAggregate")),e.computeStage==="row"&&e.resultRole==="measure"&&e.defaultAggregate===void 0&&i.push(a("missing_derived_field_default_aggregate","Row-stage measure derived fields must declare defaultAggregate so row results have explicit rollup semantics.","defaultAggregate")),_(e.defaultAggregate,"defaultAggregate",i),e.aggregationBehavior!==void 0&&!xe.has(e.aggregationBehavior)&&i.push(a("invalid_derived_field_aggregation_behavior","Derived field aggregationBehavior is not supported.","aggregationBehavior")),e.aggregationStrategy!==void 0&&!we.has(e.aggregationStrategy)&&i.push(a("invalid_derived_field_aggregation_strategy","Derived field aggregationStrategy is not supported.","aggregationStrategy")),l(e.expression)||i.push(a("invalid_derived_field_expression","Derived field needs a named-token expression.","expression")),e.expressionLanguage!==void 0&&e.expressionLanguage!=="semaphor_sql_template"&&i.push(a("invalid_derived_field_expression_language","Derived field expressionLanguage must be semaphor_sql_template.","expressionLanguage")),!u(e.inputs)||Object.keys(e.inputs).length===0?i.push(a("invalid_derived_field_inputs","Derived field needs at least one typed input.","inputs")):Object.entries(e.inputs).forEach(([t,n])=>{if(!l(t)){i.push(a("invalid_derived_field_input_name","Derived field input names must be non-empty strings.","inputs"));return}$e(n,`inputs.${t}`,i)}),l(e.expression)&&u(e.inputs)){const t=le(e.expression),n=new Set(t),o=Object.keys(e.inputs).filter(s=>l(s));t.forEach(s=>{Object.prototype.hasOwnProperty.call(e.inputs,s)||i.push(a("invalid_derived_field_expression_token",`Derived field expression token "{${s}}" needs a matching inputs.${s} entry.`,"expression"))}),o.forEach(s=>{n.has(s)||i.push(a("unused_derived_field_input",`Derived field input "${s}" is not referenced by expression.`,`inputs.${s}`))})}return D(e.format,"format",i),e.tags!==void 0&&(!Array.isArray(e.tags)||e.tags.some(t=>!l(t)))&&i.push(a("invalid_derived_field_tags","Derived field tags must be non-empty strings.","tags")),{ok:i.length===0,errors:i,warnings:[]}}function je(e){const i=[];if(!u(e))return i.push(a("invalid_result_calculation","Result calculation must be a structured object.")),{ok:!1,errors:i,warnings:[]};if(l(e.id)||i.push(a("invalid_result_calculation_id","Result calculation needs an id.","id")),l(e.label)||i.push(a("invalid_result_calculation_label","Result calculation needs a label.","label")),e.kind!=="percent_of_total"&&e.kind!=="rank"&&e.kind!=="running_total"&&e.kind!=="previous_row_delta"&&i.push(a("invalid_result_calculation_kind","Result calculation kind must be percent_of_total, rank, running_total, or previous_row_delta.","kind")),B(e.input,"input",i),Ie(e.output,"output",i),e.kind==="percent_of_total"){const t=e.denominator;t!==void 0&&(u(t)?t.scope==="population"?(m(t.metric,"denominator.metric",i,{required:!0}),x(t.filters,"denominator.filters",i)):t.scope!=="returned_result"&&i.push(a("invalid_result_calculation_denominator","Percent-of-total denominator scope must be returned_result or population.","denominator.scope")):i.push(a("invalid_result_calculation_denominator","Percent-of-total denominator must be a structured object.","denominator")))}return e.kind==="rank"&&e.order!==void 0&&e.order!=="asc"&&e.order!=="desc"&&i.push(a("invalid_result_calculation_order","Rank result calculation order must be asc or desc.","order")),(e.kind==="running_total"||e.kind==="previous_row_delta")&&e.orderBy!==void 0&&B(e.orderBy,"orderBy",i),{ok:i.length===0,errors:i,warnings:[]}}function F(e){var n;const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_analytics_intent",recommendedNextStep:"Send one structured analytics intent object with kind, source, and required fields."}]};if(e.version!==void 0&&e.version!==1&&i.push(a("invalid_version","Analytics intent version must be 1.","version")),k(e.source,"source",i),Be(e,i),fe(e,i),"relationshipHint"in e&&e.relationshipHint!==void 0&&R(e.relationshipHint,"relationshipHint",i),e.kind==="metric"){const o=Array.isArray(e.measures)?e.measures.filter(s=>u(s)&&l(s.name)):[];if(!Array.isArray(e.measures)||e.measures.length===0?i.push(a("missing_measure","Metric intent needs at least one measure.","measures")):e.measures.some(s=>!u(s)||!l(s.name))&&i.push(a("invalid_measure_list","Metric intent measures must be an array of field references with names.","measures")),o.forEach((s,r)=>{m(s,`measures.${r}`,i,{required:!0})}),o.length>0&&!J(o)){const s=o.find((r,c)=>o.some((d,p)=>p!==c&&U(d,r)));s&&i.push(a("duplicate_measure",W(s),"measures"))}if(u(e.primaryMeasure)&&l(e.primaryMeasure.name)&&M(e.primaryMeasure,o).length>1&&i.push(a("ambiguous_primary_measure","Metric intent primaryMeasure must identify exactly one selected measure.","primaryMeasure")),e.primaryMeasure!==void 0&&(m(e.primaryMeasure,"primaryMeasure",i,{required:!0}),u(e.primaryMeasure)&&l(e.primaryMeasure.name)&&o.length>0&&!ie(e.primaryMeasure,o)&&i.push(a("invalid_primary_measure","Metric intent primaryMeasure must match one measure field reference.","primaryMeasure"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?i.push(a("invalid_measure_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(s=>!u(s)||!l(s.name))&&i.push(a("invalid_measure_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&m(e.dateField,"dateField",i),e.timeWindow!==void 0&&(S(e.timeWindow,"timeWindow",i),e.dateField||i.push(a("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),x(e.filters,"filters",i),Array.isArray(e.dimensions)&&e.dimensions.forEach((s,r)=>{m(s,`dimensions.${r}`,i)}),e.orderBy!==void 0){if(!u(e.orderBy))i.push(a("invalid_measure_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(m(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(a("invalid_measure_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),u(e.orderBy.field)&&l(e.orderBy.field.name)){const s=[...o,...e.timeGrain&&e.dateField&&u(e.dateField)?[e.dateField]:[],...Array.isArray(e.dimensions)?e.dimensions.filter(r=>u(r)&&l(r.name)):[]];s.length>0&&!te(e.orderBy.field,s)&&i.push(a("invalid_measure_order_by","Metric intent orderBy.field must match one selected measure, grouped dateField, or dimension.","orderBy.field"))}}Oe(e,i)}else if(e.kind==="records"){if(!Array.isArray(e.fields)||e.fields.length===0?i.push(a("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(o=>!u(o)||!l(o.name))&&i.push(a("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((o,s)=>{m(o,`fields.${s}`,i)}),e.dateField!==void 0&&m(e.dateField,"dateField",i),O(e.pagination,"pagination",i),e.timeWindow!==void 0&&(S(e.timeWindow,"timeWindow",i),e.dateField||i.push(a("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),x(e.filters,"filters",i),Array.isArray(e.filters)&&e.filters.forEach((o,s)=>{u(o)&&o.scope==="aggregate"&&i.push(a("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${s}.scope`))}),e.orderBy!==void 0&&(u(e.orderBy)?(m(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(a("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):i.push(a("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy"))),e.totals!==void 0)if(!u(e.totals))i.push(a("invalid_records_totals","Records totals must be a structured server totals request.","totals"));else{e.totals.mode!=="server"&&i.push(a("invalid_records_totals","Records totals mode must be server.","totals.mode"));const o=e.totals.measures;!Array.isArray(o)||o.length===0?i.push(a("missing_records_totals_measures","Records server totals need at least one measure.","totals.measures")):o.forEach((s,r)=>{m(s,`totals.measures.${r}`,i,{required:!0}),(!u(s)||s.role!=="measure")&&i.push(a("invalid_records_totals_measure","Records server totals measures must be measure field references.",`totals.measures.${r}.role`))})}}else e.kind==="inputOptions"?me(e,i):e.kind==="matrix"?Ne(e,i):e.kind==="sql"?(((n=e.source)==null?void 0:n.kind)!=="sql"&&i.push(a("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),l(e.sql)||i.push(a("missing_sql","SQL analytics intent needs SQL text.","sql")),ee(e.defaultParameters,"defaultParameters",i),Array.isArray(e.fields)&&e.fields.forEach((o,s)=>{m(o,`fields.${s}`,i)}),O(e.pagination,"pagination",i)):i.push(a("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:He(i)}}function Be(e,i){if(!(!("derivedFields"in e)||e.derivedFields===void 0)){if(!Array.isArray(e.derivedFields)){i.push(a("invalid_derived_fields","Analytics intent derivedFields must be an array of derived field definitions.","derivedFields"));return}e.derivedFields.forEach((t,n)=>{Y(t).errors.forEach(s=>{i.push({...s,path:s.path?`derivedFields.${n}.${s.path}`:`derivedFields.${n}`})})})}}function K(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_operation_intent","Operation intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&i.push(a("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?i.push(a("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((n,o)=>{l(n.id)||i.push(a("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${o}.id`)),l(n.prompt)||i.push(a("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${o}.prompt`))});else if(e.kind==="dashboard_change"||e.kind==="data_app_change"){if(l(e.instruction)||i.push(a("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const n=F(e.analyticsIntent);i.push(...n.errors),t.push(...n.warnings)}}else i.push(a("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:X(i)}}function qe(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:t,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&i.push(a("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&i.push(a("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const n=K(e.operationIntent);return i.push(...n.errors),t.push(...n.warnings),Array.isArray(e.plannedToolCalls)||i.push(a("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:i.length===0,errors:i,warnings:t,repairHints:X(i)}}function X(e){return e.map(i=>({code:i.code,recommendedNextStep:i.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 He(e){return e.map(i=>{switch(i.code){case"missing_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_measure":return{code:i.code,fieldRole:"measure",recommendedNextStep:"Choose one exact measure from the grounded schema candidates."};case"missing_record_fields":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_matrix_rows":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Choose at least one row axis level for the matrix table."};case"missing_matrix_values":return{code:i.code,fieldRole:"measure",recommendedNextStep:"Choose at least one value field for the matrix table."};case"unsupported_matrix_sql_source":return{code:i.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:i.code,fieldRole:"input",recommendedNextStep:"Provide the inputId that these option values populate."};case"missing_input_options_label_field":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide the human-readable field used as option labels."};case"missing_input_options_value_field":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide the stable field used as option values."};case"missing_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:i.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:i.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return}}).filter(i=>!!i)}function Ce(e,i,t,n){if(!e||typeof e!="object"){t.push(a("invalid_view","Dashboard view must be an object.",i));return}if(l(e.title)||t.push(a("missing_view_title","Dashboard view needs a title.",i)),!e.presentation||typeof e.presentation!="object"){t.push(a("missing_presentation","Dashboard view needs a presentation.",`${i}.presentation`));return}if(e.presentation.kind==="text"){l(e.text)||n.push(a("missing_text_content","Text views should include text content.",`${i}.text`));return}if(!e.analytics){t.push(a("missing_view_analytics","Non-text dashboard views need analytics intent.",`${i}.analytics`));return}e.presentation.kind==="matrixTable"&&e.analytics.kind!=="matrix"&&t.push(a("invalid_matrix_view_analytics","Matrix table views need matrix analytics intent.",`${i}.analytics.kind`));const o=F(e.analytics);for(const s of o.errors)t.push(a(s.code,s.message,`${i}.analytics${s.path?`.${s.path}`:""}`));for(const s of o.warnings)n.push(a(s.code,s.message,`${i}.analytics${s.path?`.${s.path}`:""}`))}function Le(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:t};e.version!==1&&i.push(a("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&i.push(a("invalid_kind","Experience intent kind must be dashboard.")),l(e.title)||i.push(a("missing_title","Dashboard intent needs a title.","title"));const n=Array.isArray(e.inputs)?e.inputs:[],o=I(n.filter(u).map(d=>d.id).filter(d=>typeof d=="string"));o&&i.push(a("duplicate_input_id",`Duplicate input id: ${o}.`,"inputs"));for(const[d,p]of n.entries()){const f=`inputs.${d}`;if(!u(p)){i.push(a("invalid_input","Dashboard input must be an object.",f));continue}l(p.id)||i.push(a("missing_input_id","Input needs an id.",`${f}.id`)),l(p.label)||i.push(a("missing_input_label","Input needs a label.",`${f}.label`)),!p.field||!l(p.field.name)?i.push(a("missing_input_field","Input needs a field.",`${f}.field`)):m(p.field,`${f}.field`,i)}const s=Array.isArray(e.sections)?e.sections:[];s.length===0&&i.push(a("missing_sections","Dashboard intent needs at least one section.","sections"));const r=s.flatMap(d=>d&&typeof d=="object"&&Array.isArray(d.views)?d.views.filter(u).map(p=>p.id).filter(p=>!!p):[]),c=I(r);c&&i.push(a("duplicate_view_id",`Duplicate dashboard view id: ${c}.`,"sections"));for(const[d,p]of s.entries()){const f=`sections.${d}`;if(!p||typeof p!="object"){i.push(a("invalid_section","Dashboard section must be an object.",f));continue}if(l(p.title)||i.push(a("missing_section_title","Dashboard section needs a title.",f)),!Array.isArray(p.views)||p.views.length===0){i.push(a("missing_section_views","Dashboard section needs at least one view.",`${f}.views`));continue}for(const[b,y]of p.views.entries())Ce(y,`${f}.views.${b}`,i,t)}return{ok:i.length===0,errors:i,warnings:t}}exports.parseSemaphorIsoTimeWindowBoundary=$;exports.validateSemaphorAnalyticsIntent=F;exports.validateSemaphorAnalyticsRecoveryPlan=qe;exports.validateSemaphorDashboardIntent=Le;exports.validateSemaphorDerivedFieldDefinition=Y;exports.validateSemaphorOperationIntent=K;exports.validateSemaphorResultCalculation=je;