All files / adapters utils.ts

45.61% Statements 78/171
34.5% Branches 49/142
72.41% Functions 21/29
46.87% Lines 75/160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812                                                  19x 19x 19x 19x 19x   19x 4x 2x                                                           154x 154x 154x             51x 51x 51x   51x                                                         42x 42x 42x       42x                         12x           12x           12x         12x 12x 3x       9x   9x 9x 9x     12x 9x 9x       12x           12x         12x       12x         9x 9x       9x     9x 9x                     9x 9x             9x                                                             42x 42x 42x 42x   42x                                                           27x   27x               27x               1x 1x                     10x                     16x                                                                                                         29x                                                                     11x       23x         18x         11x 23x   18x           5x                   11x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 2x 2x             2x                                         2x 2x                               2x     2x 2x         2x   2x          
/**
 * Shared utilities for framework adapters
 * Common functions used across Express, Fastify, Next.js, and Hono adapters
 */
 
import { format } from 'sql-formatter'
import type {
  SemanticLayerCompiler,
  SemanticQuery,
  SecurityContext,
  QueryAnalysis,
  CubeDiscoveryResult,
  QuerySuggestion,
  AIValidationResult
} from '../server'
import {
  discoverCubes,
  suggestQuery,
  aiValidateQuery
} from '../server'
 
/**
 * Calculate query complexity based on query structure
 */
export function calculateQueryComplexity(query: SemanticQuery): string {
  let complexity = 0
  complexity += (query.measures?.length || 0) * 1
  complexity += (query.dimensions?.length || 0) * 1
  complexity += (query.filters?.length || 0) * 2
  complexity += (query.timeDimensions?.length || 0) * 3
 
  if (complexity <= 5) return 'low'
  if (complexity <= 15) return 'medium'
  return 'high'
}
 
/**
 * Recursively extract cube names from filters (handles nested AND/OR logical filters)
 * Similar to query-planner's extractCubeNamesFromFilter
 */
function extractCubeNamesFromFilter(filter: any, cubesSet: Set<string>): void {
  // Handle logical filters (AND/OR) - Server format: { and: [...] } or { or: [...] }
  if ('and' in filter || 'or' in filter) {
    const logicalFilters = filter.and || filter.or || []
    for (const subFilter of logicalFilters) {
      extractCubeNamesFromFilter(subFilter, cubesSet)
    }
    return
  }
 
  // Handle simple filter condition
  if ('member' in filter) {
    const [cubeName] = filter.member.split('.')
    if (cubeName) {
      cubesSet.add(cubeName)
    }
  }
}
 
/**
 * Generate a unique request ID
 */
export function generateRequestId(): string {
  const timestamp = Date.now()
  const random = Math.random().toString(36).substring(2, 9)
  return `${timestamp}-${random}`
}
 
/**
 * Build transformed query metadata for Cube.js compatibility
 */
export function buildTransformedQuery(query: SemanticQuery): any {
  const sortedDimensions = query.dimensions || []
  const sortedTimeDimensions = query.timeDimensions || []
  const measures = query.measures || []
 
  return {
    sortedDimensions,
    sortedTimeDimensions,
    timeDimensions: sortedTimeDimensions,
    measures,
    leafMeasureAdditive: true,
    leafMeasures: measures,
    measureToLeafMeasures: {},
    hasNoTimeDimensionsWithoutGranularity: true,
    allFiltersWithinSelectedDimensions: true,
    isAdditive: true,
    granularityHierarchies: {},
    hasMultipliedMeasures: false,
    hasCumulativeMeasures: false,
    windowGranularity: null,
    filterDimensionsSingleValueEqual: {},
    ownedDimensions: sortedDimensions,
    ownedTimeDimensionsWithRollupGranularity: [],
    ownedTimeDimensionsAsIs: [],
    allBackAliasMembers: {},
    hasMultiStage: false
  }
}
 
/**
 * Get database type from semantic layer
 */
export function getDatabaseType(semanticLayer: SemanticLayerCompiler): string {
  // Extract from the semantic layer's database executor
  Eif (semanticLayer.hasExecutor()) {
    const executor = (semanticLayer as any).databaseExecutor
    Iif (executor?.engineType) {
      return executor.engineType
    }
  }
  return 'postgres' // default fallback
}
 
/**
 * Helper function to handle dry-run logic for all adapters
 */
export async function handleDryRun(
  query: SemanticQuery,
  securityContext: SecurityContext,
  semanticLayer: SemanticLayerCompiler
) {
  // Check for funnel queries FIRST - they have their own dry-run path
  // Funnel queries send { funnel: { ... } } and need special SQL generation
  Iif (query.funnel && query.funnel.steps?.length >= 2) {
    return handleFunnelDryRun(query, securityContext, semanticLayer)
  }
 
  // Check for flow queries - they have their own dry-run path
  // Flow queries send { flow: { ... } } and need special SQL generation
  Iif (query.flow && query.flow.bindingKey && query.flow.eventDimension) {
    return handleFlowDryRun(query, securityContext, semanticLayer)
  }
 
  // Check for retention queries - they have their own dry-run path
  // Retention queries send { retention: { ... } } and need special SQL generation
  Iif (query.retention && query.retention.bindingKey && query.retention.timeDimension) {
    return handleRetentionDryRun(query, securityContext, semanticLayer)
  }
 
  // Validate query structure and field existence
  const validation = semanticLayer.validateQuery(query)
  if (!validation.isValid) {
    throw new Error(`Query validation failed: ${validation.errors.join(', ')}`)
  }
 
  // Get all referenced cubes from measures and dimensions
  const referencedCubes = new Set<string>()
  
  query.measures?.forEach(measure => {
    const cubeName = measure.split('.')[0]
    referencedCubes.add(cubeName)
  })
  
  query.dimensions?.forEach(dimension => {
    const cubeName = dimension.split('.')[0]
    referencedCubes.add(cubeName)
  })
 
  // Also include cubes from timeDimensions and filters
  query.timeDimensions?.forEach(timeDimension => {
    const cubeName = timeDimension.dimension.split('.')[0]
    referencedCubes.add(cubeName)
  })
 
  // Extract cubes from filters using recursive extraction to handle nested AND/OR
  query.filters?.forEach(filter => {
    extractCubeNamesFromFilter(filter, referencedCubes)
  })
 
  // Determine if this is a multi-cube query
  const isMultiCube = referencedCubes.size > 1
 
  // Generate SQL using the semantic layer compiler
  let sqlResult
  Iif (isMultiCube) {
    // For multi-cube queries, use the new multi-cube SQL generation
    sqlResult = await semanticLayer.generateMultiCubeSQL(query, securityContext)
  } else {
    // For single cube queries, use the cube-specific SQL generation
    const cubeName = Array.from(referencedCubes)[0]
    sqlResult = await semanticLayer.generateSQL(cubeName, query, securityContext)
  }
 
  // Create normalized queries array (for Cube.js compatibility)
  const normalizedQueries = Array.from(referencedCubes).map(cubeName => ({
    cube: cubeName,
    query: {
      measures: query.measures?.filter(m => m.startsWith(cubeName + '.')) || [],
      dimensions: query.dimensions?.filter(d => d.startsWith(cubeName + '.')) || [],
      filters: query.filters || [],
      timeDimensions: query.timeDimensions || [],
      order: query.order || {},
      limit: query.limit,
      offset: query.offset
    }
  }))
 
  // Generate query analysis for debugging transparency
  let analysis: QueryAnalysis | undefined
  try {
    analysis = semanticLayer.analyzeQuery(query, securityContext)
  } catch (analysisError) {
    // Analysis is optional - don't fail the dry-run if it fails
    console.warn('Query analysis failed:', analysisError)
  }
 
  // Build comprehensive response
  return {
    queryType: "regularQuery",
    normalizedQueries,
    queryOrder: Array.from(referencedCubes),
    transformedQueries: normalizedQueries,
    pivotQuery: {
      query,
      cubes: Array.from(referencedCubes)
    },
    sql: {
      sql: [sqlResult.sql],
      params: sqlResult.params || []
    },
    complexity: calculateQueryComplexity(query),
    valid: true,
    cubesUsed: Array.from(referencedCubes),
    joinType: isMultiCube ? "multi_cube_join" : "single_cube",
    query,
    // Query analysis for debugging and transparency
    analysis
  }
}
 
/**
 * Format standard Cube.js API response
 */
export function formatCubeResponse(
  query: SemanticQuery,
  result: { data: any[]; annotation?: any; cache?: { hit: boolean; cachedAt?: string; ttlMs?: number; ttlRemainingMs?: number } },
  semanticLayer: SemanticLayerCompiler
) {
  const dbType = getDatabaseType(semanticLayer)
  const requestId = generateRequestId()
  const lastRefreshTime = new Date().toISOString()
  const transformedQuery = buildTransformedQuery(query)
 
  return {
    queryType: "regularQuery",
    results: [{
      query,
      lastRefreshTime,
      usedPreAggregations: {},
      transformedQuery,
      requestId,
      annotation: result.annotation,
      dataSource: "default",
      dbType,
      extDbType: dbType,
      external: false,
      slowQuery: false,
      data: result.data,
      // Include cache metadata if present (indicates cache hit with TTL info)
      ...(result.cache && { cache: result.cache })
    }],
    pivotQuery: {
      ...query,
      queryType: "regularQuery"
    },
    slowQuery: false
  }
}
 
/**
 * Format SQL string using sql-formatter with appropriate dialect
 */
export function formatSqlString(sqlString: string, engineType: 'postgres' | 'mysql' | 'sqlite' | 'singlestore' | 'duckdb'): string {
  try {
    // Map drizzle-cube engine types to sql-formatter language options
    const dialectMap = {
      postgres: 'postgresql',
      mysql: 'mysql',
      sqlite: 'sqlite',
      singlestore: 'mysql',  // SingleStore uses MySQL dialect for formatting
      duckdb: 'postgresql'   // DuckDB is PostgreSQL-compatible for formatting
    } as const
    
    return format(sqlString, {
      language: dialectMap[engineType],
      tabWidth: 2,
      keywordCase: 'upper',
      indentStyle: 'standard'
    })
  } catch (error) {
    // If formatting fails, return original SQL
    console.warn('SQL formatting failed:', error)
    return sqlString
  }
}
 
/**
 * Format SQL generation response
 */
export function formatSqlResponse(
  query: SemanticQuery,
  sqlResult: { sql: string; params?: any[] }
) {
  return {
    sql: sqlResult.sql,
    params: sqlResult.params || [],
    query
  }
}
 
/**
 * Format metadata response with query guidance for AI consumers
 */
export function formatMetaResponse(metadata: any) {
  return {
    cubes: metadata,
    // Query guidance for AI agents - helps prevent common mistakes
    queryGuidance: {
      dateHandling: {
        critical: 'Date filtering and time grouping are DIFFERENT operations',
        forAggregatedTotals: {
          description: 'For totals over a date range (no time breakdown), use filters with inDateRange operator - NOT timeDimensions',
          example: {
            filters: [{ member: 'Cube.date', operator: 'inDateRange', values: ['last 3 months'] }]
          },
          useCase: 'User asks for "total sales last month", "top 5 last quarter", "sum over past year"'
        },
        forTimeSeries: {
          description: 'For time series grouped by period (trend analysis), use timeDimensions WITH granularity',
          example: {
            timeDimensions: [{ dimension: 'Cube.date', granularity: 'month', dateRange: 'last 3 months' }]
          },
          useCase: 'User asks for "monthly breakdown", "daily trend", "per week"'
        },
        warning: 'Using timeDimensions WITHOUT granularity groups by day, returning many rows instead of aggregates. This is the #1 query mistake.'
      },
      crossCubeQueries: {
        description: 'Include dimensions from related cubes - the system auto-joins based on relationships',
        example: 'To get employee names with productivity: measures=["Productivity.total"], dimensions=["Employees.name"]',
        howToFind: 'Check the "joins" property in each cube metadata to see relationships'
      },
      topNPattern: {
        description: 'For "top N" queries, use filters (not timeDimensions) + order + limit',
        example: {
          measures: ['Cube.total'],
          dimensions: ['RelatedCube.name'],
          filters: [{ member: 'Cube.date', operator: 'inDateRange', values: ['last 3 months'] }],
          order: { 'Cube.total': 'desc' },
          limit: 5
        }
      },
      filterSyntax: {
        description: 'Filters must be flat arrays of { member, operator, values }',
        operators: ['equals', 'notEquals', 'contains', 'notContains', 'gt', 'gte', 'lt', 'lte', 'inDateRange', 'beforeDate', 'afterDate', 'set', 'notSet'],
        dateRangeValues: {
          relative: ['last 7 days', 'last 3 months', 'last year', 'this week', 'this month', 'this quarter'],
          absolute: ['2024-01-01', '2024-03-31']
        }
      }
    }
  }
}
 
/**
 * Standard error response format
 */
export function formatErrorResponse(error: string | Error, status: number = 500) {
  return {
    error: error instanceof Error ? error.message : error,
    status
  }
}
 
/**
 * Options for batch request handling
 */
export interface BatchRequestOptions {
  /**
   * Whether to bypass server-side cache for all queries in the batch
   * When true, all queries will be executed fresh without cache
   */
  skipCache?: boolean
}
 
/**
 * Handle batch query requests - wrapper around existing single query execution
 * Executes multiple queries in parallel and returns partial success results
 *
 * @param queries - Array of semantic queries to execute
 * @param securityContext - Security context (extracted once, shared across all queries)
 * @param semanticLayer - Semantic layer compiler instance
 * @param options - Optional batch request options (e.g., skipCache)
 * @returns Array of results matching input query order (successful or error results)
 */
export async function handleBatchRequest(
  queries: SemanticQuery[],
  securityContext: SecurityContext,
  semanticLayer: SemanticLayerCompiler,
  options?: BatchRequestOptions
) {
  // Execute all queries in parallel using Promise.allSettled for partial success
  // This ensures one failing query doesn't affect others
  const settledResults = await Promise.allSettled(
    queries.map(async (query) => {
      // Use EXISTING single query execution logic - NO CODE DUPLICATION
      // Pass skipCache option to bypass server-side caching when requested
      const result = await semanticLayer.executeMultiCubeQuery(query, securityContext, {
        skipCache: options?.skipCache
      })
 
      // Use EXISTING response formatter - NO CODE DUPLICATION
      return formatCubeResponse(query, result, semanticLayer)
    })
  )
 
  // Transform Promise.allSettled results to match expected format
  const results = settledResults.map((settledResult, index) => {
    if (settledResult.status === 'fulfilled') {
      // Query succeeded - return the formatted result with success flag
      return {
        success: true,
        ...settledResult.value
      }
    } else {
      // Query failed - return error information
      return {
        success: false,
        error: settledResult.reason instanceof Error
          ? settledResult.reason.message
          : String(settledResult.reason),
        query: queries[index] // Include the query that failed for debugging
      }
    }
  })
 
  return { results }
}
 
/**
 * Helper function to handle funnel dry-run logic
 * Funnel queries have a different structure and generate CTE-based SQL
 */
async function handleFunnelDryRun(
  query: SemanticQuery,
  securityContext: SecurityContext,
  semanticLayer: SemanticLayerCompiler
) {
  // Validate funnel query
  const validation = semanticLayer.validateQuery(query)
  if (!validation.isValid) {
    throw new Error(`Funnel query validation failed: ${validation.errors.join(', ')}`)
  }
 
  // Get the funnel SQL using the dedicated dry-run method
  const sqlResult = await semanticLayer.dryRunFunnel(query, securityContext)
 
  // Extract cube names from the funnel configuration
  const referencedCubes = new Set<string>()
  const funnel = query.funnel!
 
  // Extract from binding key
  if (typeof funnel.bindingKey === 'string') {
    const [cubeName] = funnel.bindingKey.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  } else if (Array.isArray(funnel.bindingKey)) {
    for (const mapping of funnel.bindingKey) {
      referencedCubes.add(mapping.cube)
    }
  }
 
  // Extract from time dimension
  if (typeof funnel.timeDimension === 'string') {
    const [cubeName] = funnel.timeDimension.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  } else if (Array.isArray(funnel.timeDimension)) {
    for (const mapping of funnel.timeDimension) {
      referencedCubes.add(mapping.cube)
    }
  }
 
  // Extract from steps (multi-cube funnels have cube per step)
  for (const step of funnel.steps) {
    if ('cube' in step && step.cube) {
      referencedCubes.add(step.cube)
    }
  }
 
  // Build response structure
  return {
    queryType: 'funnelQuery',
    normalizedQueries: [], // Funnel is a single unified query
    queryOrder: Array.from(referencedCubes),
    transformedQueries: [],
    pivotQuery: {
      query,
      cubes: Array.from(referencedCubes)
    },
    sql: {
      sql: [sqlResult.sql],
      params: sqlResult.params || []
    },
    complexity: 'high', // Funnel queries are inherently complex (CTEs)
    valid: true,
    cubesUsed: Array.from(referencedCubes),
    joinType: 'funnel_cte',
    query,
    // Funnel-specific metadata
    funnel: {
      stepCount: funnel.steps.length,
      steps: funnel.steps.map((step, index) => ({
        index,
        name: step.name,
        timeToConvert: step.timeToConvert,
        cube: 'cube' in step ? step.cube : undefined
      })),
      bindingKey: funnel.bindingKey,
      timeDimension: funnel.timeDimension,
      includeTimeMetrics: funnel.includeTimeMetrics,
      globalTimeWindow: funnel.globalTimeWindow
    }
  }
}
 
/**
 * Helper function to handle flow dry-run logic
 * Flow queries have a different structure and generate CTE-based SQL
 */
async function handleFlowDryRun(
  query: SemanticQuery,
  securityContext: SecurityContext,
  semanticLayer: SemanticLayerCompiler
) {
  // Validate flow query
  const validation = semanticLayer.validateQuery(query)
  if (!validation.isValid) {
    throw new Error(`Flow query validation failed: ${validation.errors.join(', ')}`)
  }
 
  // Get the flow SQL using the dedicated dry-run method
  const sqlResult = await semanticLayer.dryRunFlow(query, securityContext)
 
  // Extract cube names from the flow configuration
  const referencedCubes = new Set<string>()
  const flow = query.flow!
 
  // Extract from binding key
  if (typeof flow.bindingKey === 'string') {
    const [cubeName] = flow.bindingKey.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  } else if (Array.isArray(flow.bindingKey)) {
    for (const mapping of flow.bindingKey) {
      referencedCubes.add(mapping.cube)
    }
  }
 
  // Extract from time dimension
  if (typeof flow.timeDimension === 'string') {
    const [cubeName] = flow.timeDimension.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  }
 
  // Extract from event dimension
  if (typeof flow.eventDimension === 'string') {
    const [cubeName] = flow.eventDimension.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  }
 
  // Build response structure
  return {
    queryType: 'flowQuery',
    normalizedQueries: [], // Flow is a single unified query
    queryOrder: Array.from(referencedCubes),
    transformedQueries: [],
    pivotQuery: {
      measures: [],
      dimensions: [],
      timeDimensions: [],
      order: {},
      filters: [],
      queryType: 'flowQuery',
      joinType: 'flow_cte',
      query,
      // Flow-specific metadata
      flow: {
        stepsBefore: flow.stepsBefore,
        stepsAfter: flow.stepsAfter,
        bindingKey: flow.bindingKey,
        timeDimension: flow.timeDimension,
        eventDimension: flow.eventDimension,
        startingStep: flow.startingStep
      }
    },
    sql: {
      sql: sqlResult.sql,
      params: sqlResult.params || []
    }
  }
}
 
/**
 * Handle dry-run for retention queries
 */
async function handleRetentionDryRun(
  query: SemanticQuery,
  securityContext: SecurityContext,
  semanticLayer: SemanticLayerCompiler
) {
  // Validate retention query
  const validation = semanticLayer.validateQuery(query)
  if (!validation.isValid) {
    throw new Error(`Retention query validation failed: ${validation.errors.join(', ')}`)
  }
 
  // Get the retention SQL using the dedicated dry-run method
  const sqlResult = await semanticLayer.dryRunRetention(query, securityContext)
 
  // Extract cube names from the retention configuration
  const referencedCubes = new Set<string>()
  const retention = query.retention!
 
  // Extract from time dimension (single dimension for both cohort and activity)
  if (typeof retention.timeDimension === 'string') {
    const [cubeName] = retention.timeDimension.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  } else if (retention.timeDimension && typeof retention.timeDimension === 'object') {
    referencedCubes.add(retention.timeDimension.cube)
  }
 
  // Extract from binding key
  if (typeof retention.bindingKey === 'string') {
    const [cubeName] = retention.bindingKey.split('.')
    if (cubeName) referencedCubes.add(cubeName)
  } else if (Array.isArray(retention.bindingKey)) {
    for (const mapping of retention.bindingKey) {
      referencedCubes.add(mapping.cube)
    }
  }
 
  // Extract from breakdown dimensions
  if (retention.breakdownDimensions && Array.isArray(retention.breakdownDimensions)) {
    for (const dim of retention.breakdownDimensions) {
      const [cubeName] = dim.split('.')
      if (cubeName) referencedCubes.add(cubeName)
    }
  }
 
  // Build response structure
  return {
    queryType: 'retentionQuery',
    normalizedQueries: [], // Retention is a single unified query
    queryOrder: Array.from(referencedCubes),
    transformedQueries: [],
    pivotQuery: {
      measures: [],
      dimensions: [],
      timeDimensions: [],
      order: {},
      filters: [],
      queryType: 'retentionQuery',
      joinType: 'retention_cte',
      query,
      // Retention-specific metadata
      retention: {
        timeDimension: retention.timeDimension,
        bindingKey: retention.bindingKey,
        granularity: retention.granularity,
        periods: retention.periods,
        retentionType: retention.retentionType,
        breakdownDimensions: retention.breakdownDimensions,
      }
    },
    sql: {
      sql: sqlResult.sql,
      params: sqlResult.params || []
    }
  }
}
 
// ============================================
// MCP (AI-Ready) Endpoint Handlers
// ============================================
 
/**
 * MCP Endpoint Options
 */
export interface MCPOptions {
  /** Enable MCP endpoints (default: true) */
  enabled?: boolean
  /** Which MCP tools to expose (default: all) */
  tools?: ('discover' | 'suggest' | 'validate' | 'load')[]
  /** Base path for MCP endpoints (default: '/mcp') */
  basePath?: string
  /**
   * Allowed origins for MCP requests (for Origin header validation per MCP 2025-11-25).
   * If not provided, all origins are allowed (permissive mode).
   * Set this to restrict access to specific origins for production security.
   * Example: ['http://localhost:3000', 'https://myapp.com']
   */
  allowedOrigins?: string[]
}
 
/**
 * Discovery request body
 */
export interface DiscoverRequest {
  /** Topic or keyword to search for */
  topic?: string
  /** Natural language intent */
  intent?: string
  /** Maximum results to return */
  limit?: number
  /** Minimum relevance score (0-1) */
  minScore?: number
}
 
/**
 * Suggest request body
 */
export interface SuggestRequest {
  /** Natural language query */
  naturalLanguage: string
  /** Optional target cube name */
  cube?: string
}
 
/**
 * Validate request body
 */
export interface ValidateRequest {
  /** Query to validate */
  query: SemanticQuery
}
 
/**
 * Load request body - execute a query
 */
export interface LoadRequest {
  /** Query to execute */
  query: SemanticQuery
}
 
/**
 * Handle /discover endpoint - find relevant cubes based on topic/intent
 */
export async function handleDiscover(
  semanticLayer: SemanticLayerCompiler,
  body: DiscoverRequest
): Promise<{ cubes: CubeDiscoveryResult[] }> {
  const metadata = semanticLayer.getMetadata()
  const results = discoverCubes(metadata, {
    topic: body.topic,
    intent: body.intent,
    limit: body.limit,
    minScore: body.minScore
  })
 
  return { cubes: results }
}
 
/**
 * Handle /suggest endpoint - generate query from natural language
 */
export async function handleSuggest(
  semanticLayer: SemanticLayerCompiler,
  body: SuggestRequest
): Promise<QuerySuggestion> {
  const metadata = semanticLayer.getMetadata()
  return suggestQuery(metadata, body.naturalLanguage, body.cube)
}
 
/**
 * Handle /validate endpoint - validate query with corrections
 */
export async function handleValidate(
  semanticLayer: SemanticLayerCompiler,
  body: ValidateRequest
): Promise<AIValidationResult> {
  const metadata = semanticLayer.getMetadata()
  return aiValidateQuery(body.query, metadata)
}
 
/**
 * Handle /load endpoint - execute a query and return results
 * This completes the AI workflow: discover → suggest → validate → load
 */
export async function handleLoad(
  semanticLayer: SemanticLayerCompiler,
  securityContext: SecurityContext,
  body: LoadRequest
): Promise<{
  data: Record<string, unknown>[]
  annotation: any
  query: SemanticQuery
}> {
  const query = body.query
 
  // Validate query structure and field existence
  const validation = semanticLayer.validateQuery(query)
  Iif (!validation.isValid) {
    throw new Error(`Query validation failed: ${validation.errors.join(', ')}`)
  }
 
  // Execute the query
  const result = await semanticLayer.executeMultiCubeQuery(query, securityContext)
 
  return {
    data: result.data,
    annotation: result.annotation,
    query
  }
}