react-semaphor 0.1.487 → 0.1.489

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +1 -1
  3. package/dist/brand-studio/index.cjs +1 -1
  4. package/dist/brand-studio/index.js +3 -3
  5. package/dist/briefings/index.cjs +1 -1
  6. package/dist/briefings/index.js +3 -3
  7. package/dist/chunks/{calculated-field-identity-CQb7MOl2.js → calculated-field-identity-CSabKrXt.js} +2 -2
  8. package/dist/chunks/{calculated-field-identity-Dwl8yGej.cjs → calculated-field-identity-D4VOHjBJ.cjs} +1 -1
  9. package/dist/chunks/{constants-DCOEfAqV.cjs → constants-BMfm1XgO.cjs} +1 -1
  10. package/dist/chunks/{constants-CHyHJrbM.js → constants-D47EhfJR.js} +3 -3
  11. package/dist/chunks/{dashboard-briefing-launcher-CEFTQ1Bo.js → dashboard-briefing-launcher-BkYSN0Em.js} +1177 -1161
  12. package/dist/chunks/dashboard-briefing-launcher-TwquBRrW.cjs +21 -0
  13. package/dist/chunks/{dashboard-controls-B8sB1B3b.js → dashboard-controls-AmaFS8Kl.js} +10 -10
  14. package/dist/chunks/{dashboard-controls-DJrGf3ZB.cjs → dashboard-controls-Mj_mqC8u.cjs} +1 -1
  15. package/dist/chunks/{dashboard-json-B4KiEU0Q.js → dashboard-json-CdVpJZPY.js} +6 -6
  16. package/dist/chunks/{dashboard-json-BlcAA_hB.cjs → dashboard-json-X6uhUYk3.cjs} +1 -1
  17. package/dist/chunks/{edit-dashboard-visual-CoWjnH66.js → edit-dashboard-visual-DOBFMhus.js} +1967 -1969
  18. package/dist/chunks/{edit-dashboard-visual-Dy3g1mEH.cjs → edit-dashboard-visual-ehgeS2ss.cjs} +10 -10
  19. package/dist/chunks/{editor-action-buttons-CMlgLbyo.js → editor-action-buttons-BeiN-K5d.js} +5 -5
  20. package/dist/chunks/{editor-action-buttons-CCm0eEz_.cjs → editor-action-buttons-CRrxjkAi.cjs} +1 -1
  21. package/dist/chunks/{field-aggregations-4O27uCsl.js → field-aggregations-J7de9KZm.js} +2 -2
  22. package/dist/chunks/{field-aggregations-D9ZfvxOG.cjs → field-aggregations-hx8odlTh.cjs} +1 -1
  23. package/dist/chunks/{index-BJwEDK3K.cjs → index-9g7-nCDB.cjs} +230 -229
  24. package/dist/chunks/{index-DOBJv70o.js → index-BDtC8et3.js} +5 -5
  25. package/dist/chunks/{index-DmwnCmOH.js → index-CnZ0x05b.js} +25070 -25029
  26. package/dist/chunks/{index-BhsHg66K.cjs → index-Df4YBtX5.cjs} +1 -1
  27. package/dist/chunks/{matrix-card-CoQiV9pN.js → matrix-card-5R39CCdj.js} +1 -1
  28. package/dist/chunks/{matrix-card-JYMYSX0x.cjs → matrix-card-DzkJRoM4.cjs} +1 -1
  29. package/dist/chunks/{matrix-control-sources-C5yR-8Os.cjs → matrix-control-sources-BWbqiGmN.cjs} +1 -1
  30. package/dist/chunks/{matrix-control-sources-CVKluUf_.js → matrix-control-sources-DxjWV8ry.js} +4 -4
  31. package/dist/chunks/{matrix-formatter-C3cZwlyH.cjs → matrix-formatter-3QR1mqhn.cjs} +1 -1
  32. package/dist/chunks/{matrix-formatter-PvfZAZMO.js → matrix-formatter-youWVghC.js} +2 -2
  33. package/dist/chunks/matrix-operation-contract-BiUMcd6G.cjs +1 -0
  34. package/dist/chunks/{matrix-operation-contract-DITvltmL.js → matrix-operation-contract-D5I-t3i7.js} +2 -0
  35. package/dist/chunks/{pivot-header-presentation-BNk7eOw5.js → pivot-header-presentation-BslEo_4O.js} +2 -2
  36. package/dist/chunks/{pivot-header-presentation-D07xrP9g.cjs → pivot-header-presentation-Dcd4IBM5.cjs} +1 -1
  37. package/dist/chunks/{pivot-result-lifecycle-CmTnVy3z.js → pivot-result-lifecycle-BCoOFUiU.js} +1 -1
  38. package/dist/chunks/{pivot-result-lifecycle-lfXjvoZD.cjs → pivot-result-lifecycle-H_pntnd9.cjs} +1 -1
  39. package/dist/chunks/{report-preferences-dialog-BxS10Skt.cjs → report-preferences-dialog-BkhwOcF7.cjs} +1 -1
  40. package/dist/chunks/{report-preferences-dialog-CK7Yst5x.js → report-preferences-dialog-CcyeSXxN.js} +4 -4
  41. package/dist/chunks/{semantic-format-BOzelQDB.cjs → semantic-format-CMPIcb8l.cjs} +1 -1
  42. package/dist/chunks/{semantic-format-C_bee0be.js → semantic-format-UvUAyZS-.js} +1 -1
  43. package/dist/chunks/{switch-BiQDKn8o.js → switch-BPhOmWZm.js} +6 -6
  44. package/dist/chunks/{switch-DAO_vHPc.cjs → switch-BabZv_0t.cjs} +1 -1
  45. package/dist/chunks/{update-policy-C291nphu.cjs → update-policy-BP_2uCgs.cjs} +1 -1
  46. package/dist/chunks/{update-policy-kjd-Z5jD.js → update-policy-D3I1J2kl.js} +1 -1
  47. package/dist/dashboard/index.cjs +1 -1
  48. package/dist/dashboard/index.js +1 -1
  49. package/dist/dashboard-authoring/index.cjs +1 -1
  50. package/dist/dashboard-authoring/index.js +7 -7
  51. package/dist/data-app-builder/index.cjs +1 -1
  52. package/dist/data-app-builder/index.js +2 -2
  53. package/dist/data-app-codegen/index.cjs +1 -1
  54. package/dist/data-app-codegen/index.js +2 -2
  55. package/dist/data-app-codegen-node/index.cjs +1 -1
  56. package/dist/data-app-codegen-node/index.js +3 -3
  57. package/dist/data-app-sdk/index.cjs +1 -1
  58. package/dist/data-app-sdk/index.js +2 -2
  59. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  60. package/dist/data-app-sdk-adapters/index.js +1 -1
  61. package/dist/data-app-sdk-validation/index.cjs +1 -1
  62. package/dist/data-app-sdk-validation/index.js +2 -2
  63. package/dist/format-utils/index.cjs +1 -1
  64. package/dist/format-utils/index.js +8 -8
  65. package/dist/index.cjs +1 -1
  66. package/dist/index.js +11 -11
  67. package/dist/style.css +1 -1
  68. package/dist/surfboard/index.cjs +1 -1
  69. package/dist/surfboard/index.js +2 -2
  70. package/dist/types/analytics-protocol.d.ts +60 -0
  71. package/dist/types/dashboard-assistant.d.ts +10 -0
  72. package/dist/types/data-app-sdk-validation.d.ts +10 -0
  73. package/dist/types/data-app-sdk.d.ts +36 -0
  74. package/dist/types/main.d.ts +45 -6
  75. package/package.json +1 -1
  76. package/dist/chunks/dashboard-briefing-launcher-DuUM-xZw.cjs +0 -26
  77. package/dist/chunks/matrix-operation-contract-CCfuWtro.cjs +0 -1
@@ -1,3 +1,3 @@
1
- "use strict";const V=require("./matrix-operation-contract-CCfuWtro.cjs"),S=require("../data-app-sdk-adapters/index.cjs");require("./validators-4dRtYUI1.cjs");const re=V.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION,k=V.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION,G="semaphor-generated-data-app-contract/v1",M="semaphor-generated-data-app-contract-manifest/v1";function q(e){return E(e)?[...V.validateSemaphorDataAppCodegenSummary(e).issues,...ae(e)]:["Plan artifact must be a Semaphor codegenSummary object."]}function ne(e){const t=q(e);if(t.length>0)throw new Error(`Invalid Semaphor codegenSummary:
1
+ "use strict";const V=require("./matrix-operation-contract-BiUMcd6G.cjs"),S=require("../data-app-sdk-adapters/index.cjs");require("./validators-4dRtYUI1.cjs");const re=V.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION,k=V.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION,G="semaphor-generated-data-app-contract/v1",M="semaphor-generated-data-app-contract-manifest/v1";function q(e){return E(e)?[...V.validateSemaphorDataAppCodegenSummary(e).issues,...ae(e)]:["Plan artifact must be a Semaphor codegenSummary object."]}function ne(e){const t=q(e);if(t.length>0)throw new Error(`Invalid Semaphor codegenSummary:
2
2
  - ${t.join(`
3
3
  - `)}`)}function ae(e){var r;const t=E(e);if(!t)return[];const n=[];return((r=E(t.validation))==null?void 0:r.status)==="blocked"&&n.push("validation.status blocked cannot be generated. Resolve blocked semantic model gaps and replan before generating contract files."),Array.isArray(t.unsupportedInsights)&&t.unsupportedInsights.forEach((i,o)=>{var a;((a=E(i))==null?void 0:a.reason)==="missing_relationship"&&n.push(`unsupportedInsights.${o}.reason missing_relationship blocks contract generation. Call semaphor_propose_semantic_model_change, apply an approved semantic model patch, and replan before generating contract files.`)}),Array.isArray(t.views)&&t.views.forEach((i,o)=>{var s;const a=E((s=E(i))==null?void 0:s.computation);(a==null?void 0:a.kind)==="unsupported"&&a.reason==="missing_relationship"&&n.push(`views.${o}.computation.reason missing_relationship blocks contract generation. Call semaphor_propose_semantic_model_change, apply an approved semantic model patch, and replan before generating contract files.`)}),n}function E(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}const J=["sources.ts","fields.ts","inputs.ts","queries.ts","bindings.ts","accessors.ts","metadata.ts","index.ts"],ie=["USAGE.md"],Y=[...J,...ie,"contract.manifest.json"];async function se({manifest:e,generatedFiles:t}){const n=[],r=y(e);if(!r)return{issues:[{message:"Generated contract manifest must be an object.",repairHint:"Regenerate the generated contract instead of hand-editing the manifest."}]};r.schemaVersion!==M&&n.push({path:"schemaVersion",message:`schemaVersion must be ${M}. Regenerate the contract with semaphor_create_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_create_data_app_contract."}),r.generatedContractSchemaVersion!==G&&n.push({path:"generatedContractSchemaVersion",message:`generatedContractSchemaVersion must be ${G}. Regenerate the contract with semaphor_generate_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_generate_data_app_contract."});const i=y(r.generator);A(i==null?void 0:i.name)||n.push({path:"generator.name",message:"generator.name is required.",repairHint:"Regenerate the generated contract so manifest generator metadata is written deterministically."}),A(i==null?void 0:i.version)||n.push({path:"generator.version",message:"generator.version is required.",repairHint:"Regenerate the generated contract so manifest generator metadata is written deterministically."});for(const a of q(r.codegenSummary))n.push({path:`codegenSummary.${a}`,message:`codegenSummary.${a}`,repairHint:"Regenerate the generated contract from a valid Data App codegenSummary."});if(r.codegenSummaryValidatorVersion!==k&&n.push({path:"codegenSummaryValidatorVersion",message:`codegenSummaryValidatorVersion must be ${k}. Regenerate the contract with semaphor_generate_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_generate_data_app_contract."}),typeof r.codegenSummaryHash!="string")n.push({path:"codegenSummaryHash",message:"codegenSummaryHash is required.",repairHint:"Regenerate the generated contract so manifest hashes are written deterministically."});else if(y(r.codegenSummary)){const a=await fe(r.codegenSummary);r.codegenSummaryHash!==a&&n.push({path:"codegenSummaryHash",message:"codegenSummaryHash does not match codegenSummary. Regenerate the contract instead of editing the manifest.",repairHint:"Regenerate the generated contract instead of editing the manifest."})}n.push(...de(r.codegenSummary));const o=t?oe(t):[];if(n.push(...o),t&&o.length===0&&n.push(...ce(t)),typeof r.generatedContentHash!="string")n.push({path:"generatedContentHash",message:"generatedContentHash is required.",repairHint:"Regenerate the generated contract so manifest hashes are written deterministically."});else if(t&&o.length===0){const a=await ue(t);r.generatedContentHash!==a&&n.push({path:"generatedContentHash",message:"generatedContentHash does not match generated TypeScript files. Regenerate the contract instead of hand-editing generated files.",repairHint:"Regenerate the contract instead of hand-editing generated files."})}return{issues:n}}function oe(e){var r;const t=[],n=new Set(Y);for(const i of Object.keys(e)){if(i.includes("/")||i.includes("\\")){const o=((r=i.split("/").pop())==null?void 0:r.split("\\").pop())||i;t.push({path:`generatedFiles.${i}`,message:`generatedFiles keys must be generated filenames such as "${o}", not path-qualified keys such as "${i}".`,repairHint:'Pass generatedFiles keyed by filename, for example "queries.ts", not "src/semaphor/generated/queries.ts".'});continue}n.has(i)||t.push({path:`generatedFiles.${i}`,message:`generatedFiles contains unknown generated contract file "${i}".`,repairHint:"Pass only the generated files returned by semaphor_generate_data_app_contract, keyed by filename."})}return t}function ce(e){const t=e["USAGE.md"];return typeof t!="string"?[{path:"generatedFiles.USAGE.md",message:"generatedFiles.USAGE.md is required.",repairHint:"Regenerate the generated contract so the generated usage guide is written."}]:["queries","queryOptionsForView","rowsForView","metricValuesForView","kpiPropsForView","roleValuesForView","appInputSpecs","inputOptionQueries"].filter(r=>!t.includes(`\`${r}\``)).map(r=>({path:"generatedFiles.USAGE.md",message:`generatedFiles.USAGE.md must document ${r}.`,repairHint:"Regenerate the generated contract so the usage guide matches generated exports."}))}function de(e){const t=y(e);if(!t)return[];const n=[],r=new Set(F(t.inputs).map(o=>{var a;return(a=y(o))==null?void 0:a.id}).filter(A)),i=new Set(F(t.views).map(o=>{var a;return(a=y(o))==null?void 0:a.id}).filter(A));return F(t.filterContracts).forEach((o,a)=>{const s=y(o),c=s==null?void 0:s.inputId;(!A(c)||!r.has(c))&&n.push({path:`codegenSummary.filterContracts.${a}.inputId`,message:`codegenSummary.filterContracts.${a}.inputId must reference a generated input.`,repairHint:"Regenerate the generated contract from a valid planner output."}),Array.isArray(s==null?void 0:s.bindings)&&s.bindings.forEach((u,f)=>{const p=y(u),m=p==null?void 0:p.viewId;(!A(m)||!i.has(m))&&n.push({path:`codegenSummary.filterContracts.${a}.bindings.${f}.viewId`,message:`codegenSummary.filterContracts.${a}.bindings.${f}.viewId must reference a generated view.`,repairHint:"Regenerate the generated contract from a valid planner output."});const h=y(p==null?void 0:p.fieldRef);A(h==null?void 0:h.name)||n.push({path:`codegenSummary.filterContracts.${a}.bindings.${f}.fieldRef`,message:`codegenSummary.filterContracts.${a}.bindings.${f}.fieldRef is required.`,repairHint:"Regenerate the generated contract from a valid planner output."})})}),n}async function ue(e){const t=Object.keys(e).filter(r=>r.endsWith(".ts")).sort();let n="";for(const r of t)n+=`${r}\0${e[r]}\0`;return`sha256:${await W(n)}`}async function fe(e){return`sha256:${await W(x(e))}`}function x(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>x(r)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().filter(r=>t[r]!==void 0).map(r=>`${JSON.stringify(r)}:${x(t[r])}`).join(",")}}`}async function W(e){var r;if(!((r=globalThis.crypto)!=null&&r.subtle))throw new Error("SHA-256 digest support is required for generated contract validation.");const t=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function F(e){return Array.isArray(e)?e:[]}function A(e){return typeof e=="string"&&e.length>0}function pe(e){const t=d(e),n=N(t),r=[],i=[];return I(t==null?void 0:t.views).filter(o=>{var s;const a=d((s=d(o))==null?void 0:s.sdkSpec);return!!(a!=null&&a.builder&&(a!=null&&a.spec))}).forEach((o,a)=>{var u;const s=String(((u=d(o))==null?void 0:u.id)||`view_${a}`),c=Q(o,n);if(c){r.push({viewId:s,...c});return}i.push({viewId:s,path:`views.${s}.sdkSpec`,message:`Generated view execution validation could not build intent for "${s}".`})}),{requests:r,issues:i}}function Q(e,t){const n=d(e),r=d(n==null?void 0:n.sdkSpec),i=d(r==null?void 0:r.spec);if(!n||!(r!=null&&r.builder)||!i)return null;const o=me(t)?t:N(d(t)),a=be(r.builder),s=d(w(i,o))||{},c=ye({view:n,builder:a,rawSpec:i,spec:{...s,id:n.id,label:Ne(n,i)},context:o});try{if(a==="analysis"){const u=c;return{intent:S.toSemaphorAnalysisIntent(u),resultShape:"analysis",analysisOptions:S.toSemaphorAnalysisQueryOptions(u)}}if(a==="metric")return{intent:S.toSemaphorMetricIntent(c),resultShape:"metric"};if(a==="records")return{intent:S.toSemaphorRecordsIntent(c),resultShape:"records"};if(a==="matrix")return{intent:S.toSemaphorMatrixIntent(c),matrixWindowRequest:V.matrixWindowRequestSchema.parse(c.matrixWindowRequest),resultShape:"matrix"};if(a==="sql")return{intent:S.toSemaphorSqlIntent(c),resultShape:"sql"}}catch{return null}return null}function ge({input:e,filterContract:t,codegenSummary:n}){const r=d(e),i=d(t),o=d(r==null?void 0:r.optionQuery)||d(i==null?void 0:i.optionQuery);if(!r||!o)return null;const a=N(d(n)),s=d(o.spec),c=he(o,s,a),u=o.valueFieldRef||o.valueField||(s==null?void 0:s.valueField),f=o.labelFieldRef||o.labelField||(s==null?void 0:s.labelField);if(!c||!u||!f)return null;const m={...d(w(s||{},a))||{},id:o.id||(s==null?void 0:s.id)||`${r.id}-options`,inputId:r.id,source:c,valueField:u,labelField:f,population:o.population||(s==null?void 0:s.population),dependencies:o.dependencies||(s==null?void 0:s.dependencies),limit:o.limit||(s==null?void 0:s.limit)||100};try{return S.toSemaphorInputOptionsIntent(w(m,a))}catch{return null}}function le({input:e,filterContract:t,binding:n,option:r,codegenSummary:i}){const o=N(d(i)),a=d(e),s=d(t),c=d(n),u=w((c==null?void 0:c.fieldRef)||(s==null?void 0:s.fieldRef)||(a==null?void 0:a.fieldRef),o),f=String((s==null?void 0:s.operator)||(a==null?void 0:a.operator)||"in"),p=Fe(c);return{inputId:String((s==null?void 0:s.inputId)||(a==null?void 0:a.id)||""),kind:"filter",operator:f,value:He(f,r.value),isActive:!0,...u?{field:u}:{},...p?{relationshipHint:p}:{}}}function N(e){return{sourcesByKey:new Map(I(e==null?void 0:e.sources).map(d).filter(Me).filter(t=>typeof t.sourceKey=="string").map(t=>[String(t.sourceKey),Z(t)]))}}function me(e){var t;return e instanceof Object&&((t=d(e))==null?void 0:t.sourcesByKey)instanceof Map}function he(e,t,n){if(typeof e.sourceKey=="string")return n.sourcesByKey.get(e.sourceKey)||{sourceKey:e.sourceKey};if(e.source)return e.source;if(t!=null&&t.source)return t.source;if(typeof(t==null?void 0:t.sourceKey)=="string")return n.sourcesByKey.get(t.sourceKey)||{sourceKey:t.sourceKey}}function ye({view:e,builder:t,rawSpec:n,spec:r,context:i}){var s;if(t!=="records"&&t!=="sql")return r;const o=d((s=d(e.visualSpec))==null?void 0:s.tableBehavior);if(!o)return r;const a={...r};if(Oe(o)==="server"&&(a.pagination={page:1,pageSize:Se({tableBehavior:o,spec:r})}),t==="records"&&Ve(o)==="server"){const c=Ae({view:e,rawSpec:n,tableBehavior:o,context:i});c&&(a.orderBy=c)}return a}function Se({tableBehavior:e,spec:t}){const n=d(e.pagination),r=d(t.pagination);return H(n==null?void 0:n.pageSize)||H(r==null?void 0:r.pageSize)||H(t.limit)||100}function Ae({view:e,rawSpec:t,tableBehavior:n,context:r}){const i=d(n.sorting),o=g(i==null?void 0:i.defaultField);if(!o)return;const s=_e({view:e,rawSpec:t,context:r}).filter(c=>we(c.lookup).includes(o));if(s.length===1)return{field:s[0].field,direction:(i==null?void 0:i.defaultDirection)==="desc"?"desc":"asc"}}function _e({view:e,rawSpec:t,context:n}){var i;const r=[];for(const o of I(t.fields))$(r,o,n);$(r,t.dateField,n),$(r,(i=d(t.orderBy))==null?void 0:i.field,n);for(const o of I(e.fields))$(r,o,n);return Te(r,o=>Ee(o.lookup))}function $(e,t,n){const r=d(t);if(typeof(r==null?void 0:r.name)!="string"||r.name.length===0)return;const i=d(w(r,n))||r;e.push({lookup:r,field:i})}function we(e){return ke([g(e.name),X(e),Ie(e)])}function Ee(e){return[X(e),g(e.name),g(e.role),g(e.aggregate)].join("|")}function X(e){return[g(e.sourceKey)||Re(e.source),g(e.name),g(e.aggregate)].filter(Boolean).join(":")}function Re(e){const t=d(e);if(!t)return"";if(typeof t.kind=="string"&&typeof t.domainId=="string"){if(typeof t.datasetId=="string")return`${t.kind}:${t.domainId}:datasetId:${t.datasetId}`;if(typeof t.datasetName=="string")return`${t.kind}:${t.domainId}:datasetName:${t.datasetName}`}return JSON.stringify(t)}function Ie(e){return Ge([ve(e),g(e.aggregate).toLowerCase(),g(e.label)||g(e.name)].filter(Boolean))}function ve(e){return typeof e.sourceKey=="string"?Ce(e.sourceKey):$e(e.source)}function $e(e){const t=d(e);return t?g(t.datasetName)||g(t.datasetId)||g(t.name)||g(t.kind):""}function Ce(e){const t=String(e).split(":");return t[t.length-1]||String(e)}function Oe(e){var t;return g((t=d(e.pagination))==null?void 0:t.mode)}function Ve(e){var t;return g((t=d(e.sorting))==null?void 0:t.mode)}function w(e,t){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>w(i,t));const n=e;if(typeof n.sourceKey=="string"&&typeof n.kind=="string"&&(typeof n.datasetName=="string"||typeof n.datasetId=="string"))return Z(n);const r={};for(const[i,o]of Object.entries(n))i!=="sourceKey"&&(r[i]=w(o,t));if(typeof n.sourceKey=="string"){const i=t.sourcesByKey.get(n.sourceKey);i&&!r.source&&(r.source=i)}return r}function Z(e){const{sourceKey:t,...n}=e;return n}function Ne(e,t){const n=d(e.visualSpec);return(n==null?void 0:n.title)||e.title||t.label}function be(e){const t=String(e||"").replace(/^semaphor\./,"");return["metric","records","analysis","matrix","sql"].includes(t)?t:""}function Fe(e){if(e!=null&&e.relationshipHint)return e.relationshipHint;const t=I(e==null?void 0:e.relationshipsUsed).map(n=>{var r;return(r=d(n))==null?void 0:r.id}).filter(n=>typeof n=="string"&&n.length>0);return t.length>0?{relationshipIds:t}:void 0}function He(e,t){return e==="in"||e==="not_in"?[t]:e==="between"?Array.isArray(t)?t:[t,t]:t}function H(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function g(e){return typeof e=="string"?e:""}function Te(e,t){const n=new Set,r=[];for(const i of e){const o=t(i);!o||n.has(o)||(n.add(o),r.push(i))}return r}function ke(e){return Array.from(new Set(e.filter(Boolean)))}function Ge(e){return(Array.isArray(e)?e.join(" "):e).replace(/[^a-zA-Z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,r)=>{const i=n.toLowerCase();return r===0?i:i.charAt(0).toUpperCase()+i.slice(1)}).join("")}function d(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function I(e){return Array.isArray(e)?e:[]}function Me(e){return e!==void 0}const xe=new Set(["diagnostic_fix","fix_diagnostics","fix_inspector_warnings","fix_runtime_warnings","fix_warnings"]),De=new Set(["add","edit","mixed","remove"]),j=new Set(["fields","metricBindingKeys","sdkSpec"]);function qe({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:r,constraints:i,preferences:o}){const a=l(r),s=typeof(a==null?void 0:a.kind)=="string"?a.kind.trim():"";return De.has(s)?{ok:!1,policy:{kind:s,mode:"invalid_operation_kind",reason:"Retired Data App operation aliases are not accepted. Use the hard-migrated analytics/layout/style operationIntent kinds."},violations:[{path:"operationIntent.kind",reason:"Use analytics_add, analytics_edit, analytics_remove, input_add, input_edit, layout_only, style_only, runtime_debug, semantic_model_repair, save_or_publish, or greenfield_create."}]}:B(o)?{ok:!1,policy:{kind:s,mode:"invalid_update_constraints",reason:"Metric aggregate override updates must use operationIntent.measureAggregateOverrides so deterministic update policy can guard the targeted edit."},violations:[{path:"preferences.measureAggregateOverrides",reason:"preferences is retired. Move measureAggregateOverrides to operationIntent.measureAggregateOverrides for update calls."}]}:B(i)?{ok:!1,policy:{kind:s,mode:"invalid_update_constraints",reason:"Metric aggregate override updates must use operationIntent.measureAggregateOverrides so deterministic update policy can guard the targeted edit."},violations:[{path:"constraints.measureAggregateOverrides",reason:"Move measureAggregateOverrides to operationIntent.measureAggregateOverrides for update calls."}]}:xe.has(s)?U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:a,mode:"diagnostic_warning_fix",allowedViewChangeReasons:j,label:"Diagnostic warning fixes",reason:"Diagnostic warning fixes are preserve-by-default and may not add/remove views, inputs, or filter contracts."}):s==="analytics_edit"&&Array.isArray(a==null?void 0:a.measureAggregateOverrides)&&a.measureAggregateOverrides.length>0?U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:a,mode:"metric_aggregate_override_edit",allowedViewChangeReasons:j,label:"Metric aggregate override edits",reason:"Metric aggregate override edits are preserve-by-default and may only adjust fields/sdkSpec on targeted views."}):{ok:!0,policy:{kind:s,mode:"general_iterative_update",reason:"General generated-contract edits are allowed to change the requested contract shape. Review the migration report for expected UI work."},violations:[]}}function B(e){var t;return Array.isArray((t=l(e))==null?void 0:t.measureAggregateOverrides)}function U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:r,mode:i,allowedViewChangeReasons:o,label:a,reason:s}){const c=[],u=je(r==null?void 0:r.targetViewIds),f=l(n)||{};u.size===0&&c.push({path:"operationIntent.targetViewIds",reason:`${a} must declare targetViewIds so the update cannot broaden to unrelated views.`}),T({bucket:l(f.views),label:"views",operationLabel:a,violations:c}),T({bucket:l(f.inputs),label:"inputs",operationLabel:a,violations:c}),L({bucket:l(f.inputs),label:"inputs",operationLabel:a,violations:c}),T({bucket:l(f.filterContracts),label:"filterContracts",operationLabel:a,violations:c}),L({bucket:l(f.filterContracts),label:"filterContracts",operationLabel:a,violations:c});for(const m of ee(l(f.views))){u.size>0&&!u.has(_(m.id))&&c.push({path:`views.${_(m.id)||"<unknown>"}`,reason:`${a} may only change explicitly targeted views.`});const h=Array.isArray(m.reasons)?m.reasons.filter(R=>typeof R!="string"||!o.has(R)):[];h.length>0&&c.push({path:`views.${_(m.id)||"<unknown>"}`,reason:`${a} may only adjust fields/sdkSpec/metricBindingKeys; changed ${h.join(", ")}.`})}const p=Ke({beforeSummary:e,afterSummary:t,targetViewIds:u,label:a});return p&&c.push(p),{ok:c.length===0,policy:{kind:_(r==null?void 0:r.kind)||"diagnostic_fix",mode:i,allowedViewChangeReasons:Array.from(o).sort(),targetViewIds:Array.from(u).sort(),reason:s},violations:c}}function Ke({beforeSummary:e,afterSummary:t,targetViewIds:n,label:r}){const i=l(e),o=l(t);if(!i||!o)return{path:"codegenSummary",reason:`${r} require before/after codegen summaries for full-scope verification.`};const a=P(i),s=P(o),c=z(i.views),u=z(o.views),f=Array.isArray(a.views)?a.views:[];a.views=f;for(const p of n){const m=c.get(p),h=u.get(p);if(!m||!h)continue;const R=f.find(te=>{var K;return((K=l(te))==null?void 0:K.id)===p}),v=l(h);if(!R||!v)continue;const b=R;b.fields=C(v.fields),b.metricBindingKeys=C(v.metricBindingKeys),b.sdkSpec=C(v.sdkSpec)}return O(a)===O(s)?null:{path:"codegenSummary",reason:`${r} may only change fields/sdkSpec/metricBindingKeys on targetViewIds; another generated contract section changed.`}}function P(e){const t=C(e);for(const n of["implementationChecklist","assumptions","nextStep","nextRequiredTool","validation"])delete t[n];return Ue(t.unsupportedInsights)&&delete t.unsupportedInsights,t}function T({bucket:e,label:t,operationLabel:n,violations:r}){for(const i of D(e==null?void 0:e.added))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not add ${t}.`});for(const i of D(e==null?void 0:e.removed))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not remove ${t}.`})}function L({bucket:e,label:t,operationLabel:n,violations:r}){for(const i of ee(e))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not change ${t}.`})}function ee(e){return D(e==null?void 0:e.changed)}function D(e){return Array.isArray(e)?e.map(l).filter(Be):[]}function je(e){return Array.isArray(e)?new Set(e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim())):new Set}function z(e){var n;const t=new Map;for(const r of Array.isArray(e)?e:[]){const i=(n=l(r))==null?void 0:n.id;typeof i=="string"&&i.trim()&&t.set(i,r)}return t}function C(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function O(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>O(n)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${O(t[n])}`).join(",")}}`}function l(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Be(e){return e!==void 0}function Ue(e){return Array.isArray(e)&&e.length===0}function _(e){return typeof e=="string"?e:""}exports.CODEGEN_SUMMARY_SCHEMA_VERSION=re;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=k;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=M;exports.GENERATED_CONTRACT_SCHEMA_VERSION=G;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=J;exports.REQUIRED_GENERATED_CONTRACT_FILES=Y;exports.assertValidCodegenSummary=ne;exports.buildSemaphorGeneratedActiveInput=le;exports.buildSemaphorGeneratedInputOptionIntent=ge;exports.buildSemaphorGeneratedViewExecutionRequest=Q;exports.buildSemaphorGeneratedViewExecutionRequests=pe;exports.evaluateSemaphorDataAppContractUpdatePolicy=qe;exports.validateCodegenSummary=q;exports.validateSemaphorGeneratedContract=se;
@@ -1,4 +1,4 @@
1
- import { S as Q, a as X, v as Z, u as ee } from "./matrix-operation-contract-DITvltmL.js";
1
+ import { S as Q, a as X, v as Z, u as ee } from "./matrix-operation-contract-D5I-t3i7.js";
2
2
  import { toSemaphorInputOptionsIntent as te, toSemaphorAnalysisQueryOptions as re, toSemaphorAnalysisIntent as ne, toSemaphorMetricIntent as ae, toSemaphorRecordsIntent as se, toSemaphorMatrixIntent as ie, toSemaphorSqlIntent as oe } from "../data-app-sdk-adapters/index.js";
3
3
  import "./validators-BpJDwDnG.js";
4
4
  const Ye = Q, x = X, G = "semaphor-generated-data-app-contract/v1", T = "semaphor-generated-data-app-contract-manifest/v1";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../chunks/index-BJwEDK3K.cjs"),e=require("../chunks/common-types-nBuCd3u2.cjs");exports.Dashboard=o.Dashboard;exports.CONTROL_CARD_DEFAULT_VALUE=e.CONTROL_CARD_DEFAULT_VALUE;exports.EMPTY_SELECTION=e.EMPTY_SELECTION;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../chunks/index-9g7-nCDB.cjs"),e=require("../chunks/common-types-nBuCd3u2.cjs");exports.Dashboard=o.Dashboard;exports.CONTROL_CARD_DEFAULT_VALUE=e.CONTROL_CARD_DEFAULT_VALUE;exports.EMPTY_SELECTION=e.EMPTY_SELECTION;
@@ -1,4 +1,4 @@
1
- import { D as o } from "../chunks/index-DmwnCmOH.js";
1
+ import { D as o } from "../chunks/index-CnZ0x05b.js";
2
2
  import { C as s, E as C } from "../chunks/common-types-C6cAQgyh.js";
3
3
  export {
4
4
  s as CONTROL_CARD_DEFAULT_VALUE,
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../chunks/matrix-control-sources-C5yR-8Os.cjs"),I=require("../chunks/field-aggregations-D9ZfvxOG.cjs"),v=require("../chunks/validators-4dRtYUI1.cjs");require("../chunks/matrix-operation-contract-CCfuWtro.cjs");const m=require("../chunks/calculated-field-identity-Dwl8yGej.cjs"),Fe=require("../chunks/operators-DrTQsJXv.cjs"),Q=require("../chunks/canonical-result-keys-Cb96edol.cjs"),E=require("../chunks/matrix-definition-Z80mIEfu.cjs"),Y=require("../chunks/matrix-card-JYMYSX0x.cjs");function y(e){return e&&typeof e=="object"?e:null}function O(e){return typeof e=="string"?e:null}function ce(e){var t,r,a;return!!(e&&typeof e=="object")&&(((t=y(e))==null?void 0:t.kind)==="semantic"||((r=y(e))==null?void 0:r.kind)==="physical"||((a=y(e))==null?void 0:a.kind)==="sql")}function N(e){return ce(e)?e.kind==="semantic"?!!(e.domainId&&e.datasetName):e.kind==="physical"?!!(e.connectionId&&e.tableName):!1:!1}function we(e){return v.semaphorSourceIdentityKey(e)}function J(e,t){return v.semaphorSourcesReferToSameDataset(e,t)}function ue(e,t){return v.preferSemaphorSourceMetadata(e,t)}function L(e){const t=[];for(const r of e){const a=t.findIndex(o=>J(o,r));a===-1?t.push(r):t[a]=ue(t[a],r)}return t}function xe(e){return L(e)[0]}function K(e,t){return e.kind!=="semantic"||e.connectionId||(t==null?void 0:t.kind)!=="semantic"||!v.semaphorSourcesReferToSameDataset(e,t)||!t.connectionId?e:{...e,connectionId:t.connectionId}}function W(e){return N(e)?e:void 0}function de(e,t){if(!(e.kind!=="semantic"||e.connectionId))return t.find(r=>(r==null?void 0:r.kind)==="semantic"&&v.semaphorSourcesReferToSameDataset(e,r)&&!!r.connectionId)}function T(e,t){const r=W(e==null?void 0:e.source);return r?K(r,t):void 0}function fe({explicitSource:e,field:t,defaultSource:r,fallbackSources:a}){const o=[r,...a||[]],i=W(e),n=i?K(i,de(i,o)):void 0;if(n)return n;if(e!==void 0)return;const d=T(t,r),s=d?K(d,de(d,o)):void 0;if(s)return s;if((t==null?void 0:t.source)===void 0)return W(r)}function Ne(e,t){if(!(e!=null&&e.name)||!(t!=null&&t.name)||e.name!==t.name)return!1;const r=T(e),a=T(t);return!r||!a?!0:J(r,a)}function w(e){var t;return O((t=y(e))==null?void 0:t.kind)}function pe(e){var t,r;return w(e)!=="semantic"?null:((r=O((t=y(e))==null?void 0:t.domainId))==null?void 0:r.trim())||null}function Ee(e){var t;return w(e)!=="semantic"?null:O((t=y(e))==null?void 0:t.datasetName)}function ke(e){var t;return w(e)!=="semantic"?null:O((t=y(e))==null?void 0:t.datasetId)}function Me(e){var t;return w(e)!=="physical"?null:O((t=y(e))==null?void 0:t.connectionId)}function Le(e){var t;return w(e)!=="physical"?null:O((t=y(e))==null?void 0:t.tableName)}function Be(e){var t;return w(e)!=="physical"?"":O((t=y(e))==null?void 0:t.databaseName)||""}function Pe(e){var t;return w(e)!=="physical"?"":O((t=y(e))==null?void 0:t.schemaName)||""}function he(e){if(e.analyticsIntent&&typeof e.analyticsIntent=="object"&&"source"in e.analyticsIntent)return e.analyticsIntent.source}function me({datasets:e,requireAtLeastOne:t}){if(t&&e.length<1)return{ok:!1,issue:"invalid_dataset_count"};if(e.length<=1)return{ok:!0};const r=e.map(pe),a=new Set(r.filter(Boolean));return r.some(o=>!o)||a.size!==1?{ok:!1,issue:"invalid_multi_dataset_scope"}:{ok:!0}}function q(e,t){if(!t)return!1;if(t.kind==="semantic"){const r=ke(e);return pe(e)===t.domainId?r&&t.datasetId?r===t.datasetId:Ee(e)===t.datasetName:!1}return t.kind==="physical"?Me(e)===t.connectionId&&Le(e)===t.tableName&&Be(e)===(t.databaseName||"")&&Pe(e)===(t.schemaName||""):!1}function Ve(e,t){return e.find(r=>q(r,t))}function h(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function V(e){const t=new Set;for(const r of e){if(t.has(r))return r;t.add(r)}return null}function ge({card:e,datasets:t,errors:r}){if(e.type==="text")return;const a=he(e);if(!a){if(t.length<=1)return;r.push(h("missing_card_analytics_source","Multi-dataset dashboard cards must include analytics intent with a source so the materializer can choose the correct dataset.",e.id));return}t.some(o=>q(o,a))||r.push(h("invalid_card_analytics_source","Dashboard cards with an explicit analytics source must use one of the selected datasets.",e.id))}function $(e){return e.map(t=>t==null?void 0:t.source).filter(t=>!!t)}function H(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function le(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function $e(e){var r,a;if(!e)return[];const t=[e.source];return e.kind==="metric"?t.push(...$([...H(e.measures),e.primaryMeasure,e.dateField,...H(e.dimensions),...le(e.filters).map(o=>o.field)])):e.kind==="records"?t.push(...$([...H(e.fields),e.dateField,(r=e.orderBy)==null?void 0:r.field,...le(e.filters).map(o=>o.field)])):e.kind==="inputOptions"?(((a=e.population)==null?void 0:a.kind)==="related_population"&&t.push(e.population.baseSource),t.push(...$([e.labelField,e.valueField,e.searchField,...e.disambiguationFields||[]]))):e.kind==="sql"&&t.push(...$(e.fields||[])),t}function Ie({card:e,datasets:t,errors:r}){if(e.type!=="text"){for(const a of $e(e.analyticsIntent))if(a&&!t.some(o=>q(o,a))){r.push(h("invalid_card_query_source","Dashboard card query field references must use one of the selected datasets.",e.id));return}}}function be({card:e,errors:t}){if(e.type==="text"||!e.analyticsIntent)return;const r=v.validateSemaphorAnalyticsIntent(e.analyticsIntent);if(!r.ok)for(const a of r.errors)t.push(h(a.code,a.path?`${a.path}: ${a.message}`:a.message,e.id))}function _e({datasets:e,errors:t,requireAtLeastOne:r}){const a=me({datasets:e,requireAtLeastOne:r});if(!a.ok){if(a.issue==="invalid_dataset_count"){t.push(h("invalid_dataset_count","Dashboard authoring requires at least one selected dataset."));return}t.push(h("invalid_multi_dataset_scope","Multi-dataset dashboard authoring is limited to semantic datasets from one domain."))}}function Ce({input:e,errors:t}){var r;(r=e.filter.sql)!=null&&r.trim()&&t.push(h("generated_filter_sql_out_of_scope",`Generated dashboard filter "${e.label}" must use grounded filter configuration; custom SQL is outside the dashboard-authoring contract.`))}function De(e){var p,_;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[h("invalid_plan","Dashboard plan must be a structured object.")],warnings:[]};const r=e,a=[...r.warnings||[]];r.version!==1&&t.push(h("invalid_version","Dashboard plan version must be 1.")),(p=r.title)!=null&&p.trim()||t.push(h("missing_title","Dashboard plan needs a title."));const o=Array.isArray(r.datasets)?r.datasets:[],i=Array.isArray(r.sheets)?r.sheets:[];_e({datasets:o,errors:t,requireAtLeastOne:!0}),i.length!==1&&t.push(h("invalid_sheet_count","MVP dashboard authoring creates exactly one dashboard sheet."));const n=i[0];n&&n.kind!=="dashboard"&&t.push(h("invalid_sheet_kind",'Generated sheet must use kind "dashboard".'));const d=(n==null?void 0:n.cards)||[];d.length>u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS&&t.push(h("too_many_cards",`Generated dashboards can contain at most ${u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS} cards.`));const s=V(d.map(c=>c.id));s&&t.push(h("duplicate_card_id",`Duplicate generated card id: ${s}.`));const f=V(d.map(c=>c.frameId));f&&t.push(h("duplicate_frame_id",`Duplicate generated frame id: ${f}.`));for(const c of d)(_=c.title)!=null&&_.trim()||t.push(h("missing_card_title","Card title is required.",c.id)),c.type==="custom"&&t.push(h("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",c.id)),c.type!=="text"&&!c.analyticsIntent&&a.push(h("missing_analytics_intent","Non-text card has no analytics intent and may be skipped by the app layer.",c.id)),ge({card:c,datasets:o,errors:t}),be({card:c,errors:t}),Ie({card:c,datasets:o,errors:t});const g=Array.isArray(r.filterInputs)?r.filterInputs:[],D=g.map(c=>c.id),A=V(D);A&&t.push(h("duplicate_input_id",`Duplicate dashboard input id: ${A}.`));const R=g.map(c=>c.variableName).filter(Boolean)||[],S=V(R);S&&t.push(h("duplicate_input_variable",`Duplicate dashboard input variable name: ${S}.`));for(const c of g)Ce({input:c,errors:t});const l=Array.isArray(r.calculatedFields)?r.calculatedFields:[];for(const c of l)c.scope==="domain"&&c.reuseOnly!==!0&&t.push(h("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${c.name}" is outside MVP.`));return{ok:t.length===0,errors:t,warnings:a}}function Se(e){var n;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[h("invalid_change_plan","Dashboard change plan must be a structured object.")],warnings:[]};const r=e,a=[...r.warnings||[]];r.version!==1&&t.push(h("invalid_version","Dashboard change plan version must be 1.")),(n=r.dashboardId)!=null&&n.trim()||t.push(h("missing_dashboard_id","Dashboard change plan needs a dashboard id."));const o=Array.isArray(r.datasets)?r.datasets:[],i=Array.isArray(r.operations)?r.operations:[];_e({datasets:o,errors:t,requireAtLeastOne:!1});for(const d of i){if(d.kind==="unsupported"){a.push(h("unsupported_operation",d.reason||d.requestedAction));continue}d.kind==="addCard"&&d.card.type==="custom"&&t.push(h("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",d.card.id)),d.kind==="addCard"&&(ge({card:d.card,datasets:o,errors:t}),be({card:d.card,errors:t}),Ie({card:d.card,datasets:o,errors:t})),d.kind==="addFilterInput"&&Ce({input:d.input,errors:t}),d.kind==="addCalculatedField"&&d.field.scope==="domain"&&d.field.reuseOnly!==!0&&t.push(h("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${d.field.name}" is outside MVP.`))}return{ok:t.length===0,errors:t,warnings:a}}const qe={lg:48,md:36,sm:24,xs:12,xxs:6};function Ge(e,t){let r=0,a=0,o=0;return e.map(i=>{const n=Math.min(i.w,t);r>0&&r+n>t&&(r=0,a+=o,o=0);const d={i:i.frameId,x:r,y:a,w:n,h:i.h,minW:Math.min(i.minW,t),minH:i.minH,static:!1};return r+=n,o=Math.max(o,i.h),d})}function ze(e){const t=[...e].sort((s,f)=>s.priority-f.priority),r=t.filter(s=>s.role==="kpi"),a=t.filter(s=>s.role==="chart"),o=t.filter(s=>s.role==="table"),i=t.filter(s=>s.role==="text"),n=i.slice(0,1),d=i.slice(n.length);return{kpis:r,introText:n,charts:a,tables:o,supportingText:d}}function He(e,t,r){return t==="xxs"||t==="xs"?r:t==="sm"?Math.min(12,r):t==="md"?e<=1||e===2?18:12:e<=1||e===2?24:e===3?16:12}function Ue(e,t,r,a){return r==="xxs"||r==="xs"||r==="sm"||r==="md"||t===1||t%2===1&&e===0?a:a/2}function je(e){const{item:t,band:r,index:a,bandCount:o,breakpoint:i,columns:n}=e;return r==="kpi"?{...t,band:r,w:He(o,i,n),h:15,minW:Math.min(6,n),minH:12}:r==="table"?{...t,band:r,w:n,h:i==="xxs"||i==="xs"?34:38,minW:Math.min(12,n),minH:18}:r==="introText"?{...t,band:r,w:n,h:i==="xxs"||i==="xs"?12:10,minW:Math.min(12,n),minH:8}:r==="supportingText"?{...t,band:r,w:i==="lg"?n/2:n,h:i==="xxs"||i==="xs"?12:10,minW:Math.min(12,n),minH:8}:{...t,band:r,w:Ue(a,o,i,n),h:i==="xxs"||i==="xs"?28:30,minW:Math.min(12,n),minH:16}}function k(e,t,r,a){return e.map((o,i)=>je({item:o,band:t,index:i,bandCount:e.length,breakpoint:r,columns:a}))}function G(e){const t=ze(e);return Object.fromEntries(u.DASHBOARD_AUTHORING_BREAKPOINTS.map(r=>{const a=qe[r],o=[...k(t.introText,"introText",r,a),...k(t.kpis,"kpi",r,a),...k(t.charts,"chart",r,a),...k(t.tables,"table",r,a),...k(t.supportingText,"supportingText",r,a)];return[r,Ge(o,a)]}))}function Ke(e){const t=v.normalizeAnalyticsCatalogDataType(e);return t==="datetime"?"date":t==="unknown"?"string":t}function We(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Xe(e){return We(e)&&typeof e.filterId=="string"&&typeof e.operation=="string"&&Array.isArray(e.values)}function Qe(e){return e.filter(t=>typeof t=="string"||typeof t=="number")}function Ye(e){return e.filter(t=>t instanceof Date||typeof t=="string")}function Z(e,t){if(t===void 0)return;const r=Ke(e.dataType),a=e.operation||"in";if(Xe(t))return m.materializeFilterValueNativeDataType({definition:e,sourceValue:t,value:{...t,filterId:e.id,name:t.name||e.column,valueType:r,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}});if(a==="is null"||a==="is not null")return m.materializeFilterValueNativeDataType({definition:e,value:{filterId:e.id,name:e.column,operation:a,valueType:r,values:[],dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}});const o=Array.isArray(t)?t:[t],i=r==="date"?Ye(o):Qe(o);if(i.length!==0&&!((a==="between"||a==="not between")&&i.length<2))return m.materializeFilterValueNativeDataType({definition:e,value:{filterId:e.id,name:e.column,operation:a,valueType:r,values:i,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}})}function ye(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function Je(e,t,r){const a=(t||[]).filter(o=>o.scope==="card"&&o.targetCardId===r).map(o=>o.field).filter(Boolean);return a.length===0?e:{...e,calculatedFields:[...e.calculatedFields||[],...a]}}function X(e,t){return Array.from(new Set((e||[]).map(r=>t.get(r)).filter(r=>!!r)))}function Ze(e,t){if((e==null?void 0:e.kind)!=="cards")return e;const r=X(e.cardIds,t);return r.length>0?{...e,cardIds:r}:null}function et(e,t){return!e.applyToCardIds&&!e.excludeCardIds?e:{...e,...e.applyToCardIds?{applyToCardIds:X(e.applyToCardIds,t)}:{},...e.excludeCardIds?{excludeCardIds:X(e.excludeCardIds,t)}:{}}}function tt(e,t){const r={},a=[];return{inputs:(e.filterInputs||[]).flatMap((i,n)=>{const d=Ze(i.scope,t);if(d===null)return a.push(ye("filter_input_scope_empty",`Filter input "${i.label}" was skipped because all scoped cards were skipped during query validation.`)),[];const s=Z(i.filter,i.defaultValue);return s&&(r.shared??(r.shared={}),r.shared[i.id]={status:"set",value:{kind:"filter",filterValue:s}}),[{id:i.id,kind:"filter",label:i.label,variableName:i.variableName,scope:d||{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:{placement:"toolbar",order:n},exports:["label","value","start","end","range"],filter:et(i.filter,t)}]}),warnings:a,defaultInputValues:r.shared&&Object.keys(r.shared).length>0?r:void 0}}function rt(e){var R,S;const t=De(e.plan);if(!t.ok)throw new Error(t.errors.map(l=>l.message).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../chunks/matrix-control-sources-BWbqiGmN.cjs"),I=require("../chunks/field-aggregations-hx8odlTh.cjs"),v=require("../chunks/validators-4dRtYUI1.cjs");require("../chunks/matrix-operation-contract-BiUMcd6G.cjs");const m=require("../chunks/calculated-field-identity-D4VOHjBJ.cjs"),Fe=require("../chunks/operators-DrTQsJXv.cjs"),Q=require("../chunks/canonical-result-keys-Cb96edol.cjs"),E=require("../chunks/matrix-definition-Z80mIEfu.cjs"),Y=require("../chunks/matrix-card-DzkJRoM4.cjs");function y(e){return e&&typeof e=="object"?e:null}function O(e){return typeof e=="string"?e:null}function ce(e){var t,r,a;return!!(e&&typeof e=="object")&&(((t=y(e))==null?void 0:t.kind)==="semantic"||((r=y(e))==null?void 0:r.kind)==="physical"||((a=y(e))==null?void 0:a.kind)==="sql")}function N(e){return ce(e)?e.kind==="semantic"?!!(e.domainId&&e.datasetName):e.kind==="physical"?!!(e.connectionId&&e.tableName):!1:!1}function we(e){return v.semaphorSourceIdentityKey(e)}function J(e,t){return v.semaphorSourcesReferToSameDataset(e,t)}function ue(e,t){return v.preferSemaphorSourceMetadata(e,t)}function L(e){const t=[];for(const r of e){const a=t.findIndex(o=>J(o,r));a===-1?t.push(r):t[a]=ue(t[a],r)}return t}function xe(e){return L(e)[0]}function K(e,t){return e.kind!=="semantic"||e.connectionId||(t==null?void 0:t.kind)!=="semantic"||!v.semaphorSourcesReferToSameDataset(e,t)||!t.connectionId?e:{...e,connectionId:t.connectionId}}function W(e){return N(e)?e:void 0}function de(e,t){if(!(e.kind!=="semantic"||e.connectionId))return t.find(r=>(r==null?void 0:r.kind)==="semantic"&&v.semaphorSourcesReferToSameDataset(e,r)&&!!r.connectionId)}function T(e,t){const r=W(e==null?void 0:e.source);return r?K(r,t):void 0}function fe({explicitSource:e,field:t,defaultSource:r,fallbackSources:a}){const o=[r,...a||[]],i=W(e),n=i?K(i,de(i,o)):void 0;if(n)return n;if(e!==void 0)return;const d=T(t,r),s=d?K(d,de(d,o)):void 0;if(s)return s;if((t==null?void 0:t.source)===void 0)return W(r)}function Ne(e,t){if(!(e!=null&&e.name)||!(t!=null&&t.name)||e.name!==t.name)return!1;const r=T(e),a=T(t);return!r||!a?!0:J(r,a)}function w(e){var t;return O((t=y(e))==null?void 0:t.kind)}function pe(e){var t,r;return w(e)!=="semantic"?null:((r=O((t=y(e))==null?void 0:t.domainId))==null?void 0:r.trim())||null}function Ee(e){var t;return w(e)!=="semantic"?null:O((t=y(e))==null?void 0:t.datasetName)}function ke(e){var t;return w(e)!=="semantic"?null:O((t=y(e))==null?void 0:t.datasetId)}function Me(e){var t;return w(e)!=="physical"?null:O((t=y(e))==null?void 0:t.connectionId)}function Le(e){var t;return w(e)!=="physical"?null:O((t=y(e))==null?void 0:t.tableName)}function Be(e){var t;return w(e)!=="physical"?"":O((t=y(e))==null?void 0:t.databaseName)||""}function Pe(e){var t;return w(e)!=="physical"?"":O((t=y(e))==null?void 0:t.schemaName)||""}function he(e){if(e.analyticsIntent&&typeof e.analyticsIntent=="object"&&"source"in e.analyticsIntent)return e.analyticsIntent.source}function me({datasets:e,requireAtLeastOne:t}){if(t&&e.length<1)return{ok:!1,issue:"invalid_dataset_count"};if(e.length<=1)return{ok:!0};const r=e.map(pe),a=new Set(r.filter(Boolean));return r.some(o=>!o)||a.size!==1?{ok:!1,issue:"invalid_multi_dataset_scope"}:{ok:!0}}function q(e,t){if(!t)return!1;if(t.kind==="semantic"){const r=ke(e);return pe(e)===t.domainId?r&&t.datasetId?r===t.datasetId:Ee(e)===t.datasetName:!1}return t.kind==="physical"?Me(e)===t.connectionId&&Le(e)===t.tableName&&Be(e)===(t.databaseName||"")&&Pe(e)===(t.schemaName||""):!1}function Ve(e,t){return e.find(r=>q(r,t))}function h(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function V(e){const t=new Set;for(const r of e){if(t.has(r))return r;t.add(r)}return null}function ge({card:e,datasets:t,errors:r}){if(e.type==="text")return;const a=he(e);if(!a){if(t.length<=1)return;r.push(h("missing_card_analytics_source","Multi-dataset dashboard cards must include analytics intent with a source so the materializer can choose the correct dataset.",e.id));return}t.some(o=>q(o,a))||r.push(h("invalid_card_analytics_source","Dashboard cards with an explicit analytics source must use one of the selected datasets.",e.id))}function $(e){return e.map(t=>t==null?void 0:t.source).filter(t=>!!t)}function H(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function le(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function $e(e){var r,a;if(!e)return[];const t=[e.source];return e.kind==="metric"?t.push(...$([...H(e.measures),e.primaryMeasure,e.dateField,...H(e.dimensions),...le(e.filters).map(o=>o.field)])):e.kind==="records"?t.push(...$([...H(e.fields),e.dateField,(r=e.orderBy)==null?void 0:r.field,...le(e.filters).map(o=>o.field)])):e.kind==="inputOptions"?(((a=e.population)==null?void 0:a.kind)==="related_population"&&t.push(e.population.baseSource),t.push(...$([e.labelField,e.valueField,e.searchField,...e.disambiguationFields||[]]))):e.kind==="sql"&&t.push(...$(e.fields||[])),t}function Ie({card:e,datasets:t,errors:r}){if(e.type!=="text"){for(const a of $e(e.analyticsIntent))if(a&&!t.some(o=>q(o,a))){r.push(h("invalid_card_query_source","Dashboard card query field references must use one of the selected datasets.",e.id));return}}}function be({card:e,errors:t}){if(e.type==="text"||!e.analyticsIntent)return;const r=v.validateSemaphorAnalyticsIntent(e.analyticsIntent);if(!r.ok)for(const a of r.errors)t.push(h(a.code,a.path?`${a.path}: ${a.message}`:a.message,e.id))}function _e({datasets:e,errors:t,requireAtLeastOne:r}){const a=me({datasets:e,requireAtLeastOne:r});if(!a.ok){if(a.issue==="invalid_dataset_count"){t.push(h("invalid_dataset_count","Dashboard authoring requires at least one selected dataset."));return}t.push(h("invalid_multi_dataset_scope","Multi-dataset dashboard authoring is limited to semantic datasets from one domain."))}}function Ce({input:e,errors:t}){var r;(r=e.filter.sql)!=null&&r.trim()&&t.push(h("generated_filter_sql_out_of_scope",`Generated dashboard filter "${e.label}" must use grounded filter configuration; custom SQL is outside the dashboard-authoring contract.`))}function De(e){var p,_;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[h("invalid_plan","Dashboard plan must be a structured object.")],warnings:[]};const r=e,a=[...r.warnings||[]];r.version!==1&&t.push(h("invalid_version","Dashboard plan version must be 1.")),(p=r.title)!=null&&p.trim()||t.push(h("missing_title","Dashboard plan needs a title."));const o=Array.isArray(r.datasets)?r.datasets:[],i=Array.isArray(r.sheets)?r.sheets:[];_e({datasets:o,errors:t,requireAtLeastOne:!0}),i.length!==1&&t.push(h("invalid_sheet_count","MVP dashboard authoring creates exactly one dashboard sheet."));const n=i[0];n&&n.kind!=="dashboard"&&t.push(h("invalid_sheet_kind",'Generated sheet must use kind "dashboard".'));const d=(n==null?void 0:n.cards)||[];d.length>u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS&&t.push(h("too_many_cards",`Generated dashboards can contain at most ${u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS} cards.`));const s=V(d.map(c=>c.id));s&&t.push(h("duplicate_card_id",`Duplicate generated card id: ${s}.`));const f=V(d.map(c=>c.frameId));f&&t.push(h("duplicate_frame_id",`Duplicate generated frame id: ${f}.`));for(const c of d)(_=c.title)!=null&&_.trim()||t.push(h("missing_card_title","Card title is required.",c.id)),c.type==="custom"&&t.push(h("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",c.id)),c.type!=="text"&&!c.analyticsIntent&&a.push(h("missing_analytics_intent","Non-text card has no analytics intent and may be skipped by the app layer.",c.id)),ge({card:c,datasets:o,errors:t}),be({card:c,errors:t}),Ie({card:c,datasets:o,errors:t});const g=Array.isArray(r.filterInputs)?r.filterInputs:[],D=g.map(c=>c.id),A=V(D);A&&t.push(h("duplicate_input_id",`Duplicate dashboard input id: ${A}.`));const R=g.map(c=>c.variableName).filter(Boolean)||[],S=V(R);S&&t.push(h("duplicate_input_variable",`Duplicate dashboard input variable name: ${S}.`));for(const c of g)Ce({input:c,errors:t});const l=Array.isArray(r.calculatedFields)?r.calculatedFields:[];for(const c of l)c.scope==="domain"&&c.reuseOnly!==!0&&t.push(h("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${c.name}" is outside MVP.`));return{ok:t.length===0,errors:t,warnings:a}}function Se(e){var n;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[h("invalid_change_plan","Dashboard change plan must be a structured object.")],warnings:[]};const r=e,a=[...r.warnings||[]];r.version!==1&&t.push(h("invalid_version","Dashboard change plan version must be 1.")),(n=r.dashboardId)!=null&&n.trim()||t.push(h("missing_dashboard_id","Dashboard change plan needs a dashboard id."));const o=Array.isArray(r.datasets)?r.datasets:[],i=Array.isArray(r.operations)?r.operations:[];_e({datasets:o,errors:t,requireAtLeastOne:!1});for(const d of i){if(d.kind==="unsupported"){a.push(h("unsupported_operation",d.reason||d.requestedAction));continue}d.kind==="addCard"&&d.card.type==="custom"&&t.push(h("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",d.card.id)),d.kind==="addCard"&&(ge({card:d.card,datasets:o,errors:t}),be({card:d.card,errors:t}),Ie({card:d.card,datasets:o,errors:t})),d.kind==="addFilterInput"&&Ce({input:d.input,errors:t}),d.kind==="addCalculatedField"&&d.field.scope==="domain"&&d.field.reuseOnly!==!0&&t.push(h("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${d.field.name}" is outside MVP.`))}return{ok:t.length===0,errors:t,warnings:a}}const qe={lg:48,md:36,sm:24,xs:12,xxs:6};function Ge(e,t){let r=0,a=0,o=0;return e.map(i=>{const n=Math.min(i.w,t);r>0&&r+n>t&&(r=0,a+=o,o=0);const d={i:i.frameId,x:r,y:a,w:n,h:i.h,minW:Math.min(i.minW,t),minH:i.minH,static:!1};return r+=n,o=Math.max(o,i.h),d})}function ze(e){const t=[...e].sort((s,f)=>s.priority-f.priority),r=t.filter(s=>s.role==="kpi"),a=t.filter(s=>s.role==="chart"),o=t.filter(s=>s.role==="table"),i=t.filter(s=>s.role==="text"),n=i.slice(0,1),d=i.slice(n.length);return{kpis:r,introText:n,charts:a,tables:o,supportingText:d}}function He(e,t,r){return t==="xxs"||t==="xs"?r:t==="sm"?Math.min(12,r):t==="md"?e<=1||e===2?18:12:e<=1||e===2?24:e===3?16:12}function Ue(e,t,r,a){return r==="xxs"||r==="xs"||r==="sm"||r==="md"||t===1||t%2===1&&e===0?a:a/2}function je(e){const{item:t,band:r,index:a,bandCount:o,breakpoint:i,columns:n}=e;return r==="kpi"?{...t,band:r,w:He(o,i,n),h:15,minW:Math.min(6,n),minH:12}:r==="table"?{...t,band:r,w:n,h:i==="xxs"||i==="xs"?34:38,minW:Math.min(12,n),minH:18}:r==="introText"?{...t,band:r,w:n,h:i==="xxs"||i==="xs"?12:10,minW:Math.min(12,n),minH:8}:r==="supportingText"?{...t,band:r,w:i==="lg"?n/2:n,h:i==="xxs"||i==="xs"?12:10,minW:Math.min(12,n),minH:8}:{...t,band:r,w:Ue(a,o,i,n),h:i==="xxs"||i==="xs"?28:30,minW:Math.min(12,n),minH:16}}function k(e,t,r,a){return e.map((o,i)=>je({item:o,band:t,index:i,bandCount:e.length,breakpoint:r,columns:a}))}function G(e){const t=ze(e);return Object.fromEntries(u.DASHBOARD_AUTHORING_BREAKPOINTS.map(r=>{const a=qe[r],o=[...k(t.introText,"introText",r,a),...k(t.kpis,"kpi",r,a),...k(t.charts,"chart",r,a),...k(t.tables,"table",r,a),...k(t.supportingText,"supportingText",r,a)];return[r,Ge(o,a)]}))}function Ke(e){const t=v.normalizeAnalyticsCatalogDataType(e);return t==="datetime"?"date":t==="unknown"?"string":t}function We(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Xe(e){return We(e)&&typeof e.filterId=="string"&&typeof e.operation=="string"&&Array.isArray(e.values)}function Qe(e){return e.filter(t=>typeof t=="string"||typeof t=="number")}function Ye(e){return e.filter(t=>t instanceof Date||typeof t=="string")}function Z(e,t){if(t===void 0)return;const r=Ke(e.dataType),a=e.operation||"in";if(Xe(t))return m.materializeFilterValueNativeDataType({definition:e,sourceValue:t,value:{...t,filterId:e.id,name:t.name||e.column,valueType:r,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}});if(a==="is null"||a==="is not null")return m.materializeFilterValueNativeDataType({definition:e,value:{filterId:e.id,name:e.column,operation:a,valueType:r,values:[],dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}});const o=Array.isArray(t)?t:[t],i=r==="date"?Ye(o):Qe(o);if(i.length!==0&&!((a==="between"||a==="not between")&&i.length<2))return m.materializeFilterValueNativeDataType({definition:e,value:{filterId:e.id,name:e.column,operation:a,valueType:r,values:i,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}})}function ye(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function Je(e,t,r){const a=(t||[]).filter(o=>o.scope==="card"&&o.targetCardId===r).map(o=>o.field).filter(Boolean);return a.length===0?e:{...e,calculatedFields:[...e.calculatedFields||[],...a]}}function X(e,t){return Array.from(new Set((e||[]).map(r=>t.get(r)).filter(r=>!!r)))}function Ze(e,t){if((e==null?void 0:e.kind)!=="cards")return e;const r=X(e.cardIds,t);return r.length>0?{...e,cardIds:r}:null}function et(e,t){return!e.applyToCardIds&&!e.excludeCardIds?e:{...e,...e.applyToCardIds?{applyToCardIds:X(e.applyToCardIds,t)}:{},...e.excludeCardIds?{excludeCardIds:X(e.excludeCardIds,t)}:{}}}function tt(e,t){const r={},a=[];return{inputs:(e.filterInputs||[]).flatMap((i,n)=>{const d=Ze(i.scope,t);if(d===null)return a.push(ye("filter_input_scope_empty",`Filter input "${i.label}" was skipped because all scoped cards were skipped during query validation.`)),[];const s=Z(i.filter,i.defaultValue);return s&&(r.shared??(r.shared={}),r.shared[i.id]={status:"set",value:{kind:"filter",filterValue:s}}),[{id:i.id,kind:"filter",label:i.label,variableName:i.variableName,scope:d||{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:{placement:"toolbar",order:n},exports:["label","value","start","end","range"],filter:et(i.filter,t)}]}),warnings:a,defaultInputValues:r.shared&&Object.keys(r.shared).length>0?r:void 0}}function rt(e){var R,S;const t=De(e.plan);if(!t.ok)throw new Error(t.errors.map(l=>l.message).join(`
2
2
  `)||"Dashboard plan is invalid.");const r=e.plan.sheets[0],a=[...t.warnings],o=[],i=new Map(e.cardArtifacts.map(l=>[l.planCardId,l])),n=new Map(e.cardArtifacts.map(l=>[l.planCardId,l.card.id])),d=[];for(const l of r.cards){const p=i.get(l.id);if(!p){const c=ye("missing_card_artifact",`Card "${l.title}" was skipped because no generated artifact was supplied.`,l.id);o.push(c);continue}a.push(...p.warnings||[]);const _=Je(p.card,e.plan.calculatedFields,l.id);d.push({id:l.frameId,cards:[_],activeCardId:_.id})}if(d.length===0)throw new Error("Dashboard plan did not produce any persistable cards.");const{inputs:s,defaultInputValues:f,warnings:g}=tt(e.plan,n);a.push(...g);const D=G(r.cards.filter(l=>d.some(p=>p.id===l.frameId)).map(l=>({frameId:l.frameId,priority:l.priority,role:l.role})));return{dashboard:{id:e.dashboardId,title:e.plan.title,description:e.plan.description||"",sheets:[{id:r.id,kind:"dashboard",title:r.title,description:r.description,frames:d,layouts:D,calculatedFields:(R=e.plan.calculatedFields)==null?void 0:R.filter(l=>l.scope==="sheet"&&l.field).map(l=>l.field)}],calculatedFields:(S=e.plan.calculatedFields)==null?void 0:S.filter(l=>l.scope==="dashboard"&&l.field).map(l=>l.field),inputs:s,...f?{defaultInputValues:f}:{}},warnings:a,skippedOperations:o}}function x(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function at(e){return JSON.parse(JSON.stringify(e))}function nt(e){var t;return(t=e.sheets)==null?void 0:t.find(r=>(r.kind||"dashboard")==="dashboard")}function U(e,t){var r;for(const a of e.sheets||[])for(const o of a.frames||[]){const i=(r=o.cards)==null?void 0:r.find(n=>n.id===t);if(i)return{sheet:a,frame:o,card:i}}return null}function Ae(e){var r,a;const t=(a=(r=e.cards)==null?void 0:r[0])==null?void 0:a.type;return t==="kpi"?"kpi":t==="table"||t==="detailTable"||t==="pivotTable"?"table":t==="text"?"text":"chart"}function it(e){var t;return new Map((((t=e.layouts)==null?void 0:t.lg)||[]).map((r,a)=>[r.i,a]))}function Re(e,t=new Map){const r=it(e),a=Math.max(r.size,t.size),o=(e.frames||[]).map((i,n)=>({frameId:i.id,role:Ae(i),priority:t.get(i.id)??r.get(i.id)??a+n}));e.layouts=G(o)}function ot(e){return Object.values(e.layouts||{}).some(t=>t.length>0)}function st(e,t){if(!ot(e)){Re(e);return}const r=G([{frameId:t.id,role:Ae(t),priority:0}]);e.layouts??(e.layouts={});for(const[a,o]of Object.entries(r)){const i=e.layouts[a]||[];if(i.some(s=>s.i===t.id))continue;const n=o[0];if(!n)continue;const d=i.reduce((s,f)=>Math.max(s,f.y+f.h),0);e.layouts[a]=[...i,{...n,y:d}]}}function dt(e,t){var a;const r=Z(t.filter,t.defaultValue);r&&(e.defaultInputValues??(e.defaultInputValues={}),(a=e.defaultInputValues).shared??(a.shared={}),e.defaultInputValues.shared[t.id]={status:"set",value:{kind:"filter",filterValue:r}})}function lt(e){var d;const t=Se(e.changePlan);if(!t.ok)throw new Error(t.errors.map(s=>s.message).join(`
3
3
  `)||"Dashboard change plan is invalid.");const r=at(e.dashboard),a=[...t.warnings],o=[],i=new Map(e.cardArtifacts.map(s=>[s.planCardId,s])),n=nt(r);if(!n)throw new Error("Dashboard has no editable dashboard sheet.");n.frames??(n.frames=[]);for(const s of e.changePlan.operations)switch(s.kind){case"addCard":{if((n.frames||[]).reduce((A,R)=>{var S;return A+(((S=R.cards)==null?void 0:S.length)||0)},0)>=u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS){o.push(x("generated_card_limit_reached",`AI refinement is capped at ${u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS} cards.`,s.card.id));break}const g=i.get(s.card.id);if(!g){o.push(x("missing_card_artifact",`Card "${s.card.title}" was skipped because no generated artifact was supplied.`,s.card.id));break}const D={id:s.card.frameId,cards:[g.card],activeCardId:g.card.id};n.frames.push(D),st(n,D);break}case"addFilterInput":{r.inputs??(r.inputs=[]);const f={id:s.input.id,kind:"filter",label:s.input.label,variableName:s.input.variableName,scope:s.input.scope||{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:{placement:"toolbar",order:r.inputs.length},exports:["label","value","start","end","range"],filter:s.input.filter};r.inputs.push(f),dt(r,s.input);break}case"addCalculatedField":{if(s.field.scope==="dashboard"&&s.field.field)r.calculatedFields??(r.calculatedFields=[]),r.calculatedFields.push(s.field.field);else if(s.field.scope==="sheet"&&s.field.field)n.calculatedFields??(n.calculatedFields=[]),n.calculatedFields.push(s.field.field);else if(s.field.scope==="card"&&s.field.field){const f=s.field.targetCardId?U(r,s.field.targetCardId):null;f?((d=f.card).calculatedFields??(d.calculatedFields=[]),f.card.calculatedFields.push(s.field.field)):o.push(x("missing_calculated_field_target",`Calculated field "${s.field.name}" needs a valid target card.`))}break}case"renameCard":{const f=U(r,s.cardId);if(!f){o.push(x("card_not_found",`Card "${s.cardId}" could not be renamed because it was not found.`,s.cardId));break}f.card.title=s.title,s.description!==void 0&&(f.card.description=s.description);break}case"reorderCards":{const f=new Map;for(let g=0;g<s.cardIds.length;g+=1){const D=s.cardIds[g],A=U(r,D);A&&f.set(A.frame.id,g)}Re(n,f);break}case"reuseCalculatedField":a.push(x("reused_calculated_field",`Calculated field "${s.fieldId}" is reused by reference.`));break;case"unsupported":o.push(x("unsupported_operation",s.reason||s.requestedAction));break}return{dashboard:r,warnings:a,skippedOperations:o}}function C(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function M(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Te(e,t){if(!t.has(e))return t.add(e),e;let r=2,a=`${e}-${r}`;for(;t.has(a);)r+=1,a=`${e}-${r}`;return t.add(a),a}function B(e){return!!(e&&typeof e=="object")}function ve(e){return Array.isArray(e.inputs)?e.inputs.filter(t=>B(t)&&typeof t.id=="string"):[]}function ee(e){return Array.isArray(e.sections)?e.sections.filter(t=>B(t)):[]}function te(e){return Array.isArray(e.views)?e.views.filter(t=>B(t)):[]}function F(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const a=T(r);a&&t.push(a)}return t}function ct(e){var a,o,i;if(!e)return[];const t=[];if(N(e.source)&&t.push(e.source),e.kind==="metric"){t.push(...F(e.measures));const n=T(e.dateField);n&&t.push(n),t.push(...F(e.dimensions)),t.push(...F((a=e.filters)==null?void 0:a.map(d=>d.field)))}else if(e.kind==="records"){const n=T(e.dateField);n&&t.push(n),t.push(...F(e.fields)),t.push(...F((o=e.filters)==null?void 0:o.map(d=>d.field)))}else e.kind==="inputOptions"?(((i=e.population)==null?void 0:i.kind)==="related_population"&&N(e.population.baseSource)&&t.push(e.population.baseSource),t.push(...F([e.labelField,e.valueField,e.searchField,...e.disambiguationFields||[]].filter(n=>!!n)))):e.kind==="sql"&&t.push(...F(e.fields));const r="inputs"in e&&Array.isArray(e.inputs)?e.inputs:[];for(const n of r){const d=T(n.field);d&&t.push(d)}return t}function ut(e){const t=[];for(const r of ve(e)){const a=T(r.field);a&&t.push(a)}for(const r of ee(e))for(const a of te(r))t.push(...ct(a.analytics));return t}function ft(e){var r;const t=[];for(const a of ee(e))for(const o of te(a))N((r=o.analytics)==null?void 0:r.source)&&t.push(o.analytics.source);return t}function pt(e,t){const r=L(e).filter(N);if(r.length===0)return t.push(C("missing_materializable_dataset","No semantic or physical source could be converted into the current dashboard authoring dataset reference.")),[];const a=r.every(i=>i.kind==="semantic"),o=Array.from(new Set(r.filter(i=>i.kind==="semantic").map(i=>i.domainId)));return r.length>1&&(!a||o.length!==1)?(t.push(C("multiple_datasets_out_of_scope","The dashboard authoring compiler supports multiple datasets only within one semantic domain; using the first source and deferring the rest.")),[r[0]]):r}function ht(e,t){const r=ee(e),a=ve(e),o=L(ut(e)),i=L(ft(e));return{sections:r,inputs:a,sources:o,primarySources:i,defaultSource:i.length===1?i[0]:void 0,datasets:pt(o,t)}}function mt(e){return e&&v.validateSemaphorAnalyticsIntent(e).ok?e:void 0}function gt(e){var t;switch((t=e.presentation)==null?void 0:t.kind){case"kpi":return"kpi";case"lineChart":return"line";case"barChart":return"bar";case"areaChart":return"area";case"table":return"table";case"text":return"text";default:return null}}function It(e){var t,r,a;return((t=e.presentation)==null?void 0:t.kind)==="kpi"?"kpi":((r=e.presentation)==null?void 0:r.kind)==="table"?"table":((a=e.presentation)==null?void 0:a.kind)==="text"?"text":"chart"}function bt(e){const t=Fe.normalizeSemaphorInputOperator(e);switch(t){case"not_in":return"not in";case"not_between":return"not between";case"contains":return"like";case"not_contains":return"not like";default:return t||"in"}}function _t(e){return B(e.field)?e.field.dataType==="datetime"?"date":e.field.dataType||"string":"string"}function Ct(e){if(!(!e||e.kind!=="physical"))return[e.databaseName,e.schemaName,e.tableName].filter(Boolean).join(".")}function Dt(e,t,r,a,o,i){if(e.kind!=="filter")return i.push(C("control_inputs_deferred",`Control input "${e.label}" is represented in the protocol but not yet materialized by the dashboard authoring adapter.`)),null;if(!B(e.field)||typeof e.field.name!="string")return i.push(C("filter_requires_field",`Filter "${e.label||e.id}" needs a field before the dashboard compiler can materialize it.`)),null;const n=fe({explicitSource:void 0,field:e.field,defaultSource:t,fallbackSources:r}),d=(n==null?void 0:n.kind)==="semantic"||(n==null?void 0:n.kind)==="physical"?n.connectionId:void 0;if(!d)return i.push(C("filter_requires_connection_id",`Filter "${e.label}" needs a source connectionId before the dashboard compiler can materialize it.`)),null;const g={id:`filter-${Te(M(e.id,e.field.name),o)}`,variableName:e.id,connectionId:d,title:e.label,column:e.field.name,dataType:_t(e),qualifiedTableName:Ct(n),sql:"",operation:bt(e.operator),type:e.multi===!1?"single":"multiple",location:"dashboard",displayMode:"toolbar",fieldMeta:(n==null?void 0:n.kind)==="semantic"?{name:e.field.name,qualifiedFieldName:e.field.name,dataType:e.field.dataType,role:e.field.role==="measure"?"metric":"groupby"}:void 0,semanticContext:(n==null?void 0:n.kind)==="semantic"?{semanticDomainId:n.domainId,connectionId:n.connectionId}:(n==null?void 0:n.kind)==="physical"?{connectionId:n.connectionId,connectionType:n.connectionType,selectedEntities:[{type:"table",connectionId:n.connectionId,connectionType:n.connectionType,dialect:n.dialect,database:n.databaseName,schema:n.schemaName,name:n.tableName}]}:void 0};return{id:e.id,label:e.label,variableName:e.id,scope:a,filter:g,defaultValue:Z(g,e.defaultValue)}}function j(e){const t=[],r=[];for(const a of e.viewIds){const o=e.viewIdToCardId.get(a);o?t.push(o):r.push(a)}return r.length>0&&e.warnings.push(C("input_scope_view_not_found",`Filter "${e.inputLabel}" referenced unknown view ids: ${r.join(", ")}.`)),Array.from(new Set(t))}function St(e){var a,o;if(!e.protocolScope){const i=Array.from(new Set(e.boundCardIds));return i.length>0&&i.length<e.allCardIds.length?{kind:"cards",cardIds:i}:void 0}if(e.protocolScope.level==="dashboard"){if(!((a=e.protocolScope.excludeViewIds)!=null&&a.length))return;const i=new Set(j({inputLabel:e.inputLabel,viewIds:e.protocolScope.excludeViewIds,viewIdToCardId:e.viewIdToCardId,warnings:e.warnings}));return{kind:"cards",cardIds:e.allCardIds.filter(n=>!i.has(n))}}if(e.protocolScope.level==="view"){const i=j({inputLabel:e.inputLabel,viewIds:e.protocolScope.viewIds,viewIdToCardId:e.viewIdToCardId,warnings:e.warnings});return i.length===0?(e.warnings.push(C("input_scope_has_no_materialized_cards",`Filter "${e.inputLabel}" was deferred because its view scope does not match any materialized cards.`)),null):{kind:"cards",cardIds:i}}const t=e.sectionIdToCardIds.get(e.protocolScope.sectionId)||[];if(t.length===0)return e.warnings.push(C("input_scope_section_not_found",`Filter "${e.inputLabel}" was deferred because section "${e.protocolScope.sectionId}" does not match any materialized cards.`)),null;if(!((o=e.protocolScope.excludeViewIds)!=null&&o.length))return{kind:"cards",cardIds:t};const r=new Set(j({inputLabel:e.inputLabel,viewIds:e.protocolScope.excludeViewIds,viewIdToCardId:e.viewIdToCardId,warnings:e.warnings}));return{kind:"cards",cardIds:t.filter(i=>!r.has(i))}}function yt(e){var R,S,l;const t=[],r=v.validateSemaphorDashboardIntent(e);for(const p of r.warnings)t.push(C(p.code,p.message));for(const p of r.errors)t.push(C(p.code,p.message));const a=ht(e,t),o=[],i=new Map,n=new Map,d=new Map,s=new Set,f=new Set;let g=0;for(const[p,_]of a.sections.entries()){const c=typeof _.title=="string"?_.title:`Section ${p+1}`,re=_.id||M(c,`section-${p+1}`);n.set(re,[]);for(const[ae,b]of te(_).entries()){const ne=gt(b),z=M(b.id||`${c}-${b.title||`View ${ae+1}`}`,`card-${p+1}-${ae+1}`);if(!ne){t.push(C("unsupported_presentation",`Dashboard presentation "${((R=b.presentation)==null?void 0:R.kind)||"unknown"}" is not supported by the dashboard authoring adapter.`,`card-${z}`));continue}if(((S=b.analytics)==null?void 0:S.kind)==="sql"){t.push(C("sql_intent_deferred","SQL analytics intent is valid protocol, but the current dashboard authoring adapter only materializes semantic and physical config-card intents.",`card-${z}`));continue}const ie=Te(z,s),P=`card-${ie}`;b.id&&i.set(b.id,P),(l=n.get(re))==null||l.push(P);const Oe=b.analytics&&"inputs"in b.analytics?b.analytics.inputs:void 0;for(const oe of Oe||[]){const se=d.get(oe.inputId)||[];se.push(P),d.set(oe.inputId,se)}o.push({id:P,frameId:`frame-${ie}`,title:b.title,description:b.description,type:ne,role:It(b),priority:g,section:c,analyticsIntent:mt(b.analytics),text:b.text}),g+=1}}const D=a.inputs.map(p=>{const _=St({protocolScope:p.scope,inputLabel:p.label,allCardIds:o.map(c=>c.id),boundCardIds:d.get(p.id)||[],viewIdToCardId:i,sectionIdToCardIds:n,warnings:t});return _===null?null:Dt(p,a.defaultSource,a.sources,_,f,t)}).filter(p=>!!p);return{plan:{version:1,id:`plan-${M(e.title,"dashboard")}`,title:e.title,description:e.description,datasets:a.datasets,sheets:[{id:`sheet-${M(e.title,"dashboard")}`,title:e.title,description:e.description,kind:"dashboard",cards:o}],filterInputs:D.length?D:void 0,warnings:t.length?t:void 0,unresolvedRequests:r.ok?void 0:r.errors.map(p=>p.message)},warnings:t}}exports.CONTROL_BINDING_MAPPING_MISSING_ERROR_CODE=u.CONTROL_BINDING_MAPPING_MISSING_ERROR_CODE;exports.CONTROL_BINDING_TARGET_INVALID_ERROR_CODE=u.CONTROL_BINDING_TARGET_INVALID_ERROR_CODE;exports.CONTROL_BINDING_VALUE_INVALID_ERROR_CODE=u.CONTROL_BINDING_VALUE_INVALID_ERROR_CODE;exports.CONTROL_CONTEXT_UNSUPPORTED_ERROR_CODE=u.CONTROL_CONTEXT_UNSUPPORTED_ERROR_CODE;exports.CONTROL_DEFINITION_DUPLICATE_ERROR_CODE=u.CONTROL_DEFINITION_DUPLICATE_ERROR_CODE;exports.CONTROL_DEFINITION_INVALID_ERROR_CODE=u.CONTROL_DEFINITION_INVALID_ERROR_CODE;exports.CONTROL_PLACEHOLDER_QUOTED_ERROR_CODE=u.CONTROL_PLACEHOLDER_QUOTED_ERROR_CODE;exports.CONTROL_REFERENCE_MISSING_ERROR_CODE=u.CONTROL_REFERENCE_MISSING_ERROR_CODE;exports.CONTROL_VALUE_INVALID_ERROR_CODE=u.CONTROL_VALUE_INVALID_ERROR_CODE;exports.CONTROL_VALUE_MISSING_ERROR_CODE=u.CONTROL_VALUE_MISSING_ERROR_CODE;exports.ControlResolutionError=u.ControlResolutionError;exports.DASHBOARD_AUTHORING_BREAKPOINTS=u.DASHBOARD_AUTHORING_BREAKPOINTS;exports.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS=u.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS;exports.buildControlDefinitionIndex=u.buildControlDefinitionIndex;exports.getColumnCatalogFieldId=u.getColumnCatalogFieldId;exports.matrixCatalogSources=u.matrixCatalogSources;exports.matrixExecutionSources=u.matrixExecutionSources;exports.resolveBindingControlValue=u.resolveBindingControlValue;exports.resolveGroupByFieldTarget=u.resolveGroupByFieldTarget;exports.resolveMatrixControlBindings=u.resolveMatrixControlBindings;exports.resolveMetricFieldTarget=u.resolveMetricFieldTarget;exports.resolveScalarMappedValue=u.resolveScalarMappedValue;exports.validateControlValue=u.validateControlValue;exports.AUTOMATIC_TEMPORAL_BUCKET_FORMAT=I.AUTOMATIC_TEMPORAL_BUCKET_FORMAT;exports.SEMAPHOR_CARTESIAN_CHART_TYPES=I.SEMAPHOR_CARTESIAN_CHART_TYPES;exports.buildDashboardCardSourceIndex=I.buildDashboardCardSourceIndex;exports.dashboardCardFilterSourceInventoryContains=I.dashboardCardFilterSourceInventoryContains;exports.findDashboardCardExecutableSource=I.findDashboardCardExecutableSource;exports.findDashboardCardPinnedCatalogSource=I.findDashboardCardPinnedCatalogSource;exports.findDashboardSqlPinnedCatalogSource=I.findDashboardSqlPinnedCatalogSource;exports.getFieldAggregationOptions=I.getFieldAggregationOptions;exports.getTemporalBucketAuthoringOptions=I.getTemporalBucketAuthoringOptions;exports.getTemporalBucketAuthoringSelection=I.getTemporalBucketAuthoringSelection;exports.isSemaphorCartesianChartType=I.isSemaphorCartesianChartType;exports.previewTemporalBucketAuthoringFormat=I.previewTemporalBucketAuthoringFormat;exports.reconcileTemporalBucketAuthoringFormat=I.reconcileTemporalBucketAuthoringFormat;exports.resolveDashboardEntitySource=I.resolveDashboardEntitySource;exports.resolveTemporalBucketAuthoringFormat=I.resolveTemporalBucketAuthoringFormat;exports.resolveTemporalResultOwner=I.resolveTemporalResultOwner;exports.supportsCanonicalDashboardTemporalResult=I.supportsCanonicalDashboardTemporalResult;exports.transformComparisonDocument=I.transformComparisonDocument;exports.DashboardFilterMappingContractError=m.DashboardFilterMappingContractError;exports.applyCardReferenceRemapping=m.applyCardReferenceRemapping;exports.composeCardReferenceRemapping=m.composeCardReferenceRemapping;exports.createDashboardFilterBindingId=m.createDashboardFilterBindingId;exports.dashboardFilterTargetMatchesLogicalValue=m.dashboardFilterTargetMatchesLogicalValue;exports.dashboardFilterValueTypeForDataType=m.dashboardFilterValueTypeForDataType;exports.getCalculatedFieldNamespace=m.getCalculatedFieldNamespace;exports.getDashboardFilterSubscriptionHint=m.getDashboardFilterSubscriptionHint;exports.getMatrixBindingTargets=m.getMatrixBindingTargets;exports.getStableDomainCalculatedFieldId=m.getStableDomainCalculatedFieldId;exports.hasDashboardFilterSubscription=m.hasDashboardFilterSubscription;exports.isDashboardFilterOperationCompatible=m.isDashboardFilterOperationCompatible;exports.moveMatrixLevel=m.moveMatrixLevel;exports.normalizeDashboardInputs=m.normalizeDashboardInputs;exports.reconcileMatrixSpecStructure=m.reconcileMatrixSpecStructure;exports.requireNormalizedDashboardInputs=m.requireNormalizedDashboardInputs;exports.resolveDashboardFilterAutomaticTarget=m.resolveDashboardFilterAutomaticTarget;exports.resolveDashboardFilterInheritedTarget=m.resolveDashboardFilterInheritedTarget;exports.resolveDashboardSqlFilterTarget=m.resolveDashboardSqlFilterTarget;exports.retainMatrixConditionalFormatting=m.retainMatrixConditionalFormatting;exports.updateMatrixConfig=m.updateMatrixConfig;exports.resolveCanonicalDetailResultRawKey=Q.resolveCanonicalDetailResultRawKey;exports.resolveCanonicalResultOutputKey=Q.resolveCanonicalResultOutputKey;exports.resolveCanonicalResultRawKey=Q.resolveCanonicalResultRawKey;exports.createMatrixAuthoringDraft=E.createMatrixAuthoringDraft;exports.createMatrixConfig=E.createMatrixConfig;exports.getMatrixLevelLabel=E.getMatrixLevelLabel;exports.getMatrixMeasureLabel=E.getMatrixMeasureLabel;exports.mergeMatrixSorts=E.mergeMatrixSorts;exports.resolveMatrixDefinition=E.resolveMatrixDefinition;exports.matrixDefinitionFields=Y.matrixDefinitionFields;exports.matrixDefinitionSources=Y.matrixDefinitionSources;exports.readMatrixCardConfig=Y.readMatrixCardConfig;exports.applyDashboardChangePlan=lt;exports.compileDashboardFromPlan=rt;exports.compileResponsiveDashboardLayouts=G;exports.dashboardAuthoringDatasetMatchesSource=q;exports.dashboardAuthoringFieldsReferToSameTarget=Ne;exports.dashboardAuthoringSourceFromField=T;exports.dashboardAuthoringSourceKey=we;exports.dashboardAuthoringSourcesReferToSameDataset=J;exports.dashboardPlanFromSemaphorDashboardIntent=yt;exports.findDashboardAuthoringDatasetForSource=Ve;exports.getDashboardAuthoringCardSource=he;exports.isMaterializableDashboardAuthoringSource=N;exports.isSemaphorSourceRef=ce;exports.mergeDashboardAuthoringSources=L;exports.preferDashboardAuthoringSourceMetadata=ue;exports.preferredDashboardAuthoringSource=xe;exports.resolveDashboardAuthoringSource=fe;exports.validateDashboardAuthoringDatasetScope=me;exports.validateDashboardChangePlan=Se;exports.validateDashboardPlan=De;
@@ -1,14 +1,14 @@
1
- import { D as E, a as _e } from "../chunks/matrix-control-sources-CVKluUf_.js";
2
- import { j as Nt, k as Mt, l as Et, f as $t, h as Lt, i as Bt, C as Pt, c as Vt, e as qt, d as zt, n as jt, o as Gt, g as Ht, m as Ut, b as Wt, r as Kt, q as Qt, t as Xt, s as Yt, p as Jt, v as Zt } from "../chunks/matrix-control-sources-CVKluUf_.js";
3
- import { A as ta, S as aa, f as ra, h as na, j as ia, k as oa, l as sa, g as da, a as ca, b as la, i as ua, p as fa, d as pa, e as ha, c as ma, r as ga, s as ba, t as Ia } from "../chunks/field-aggregations-4O27uCsl.js";
1
+ import { D as E, a as _e } from "../chunks/matrix-control-sources-DxjWV8ry.js";
2
+ import { j as Nt, k as Mt, l as Et, f as $t, h as Lt, i as Bt, C as Pt, c as Vt, e as qt, d as zt, n as jt, o as Gt, g as Ht, m as Ut, b as Wt, r as Kt, q as Qt, t as Xt, s as Yt, p as Jt, v as Zt } from "../chunks/matrix-control-sources-DxjWV8ry.js";
3
+ import { A as ta, S as aa, f as ra, h as na, j as ia, k as oa, l as sa, g as da, a as ca, b as la, i as ua, p as fa, d as pa, e as ha, c as ma, r as ga, s as ba, t as Ia } from "../chunks/field-aggregations-J7de9KZm.js";
4
4
  import { l as ye, aO as H, aP as Ce, a2 as ie, aa as ve, a5 as Se } from "../chunks/validators-BpJDwDnG.js";
5
- import "../chunks/matrix-operation-contract-DITvltmL.js";
6
- import { m as B } from "../chunks/calculated-field-identity-CQb7MOl2.js";
7
- import { D as ya, p as Ca, o as va, j as Sa, d as Da, k as wa, t as xa, e as Ta, g as Aa, v as Fa, h as ka, l as Ra, q as Oa, n as Na, r as Ma, i as Ea, a as $a, b as La, f as Ba, s as Pa, u as Va } from "../chunks/calculated-field-identity-CQb7MOl2.js";
5
+ import "../chunks/matrix-operation-contract-D5I-t3i7.js";
6
+ import { m as B } from "../chunks/calculated-field-identity-CSabKrXt.js";
7
+ import { D as ya, p as Ca, o as va, j as Sa, d as Da, k as wa, t as xa, e as Ta, g as Aa, v as Fa, h as ka, l as Ra, q as Oa, n as Na, r as Ma, i as Ea, a as $a, b as La, f as Ba, s as Pa, u as Va } from "../chunks/calculated-field-identity-CSabKrXt.js";
8
8
  import { n as De } from "../chunks/operators-C8TxpM4C.js";
9
9
  import { a as za, b as ja, r as Ga } from "../chunks/canonical-result-keys-CEQefvdO.js";
10
10
  import { b as Ua, c as Wa, g as Ka, a as Qa, m as Xa, r as Ya } from "../chunks/matrix-definition-BcJi7qGZ.js";
11
- import { m as Za, a as er, r as tr } from "../chunks/matrix-card-CoQiV9pN.js";
11
+ import { m as Za, a as er, r as tr } from "../chunks/matrix-card-5R39CCdj.js";
12
12
  function y(e) {
13
13
  return e && typeof e == "object" ? e : null;
14
14
  }
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),p=require("react"),An=require("react-dom/client"),k=require("../chunks/index-BJwEDK3K.cjs"),w=require("../chunks/switch-DAO_vHPc.cjs"),Ze=require("../data-app-builder-browser-runtime/index.cjs"),te=require("../chunks/x-B6ghREd2.cjs"),Cn=require("../chunks/save-3dYRmehL.cjs"),Rn=require("../chunks/mouse-pointer-2-DX4A_XZw.cjs"),tt=require("../chunks/search-BqqhaMx9.cjs");function Tr(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const d=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,a,d.get?d:{enumerable:!0,get:()=>t[a]})}}return s.default=t,Object.freeze(s)}const Bn=Tr(p),Dn=Tr(An);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),p=require("react"),An=require("react-dom/client"),k=require("../chunks/index-9g7-nCDB.cjs"),w=require("../chunks/switch-BabZv_0t.cjs"),Ze=require("../data-app-builder-browser-runtime/index.cjs"),te=require("../chunks/x-B6ghREd2.cjs"),Cn=require("../chunks/save-3dYRmehL.cjs"),Rn=require("../chunks/mouse-pointer-2-DX4A_XZw.cjs"),tt=require("../chunks/search-BqqhaMx9.cjs");function Tr(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const d=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,a,d.get?d:{enumerable:!0,get:()=>t[a]})}}return s.default=t,Object.freeze(s)}const Bn=Tr(p),Dn=Tr(An);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -2,8 +2,8 @@ import { jsx as r, jsxs as c, Fragment as re } from "react/jsx-runtime";
2
2
  import * as Zn from "react";
3
3
  import { useContext as qn, useState as x, useRef as oe, useMemo as je, useEffect as W, useCallback as Ot } from "react";
4
4
  import * as Xn from "react-dom/client";
5
- import { aK as ea, aL as ta, aM as Ir, aN as jr, aO as zr, aP as ra, aQ as Wr, aR as Hr, aS as Jr, aT as Vr, aU as _r, aV as Ur, aW as Kr, aX as na, aY as aa, aZ as oa, a_ as Ht, a$ as on, R as Gr, b0 as sa, b1 as Vt, b2 as sn, b3 as ia, b4 as la } from "../chunks/index-DmwnCmOH.js";
6
- import { B as H, P as it, a as lt, b as dt, _ as da, $ as ca, a0 as ua, a1 as pa, a2 as ha, L as me, R as ma, d as _t } from "../chunks/switch-BiQDKn8o.js";
5
+ import { aK as ea, aL as ta, aM as Ir, aN as jr, aO as zr, aP as ra, aQ as Wr, aR as Hr, aS as Jr, aT as Vr, aU as _r, aV as Ur, aW as Kr, aX as na, aY as aa, aZ as oa, a_ as Ht, a$ as on, R as Gr, b0 as sa, b1 as Vt, b2 as sn, b3 as ia, b4 as la } from "../chunks/index-CnZ0x05b.js";
6
+ import { B as H, P as it, a as lt, b as dt, _ as da, $ as ca, a0 as ua, a1 as pa, a2 as ha, L as me, R as ma, d as _t } from "../chunks/switch-BPhOmWZm.js";
7
7
  import { loadSemaphorBrowserRuntime as ot } from "../data-app-builder-browser-runtime/index.js";
8
8
  import { c as Ve, X as He } from "../chunks/x-CXDkqdur.js";
9
9
  import { S as fa } from "../chunks/save-DgMfP0j8.js";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../chunks/matrix-operation-contract-CCfuWtro.cjs"),e=require("../chunks/update-policy-C291nphu.cjs");exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.isSemaphorDataAppCodegenSummary=a.isSemaphorDataAppCodegenSummary;exports.validateSemaphorDataAppCodegenSummary=a.validateSemaphorDataAppCodegenSummary;exports.CODEGEN_SUMMARY_SCHEMA_VERSION=e.CODEGEN_SUMMARY_SCHEMA_VERSION;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=e.CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=e.CONTRACT_MANIFEST_SCHEMA_VERSION;exports.GENERATED_CONTRACT_SCHEMA_VERSION=e.GENERATED_CONTRACT_SCHEMA_VERSION;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=e.GENERATED_CONTRACT_TYPESCRIPT_FILES;exports.REQUIRED_GENERATED_CONTRACT_FILES=e.REQUIRED_GENERATED_CONTRACT_FILES;exports.assertValidCodegenSummary=e.assertValidCodegenSummary;exports.buildSemaphorGeneratedActiveInput=e.buildSemaphorGeneratedActiveInput;exports.buildSemaphorGeneratedInputOptionIntent=e.buildSemaphorGeneratedInputOptionIntent;exports.buildSemaphorGeneratedViewExecutionRequest=e.buildSemaphorGeneratedViewExecutionRequest;exports.buildSemaphorGeneratedViewExecutionRequests=e.buildSemaphorGeneratedViewExecutionRequests;exports.evaluateSemaphorDataAppContractUpdatePolicy=e.evaluateSemaphorDataAppContractUpdatePolicy;exports.validateCodegenSummary=e.validateCodegenSummary;exports.validateSemaphorGeneratedContract=e.validateSemaphorGeneratedContract;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../chunks/matrix-operation-contract-BiUMcd6G.cjs"),e=require("../chunks/update-policy-BP_2uCgs.cjs");exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.isSemaphorDataAppCodegenSummary=a.isSemaphorDataAppCodegenSummary;exports.validateSemaphorDataAppCodegenSummary=a.validateSemaphorDataAppCodegenSummary;exports.CODEGEN_SUMMARY_SCHEMA_VERSION=e.CODEGEN_SUMMARY_SCHEMA_VERSION;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=e.CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=e.CONTRACT_MANIFEST_SCHEMA_VERSION;exports.GENERATED_CONTRACT_SCHEMA_VERSION=e.GENERATED_CONTRACT_SCHEMA_VERSION;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=e.GENERATED_CONTRACT_TYPESCRIPT_FILES;exports.REQUIRED_GENERATED_CONTRACT_FILES=e.REQUIRED_GENERATED_CONTRACT_FILES;exports.assertValidCodegenSummary=e.assertValidCodegenSummary;exports.buildSemaphorGeneratedActiveInput=e.buildSemaphorGeneratedActiveInput;exports.buildSemaphorGeneratedInputOptionIntent=e.buildSemaphorGeneratedInputOptionIntent;exports.buildSemaphorGeneratedViewExecutionRequest=e.buildSemaphorGeneratedViewExecutionRequest;exports.buildSemaphorGeneratedViewExecutionRequests=e.buildSemaphorGeneratedViewExecutionRequests;exports.evaluateSemaphorDataAppContractUpdatePolicy=e.evaluateSemaphorDataAppContractUpdatePolicy;exports.validateCodegenSummary=e.validateCodegenSummary;exports.validateSemaphorGeneratedContract=e.validateSemaphorGeneratedContract;
@@ -1,5 +1,5 @@
1
- import { S as E, a as S, i as A, v as t } from "../chunks/matrix-operation-contract-DITvltmL.js";
2
- import { C as R, a as r, b as s, G as C, e as o, R as p, c as d, f as O, g as i, h as m, i as n, j as N, v as T, d as I } from "../chunks/update-policy-kjd-Z5jD.js";
1
+ import { S as E, a as S, i as A, v as t } from "../chunks/matrix-operation-contract-D5I-t3i7.js";
2
+ import { C as R, a as r, b as s, G as C, e as o, R as p, c as d, f as O, g as i, h as m, i as n, j as N, v as T, d as I } from "../chunks/update-policy-D3I1J2kl.js";
3
3
  export {
4
4
  R as CODEGEN_SUMMARY_SCHEMA_VERSION,
5
5
  r as CODEGEN_SUMMARY_VALIDATOR_VERSION,
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("../chunks/matrix-operation-contract-CCfuWtro.cjs"),R=require("../chunks/update-policy-C291nphu.cjs"),he=require("node:crypto"),Ce="src/semaphor/generated",H=`// Generated by Semaphor Agent Plugin. Do not hand-edit analytics wiring here.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("../chunks/matrix-operation-contract-BiUMcd6G.cjs"),R=require("../chunks/update-policy-BP_2uCgs.cjs"),he=require("node:crypto"),Ce="src/semaphor/generated",H=`// Generated by Semaphor Agent Plugin. Do not hand-edit analytics wiring here.
2
2
  // Regenerate from the accepted semaphor_plan_data_app codegenSummary when the plan changes.
3
3
  `;function Oe(e,n={}){R.assertValidCodegenSummary(e);const r=Me(e);if(r.views.length===0&&!n.allowEmpty)throw new Error("Contract generation produced zero executable views. Stop and ask for a different domain/goal or semantic model improvement; pass --allow-empty only for an explicit model-gap report.");const t=ke(r),o=Ne({contract:r,files:t,generatorName:n.generatorName||"react-semaphor/data-app-codegen/node",generatorVersion:n.generatorVersion||"unknown"}),a={...t,"contract.manifest.json":`${JSON.stringify(o,null,2)}
4
4
  `};return{schemaVersion:R.GENERATED_CONTRACT_SCHEMA_VERSION,files:a,manifest:o,contentHash:String(o.generatedContentHash||""),usageExample:Te(r),warnings:r.warnings,stats:{inputCount:r.inputs.length,executableViewCount:r.views.length,presentationViewCount:r.presentationViews.length,queryCount:r.views.length,optionQueryCount:r.optionQueries.length}}}function Me(e){var d,p,m,i,l,g,h,I,$,M,b,E;const n=[],r=[];for(const s of e.inputs){S(r,s.fieldRef);for(const V of s.bindings||[])S(r,V.fieldRef);S(r,(d=s.optionQuery)==null?void 0:d.valueFieldRef),S(r,(p=s.optionQuery)==null?void 0:p.labelFieldRef),S(r,(m=s.optionQuery)==null?void 0:m.filterFieldRef),D(r,(i=s.optionQuery)==null?void 0:i.spec)}for(const s of e.filterContracts){S(r,s.fieldRef),S(r,(l=s.optionQuery)==null?void 0:l.valueFieldRef),S(r,(g=s.optionQuery)==null?void 0:g.labelFieldRef),S(r,(h=s.optionQuery)==null?void 0:h.filterFieldRef),D(r,(I=s.optionQuery)==null?void 0:I.spec);for(const V of s.bindings||[])S(r,V.fieldRef)}for(const s of e.views){for(const V of s.fields||[])S(r,V);D(r,($=s.sdkSpec)==null?void 0:$.spec),D(r,s.visualSpec)}const t=e.implementationChecklist||{};for(const s of Object.values(t.bindingsByView||{}))for(const V of Array.isArray(s)?s:[])S(r,V.fieldRef),S(r,V.optionValueField),S(r,V.optionLabelField);for(const s of t.requiredInputOptions||[])S(r,s.visibleLabelField),S(r,s.optionValueField),S(r,s.runtimeFilterField);const o=pn([...e.sources.map(s=>({raw:s,key:Ie(s),aliases:Ve(s),name:""})),...r.map(s=>an(s)).filter(x)]);P(o,s=>{const V=F(s.raw);return j(s.raw.label||(V==null?void 0:V.datasetName)||(V==null?void 0:V.datasetId)||(V==null?void 0:V.name)||s.raw.kind||"source")});const a=ln(o),u=ne(r.filter(s=>s.name).map(s=>({raw:s,key:X(s),name:""})),s=>s.key);P(u,s=>j([s.raw.sourceKey?yn(s.raw.sourceKey):"",s.raw.aggregate?s.raw.aggregate.toLowerCase():"",s.raw.name].filter(Boolean).join("_")));const c=new Map(u.map(s=>[s.key,s.name])),w=e.inputs.map(s=>({raw:s,name:j(s.id||s.label||"input")}));P(w,s=>s.name);const f=w.filter(s=>!!s.raw.optionQuery).map(s=>({input:s,name:`${s.name}Options`,raw:s.raw.optionQuery}));P(f,s=>s.name);for(const s of f)un(s.raw.labelFieldRef,s.raw.valueFieldRef)&&dn(s.raw.valueFieldRef)&&n.push(`Input option query ${((M=s.raw.spec)==null?void 0:M.inputId)||s.input.raw.id||s.name} uses identifier field ${s.raw.valueFieldRef.name} as both label and value. It can execute, but the UI will show key values unless the semantic model exposes a human-readable label through a modeled relationship.`);const y=e.views.filter(s=>{var V,K;return!!((V=s.sdkSpec)!=null&&V.builder&&((K=s.sdkSpec)!=null&&K.spec))}).map(s=>({raw:s,name:j(s.id||s.title||"query")}));P(y,s=>s.name);const k=e.views.filter(s=>fe(s)&&!("sdkSpec"in s)).map(s=>sn(s));for(const s of e.views)(!("sdkSpec"in s)||!((b=s.sdkSpec)!=null&&b.builder)||!((E=s.sdkSpec)!=null&&E.spec))&&!fe(s)&&n.push(`Skipped view ${s.id||s.title||"unknown"} because it has no sdkSpec.`);return Ee({inputs:w,views:y,filterContracts:e.filterContracts}),{summary:e,title:e.title||"Semaphor Data App",sources:o,fields:u,inputs:w,optionQueries:f,views:y,presentationViews:k,filterContracts:e.filterContracts,checklist:t,sourceNameByKey:a,fieldNameByKey:c,warnings:n}}function Ee({inputs:e,views:n,filterContracts:r}){const t=new Set(e.map(a=>a.raw.id).filter(Boolean)),o=new Set(n.map(a=>a.raw.id).filter(Boolean));for(const[a,u]of r.entries()){if(!t.has(u.inputId))throw new Error(`filterContracts.${a}.inputId must reference a generated input.`);const c=new Set(u.appliesToViewIds||[]),w=new Set(u.notAppliedToViewIds||[]);for(const[f,y]of(u.appliesToViewIds||[]).entries())if(!o.has(y))throw new Error(`filterContracts.${a}.appliesToViewIds.${f} must reference an executable generated view.`);for(const[f,y]of(u.notAppliedToViewIds||[]).entries())if(!o.has(y))throw new Error(`filterContracts.${a}.notAppliedToViewIds.${f} must reference an executable generated view.`);for(const[f,y]of(u.bindings||[]).entries()){if(!o.has(y.viewId))throw new Error(`filterContracts.${a}.bindings.${f}.viewId must reference an executable generated view.`);if(!c.has(y.viewId))throw new Error(`filterContracts.${a}.bindings.${f}.viewId must be included in appliesToViewIds.`);if(w.has(y.viewId))throw new Error(`filterContracts.${a}.bindings.${f}.viewId must not be listed in notAppliedToViewIds.`)}}}function ke(e){return{"sources.ts":ve(e),"fields.ts":qe(e),"inputs.ts":De(e),"queries.ts":Pe(e),"bindings.ts":Le(e),"accessors.ts":Ye(e),"metadata.ts":We(e),"index.ts":Xe(),"USAGE.md":Ae(e)}}function Ne({contract:e,files:n,generatorName:r,generatorVersion:t}){return{schemaVersion:R.CONTRACT_MANIFEST_SCHEMA_VERSION,generatedContractSchemaVersion:R.GENERATED_CONTRACT_SCHEMA_VERSION,generator:{name:r,version:t},generatedContentHash:Ge(n),codegenSummaryValidatorVersion:R.CODEGEN_SUMMARY_VALIDATOR_VERSION,codegenSummaryHash:xe(e.summary),codegenSummary:e.summary}}function Ge(e){const n=he.createHash("sha256");for(const r of Object.keys(e).filter(t=>t.endsWith(".ts")).sort())n.update(r),n.update("\0"),n.update(e[r]),n.update("\0");return`sha256:${n.digest("hex")}`}function Ae(e){const n=["# Semaphor Generated Data App Contract","","Generated files in this directory are governed Semaphor analytics wiring. Do not hand-edit them.","","Use the app-facing exports from `index.ts`:","","- `queries`: generated governed query factories.","- `queryOptionsForView`: active-input wiring for each generated view.","- `rowsForView`: table/records row readers.","- `rowValuesForView`: friendly row object readers for chart/table views.","- `metricValuesForView`: friendly metric-value readers.","- `kpiPropsForView`: KPI component props derived from runtime metric results.","- `roleValuesForView`: canonical dimension/measure/date/id role readers.","- `appInputSpecs`: generated input/filter specs.","- `inputOptionQueries`: option-list query factories for generated inputs.","- `semaphorGeneratedContractMetadata`: generated view/input metadata and presentation-only views.","","Start with these exports before opening large generated internals such as `metadata.ts`.",""];return e.views.length>0&&(n.push("Generated executable views:"),e.views.forEach(r=>{n.push(`- \`${r.raw.id}\`: ${r.raw.title||r.name}`)}),n.push("")),e.inputs.length>0&&(n.push("Generated inputs:"),e.inputs.forEach(r=>{n.push(`- \`${r.raw.id}\`: ${r.raw.label||r.name}`)}),n.push("")),`${n.join(`
@@ -1,6 +1,6 @@
1
- import { S as Vn, a as Fn, i as bn, v as kn } from "../chunks/matrix-operation-contract-DITvltmL.js";
2
- import { c as ke, G as fe, a as Re, b as Me } from "../chunks/update-policy-kjd-Z5jD.js";
3
- import { C as Mn, e as Cn, R as On, f as xn, g as Gn, h as Nn, i as En, j as An, v as jn, d as vn } from "../chunks/update-policy-kjd-Z5jD.js";
1
+ import { S as Vn, a as Fn, i as bn, v as kn } from "../chunks/matrix-operation-contract-D5I-t3i7.js";
2
+ import { c as ke, G as fe, a as Re, b as Me } from "../chunks/update-policy-D3I1J2kl.js";
3
+ import { C as Mn, e as Cn, R as On, f as xn, g as Gn, h as Nn, i as En, j as An, v as jn, d as vn } from "../chunks/update-policy-D3I1J2kl.js";
4
4
  import { createHash as ye } from "node:crypto";
5
5
  const wn = "src/semaphor/generated", v = `// Generated by Semaphor Agent Plugin. Do not hand-edit analytics wiring here.
6
6
  // Regenerate from the accepted semaphor_plan_data_app codegenSummary when the plan changes.
@@ -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"),u=require("react"),B=require("../chunks/validators-4dRtYUI1.cjs"),Re=require("../chunks/matrix-operation-contract-CCfuWtro.cjs"),rr=require("../chunks/matrix-formatter-C3cZwlyH.cjs"),ie=require("../chunks/search-BqqhaMx9.cjs"),Ke=require("../chunks/x-B6ghREd2.cjs");function ue(e,r,t){return{...t,name:e,role:r}}function zr(e){return e}function Pr(e){return e}const Hr={source:{semantic(e){return{...e,kind:"semantic"}},sql(e){return{...e,kind:"sql"}}},field:{measure(e,r={}){return ue(e,"measure",r)},dimension(e,r={}){return ue(e,"dimension",r)},date(e,r={}){return ue(e,"date",r)},id(e,r={}){return ue(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"}}},oe=10,Le=8;function We(e,r){const t=e==null?void 0:e.result;if(t)switch(t.kind){case"records":return ne({title:"Records",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"sql":return ne({title:"SQL Rows",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"inputOptions":return ne({title:"Options",rowNoun:"options",records:t.options.slice(0,oe).map(n=>{var s;return{label:n.label,value:n.value,count:n.count,disambiguation:(s=n.disambiguation)==null?void 0:s.join(" / ")}}),columns:[{key:"label",label:"Label"},{key:"value",label:"Value"},{key:"count",label:"Count"},{key:"disambiguation",label:"Disambiguation"}],rowCount:t.rowCount??t.options.length});case"metric":return Vr(t,r);case"matrix":return ne({title:"Matrix Cells",rowNoun:"cells",records:t.window.blocks.flatMap(n=>n.cells).slice(0,oe).map(n=>{const s=t.window.descriptors.measures.find(o=>o.id===n.measureId);return{row:rr.matrixMemberLabel(n.rowPath),column:rr.matrixMemberLabel(n.columnPath),measure:(s==null?void 0:s.column.label)||n.measureId,value:n.value}}),columns:[{key:"row",label:"Row"},{key:"column",label:"Column"},{key:"measure",label:"Measure"},{key:"value",label:"Value"}],rowCount:t.window.blocks.reduce((n,s)=>n+s.cells.length,0)});default:return Ur(t)}}function Vr(e,r){var o,a,f,c,p;const t=[{metric:"primaryValue",value:(r==null?void 0:r.primaryValue)??e.primaryValue}],n=(r==null?void 0:r.comparisonKind)??((o=e.comparison)==null?void 0:o.kind);return n&&t.push({metric:`${n} value`,value:(r==null?void 0:r.comparisonValue)??((a=e.comparison)==null?void 0:a.value)},{metric:"delta",value:(r==null?void 0:r.delta)??((f=e.comparison)==null?void 0:f.delta)},{metric:"deltaPercent",value:(r==null?void 0:r.deltaPercent)??((c=e.comparison)==null?void 0:c.deltaPercent)}),(((p=r==null?void 0:r.missingMeasures)==null?void 0:p.filter(Boolean))??[]).forEach(g=>{t.push({metric:`missing:${g}`,value:"missing"})}),Object.entries((r==null?void 0:r.measures)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`measure:${g}`,value:m})}),Object.entries((r==null?void 0:r.measureBindings)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`binding:${g}`,value:m})}),ne({title:"Metric",rowNoun:"values",records:t,columns:[{key:"metric",label:"Metric"},{key:"value",label:"Value"}],rowCount:t.length})}function ne({title:e,rowNoun:r,records:t,columns:n,rowCount:s}){const o=Qr(n,t);if(!o.length)return;const a=s??t.length,f=t.slice(0,oe);return{title:e,summary:`${Jr(a)} ${r}`,columns:o.slice(0,Le),rows:f,truncatedRows:a>f.length,truncatedColumns:o.length>Le}}function Qr(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,oe).forEach(n=>{Object.keys(n).forEach(s=>t.add(s))}),[...t].map(n=>({key:n,label:n}))}function Ur(e){throw new Error(`Unhandled Semaphor result kind: ${mr(e)}`)}function Gr(e){return e===null?"null":e===void 0?"":typeof e=="string"?tr(e):typeof e=="number"||typeof e=="boolean"?String(e):tr(mr(e))}function Jr(e){return typeof e=="number"?e.toLocaleString():"-"}function mr(e){return JSON.stringify(e,null,2)??"undefined"}function tr(e){return e.length>80?`${e.slice(0,77)}...`:e}function he(e){return e.viewTitle||e.queryLabel||e.viewId||e.queryId}function Yr(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`${Xr(t)} Options`}function Xr(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 Ne(e){return e.flatMap(r=>{var g,m,v,y;const t=r.latestAttempt,n=t==null?void 0:t.executionResult,s=Se((g=n==null?void 0:n.validation)==null?void 0:g.warnings),o=Se((m=n==null?void 0:n.validation)==null?void 0:m.errors),a=tt((v=n==null?void 0:n.coverage)==null?void 0:v.missingObligations),f=Se((y=n==null?void 0:n.coverage)==null?void 0:y.warnings),c=[],p=he(r);(t==null?void 0:t.status)==="error"&&c.push({trace:r,tone:"error",title:p,message:t.errorMessage||"Query attempt failed."});for(const b of r.clientWarnings)c.push({trace:r,tone:"warning",title:p,message:b});for(const b of s)c.push({trace:r,tone:"warning",title:p,...b});for(const b of o)c.push({trace:r,tone:"error",title:p,...b});for(const b of a)c.push({trace:r,tone:"warning",title:p,message:b});for(const b of f)c.push({trace:r,tone:"warning",title:p,...b});return c})}function Zr(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 et(e,r){return e.filter(t=>t.trace.traceId===r.traceId).length}function rt(e){const r=Ne(e),t=e.filter(a=>{var f;return((f=a.latestAttempt)==null?void 0:f.status)==="error"}).length,n=e.filter(a=>{var f;return((f=a.latestAttempt)==null?void 0:f.status)==="loading"}).length,s=r.filter(a=>a.tone==="error").length,o=r.filter(a=>a.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 tt(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function Se(e){return Array.isArray(e)?e.map(nt).filter(r=>!!r):[]}function nt(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 st(e){if(!e.enabled)return e;const r=e.queries.map(yr);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 nr(e){return e?yr(e):void 0}function yr(e){var r;return(r=e==null?void 0:e.latestAttempt)!=null&&r.executionResult?{...e,latestAttempt:{...e.latestAttempt,resultPreview:e.latestAttempt.resultPreview||We(e.latestAttempt.executionResult),executionResult:it(e.latestAttempt.executionResult)}}:e}function it(e){const{compiledQuery:r,intent:t,result:n,...s}=e,o=ot(s.metadata);return{...s,...o?{metadata:o}:{}}}function ot(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 at(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 lt(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 dt(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 ut(e){return e==="right"?{gridTemplateColumns:"minmax(210px, 280px) minmax(0, 1fr)"}:{gridTemplateColumns:"minmax(260px, 340px) minmax(0, 1fr)"}}function ct(e){return{borderRight:"1px solid var(--sd-border)",borderBottom:0}}function hr(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 ft(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 sr="semaphor-devtools-stylesheet",E="semaphor-devtools",pt=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../data-app-sdk-adapters/index.cjs"),i=require("react/jsx-runtime"),u=require("react"),B=require("../chunks/validators-4dRtYUI1.cjs"),Re=require("../chunks/matrix-operation-contract-BiUMcd6G.cjs"),rr=require("../chunks/matrix-formatter-3QR1mqhn.cjs"),ie=require("../chunks/search-BqqhaMx9.cjs"),Ke=require("../chunks/x-B6ghREd2.cjs");function ue(e,r,t){return{...t,name:e,role:r}}function zr(e){return e}function Pr(e){return e}const Hr={source:{semantic(e){return{...e,kind:"semantic"}},sql(e){return{...e,kind:"sql"}}},field:{measure(e,r={}){return ue(e,"measure",r)},dimension(e,r={}){return ue(e,"dimension",r)},date(e,r={}){return ue(e,"date",r)},id(e,r={}){return ue(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"}}},oe=10,Le=8;function We(e,r){const t=e==null?void 0:e.result;if(t)switch(t.kind){case"records":return ne({title:"Records",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"sql":return ne({title:"SQL Rows",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"inputOptions":return ne({title:"Options",rowNoun:"options",records:t.options.slice(0,oe).map(n=>{var s;return{label:n.label,value:n.value,count:n.count,disambiguation:(s=n.disambiguation)==null?void 0:s.join(" / ")}}),columns:[{key:"label",label:"Label"},{key:"value",label:"Value"},{key:"count",label:"Count"},{key:"disambiguation",label:"Disambiguation"}],rowCount:t.rowCount??t.options.length});case"metric":return Vr(t,r);case"matrix":return ne({title:"Matrix Cells",rowNoun:"cells",records:t.window.blocks.flatMap(n=>n.cells).slice(0,oe).map(n=>{const s=t.window.descriptors.measures.find(o=>o.id===n.measureId);return{row:rr.matrixMemberLabel(n.rowPath),column:rr.matrixMemberLabel(n.columnPath),measure:(s==null?void 0:s.column.label)||n.measureId,value:n.value}}),columns:[{key:"row",label:"Row"},{key:"column",label:"Column"},{key:"measure",label:"Measure"},{key:"value",label:"Value"}],rowCount:t.window.blocks.reduce((n,s)=>n+s.cells.length,0)});default:return Ur(t)}}function Vr(e,r){var o,a,f,c,p;const t=[{metric:"primaryValue",value:(r==null?void 0:r.primaryValue)??e.primaryValue}],n=(r==null?void 0:r.comparisonKind)??((o=e.comparison)==null?void 0:o.kind);return n&&t.push({metric:`${n} value`,value:(r==null?void 0:r.comparisonValue)??((a=e.comparison)==null?void 0:a.value)},{metric:"delta",value:(r==null?void 0:r.delta)??((f=e.comparison)==null?void 0:f.delta)},{metric:"deltaPercent",value:(r==null?void 0:r.deltaPercent)??((c=e.comparison)==null?void 0:c.deltaPercent)}),(((p=r==null?void 0:r.missingMeasures)==null?void 0:p.filter(Boolean))??[]).forEach(g=>{t.push({metric:`missing:${g}`,value:"missing"})}),Object.entries((r==null?void 0:r.measures)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`measure:${g}`,value:m})}),Object.entries((r==null?void 0:r.measureBindings)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`binding:${g}`,value:m})}),ne({title:"Metric",rowNoun:"values",records:t,columns:[{key:"metric",label:"Metric"},{key:"value",label:"Value"}],rowCount:t.length})}function ne({title:e,rowNoun:r,records:t,columns:n,rowCount:s}){const o=Qr(n,t);if(!o.length)return;const a=s??t.length,f=t.slice(0,oe);return{title:e,summary:`${Jr(a)} ${r}`,columns:o.slice(0,Le),rows:f,truncatedRows:a>f.length,truncatedColumns:o.length>Le}}function Qr(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,oe).forEach(n=>{Object.keys(n).forEach(s=>t.add(s))}),[...t].map(n=>({key:n,label:n}))}function Ur(e){throw new Error(`Unhandled Semaphor result kind: ${mr(e)}`)}function Gr(e){return e===null?"null":e===void 0?"":typeof e=="string"?tr(e):typeof e=="number"||typeof e=="boolean"?String(e):tr(mr(e))}function Jr(e){return typeof e=="number"?e.toLocaleString():"-"}function mr(e){return JSON.stringify(e,null,2)??"undefined"}function tr(e){return e.length>80?`${e.slice(0,77)}...`:e}function he(e){return e.viewTitle||e.queryLabel||e.viewId||e.queryId}function Yr(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`${Xr(t)} Options`}function Xr(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 Ne(e){return e.flatMap(r=>{var g,m,v,y;const t=r.latestAttempt,n=t==null?void 0:t.executionResult,s=Se((g=n==null?void 0:n.validation)==null?void 0:g.warnings),o=Se((m=n==null?void 0:n.validation)==null?void 0:m.errors),a=tt((v=n==null?void 0:n.coverage)==null?void 0:v.missingObligations),f=Se((y=n==null?void 0:n.coverage)==null?void 0:y.warnings),c=[],p=he(r);(t==null?void 0:t.status)==="error"&&c.push({trace:r,tone:"error",title:p,message:t.errorMessage||"Query attempt failed."});for(const b of r.clientWarnings)c.push({trace:r,tone:"warning",title:p,message:b});for(const b of s)c.push({trace:r,tone:"warning",title:p,...b});for(const b of o)c.push({trace:r,tone:"error",title:p,...b});for(const b of a)c.push({trace:r,tone:"warning",title:p,message:b});for(const b of f)c.push({trace:r,tone:"warning",title:p,...b});return c})}function Zr(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 et(e,r){return e.filter(t=>t.trace.traceId===r.traceId).length}function rt(e){const r=Ne(e),t=e.filter(a=>{var f;return((f=a.latestAttempt)==null?void 0:f.status)==="error"}).length,n=e.filter(a=>{var f;return((f=a.latestAttempt)==null?void 0:f.status)==="loading"}).length,s=r.filter(a=>a.tone==="error").length,o=r.filter(a=>a.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 tt(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function Se(e){return Array.isArray(e)?e.map(nt).filter(r=>!!r):[]}function nt(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 st(e){if(!e.enabled)return e;const r=e.queries.map(yr);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 nr(e){return e?yr(e):void 0}function yr(e){var r;return(r=e==null?void 0:e.latestAttempt)!=null&&r.executionResult?{...e,latestAttempt:{...e.latestAttempt,resultPreview:e.latestAttempt.resultPreview||We(e.latestAttempt.executionResult),executionResult:it(e.latestAttempt.executionResult)}}:e}function it(e){const{compiledQuery:r,intent:t,result:n,...s}=e,o=ot(s.metadata);return{...s,...o?{metadata:o}:{}}}function ot(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 at(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 lt(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 dt(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 ut(e){return e==="right"?{gridTemplateColumns:"minmax(210px, 280px) minmax(0, 1fr)"}:{gridTemplateColumns:"minmax(260px, 340px) minmax(0, 1fr)"}}function ct(e){return{borderRight:"1px solid var(--sd-border)",borderBottom:0}}function hr(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 ft(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 sr="semaphor-devtools-stylesheet",E="semaphor-devtools",pt=`
2
2
  .${E} {
3
3
  --sd-bg: #ffffff;
4
4
  --sd-bg-muted: #fafafa;
@@ -3,8 +3,8 @@ import { jsxs as p, Fragment as Sr, jsx as l } from "react/jsx-runtime";
3
3
  import { createContext as xe, useContext as Q, useState as z, useRef as E, useEffect as B, useMemo as I, Fragment as it, useId as Ir, useCallback as D, useReducer as ot } from "react";
4
4
  import { l as st, q as at, a2 as lt, aK as Se } from "../chunks/validators-BpJDwDnG.js";
5
5
  import { f as ho, aQ as bo } from "../chunks/validators-BpJDwDnG.js";
6
- import { u as dt, N as ut, L as ct } from "../chunks/matrix-operation-contract-DITvltmL.js";
7
- import { m as or } from "../chunks/matrix-formatter-PvfZAZMO.js";
6
+ import { u as dt, N as ut, L as ct } from "../chunks/matrix-operation-contract-D5I-t3i7.js";
7
+ import { m as or } from "../chunks/matrix-formatter-youWVghC.js";
8
8
  import { M as ft, a as pt, S as gt, E as mt, C as yt } from "../chunks/search-BHsQIWBV.js";
9
9
  import { X as ht, C as bt, j as vt } from "../chunks/x-CXDkqdur.js";
10
10
  function me(e, r, t) {
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("../chunks/operators-DrTQsJXv.cjs"),l=require("../chunks/validators-4dRtYUI1.cjs");require("../chunks/matrix-operation-contract-CCfuWtro.cjs");function g(i){var e,r,o;const t=b(i);return{version:1,kind:"metric",id:i.id,label:i.label,source:h(i),measures:t,primaryMeasure:M(i,t),dateField:i.dateField?a(i.dateField,"date"):void 0,timeGrain:i.timeGrain,dimensions:(e=i.dimensions)==null?void 0:e.map(n=>a(n,"dimension")),comparison:$(i.comparison),orderBy:i.orderBy?{field:a(i.orderBy.field),direction:i.orderBy.direction}:void 0,inputs:u(i.inputs),...(r=i.filters)!=null&&r.length?{filters:i.filters}:{},...i.relationshipHint?{relationshipHint:i.relationshipHint}:{},limit:i.limit,...(o=i.derivedFields)!=null&&o.length?{derivedFields:i.derivedFields}:{}}}function v(i){return{...g(i),...i.timeWindow?{timeWindow:i.timeWindow}:{},...i.analysis?{analysis:i.analysis}:{}}}function F(i){return{...i.chartTitle?{chartTitle:i.chartTitle}:{},...i.chartType?{chartType:i.chartType}:{},...i.driverMode?{driverMode:i.driverMode}:{},...i.includePopulation!==void 0?{includePopulation:i.includePopulation}:{},...i.calendarContext?{calendarContext:i.calendarContext}:{}}}function M(i,t){if(!i.primaryMeasure)return t[0]||{name:"",role:"measure"};const e=a(i.primaryMeasure,"measure"),r=H(e,t),o=r.length===1?r[0]:void 0;return o?p(e,o):e}function b(i){const t=[];for(const e of i.measures.map(r=>a(r,"measure"))){if(!e.name)continue;const r=t.findIndex(o=>R(o,e));if(r===-1){t.push(e);continue}t[r]=p(t[r],e)}return t}function R(i,t){return l.semaphorFieldRefsMatch(i,t)&&d(i)===d(t)}function w(i,t){return d(t)===d(i)}function k(i,t){return t.name!==i.name||i.source&&!l.semaphorFieldRefsMatch(t,i)?!1:w(i,t)}function H(i,t){const e=t.filter(r=>k(i,r));return i.aggregate!==void 0,e}function d(i){return l.semaphorMetricAggregate(i)}function p(i,t){if(i.aggregate&&t.aggregate&&i.aggregate!==t.aggregate)throw new Error(`Measure "${i.name}" was requested with conflicting aggregate semantics: ${i.aggregate} and ${t.aggregate}.`);return{...l.preferSemaphorFieldRefMetadata(i,t),aggregate:i.aggregate||t.aggregate}}function A(i){var e,r;if("sort"in i)throw new Error("semaphor.records supports orderBy for a single deterministic sort. Multiple sort clauses are not supported by the analytics protocol yet.");if(!E(i))throw new Error("semaphor.records needs at least one field.");const t=B(i.fields);return{version:1,kind:"records",id:i.id,label:i.label,source:h(i),fields:t,dateField:i.dateField?a(i.dateField,"date"):void 0,timeGrain:i.timeGrain,...i.timeWindow?{timeWindow:i.timeWindow}:{},...(e=i.filters)!=null&&e.length?{filters:i.filters}:{},orderBy:i.orderBy?{field:a(i.orderBy.field),direction:i.orderBy.direction}:void 0,inputs:u(i.inputs),...i.relationshipHint?{relationshipHint:i.relationshipHint}:{},limit:i.limit,...i.pagination?{pagination:i.pagination}:{},...i.totals?{totals:{mode:"server",measures:i.totals.measures.map(o=>a(o,"measure"))}}:{},...(r=i.derivedFields)!=null&&r.length?{derivedFields:i.derivedFields}:{}}}function B(i){return i.map(t=>{const e=a(t);if(!e.role)throw new Error(`semaphor.records field "${e.name}" needs an explicit role.`);return e})}function O(i){var e,r,o;const t=h(i);if(t.kind==="sql")throw new Error("semaphor.inputOptions requires a semantic or physical option source.");return{version:1,kind:"inputOptions",id:i.id,label:i.label,inputId:i.inputId,source:t,labelField:a(i.labelField,"dimension"),valueField:a(i.valueField,"dimension"),...i.searchField?{searchField:a(i.searchField,"dimension")}:{},...(e=i.disambiguationFields)!=null&&e.length?{disambiguationFields:i.disambiguationFields.map(n=>a(n,"dimension"))}:{},...i.population?{population:i.population}:{},...i.dependencies?{dependencies:i.dependencies}:{},search:i.search,limit:i.limit,...(r=i.inputs)!=null&&r.length?{inputs:i.inputs.map(n=>m(n))}:{},...(o=i.derivedFields)!=null&&o.length?{derivedFields:i.derivedFields}:{}}}function q(i){var t;return{version:1,kind:"sql",id:i.id,label:i.label,source:i.source,sql:i.sql,...i.defaultParameters?{defaultParameters:i.defaultParameters}:{},...i.pythonCode?{pythonCode:i.pythonCode}:{},...(t=i.fields)!=null&&t.length?{fields:i.fields.map(e=>a(e))}:{},inputs:u(i.inputs),limit:i.limit,...i.pagination?{pagination:i.pagination}:{},rationale:i.rationale}}function P(i){const{id:t,label:e,inputs:r,matrixWindowRequest:o,...n}=i,{queryKind:_,...S}=n;return l.matrixAnalyticalIntentSchema.parse({...S,kind:"matrix"})}function m(i){if("toAnalyticsInput"in i){const n=i.toAnalyticsInput();return{inputId:n.inputId,kind:n.kind,...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}if("id"in i){const n=f(i);return{inputId:n.inputId,kind:n.kind,...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}const t="kind"in i?i.kind:void 0,e="operator"in i?I(i.operator,i.inputId):void 0,r="controlRole"in i?i.controlRole:"role"in i?i.role:void 0,o=z(r)?r:void 0;return{inputId:i.inputId,...t?{kind:t}:{},...o?{controlRole:o}:{},...e?{operator:e}:{},...i.field?{field:i.field}:{},...i.relationshipHint?{relationshipHint:i.relationshipHint}:{}}}function z(i){return i==="grain"||i==="measure"||i==="dimension"||i==="aggregation"||i==="sqlParam"}function C(i){const t=u(i);return t.length>0?t:void 0}function c(i){return(i||[]).map(W)}function T(i){return c(i).filter(t=>t.isActive)}function f(i){if(i.kind==="filter"){const t=I(i.operator,i.id);return{inputId:i.id,kind:i.kind,label:i.label,field:a(i.field,"dimension"),operator:t||"in",...i.relationshipHint?{relationshipHint:i.relationshipHint}:{}}}return{inputId:i.id,kind:i.kind,label:i.label,controlRole:i.role}}function x(i=[]){return i.map(t=>typeof t=="object"?t:{label:String(t),value:t})}function s(i){return i==null?!1:Array.isArray(i)?i.length>0:typeof i=="string"?i.trim().length>0:!0}function W(i){if("toAnalyticsInput"in i)return i.toAnalyticsInput();if("kind"in i&&"isActive"in i)return i;if("id"in i){const t=f(i),e=Object.prototype.hasOwnProperty.call(i,"value")?i.value:i.defaultValue;return{inputId:t.inputId,kind:t.kind,label:t.label,...t.field?{field:t.field}:{},...t.operator?{operator:t.operator}:{},...t.controlRole?{controlRole:t.controlRole}:{},...t.relationshipHint?{relationshipHint:t.relationshipHint}:{},value:e,isActive:s(e)}}return{...i,kind:"filter",isActive:s(i.value),value:i.value}}function h(i){return i.source}function E(i){var t;return!!((t=i.fields)!=null&&t.length)}function a(i,t){return{...i,role:i.role||t}}function u(i){return(i||[]).map(m)}function $(i){if(i)return i}function I(i,t){if(i===void 0)return;const e=y.normalizeSemaphorInputOperator(i);if(!e)throw new Error(`useSemaphorInput "${t}" uses unsupported filter operator "${i}".`);return e}exports.hasSemaphorInputValue=s;exports.normalizeSemaphorInputOptions=x;exports.toSemaphorActiveInputSnapshots=T;exports.toSemaphorAnalysisIntent=v;exports.toSemaphorAnalysisQueryOptions=F;exports.toSemaphorInputBinding=m;exports.toSemaphorInputBindings=C;exports.toSemaphorInputOptionsIntent=O;exports.toSemaphorInputSnapshots=c;exports.toSemaphorInputSpec=f;exports.toSemaphorMatrixIntent=P;exports.toSemaphorMetricIntent=g;exports.toSemaphorRecordsIntent=A;exports.toSemaphorSqlIntent=q;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("../chunks/operators-DrTQsJXv.cjs"),l=require("../chunks/validators-4dRtYUI1.cjs");require("../chunks/matrix-operation-contract-BiUMcd6G.cjs");function g(i){var e,r,o;const t=b(i);return{version:1,kind:"metric",id:i.id,label:i.label,source:h(i),measures:t,primaryMeasure:M(i,t),dateField:i.dateField?a(i.dateField,"date"):void 0,timeGrain:i.timeGrain,dimensions:(e=i.dimensions)==null?void 0:e.map(n=>a(n,"dimension")),comparison:$(i.comparison),orderBy:i.orderBy?{field:a(i.orderBy.field),direction:i.orderBy.direction}:void 0,inputs:u(i.inputs),...(r=i.filters)!=null&&r.length?{filters:i.filters}:{},...i.relationshipHint?{relationshipHint:i.relationshipHint}:{},limit:i.limit,...(o=i.derivedFields)!=null&&o.length?{derivedFields:i.derivedFields}:{}}}function v(i){return{...g(i),...i.timeWindow?{timeWindow:i.timeWindow}:{},...i.analysis?{analysis:i.analysis}:{}}}function F(i){return{...i.chartTitle?{chartTitle:i.chartTitle}:{},...i.chartType?{chartType:i.chartType}:{},...i.driverMode?{driverMode:i.driverMode}:{},...i.includePopulation!==void 0?{includePopulation:i.includePopulation}:{},...i.calendarContext?{calendarContext:i.calendarContext}:{}}}function M(i,t){if(!i.primaryMeasure)return t[0]||{name:"",role:"measure"};const e=a(i.primaryMeasure,"measure"),r=H(e,t),o=r.length===1?r[0]:void 0;return o?p(e,o):e}function b(i){const t=[];for(const e of i.measures.map(r=>a(r,"measure"))){if(!e.name)continue;const r=t.findIndex(o=>R(o,e));if(r===-1){t.push(e);continue}t[r]=p(t[r],e)}return t}function R(i,t){return l.semaphorFieldRefsMatch(i,t)&&d(i)===d(t)}function w(i,t){return d(t)===d(i)}function k(i,t){return t.name!==i.name||i.source&&!l.semaphorFieldRefsMatch(t,i)?!1:w(i,t)}function H(i,t){const e=t.filter(r=>k(i,r));return i.aggregate!==void 0,e}function d(i){return l.semaphorMetricAggregate(i)}function p(i,t){if(i.aggregate&&t.aggregate&&i.aggregate!==t.aggregate)throw new Error(`Measure "${i.name}" was requested with conflicting aggregate semantics: ${i.aggregate} and ${t.aggregate}.`);return{...l.preferSemaphorFieldRefMetadata(i,t),aggregate:i.aggregate||t.aggregate}}function A(i){var e,r;if("sort"in i)throw new Error("semaphor.records supports orderBy for a single deterministic sort. Multiple sort clauses are not supported by the analytics protocol yet.");if(!E(i))throw new Error("semaphor.records needs at least one field.");const t=B(i.fields);return{version:1,kind:"records",id:i.id,label:i.label,source:h(i),fields:t,dateField:i.dateField?a(i.dateField,"date"):void 0,timeGrain:i.timeGrain,...i.timeWindow?{timeWindow:i.timeWindow}:{},...(e=i.filters)!=null&&e.length?{filters:i.filters}:{},orderBy:i.orderBy?{field:a(i.orderBy.field),direction:i.orderBy.direction}:void 0,inputs:u(i.inputs),...i.relationshipHint?{relationshipHint:i.relationshipHint}:{},limit:i.limit,...i.pagination?{pagination:i.pagination}:{},...i.totals?{totals:{mode:"server",measures:i.totals.measures.map(o=>a(o,"measure"))}}:{},...(r=i.derivedFields)!=null&&r.length?{derivedFields:i.derivedFields}:{}}}function B(i){return i.map(t=>{const e=a(t);if(!e.role)throw new Error(`semaphor.records field "${e.name}" needs an explicit role.`);return e})}function O(i){var e,r,o;const t=h(i);if(t.kind==="sql")throw new Error("semaphor.inputOptions requires a semantic or physical option source.");return{version:1,kind:"inputOptions",id:i.id,label:i.label,inputId:i.inputId,source:t,labelField:a(i.labelField,"dimension"),valueField:a(i.valueField,"dimension"),...i.searchField?{searchField:a(i.searchField,"dimension")}:{},...(e=i.disambiguationFields)!=null&&e.length?{disambiguationFields:i.disambiguationFields.map(n=>a(n,"dimension"))}:{},...i.population?{population:i.population}:{},...i.dependencies?{dependencies:i.dependencies}:{},search:i.search,limit:i.limit,...(r=i.inputs)!=null&&r.length?{inputs:i.inputs.map(n=>m(n))}:{},...(o=i.derivedFields)!=null&&o.length?{derivedFields:i.derivedFields}:{}}}function q(i){var t;return{version:1,kind:"sql",id:i.id,label:i.label,source:i.source,sql:i.sql,...i.defaultParameters?{defaultParameters:i.defaultParameters}:{},...i.pythonCode?{pythonCode:i.pythonCode}:{},...(t=i.fields)!=null&&t.length?{fields:i.fields.map(e=>a(e))}:{},inputs:u(i.inputs),limit:i.limit,...i.pagination?{pagination:i.pagination}:{},rationale:i.rationale}}function P(i){const{id:t,label:e,inputs:r,matrixWindowRequest:o,...n}=i,{queryKind:_,...S}=n;return l.matrixAnalyticalIntentSchema.parse({...S,kind:"matrix"})}function m(i){if("toAnalyticsInput"in i){const n=i.toAnalyticsInput();return{inputId:n.inputId,kind:n.kind,...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}if("id"in i){const n=f(i);return{inputId:n.inputId,kind:n.kind,...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}const t="kind"in i?i.kind:void 0,e="operator"in i?I(i.operator,i.inputId):void 0,r="controlRole"in i?i.controlRole:"role"in i?i.role:void 0,o=z(r)?r:void 0;return{inputId:i.inputId,...t?{kind:t}:{},...o?{controlRole:o}:{},...e?{operator:e}:{},...i.field?{field:i.field}:{},...i.relationshipHint?{relationshipHint:i.relationshipHint}:{}}}function z(i){return i==="grain"||i==="measure"||i==="dimension"||i==="aggregation"||i==="sqlParam"}function C(i){const t=u(i);return t.length>0?t:void 0}function c(i){return(i||[]).map(W)}function T(i){return c(i).filter(t=>t.isActive)}function f(i){if(i.kind==="filter"){const t=I(i.operator,i.id);return{inputId:i.id,kind:i.kind,label:i.label,field:a(i.field,"dimension"),operator:t||"in",...i.relationshipHint?{relationshipHint:i.relationshipHint}:{}}}return{inputId:i.id,kind:i.kind,label:i.label,controlRole:i.role}}function x(i=[]){return i.map(t=>typeof t=="object"?t:{label:String(t),value:t})}function s(i){return i==null?!1:Array.isArray(i)?i.length>0:typeof i=="string"?i.trim().length>0:!0}function W(i){if("toAnalyticsInput"in i)return i.toAnalyticsInput();if("kind"in i&&"isActive"in i)return i;if("id"in i){const t=f(i),e=Object.prototype.hasOwnProperty.call(i,"value")?i.value:i.defaultValue;return{inputId:t.inputId,kind:t.kind,label:t.label,...t.field?{field:t.field}:{},...t.operator?{operator:t.operator}:{},...t.controlRole?{controlRole:t.controlRole}:{},...t.relationshipHint?{relationshipHint:t.relationshipHint}:{},value:e,isActive:s(e)}}return{...i,kind:"filter",isActive:s(i.value),value:i.value}}function h(i){return i.source}function E(i){var t;return!!((t=i.fields)!=null&&t.length)}function a(i,t){return{...i,role:i.role||t}}function u(i){return(i||[]).map(m)}function $(i){if(i)return i}function I(i,t){if(i===void 0)return;const e=y.normalizeSemaphorInputOperator(i);if(!e)throw new Error(`useSemaphorInput "${t}" uses unsupported filter operator "${i}".`);return e}exports.hasSemaphorInputValue=s;exports.normalizeSemaphorInputOptions=x;exports.toSemaphorActiveInputSnapshots=T;exports.toSemaphorAnalysisIntent=v;exports.toSemaphorAnalysisQueryOptions=F;exports.toSemaphorInputBinding=m;exports.toSemaphorInputBindings=C;exports.toSemaphorInputOptionsIntent=O;exports.toSemaphorInputSnapshots=c;exports.toSemaphorInputSpec=f;exports.toSemaphorMatrixIntent=P;exports.toSemaphorMetricIntent=g;exports.toSemaphorRecordsIntent=A;exports.toSemaphorSqlIntent=q;
@@ -1,6 +1,6 @@
1
1
  import { n as y } from "../chunks/operators-C8TxpM4C.js";
2
2
  import { m as v, s as m, p as I, f as S } from "../chunks/validators-BpJDwDnG.js";
3
- import "../chunks/matrix-operation-contract-DITvltmL.js";
3
+ import "../chunks/matrix-operation-contract-D5I-t3i7.js";
4
4
  function F(i) {
5
5
  var e, r, o;
6
6
  const t = w(i);
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../chunks/validators-4dRtYUI1.cjs"),N=require("../chunks/matrix-operation-contract-CCfuWtro.cjs"),E=require("../chunks/report-runtime-context-Bb0ejvVq.cjs"),K=require("../chunks/source-entity-resolution-DeH38dTU.cjs"),y=require("../data-app-sdk-adapters/index.cjs"),Q=require("../chunks/matrix-card-JYMYSX0x.cjs");function W({intent:e,field:r,catalogField:t,relativePath:o}){const i=J({intent:e,field:r,relativePath:o});if(!i||i.allowedRelatedRoles.length===0)return!1;const n=I(r,i.selectedField),s=$(t),c=h(n);return P(s,i.allowedRelatedRoles)?c===s:!1}function U(e){return e.kind==="records"?L(e):e.kind==="metric"?X(e):[]}function $(e){const r=d.normalizeAnalyticsCatalogName(e.role);if(r==="measure")return"measure";if(r==="id")return"id";const t=d.normalizeAnalyticsCatalogDataType(e.dataType);if(r==="date"||t==="date"||t==="datetime")return"date";if(r==="dimension")return"dimension"}function P(e,r){return!!(e&&r.includes(e))}function I(e,r){const t=h(e);if(t)return e.role===t?e:{...e,role:t};const o=r?h(r):void 0;return o?{...e,role:o}:e}function v(e,r){return e.find(t=>T(t,r))}function J({intent:e,field:r,relativePath:t}){if(e.kind==="records")return V(e,r,t);if(e.kind==="metric")return G(e,r,t)}function V(e,r,t){if(t.startsWith("spec.fields."))return{allowedRelatedRoles:["dimension","date","id"]};if(t==="spec.dateField"&&!e.timeWindow)return{allowedRelatedRoles:["date"]};if(t==="spec.orderBy.field"){const o=v(H(e),r);return{selectedField:o,allowedRelatedRoles:o?k(o):[]}}}function G(e,r,t){if(t.startsWith("spec.dimensions."))return{allowedRelatedRoles:["dimension"]};if(t==="spec.orderBy.field"){const o=v(e.dimensions||[],r);return{selectedField:o,allowedRelatedRoles:o?["dimension"]:[]}}}function L(e){var o,i;const r=H(e),t=(o=e.orderBy)!=null&&o.field?v(r,e.orderBy.field):void 0;return b([...r.map(n=>p(n,k(n))),...(i=e.orderBy)!=null&&i.field?[p(I(e.orderBy.field,t),t?k(t):[],{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 X(e){var t,o;const r=(t=e.orderBy)!=null&&t.field?v(e.dimensions||[],e.orderBy.field):void 0;return b([...e.measures.map(i=>p(i,[])),...e.primaryMeasure?[p(e.primaryMeasure,[])]:[],...(e.dimensions||[]).map(i=>p(i,["dimension"])),...e.dateField?[p({...e.dateField,role:"date"},[])]:[],...(o=e.orderBy)!=null&&o.field?[p(I(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 k(e){const r=e?h(e):void 0;return r==="dimension"?["dimension"]:r==="date"?["date"]:r==="id"?["id"]:["dimension","date","id"]}function p(e,r,t={}){return{field:I(e),allowedRelatedRoles:r,...t}}function b(e){const r=[];return e.forEach(t=>{r.some(o=>Y(o,t))||r.push(t)}),r}function H(e){const r=[...e.fields];return e.dateField&&!r.some(t=>w(t,e.dateField))&&r.push({...e.dateField,role:"date"}),r}function Y(e,r){return T(e.field,r.field)&&e.allowedRelatedRoles.join("|")===r.allowedRelatedRoles.join("|")&&(e.unsupportedRelatedRoleMessage||"")===(r.unsupportedRelatedRoleMessage||"")&&(e.recommendedNextStep||"")===(r.recommendedNextStep||"")}function w(e,r){return d.semaphorFieldRefsMatch(e,r)}function T(e,r){return w(e,r)&&Z(h(e),h(r))}function Z(e,r){return!!(e&&(!r||e===r))}function h(e){return $(e)}function j({intent:e,field:r,relativePath:t,baseCatalog:o,fieldCatalogs:i}){const n=g(r,e.source),s=d.semaphorSourcesReferToSameDataset(n,e.source);if(e.kind!=="matrix"&&!s&&!re(e.source,n))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:n};const c=s?o:S(i,n);if(!c)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:n};const a=q(c,r,e.source);return a?e.kind!=="matrix"&&!s&&!ee({intent:e,field:r,catalogField:a,relativePath:t})?{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:n}:{ok:!0,source:n,catalogField:a,usesBaseSource:s}:{ok:!1,code:"missing_field",message:`Field "${r.name}" is not visible on the selected Semaphor source.`,source:n}}function ee({intent:e,field:r,catalogField:t,relativePath:o}){return W({intent:e,field:r,catalogField:t,relativePath:o})}function re(e,r){return e.kind==="semantic"&&r.kind==="semantic"&&e.domainId===r.domainId}function S(e,r){return e.find(t=>F(t,r))}function q(e,r,t){const o=g(r,t);if(F(e,o))return e.fields.find(i=>te(i,r)&&F(e,g(i,e.source)))}function R(e){return d.normalizeAnalyticsCatalogName(e)}function g(e,r){return e.source||r}function F(e,r){return[e.source,...e.sourceAliases||[]].some(t=>d.semaphorSourcesReferToSameDataset(t,r))}function te(e,r){return!!(e.name&&r.name&&e.name===r.name)}function oe(e){const r=[];if(!e.intent.filters)return r;const t=e.intent.source,i=d.mergeSemaphorSourcesByIdentity(e.fieldCatalogs.flatMap(a=>[a.source,...a.sourceAliases??[]])).filter(a=>t.kind==="semantic"?a.kind==="semantic"&&a.domainId===t.domainId:a.kind==="physical"&&a.connectionId===t.connectionId).map(a=>a.kind==="semantic"?{type:"dataset",name:a.datasetName,id:a.datasetId,domainId:a.domainId,connectionId:a.connectionId}:{type:"table",name:a.tableName,database:a.databaseName,schema:a.schemaName,connectionId:a.connectionId,connectionType:a.connectionType,dialect:a.dialect}),n=(a,u)=>{r.push({field:a,path:u,validation:j({...e,field:a,relativePath:u})})},s=(a,u)=>{if(a.derivedField)Object.entries(a.derivedField.inputs).forEach(([l,f])=>n(f.field,`${u}.derivedField.inputs.${l}.field`));else if(a.calculatedFormula)a.calculatedFormula.inputFields.forEach((l,f)=>s(l,`${u}.calculatedFormula.inputFields.${f}`));else{const l=K.resolveSemaphorSourceEntity({entities:i,semanticDomainId:t.kind==="semantic"?t.domainId:void 0,connectionId:t.connectionId,connectionType:t.kind==="physical"?t.connectionType:void 0,dialect:t.kind==="physical"?t.dialect:void 0,fieldEntityType:a.entityType,entityId:a.entityId,entityName:a.entityName,qualifiedHints:[a.qualifiedEntityName]});l.kind==="resolved"?n({name:a.name,source:l.source},u):r.push({field:{name:a.name},path:u,validation:{ok:!1,code:"invalid_source_ref",source:t,message:`Filter field "${a.name}" has no unambiguous source in the visible field catalog (${l.kind}).`}})}},c=(a,u)=>{a.conditions.forEach((l,f)=>s(l.field,`${u}.conditions.${f}.field`)),a.groups.forEach((l,f)=>c(l,`${u}.groups.${f}`))};return c(e.intent.filters,"spec.filters"),r}function M(e,r={}){const t=r.pathPrefix||"analysisOptions";if(e===void 0)return{ok:!0};if(!e||typeof e!="object"||Array.isArray(e))return m(t,"Data App analysis options must be an object.");const o=e,i={};if(o.chartTitle!==void 0){if(typeof o.chartTitle!="string")return m(`${t}.chartTitle`,'Data App analysis option "chartTitle" must be a string.');i.chartTitle=o.chartTitle}if(o.chartType!==void 0){if(typeof o.chartType!="string")return m(`${t}.chartType`,'Data App analysis option "chartType" must be a string.');i.chartType=o.chartType}if(o.driverMode!==void 0){if(!ne(o.driverMode))return m(`${t}.driverMode`,'Data App analysis option "driverMode" must be absolute_delta, largest_negative, largest_positive, positive_and_negative, or all.');i.driverMode=o.driverMode}if(o.includePopulation!==void 0){if(typeof o.includePopulation!="boolean")return m(`${t}.includePopulation`,'Data App analysis option "includePopulation" must be a boolean.');i.includePopulation=o.includePopulation}if(o.calendarContext!==void 0){const n=se(o.calendarContext,{pathPrefix:`${t}.calendarContext`,validateTimezone:r.validateTimezone});if(!n.ok)return n;i.calendarContext=n.calendarContext}return{ok:!0,analysisOptions:i}}function ie(e){const r=e.queries.map((i,n)=>ae(i,n,{fieldCatalogs:e.fieldCatalogs||[],requireFieldCatalog:!!e.requireFieldCatalog,validateTimezone:e.validateTimezone})),t=r.flatMap(i=>i.diagnostics),o=r.map(i=>i.executionResult);return{ok:t.every(i=>i.severity!=="error"),diagnostics:t,queries:r,intents:r.flatMap(i=>i.intent?[i.intent]:[]),executionResults:o}}function ae(e,r,t){const o=`queries.${r}`;try{const i=de(e),n=ke(e,i),s=d.validateSemaphorAnalyticsIntent(i),c=[...ge({querySpec:e,queryId:n,intent:i,pathPrefix:o}),...s.errors.map(u=>_(u,{queryHook:e.queryHook,queryId:n,pathPrefix:o,severity:"error",intent:i})),...s.warnings.map(u=>_(u,{queryHook:e.queryHook,queryId:n,pathPrefix:o,severity:"warning",intent:i})),...ce({querySpec:e,queryId:n,intent:i,pathPrefix:o,fieldCatalogs:t.fieldCatalogs,requireFieldCatalog:t.requireFieldCatalog}),...he({querySpec:e,queryId:n,intent:i,pathPrefix:o,validateTimezone:t.validateTimezone})],a=Se(s,c);return{queryHook:e.queryHook,queryId:n,intent:i,diagnostics:c,executionResult:x({intent:i,validation:a,diagnostics:c})}}catch(i){const n={severity:"error",code:"invalid_query_spec",message:i instanceof Error?i.message:String(i),path:o,queryHook:e.queryHook,queryId:O(e.spec)},s=z([n]);return{queryHook:e.queryHook,queryId:n.queryId,diagnostics:[n],executionResult:x({validation:s,diagnostics:[n]})}}}function m(e,r){return{ok:!1,issues:[{code:"invalid_analysis_option",message:r,path:e}]}}function D(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function ne(e){return e==="absolute_delta"||e==="largest_negative"||e==="largest_positive"||e==="positive_and_negative"||e==="all"}function se(e,r){if(!e||typeof e!="object"||Array.isArray(e))return m(r.pathPrefix,'Data App analysis option "calendarContext" must be an object.');const t=e,o=t.tz;let i=o;if(typeof o=="string"&&r.validateTimezone&&(i=r.validateTimezone(o)),i===null)return m(`${r.pathPrefix}.tz`,'Data App analysis option "calendarContext.tz" must be a valid timezone string.');const n=E.parseCalendarContext({...t,tz:i});if(!n.ok){const s=n.issues[0];return m(s!=null&&s.path?`${r.pathPrefix}.${s.path}`:r.pathPrefix,`Data App analysis option "calendarContext" is invalid: ${(s==null?void 0:s.message)??"invalid value"}.`)}return{ok:!0,calendarContext:n.value}}function de(e){return le(e.spec)}function le(e){if(!D(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 ce(e){if(e.intent.kind==="sql")return[];if(e.fieldCatalogs.length===0&&!e.requireFieldCatalog)return[];const r=S(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:d.getAnalyticsIntentId(e.intent),source:e.intent.source}];const t=fe({...e,catalog:r}),o={...r,fields:[...r.fields,...ve(e.intent,r,e.intent.source)]};return[...t,...ue({...e,fieldCatalogs:e.fieldCatalogs}),...me({...e,catalog:o,fieldCatalogs:e.fieldCatalogs}),...pe({...e,catalog:o,fieldCatalogs:e.fieldCatalogs})]}function ue(e){var t;if(e.intent.kind!=="inputOptions"||((t=e.intent.population)==null?void 0:t.kind)!=="related_population")return[];const r=e.intent.population.baseSource;return S(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:d.getAnalyticsIntentId(e.intent),source:r}]}function fe(e){const r=B(e.intent);if(r.length===0)return[];const t=[],o=new Set;return r.forEach((i,n)=>{const s=`${e.pathPrefix}.spec.derivedFields.${n}`,c=R(i.name);c&&(o.has(c)&&t.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:d.getAnalyticsIntentId(e.intent),source:e.intent.source}),o.add(c),e.catalog.fields.some(a=>R(a.name)===c)&&t.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:d.getAnalyticsIntentId(e.intent),source:e.intent.source})),Object.entries(i.inputs||{}).forEach(([a,u])=>{const l=qe(u);if(!l)return;const f=g(l,e.intent.source);if(!d.semaphorSourcesReferToSameDataset(f,e.intent.source)){t.push({severity:"error",code:"unsupported_derived_field_source",message:`Derived field "${i.name}" input "${a}" references a different Semaphor source. App-local derived fields must use fields from the query source.`,path:`${s}.inputs.${a}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:f,field:l});return}q(e.catalog,l,e.intent.source)||t.push({severity:"error",code:"missing_field",message:`Derived field "${i.name}" input "${a}" references field "${l.name}", which is not visible on the selected Semaphor source.`,path:`${s}.inputs.${a}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:f,field:l})})}),t}function me(e){const r=Ie(e.intent).map(({field:t,path:o})=>{const i=j({intent:e.intent,field:t,relativePath:o,baseCatalog:e.catalog,fieldCatalogs:e.fieldCatalogs});return{field:t,path:o,validation:i}});return e.intent.kind==="matrix"&&r.push(...oe({intent:e.intent,baseCatalog:e.catalog,fieldCatalogs:e.fieldCatalogs})),r.flatMap(({field:t,path:o,validation:i})=>i.ok?[]:[{severity:"error",code:i.code,message:i.message,path:`${e.pathPrefix}.${o}${i.pathSuffix||""}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i.source,field:t}])}function pe(e){return("inputs"in e.intent?e.intent.inputs||[]:[]).flatMap((t,o)=>{if(!t.field)return[];const i=g(t.field,e.intent.source);if(!d.semaphorSourcesReferToSameDataset(i,e.intent.source)){if(ye(e.intent,i)){const n=S(e.fieldCatalogs,i);return n?q(n,t.field,i)?[]:[{severity:"error",code:"missing_field",message:`Input "${t.inputId}" references field "${t.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${o}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]:[{severity:"error",code:"invalid_source_ref",message:`Input "${t.inputId}" references a Semaphor source that is not present in the visible field catalog.`,path:`${e.pathPrefix}.spec.inputs.${o}.field.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]}return[{severity:"error",code:"unsupported_input_filter_composition",message:`Input "${t.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.${o}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]}return q(e.catalog,t.field,e.intent.source)?[]:[{severity:"error",code:"missing_field",message:`Input "${t.inputId}" references field "${t.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${o}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]})}function ye(e,r){return e.source.kind==="semantic"&&r.kind==="semantic"&&r.domainId===e.source.domainId}function he(e){if(e.querySpec.spec.queryKind!=="analysis")return[];const r=M(e.querySpec.spec,{pathPrefix:`${e.pathPrefix}.spec`,validateTimezone:e.validateTimezone});return r.ok?[]:r.issues.map(t=>({severity:"error",code:t.code,message:t.message,path:t.path,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:e.intent.source}))}function ge(e){if(e.querySpec.spec.queryKind==="matrix"){const r=N.matrixWindowRequestSchema.safeParse(e.querySpec.spec.matrixWindowRequest);return r.success?[]:r.error.issues.map(t=>({severity:"error",code:"invalid_query_spec",message:t.message,path:[e.pathPrefix,"spec","matrixWindowRequest",...t.path].join("."),queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent)}))}return e.querySpec.spec.queryKind!=="sql"?[]:D(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:d.getAnalyticsIntentId(e.intent)}]:[]:[]}function Ie(e){return e.kind==="metric"?[...e.measures.map((r,t)=>({field:r,path:`spec.measures.${t}`})),...e.primaryMeasure?[{field:e.primaryMeasure,path:"spec.primaryMeasure"}]:[],...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...(e.dimensions||[]).map((r,t)=>({field:r,path:`spec.dimensions.${t}`})),...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.field`}))]:e.kind==="records"?[...e.fields.map((r,t)=>({field:r,path:`spec.fields.${t}`})),...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.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,t)=>({field:r,path:`spec.disambiguationFields.${t}`}))]:e.kind==="matrix"?Q.matrixDefinitionFields(e).flatMap((r,t)=>r.derivedField||r.name==="*"?[]:[{field:r,path:`spec.fields.${t}`}]):[]}function B(e){return!("derivedFields"in e)||!Array.isArray(e.derivedFields)?[]:e.derivedFields}function ve(e,r,t){return B(e).map(o=>({name:o.name,label:o.label,role:o.resultRole,dataType:o.dataType,source:r.source||t,...o.defaultAggregate?{aggregate:o.defaultAggregate}:{}}))}function qe(e){if(!(!e||typeof e!="object"))return e.field}function _(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:d.getAnalyticsIntentId(r.intent),source:r.intent.source}}function Se(e,r){const t=z(r);return{ok:t.ok&&e.ok,errors:C([...e.errors,...t.errors]),warnings:C([...e.warnings,...t.warnings]),repairHints:[...e.repairHints,...t.repairHints]}}function z(e){const r=e.filter(o=>o.severity==="error").map(A),t=e.filter(o=>o.severity==="warning").map(A);return{ok:r.length===0,errors:r,warnings:t,repairHints:r.map(o=>{var i,n;return{code:o.code,message:o.message,fieldRole:o.fieldRole,invalidField:(i=o.repairHint)==null?void 0:i.invalidField,recommendedNextStep:((n=o.repairHint)==null?void 0:n.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 C(e){const r=new Set;return e.filter(t=>{const o=`${t.code}:${t.path||""}:${t.message}`;return r.has(o)?!1:(r.add(o),!0)})}function x(e){var t;const r=e.diagnostics.filter(o=>o.severity==="error");return{intentId:d.getAnalyticsIntentId(e.intent),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(o=>o.code==="missing_field").flatMap(o=>{var i;return(i=o.field)!=null&&i.name?[o.field.name]:[]}),warnings:e.diagnostics.filter(o=>o.severity==="warning").map(o=>o.message),metadata:{validationKind:"data_app_sdk_query_spec"}}}function ke(e,r){return d.getAnalyticsIntentId(r)||O(e.spec)}function O(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=I;exports.findMatchingRelatedProjectionField=v;exports.isAllowedRelatedProjectionRole=P;exports.normalizeSemaphorAnalysisQueryOptions=M;exports.normalizeSemaphorFieldRole=$;exports.relatedProjectionFieldCandidatesForIntent=U;exports.validateSemaphorDataAppQuerySpecs=ie;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../chunks/validators-4dRtYUI1.cjs"),N=require("../chunks/matrix-operation-contract-BiUMcd6G.cjs"),E=require("../chunks/report-runtime-context-Bb0ejvVq.cjs"),K=require("../chunks/source-entity-resolution-DeH38dTU.cjs"),y=require("../data-app-sdk-adapters/index.cjs"),Q=require("../chunks/matrix-card-DzkJRoM4.cjs");function W({intent:e,field:r,catalogField:t,relativePath:o}){const i=J({intent:e,field:r,relativePath:o});if(!i||i.allowedRelatedRoles.length===0)return!1;const n=I(r,i.selectedField),s=$(t),c=h(n);return P(s,i.allowedRelatedRoles)?c===s:!1}function U(e){return e.kind==="records"?L(e):e.kind==="metric"?X(e):[]}function $(e){const r=d.normalizeAnalyticsCatalogName(e.role);if(r==="measure")return"measure";if(r==="id")return"id";const t=d.normalizeAnalyticsCatalogDataType(e.dataType);if(r==="date"||t==="date"||t==="datetime")return"date";if(r==="dimension")return"dimension"}function P(e,r){return!!(e&&r.includes(e))}function I(e,r){const t=h(e);if(t)return e.role===t?e:{...e,role:t};const o=r?h(r):void 0;return o?{...e,role:o}:e}function v(e,r){return e.find(t=>T(t,r))}function J({intent:e,field:r,relativePath:t}){if(e.kind==="records")return V(e,r,t);if(e.kind==="metric")return G(e,r,t)}function V(e,r,t){if(t.startsWith("spec.fields."))return{allowedRelatedRoles:["dimension","date","id"]};if(t==="spec.dateField"&&!e.timeWindow)return{allowedRelatedRoles:["date"]};if(t==="spec.orderBy.field"){const o=v(H(e),r);return{selectedField:o,allowedRelatedRoles:o?k(o):[]}}}function G(e,r,t){if(t.startsWith("spec.dimensions."))return{allowedRelatedRoles:["dimension"]};if(t==="spec.orderBy.field"){const o=v(e.dimensions||[],r);return{selectedField:o,allowedRelatedRoles:o?["dimension"]:[]}}}function L(e){var o,i;const r=H(e),t=(o=e.orderBy)!=null&&o.field?v(r,e.orderBy.field):void 0;return b([...r.map(n=>p(n,k(n))),...(i=e.orderBy)!=null&&i.field?[p(I(e.orderBy.field,t),t?k(t):[],{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 X(e){var t,o;const r=(t=e.orderBy)!=null&&t.field?v(e.dimensions||[],e.orderBy.field):void 0;return b([...e.measures.map(i=>p(i,[])),...e.primaryMeasure?[p(e.primaryMeasure,[])]:[],...(e.dimensions||[]).map(i=>p(i,["dimension"])),...e.dateField?[p({...e.dateField,role:"date"},[])]:[],...(o=e.orderBy)!=null&&o.field?[p(I(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 k(e){const r=e?h(e):void 0;return r==="dimension"?["dimension"]:r==="date"?["date"]:r==="id"?["id"]:["dimension","date","id"]}function p(e,r,t={}){return{field:I(e),allowedRelatedRoles:r,...t}}function b(e){const r=[];return e.forEach(t=>{r.some(o=>Y(o,t))||r.push(t)}),r}function H(e){const r=[...e.fields];return e.dateField&&!r.some(t=>w(t,e.dateField))&&r.push({...e.dateField,role:"date"}),r}function Y(e,r){return T(e.field,r.field)&&e.allowedRelatedRoles.join("|")===r.allowedRelatedRoles.join("|")&&(e.unsupportedRelatedRoleMessage||"")===(r.unsupportedRelatedRoleMessage||"")&&(e.recommendedNextStep||"")===(r.recommendedNextStep||"")}function w(e,r){return d.semaphorFieldRefsMatch(e,r)}function T(e,r){return w(e,r)&&Z(h(e),h(r))}function Z(e,r){return!!(e&&(!r||e===r))}function h(e){return $(e)}function j({intent:e,field:r,relativePath:t,baseCatalog:o,fieldCatalogs:i}){const n=g(r,e.source),s=d.semaphorSourcesReferToSameDataset(n,e.source);if(e.kind!=="matrix"&&!s&&!re(e.source,n))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:n};const c=s?o:S(i,n);if(!c)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:n};const a=q(c,r,e.source);return a?e.kind!=="matrix"&&!s&&!ee({intent:e,field:r,catalogField:a,relativePath:t})?{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:n}:{ok:!0,source:n,catalogField:a,usesBaseSource:s}:{ok:!1,code:"missing_field",message:`Field "${r.name}" is not visible on the selected Semaphor source.`,source:n}}function ee({intent:e,field:r,catalogField:t,relativePath:o}){return W({intent:e,field:r,catalogField:t,relativePath:o})}function re(e,r){return e.kind==="semantic"&&r.kind==="semantic"&&e.domainId===r.domainId}function S(e,r){return e.find(t=>F(t,r))}function q(e,r,t){const o=g(r,t);if(F(e,o))return e.fields.find(i=>te(i,r)&&F(e,g(i,e.source)))}function R(e){return d.normalizeAnalyticsCatalogName(e)}function g(e,r){return e.source||r}function F(e,r){return[e.source,...e.sourceAliases||[]].some(t=>d.semaphorSourcesReferToSameDataset(t,r))}function te(e,r){return!!(e.name&&r.name&&e.name===r.name)}function oe(e){const r=[];if(!e.intent.filters)return r;const t=e.intent.source,i=d.mergeSemaphorSourcesByIdentity(e.fieldCatalogs.flatMap(a=>[a.source,...a.sourceAliases??[]])).filter(a=>t.kind==="semantic"?a.kind==="semantic"&&a.domainId===t.domainId:a.kind==="physical"&&a.connectionId===t.connectionId).map(a=>a.kind==="semantic"?{type:"dataset",name:a.datasetName,id:a.datasetId,domainId:a.domainId,connectionId:a.connectionId}:{type:"table",name:a.tableName,database:a.databaseName,schema:a.schemaName,connectionId:a.connectionId,connectionType:a.connectionType,dialect:a.dialect}),n=(a,u)=>{r.push({field:a,path:u,validation:j({...e,field:a,relativePath:u})})},s=(a,u)=>{if(a.derivedField)Object.entries(a.derivedField.inputs).forEach(([l,f])=>n(f.field,`${u}.derivedField.inputs.${l}.field`));else if(a.calculatedFormula)a.calculatedFormula.inputFields.forEach((l,f)=>s(l,`${u}.calculatedFormula.inputFields.${f}`));else{const l=K.resolveSemaphorSourceEntity({entities:i,semanticDomainId:t.kind==="semantic"?t.domainId:void 0,connectionId:t.connectionId,connectionType:t.kind==="physical"?t.connectionType:void 0,dialect:t.kind==="physical"?t.dialect:void 0,fieldEntityType:a.entityType,entityId:a.entityId,entityName:a.entityName,qualifiedHints:[a.qualifiedEntityName]});l.kind==="resolved"?n({name:a.name,source:l.source},u):r.push({field:{name:a.name},path:u,validation:{ok:!1,code:"invalid_source_ref",source:t,message:`Filter field "${a.name}" has no unambiguous source in the visible field catalog (${l.kind}).`}})}},c=(a,u)=>{a.conditions.forEach((l,f)=>s(l.field,`${u}.conditions.${f}.field`)),a.groups.forEach((l,f)=>c(l,`${u}.groups.${f}`))};return c(e.intent.filters,"spec.filters"),r}function M(e,r={}){const t=r.pathPrefix||"analysisOptions";if(e===void 0)return{ok:!0};if(!e||typeof e!="object"||Array.isArray(e))return m(t,"Data App analysis options must be an object.");const o=e,i={};if(o.chartTitle!==void 0){if(typeof o.chartTitle!="string")return m(`${t}.chartTitle`,'Data App analysis option "chartTitle" must be a string.');i.chartTitle=o.chartTitle}if(o.chartType!==void 0){if(typeof o.chartType!="string")return m(`${t}.chartType`,'Data App analysis option "chartType" must be a string.');i.chartType=o.chartType}if(o.driverMode!==void 0){if(!ne(o.driverMode))return m(`${t}.driverMode`,'Data App analysis option "driverMode" must be absolute_delta, largest_negative, largest_positive, positive_and_negative, or all.');i.driverMode=o.driverMode}if(o.includePopulation!==void 0){if(typeof o.includePopulation!="boolean")return m(`${t}.includePopulation`,'Data App analysis option "includePopulation" must be a boolean.');i.includePopulation=o.includePopulation}if(o.calendarContext!==void 0){const n=se(o.calendarContext,{pathPrefix:`${t}.calendarContext`,validateTimezone:r.validateTimezone});if(!n.ok)return n;i.calendarContext=n.calendarContext}return{ok:!0,analysisOptions:i}}function ie(e){const r=e.queries.map((i,n)=>ae(i,n,{fieldCatalogs:e.fieldCatalogs||[],requireFieldCatalog:!!e.requireFieldCatalog,validateTimezone:e.validateTimezone})),t=r.flatMap(i=>i.diagnostics),o=r.map(i=>i.executionResult);return{ok:t.every(i=>i.severity!=="error"),diagnostics:t,queries:r,intents:r.flatMap(i=>i.intent?[i.intent]:[]),executionResults:o}}function ae(e,r,t){const o=`queries.${r}`;try{const i=de(e),n=ke(e,i),s=d.validateSemaphorAnalyticsIntent(i),c=[...ge({querySpec:e,queryId:n,intent:i,pathPrefix:o}),...s.errors.map(u=>_(u,{queryHook:e.queryHook,queryId:n,pathPrefix:o,severity:"error",intent:i})),...s.warnings.map(u=>_(u,{queryHook:e.queryHook,queryId:n,pathPrefix:o,severity:"warning",intent:i})),...ce({querySpec:e,queryId:n,intent:i,pathPrefix:o,fieldCatalogs:t.fieldCatalogs,requireFieldCatalog:t.requireFieldCatalog}),...he({querySpec:e,queryId:n,intent:i,pathPrefix:o,validateTimezone:t.validateTimezone})],a=Se(s,c);return{queryHook:e.queryHook,queryId:n,intent:i,diagnostics:c,executionResult:x({intent:i,validation:a,diagnostics:c})}}catch(i){const n={severity:"error",code:"invalid_query_spec",message:i instanceof Error?i.message:String(i),path:o,queryHook:e.queryHook,queryId:O(e.spec)},s=z([n]);return{queryHook:e.queryHook,queryId:n.queryId,diagnostics:[n],executionResult:x({validation:s,diagnostics:[n]})}}}function m(e,r){return{ok:!1,issues:[{code:"invalid_analysis_option",message:r,path:e}]}}function D(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function ne(e){return e==="absolute_delta"||e==="largest_negative"||e==="largest_positive"||e==="positive_and_negative"||e==="all"}function se(e,r){if(!e||typeof e!="object"||Array.isArray(e))return m(r.pathPrefix,'Data App analysis option "calendarContext" must be an object.');const t=e,o=t.tz;let i=o;if(typeof o=="string"&&r.validateTimezone&&(i=r.validateTimezone(o)),i===null)return m(`${r.pathPrefix}.tz`,'Data App analysis option "calendarContext.tz" must be a valid timezone string.');const n=E.parseCalendarContext({...t,tz:i});if(!n.ok){const s=n.issues[0];return m(s!=null&&s.path?`${r.pathPrefix}.${s.path}`:r.pathPrefix,`Data App analysis option "calendarContext" is invalid: ${(s==null?void 0:s.message)??"invalid value"}.`)}return{ok:!0,calendarContext:n.value}}function de(e){return le(e.spec)}function le(e){if(!D(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 ce(e){if(e.intent.kind==="sql")return[];if(e.fieldCatalogs.length===0&&!e.requireFieldCatalog)return[];const r=S(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:d.getAnalyticsIntentId(e.intent),source:e.intent.source}];const t=fe({...e,catalog:r}),o={...r,fields:[...r.fields,...ve(e.intent,r,e.intent.source)]};return[...t,...ue({...e,fieldCatalogs:e.fieldCatalogs}),...me({...e,catalog:o,fieldCatalogs:e.fieldCatalogs}),...pe({...e,catalog:o,fieldCatalogs:e.fieldCatalogs})]}function ue(e){var t;if(e.intent.kind!=="inputOptions"||((t=e.intent.population)==null?void 0:t.kind)!=="related_population")return[];const r=e.intent.population.baseSource;return S(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:d.getAnalyticsIntentId(e.intent),source:r}]}function fe(e){const r=B(e.intent);if(r.length===0)return[];const t=[],o=new Set;return r.forEach((i,n)=>{const s=`${e.pathPrefix}.spec.derivedFields.${n}`,c=R(i.name);c&&(o.has(c)&&t.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:d.getAnalyticsIntentId(e.intent),source:e.intent.source}),o.add(c),e.catalog.fields.some(a=>R(a.name)===c)&&t.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:d.getAnalyticsIntentId(e.intent),source:e.intent.source})),Object.entries(i.inputs||{}).forEach(([a,u])=>{const l=qe(u);if(!l)return;const f=g(l,e.intent.source);if(!d.semaphorSourcesReferToSameDataset(f,e.intent.source)){t.push({severity:"error",code:"unsupported_derived_field_source",message:`Derived field "${i.name}" input "${a}" references a different Semaphor source. App-local derived fields must use fields from the query source.`,path:`${s}.inputs.${a}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:f,field:l});return}q(e.catalog,l,e.intent.source)||t.push({severity:"error",code:"missing_field",message:`Derived field "${i.name}" input "${a}" references field "${l.name}", which is not visible on the selected Semaphor source.`,path:`${s}.inputs.${a}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:f,field:l})})}),t}function me(e){const r=Ie(e.intent).map(({field:t,path:o})=>{const i=j({intent:e.intent,field:t,relativePath:o,baseCatalog:e.catalog,fieldCatalogs:e.fieldCatalogs});return{field:t,path:o,validation:i}});return e.intent.kind==="matrix"&&r.push(...oe({intent:e.intent,baseCatalog:e.catalog,fieldCatalogs:e.fieldCatalogs})),r.flatMap(({field:t,path:o,validation:i})=>i.ok?[]:[{severity:"error",code:i.code,message:i.message,path:`${e.pathPrefix}.${o}${i.pathSuffix||""}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i.source,field:t}])}function pe(e){return("inputs"in e.intent?e.intent.inputs||[]:[]).flatMap((t,o)=>{if(!t.field)return[];const i=g(t.field,e.intent.source);if(!d.semaphorSourcesReferToSameDataset(i,e.intent.source)){if(ye(e.intent,i)){const n=S(e.fieldCatalogs,i);return n?q(n,t.field,i)?[]:[{severity:"error",code:"missing_field",message:`Input "${t.inputId}" references field "${t.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${o}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]:[{severity:"error",code:"invalid_source_ref",message:`Input "${t.inputId}" references a Semaphor source that is not present in the visible field catalog.`,path:`${e.pathPrefix}.spec.inputs.${o}.field.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]}return[{severity:"error",code:"unsupported_input_filter_composition",message:`Input "${t.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.${o}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]}return q(e.catalog,t.field,e.intent.source)?[]:[{severity:"error",code:"missing_field",message:`Input "${t.inputId}" references field "${t.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${o}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:i,field:t.field}]})}function ye(e,r){return e.source.kind==="semantic"&&r.kind==="semantic"&&r.domainId===e.source.domainId}function he(e){if(e.querySpec.spec.queryKind!=="analysis")return[];const r=M(e.querySpec.spec,{pathPrefix:`${e.pathPrefix}.spec`,validateTimezone:e.validateTimezone});return r.ok?[]:r.issues.map(t=>({severity:"error",code:t.code,message:t.message,path:t.path,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent),source:e.intent.source}))}function ge(e){if(e.querySpec.spec.queryKind==="matrix"){const r=N.matrixWindowRequestSchema.safeParse(e.querySpec.spec.matrixWindowRequest);return r.success?[]:r.error.issues.map(t=>({severity:"error",code:"invalid_query_spec",message:t.message,path:[e.pathPrefix,"spec","matrixWindowRequest",...t.path].join("."),queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:d.getAnalyticsIntentId(e.intent)}))}return e.querySpec.spec.queryKind!=="sql"?[]:D(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:d.getAnalyticsIntentId(e.intent)}]:[]:[]}function Ie(e){return e.kind==="metric"?[...e.measures.map((r,t)=>({field:r,path:`spec.measures.${t}`})),...e.primaryMeasure?[{field:e.primaryMeasure,path:"spec.primaryMeasure"}]:[],...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...(e.dimensions||[]).map((r,t)=>({field:r,path:`spec.dimensions.${t}`})),...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.field`}))]:e.kind==="records"?[...e.fields.map((r,t)=>({field:r,path:`spec.fields.${t}`})),...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.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,t)=>({field:r,path:`spec.disambiguationFields.${t}`}))]:e.kind==="matrix"?Q.matrixDefinitionFields(e).flatMap((r,t)=>r.derivedField||r.name==="*"?[]:[{field:r,path:`spec.fields.${t}`}]):[]}function B(e){return!("derivedFields"in e)||!Array.isArray(e.derivedFields)?[]:e.derivedFields}function ve(e,r,t){return B(e).map(o=>({name:o.name,label:o.label,role:o.resultRole,dataType:o.dataType,source:r.source||t,...o.defaultAggregate?{aggregate:o.defaultAggregate}:{}}))}function qe(e){if(!(!e||typeof e!="object"))return e.field}function _(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:d.getAnalyticsIntentId(r.intent),source:r.intent.source}}function Se(e,r){const t=z(r);return{ok:t.ok&&e.ok,errors:C([...e.errors,...t.errors]),warnings:C([...e.warnings,...t.warnings]),repairHints:[...e.repairHints,...t.repairHints]}}function z(e){const r=e.filter(o=>o.severity==="error").map(A),t=e.filter(o=>o.severity==="warning").map(A);return{ok:r.length===0,errors:r,warnings:t,repairHints:r.map(o=>{var i,n;return{code:o.code,message:o.message,fieldRole:o.fieldRole,invalidField:(i=o.repairHint)==null?void 0:i.invalidField,recommendedNextStep:((n=o.repairHint)==null?void 0:n.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 C(e){const r=new Set;return e.filter(t=>{const o=`${t.code}:${t.path||""}:${t.message}`;return r.has(o)?!1:(r.add(o),!0)})}function x(e){var t;const r=e.diagnostics.filter(o=>o.severity==="error");return{intentId:d.getAnalyticsIntentId(e.intent),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(o=>o.code==="missing_field").flatMap(o=>{var i;return(i=o.field)!=null&&i.name?[o.field.name]:[]}),warnings:e.diagnostics.filter(o=>o.severity==="warning").map(o=>o.message),metadata:{validationKind:"data_app_sdk_query_spec"}}}function ke(e,r){return d.getAnalyticsIntentId(r)||O(e.spec)}function O(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=I;exports.findMatchingRelatedProjectionField=v;exports.isAllowedRelatedProjectionRole=P;exports.normalizeSemaphorAnalysisQueryOptions=M;exports.normalizeSemaphorFieldRole=$;exports.relatedProjectionFieldCandidatesForIntent=U;exports.validateSemaphorDataAppQuerySpecs=ie;
@@ -1,9 +1,9 @@
1
1
  import { a7 as b, aa as N, s as O, aO as v, q as E, a2 as K, aK as l } from "../chunks/validators-BpJDwDnG.js";
2
- import { u as Q } from "../chunks/matrix-operation-contract-DITvltmL.js";
2
+ import { u as Q } from "../chunks/matrix-operation-contract-D5I-t3i7.js";
3
3
  import { p as W } from "../chunks/report-runtime-context-nCHl3uHC.js";
4
4
  import { m as U } from "../chunks/source-entity-resolution-Dm4in31q.js";
5
5
  import { toSemaphorMetricIntent as J, toSemaphorAnalysisIntent as V, toSemaphorRecordsIntent as G, toSemaphorSqlIntent as L, toSemaphorMatrixIntent as X, toSemaphorInputOptionsIntent as Y } from "../data-app-sdk-adapters/index.js";
6
- import { m as Z } from "../chunks/matrix-card-CoQiV9pN.js";
6
+ import { m as Z } from "../chunks/matrix-card-5R39CCdj.js";
7
7
  function ee({
8
8
  intent: e,
9
9
  field: r,