CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lightdash--common

Shared TypeScript library for the Lightdash platform containing common types, utilities, and business logic for analytics workflows

Overall
score

72%

Evaluation72%

1.09x

Agent success when using this tile

Overview
Eval results
Files

analytics.mddocs/api/types/

Analytics and Content Types

This document contains types for analytics tracking, content management, data catalog, and scheduler functionality.

Capabilities

This module provides the following functionality:

Analytics Types

Types for tracking user activity, content views, and query execution contexts.

interface UserActivity {
  userId: string;
  organizationId: string;
  numberWeeklyQueryExecutions: number;
}

interface ActivityViews {
  userId: string;
  views: number;
}

interface ViewStatistics {
  views: number;
  firstViewedAt: Date | null;
}

interface UnusedContentItem {
  uuid: string;
  name: string;
  type: 'chart' | 'dashboard';
  spaceUuid: string;
  spaceName: string;
  lastViewedAt: Date | null;
  createdAt: Date;
}

interface UnusedContent {
  charts: UnusedContentItem[];
  dashboards: UnusedContentItem[];
}

enum QueryExecutionContext {
  DASHBOARD = 'DASHBOARD',
  EXPLORE = 'EXPLORE',
  SAVED_CHART = 'SAVED_CHART',
  SQL_RUNNER = 'SQL_RUNNER',
  VIEW_UNDERLYING_DATA = 'VIEW_UNDERLYING_DATA',
  PIVOT_TABLE = 'PIVOT_TABLE',
  CSV_DOWNLOAD = 'CSV_DOWNLOAD',
  SCHEDULED_DELIVERY = 'SCHEDULED_DELIVERY',
  EMBEDDED = 'EMBEDDED',
  WEB_APP = 'WEB_APP',
  EXTERNAL = 'EXTERNAL',
  METRICS_EXPLORER = 'METRICS_EXPLORER',
  REFRESH_DASHBOARD_TILE = 'REFRESH_DASHBOARD_TILE',
  REFRESH_SAVED_CHART = 'REFRESH_SAVED_CHART',
  REFRESH_DASHBOARD_FILTERS = 'REFRESH_DASHBOARD_FILTERS',
  AI_AGENT = 'AI_AGENT',
  API = 'API',
  CLI = 'CLI',
  BULK_EXPORT = 'BULK_EXPORT',
  GDRIVE_EXPORT = 'GDRIVE_EXPORT',
  REFRESH_DASHBOARD_TAB = 'REFRESH_DASHBOARD_TAB',
  CATALOG = 'CATALOG',
}

API response types:

interface ApiUserActivity {
  status: 'ok';
  results: UserActivity[];
}

interface ApiUnusedContent {
  status: 'ok';
  results: UnusedContent;
}

Project Compilation Log Types

Types for tracking project compilation history, including dbt project refresh and deployment operations.

/**
 * Source of project compilation
 */
type CompilationSource = 'cli_deploy' | 'refresh_dbt' | 'create_project';

/**
 * Project compilation log entry tracking dbt compilation history and results
 */
interface ProjectCompileLog {
  projectCompileLogId: string;
  projectUuid: string;
  jobUuid: string | null;
  userUuid: string | null;
  userName: string | null;
  organizationUuid: string;
  createdAt: Date;
  compilationSource: CompilationSource;
  dbtConnectionType: string | null;
  requestMethod: string | null;
  warehouseType: string | null;
  report: CompilationHistoryReport;
}

/**
 * Data for creating a new project compile log
 */
type ProjectCompileLogInsert = Omit<
  ProjectCompileLog,
  'projectCompileLogId' | 'createdAt' | 'userName'
>;

/**
 * Paginated results for project compile logs
 */
interface ApiProjectCompileLogsResults {
  data: ProjectCompileLog[];
  pagination?: {
    page: number;
    pageSize: number;
    totalPageCount: number;
    totalResults: number;
  };
}

/**
 * API response for getting multiple project compile logs
 */
interface ApiProjectCompileLogsResponse {
  status: 'ok';
  results: ApiProjectCompileLogsResults;
}

/**
 * API response for getting a single project compile log
 */
interface ApiProjectCompileLogResponse {
  status: 'ok';
  results: {
    log: ProjectCompileLog | undefined;
  };
}

Resource View Item Types

Unified types for displaying resources (charts, dashboards, spaces) in list views with sorting, filtering, and categorization.

/**
 * Category for resource items in views
 */
enum ResourceItemCategory {
  MOST_POPULAR = 'mostPopular',
  RECENTLY_UPDATED = 'recentlyUpdated',
  PINNED = 'pinned',
}

/**
 * Chart resource view item with metadata
 */
interface ResourceViewChartItem {
  type: ContentType.CHART;
  data: {
    uuid: string;
    name: string;
    chartType: ChartKind;
    chartKind: ChartKind;
    firstViewedAt: Date | null;
    views: number;
    pinnedListUuid: string | null;
    pinnedListOrder: number | null;
    spaceUuid: string;
    description?: string;
    updatedAt: Date;
    updatedByUser: {
      userUuid: string;
      firstName: string;
      lastName: string;
    };
    validationErrors?: ValidationErrorChartResponse[];
    slug: string;
    source?: ChartSourceType;
  };
  category?: ResourceItemCategory;
}

/**
 * Dashboard resource view item with metadata
 */
interface ResourceViewDashboardItem {
  type: ContentType.DASHBOARD;
  data: {
    uuid: string;
    spaceUuid: string;
    description?: string;
    name: string;
    views: number;
    firstViewedAt: Date | null;
    pinnedListUuid: string | null;
    pinnedListOrder: number | null;
    updatedAt: Date;
    updatedByUser: {
      userUuid: string;
      firstName: string;
      lastName: string;
    };
    validationErrors?: ValidationErrorDashboardResponse[];
  };
  category?: ResourceItemCategory;
}

/**
 * Space resource view item with access and content counts
 */
interface ResourceViewSpaceItem {
  type: ContentType.SPACE;
  data: {
    projectUuid: string;
    uuid: string;
    name: string;
    isPrivate: boolean;
    pinnedListUuid: string | null;
    pinnedListOrder: number | null;
    organizationUuid: string;
    parentSpaceUuid: string | null;
    path: string[];
    access: string[];
    accessListLength: number;
    dashboardCount: number;
    chartCount: number;
  };
}

/**
 * Union type for all resource view items
 */
type ResourceViewItem =
  | ResourceViewChartItem
  | ResourceViewDashboardItem
  | ResourceViewSpaceItem;

/**
 * Type guard for chart resource items
 */
function isResourceViewItemChart(
  item: ResourceViewItem
): item is ResourceViewChartItem;

/**
 * Type guard for dashboard resource items
 */
function isResourceViewItemDashboard(
  item: ResourceViewItem
): item is ResourceViewDashboardItem;

/**
 * Type guard for space resource items
 */
function isResourceViewSpaceItem(
  item: ResourceViewItem
): item is ResourceViewSpaceItem;

/**
 * Wraps a resource object into a ResourceViewItem
 */
function wrapResource<T>(
  resource: T,
  type: ContentType
): ResourceViewItem;

/**
 * Wraps multiple resource objects into ResourceViewItems
 */
function wrapResourceView(
  resources: Array<any>,
  type: ContentType
): ResourceViewItem[];

/**
 * Converts a SpaceSummary to a ResourceViewSpaceItem data object
 */
function spaceToResourceViewItem(
  space: SpaceSummary
): ResourceViewSpaceItem['data'];

/**
 * Converts a SummaryContent to a ResourceViewItem
 */
function contentToResourceViewItem(content: SummaryContent): ResourceViewItem;

/**
 * Extracts the data from a ResourceViewItem
 */
function resourceToContent(resource: ResourceViewItem): any;

/**
 * Combined type for most popular and recently updated resources
 */
interface MostPopularAndRecentlyUpdated {
  mostPopular: Array<DashboardBasicDetails | SpaceQuery>;
  recentlyUpdated: Array<DashboardBasicDetails | SpaceQuery>;
}

Content Management Types

Content browsing, filtering, and search across charts, dashboards, and spaces.

enum ContentType {
  CHART = 'chart',
  DASHBOARD = 'dashboard',
  SPACE = 'space',
}

type Content = {
  contentType: ContentType;
  uuid: string;
  slug: string;
  name: string;
  description: string | null;
  createdAt: Date;
  createdBy: {
    uuid: string;
    firstName: string;
    lastName: string;
  } | null;
  lastUpdatedAt: Date | null;
  lastUpdatedBy: {
    uuid: string;
    firstName: string;
    lastName: string;
  } | null;
  project: {
    uuid: string;
    name: string;
  };
  organization: {
    uuid: string;
    name: string;
  };
  space: {
    uuid: string;
    name: string;
  };
  pinnedList: {
    uuid: string;
  } | null;
  views: number;
  firstViewedAt: Date | null;
};

enum ContentSortByColumns {
  NAME = 'name',
  SPACE_NAME = 'space_name',
  LAST_UPDATED_AT = 'last_updated_at',
}

enum ChartSourceType {
  DBT_EXPLORE = 'dbt_explore',
  SQL = 'sql',
}

Additional Content Types

Additional content types for managing charts, dashboards, and spaces:

import {
  type ChartContent,
  type DashboardContent,
  type SpaceContent,
  type ApiChartContentResponse,
  type ApiContentActionBody,
  type ApiContentBulkActionBody,
  type ApiContentResponse,
  type ContentActionDelete,
  type ContentActionMove,
  type BulkActionable,
  isChartContent,
  isDashboardContent,
  isSpaceContent
} from '@lightdash/common';

/**
 * Chart content with source and kind information
 */
interface ChartContent extends Content {
  contentType: ContentType.CHART;
  source: ChartSourceType;
  chartKind: ChartKind;
  dashboard: {
    uuid: string;
    name: string;
  } | null;
}

/**
 * Dashboard content
 */
interface DashboardContent extends Content {
  contentType: ContentType.DASHBOARD;
}

/**
 * Space content with access and child counts
 */
interface SpaceContent extends Content {
  contentType: ContentType.SPACE;
  isPrivate: boolean;
  access: string[];
  dashboardCount: number;
  chartCount: number;
  pinnedList: {
    uuid: string;
    order: number;
  } | null;
  parentSpaceUuid: string | null;
  path: string;
}

/**
 * Action to move content to a different space
 */
type ContentActionMove = {
  type: 'move';
  targetSpaceUuid: string | null;
};

/**
 * Action to delete content
 */
type ContentActionDelete = {
  type: 'delete';
};

/**
 * API request body for single content action
 */
type ApiContentActionBody<T extends ContentAction = ContentAction> = {
  item: ItemPayload;
  action: T;
};

/**
 * API request body for bulk content actions
 */
type ApiContentBulkActionBody<T extends ContentAction = ContentAction> = {
  content: ItemPayload[];
  action: T;
};

/**
 * API response for content listing
 */
type ApiContentResponse = {
  status: 'ok';
  results: KnexPaginatedData<SummaryContent[]>;
};

/**
 * API response for chart content listing
 */
type ApiChartContentResponse = {
  status: 'ok';
  results: KnexPaginatedData<ChartContent[]>;
};

/**
 * Interface for models that support bulk operations
 */
interface BulkActionable<Tx extends unknown> {
  moveToSpace: (
    user: SessionUser,
    args: {
      projectUuid: string;
      itemUuid: string;
      targetSpaceUuid: string | null;
    },
    tx?: Tx
  ) => Promise<void>;

  delete: (
    user: SessionUser,
    args: {
      projectUuid: string;
      itemUuid: string;
    },
    tx?: Tx
  ) => Promise<void>;
}

/**
 * Type guard to check if content is a chart
 */
function isChartContent(content: Content): content is ChartContent;

/**
 * Type guard to check if content is a dashboard
 */
function isDashboardContent(content: Content): content is DashboardContent;

/**
 * Type guard to check if content is a space
 */
function isSpaceContent(content: Content): content is SpaceContent;

Catalog Types

Types for the data catalog system including search, metrics trees, catalog items, metadata, and usage tracking.

Catalog Core Types

/**
 * Type discriminator for catalog items
 */
enum CatalogType {
  Table = 'table',
  Field = 'field',
}

/**
 * Filter options for catalog search
 */
enum CatalogFilter {
  Tables = 'tables',
  Dimensions = 'dimensions',
  Metrics = 'metrics',
}

/**
 * Selection context for catalog items
 */
interface CatalogSelection {
  group: string;
  table?: string;
  field?: string;
}

/**
 * Search parameters for catalog API
 */
interface ApiCatalogSearch {
  searchQuery?: string;
  type?: CatalogType;
  filter?: CatalogFilter;
  catalogTags?: string[];
}

/**
 * Icon types for catalog items
 */
type CatalogItemIcon =
  | { unicode: string }  // Emoji icon
  | { url: string };      // Custom icon URL

/**
 * UUID constant for uncategorized items
 */
const UNCATEGORIZED_TAG_UUID = '__uncategorized__';

/**
 * Type guard for emoji icons
 */
function isEmojiIcon(icon: CatalogItemIcon | null): icon is { unicode: string };

/**
 * Type guard for custom icons
 */
function isCustomIcon(icon: CatalogItemIcon | null): icon is { url: string };

Catalog Field and Table Types

/**
 * Catalog entry for a field (dimension or metric)
 */
interface CatalogField {
  catalogSearchUuid: string;
  type: CatalogType.Field;
  name: string;
  label: string;
  fieldType: FieldType;
  tableLabel: string;
  description: string | undefined;

  // Field characteristics
  basicType: 'string' | 'number' | 'date' | 'timestamp' | 'boolean';
  fieldValueType: MetricType | DimensionType;
  tableName: string;
  tableGroupLabel?: string;
  requiredAttributes?: Record<string, string | string[]>;

  // Metadata and organization
  tags?: string[];  // Tags from table for filtering
  categories: Array<Pick<Tag, 'name' | 'color' | 'tagUuid' | 'yamlReference'>>;  // User-added tags in catalog
  icon: CatalogItemIcon | null;
  aiHints: string[] | null;

  // Usage metrics
  chartUsage: number | undefined;
  searchRank?: number;
}

/**
 * Catalog entry for a table (explore)
 */
interface CatalogTable {
  catalogSearchUuid: string;
  type: CatalogType.Table;
  name: string;
  label: string;
  groupLabel?: string;
  description: string | undefined;

  // Table metadata
  requiredAttributes?: Record<string, string | string[]>;
  tags?: string[];
  categories: Array<Pick<Tag, 'name' | 'color' | 'tagUuid' | 'yamlReference'>>;
  icon: CatalogItemIcon | null;
  aiHints: string[] | null;
  joinedTables: string[] | null;

  // Usage and validation
  chartUsage: number | undefined;
  errors?: Array<{ type: string; message: string }>;  // For explore errors
  searchRank?: number;
}

/**
 * Union type for catalog items
 */
type CatalogItem = CatalogField | CatalogTable;

/**
 * Utility function to determine basic type from field type
 */
function getBasicType(
  field: CompiledDimension | CompiledMetric
): 'string' | 'number' | 'date' | 'timestamp' | 'boolean';

Metrics Tree Types

/**
 * Node in the metrics tree (represents a metric)
 */
interface CatalogMetricsTreeNode {
  catalogSearchUuid: string;
  name: string;
  tableName: string;
}

/**
 * Edge in the metrics tree (relationship between metrics)
 */
interface CatalogMetricsTreeEdge {
  source: CatalogMetricsTreeNode;
  target: CatalogMetricsTreeNode;
  createdAt: Date;
  createdByUserUuid: string | null;
  projectUuid: string;
}

/**
 * Payload for creating metrics tree edges
 */
interface ApiMetricsTreeEdgePayload {
  sourceCatalogSearchUuid: string;
  targetCatalogSearchUuid: string;
}

Metrics with Time Dimensions

/**
 * Metric with its associated time dimension
 */
interface MetricWithAssociatedTimeDimension extends CompiledMetric {
  timeDimension:
    | (CompiledMetric['defaultTimeDimension'] & { table: string })
    | undefined;
  availableTimeDimensions?: Array<CompiledDimension & {
    type: DimensionType.DATE | DimensionType.TIMESTAMP;
  }>;
}

Catalog Metadata Types

/**
 * Detailed metadata for a catalog item
 */
interface CatalogMetadata {
  name: string;
  description: string | undefined;
  label: string;
  modelName: string;
  source: string | undefined;
  fields: CatalogField[];
  joinedTables: string[];
  tableLabel?: string;
  fieldType?: FieldType;
}

/**
 * Analytics data for catalog items
 */
interface CatalogAnalytics {
  charts: Array<Pick<
    ChartSummary,
    'uuid' | 'name' | 'spaceUuid' | 'spaceName' | 'dashboardName' | 'dashboardUuid' | 'chartKind'
  >>;
}

Catalog Field Mapping and Summaries

/**
 * Map of field IDs to field metadata
 */
interface CatalogFieldMap {
  [fieldId: string]: {
    fieldName: string;
    tableName: string;
    cachedExploreUuid: string;
    fieldType: FieldType;
  };
}

/**
 * Summary of a catalog item
 */
interface CatalogItemSummary {
  catalogSearchUuid: string;
  name: string;
  type: CatalogType;
  projectUuid: string;
  cachedExploreUuid: string;
  tableName: string;
  fieldType: string | undefined;
}

/**
 * Catalog item with associated tag UUIDs
 */
interface CatalogItemWithTagUuids extends CatalogItemSummary {
  catalogTags: Array<{
    tagUuid: string;
    createdByUserUuid: string | null;
    createdAt: Date;
    taggedViaYaml: boolean;
  }>;
}

/**
 * Catalog item with icon information
 */
interface CatalogItemsWithIcons extends CatalogItemSummary {
  icon: CatalogItemIcon | null;
}

Chart Field Usage Tracking

/**
 * Updates to chart fields (old vs new)
 */
interface ChartFieldUpdates {
  oldChartFields: {
    metrics: string[];
    dimensions: string[];
  };
  newChartFields: {
    metrics: string[];
    dimensions: string[];
  };
}

/**
 * Changes in chart fields (added/removed)
 */
interface ChartFieldChanges {
  added: {
    dimensions: string[];
    metrics: string[];
  };
  removed: {
    dimensions: string[];
    metrics: string[];
  };
}

/**
 * Where clause for catalog field queries
 */
interface CatalogFieldWhere {
  fieldName: string;
  fieldType: FieldType;
  cachedExploreUuid: string;
}

/**
 * Changes to chart field usage counts
 */
interface ChartFieldUsageChanges {
  fieldsToIncrement: CatalogFieldWhere[];
  fieldsToDecrement: CatalogFieldWhere[];
}

/**
 * Chart usage count for a field
 */
interface ChartUsageIn extends CatalogFieldWhere {
  chartUsage: number;
}

Scheduler Catalog Job Types

/**
 * Payload for catalog indexing background job
 */
interface SchedulerIndexCatalogJobPayload {
  organizationUuid: string;
  projectUuid: string;
  prevCatalogItemsWithTags: CatalogItemWithTagUuids[];
  prevCatalogItemsWithIcons: CatalogItemsWithIcons[];
  prevMetricTreeEdges: CatalogMetricsTreeEdge[];
}

API Response Types

/**
 * Search results from catalog API
 */
type ApiCatalogResults = CatalogItem[];

/**
 * Metrics catalog results with pagination
 */
type ApiMetricsCatalogResults = CatalogField[];

interface ApiMetricsCatalog {
  status: 'ok';
  results: KnexPaginatedData<ApiMetricsCatalogResults>;
}

/**
 * Single metric peek with time dimension
 */
interface ApiGetMetricPeek {
  status: 'ok';
  results: MetricWithAssociatedTimeDimension;
}

/**
 * Metrics tree graph data
 */
interface ApiGetMetricsTree {
  status: 'ok';
  results: {
    edges: CatalogMetricsTreeEdge[];
  };
}

/**
 * Catalog metadata response
 */
type ApiCatalogMetadataResults = CatalogMetadata;

/**
 * Catalog analytics response
 */
type ApiCatalogAnalyticsResults = CatalogAnalytics;

/**
 * Multiple metrics with time dimensions
 */
interface ApiMetricsWithAssociatedTimeDimensionResponse {
  status: 'ok';
  results: MetricWithAssociatedTimeDimension[];
}

/**
 * Segment dimensions response
 */
interface ApiSegmentDimensionsResponse {
  status: 'ok';
  results: CompiledDimension[];
}

Scheduler Types

Types for scheduled delivery of charts and dashboards including formats, targets, and notification settings.

enum SchedulerFormat {
  CSV = 'csv',
  IMAGE = 'image',
  GSHEETS = 'gsheets',
}

enum SchedulerJobStatus {
  SCHEDULED = 'scheduled',
  STARTED = 'started',
  COMPLETED = 'completed',
  ERROR = 'error',
}

enum JobPriority {
  LOW = 'low',
  NORMAL = 'normal',
  HIGH = 'high',
}

enum ThresholdOperator {
  INCREASED_BY = 'increasedBy',
  DECREASED_BY = 'decreasedBy',
  IS_GREATER_THAN = 'greaterThan',
  IS_LESS_THAN = 'lessThan',
}

enum NotificationFrequency {
  ALWAYS = 'always',
  ONCE = 'once',
}

interface SchedulerBase {
  schedulerUuid: string;
  name: string;
  createdAt: Date;
  updatedAt: Date;
  createdBy: string;
  format: SchedulerFormat;
  cron: string;
  timezone: string;
  enabled: boolean;
  savedChartUuid: string | null;
  dashboardUuid: string | null;
  targets: SchedulerTarget[];
  filters?: DashboardFilters;
  customViewportWidth?: number | null;
  options: SchedulerOptions;
  thresholds?: SchedulerThreshold[];
  message?: string;
}

type SchedulerOptions =
  | SchedulerCsvOptions
  | SchedulerImageOptions
  | SchedulerGsheetsOptions;

interface SchedulerCsvOptions {
  formatted: boolean;
  limit: 'all' | 'table' | number;
}

interface SchedulerImageOptions {
  withPdf?: boolean;
}

interface SchedulerGsheetsOptions {
  url: string;
  gdriveId: string;
  gdriveName: string;
}

interface ChartScheduler extends SchedulerBase {
  savedChartUuid: string;
  dashboardUuid: null;
}

interface DashboardScheduler extends SchedulerBase {
  savedChartUuid: null;
  dashboardUuid: string;
}

type Scheduler = ChartScheduler | DashboardScheduler;

interface SchedulerSlackTarget {
  schedulerSlackTargetUuid: string;
  createdAt: Date;
  updatedAt: Date;
  schedulerUuid: string;
  channel: string;
}

interface SchedulerEmailTarget {
  schedulerEmailTargetUuid: string;
  createdAt: Date;
  updatedAt: Date;
  schedulerUuid: string;
  recipient: string;
}

interface SchedulerMsTeamsTarget {
  schedulerMsTeamsTargetUuid: string;
  createdAt: Date;
  updatedAt: Date;
  schedulerUuid: string;
  webhookUrl: string;
}

type SchedulerTarget =
  | SchedulerSlackTarget
  | SchedulerEmailTarget
  | SchedulerMsTeamsTarget;

interface SchedulerThreshold {
  fieldId: string;
  operator: ThresholdOperator;
  value: number;
  notificationFrequency: NotificationFrequency;
}

interface CreateSchedulerAndTargets {
  name: string;
  format: SchedulerFormat;
  cron: string;
  timezone: string;
  enabled: boolean;
  savedChartUuid?: string;
  dashboardUuid?: string;
  targets: Array<{
    channel?: string;
    recipient?: string;
    webhookUrl?: string;
  }>;
  filters?: DashboardFilters;
  customViewportWidth?: number;
  options: SchedulerOptions;
  thresholds?: SchedulerThreshold[];
  message?: string;
}

interface UpdateSchedulerAndTargets extends Partial<CreateSchedulerAndTargets> {
  schedulerUuid: string;
}

function isDashboardScheduler(scheduler: Scheduler): scheduler is DashboardScheduler;
function isChartScheduler(scheduler: Scheduler): scheduler is ChartScheduler;

Additional Scheduler Types

Additional type guards, utility functions, and types for scheduler operations:

import {
  type SchedulerAndTargets,
  type CreateSchedulerAndTargets,
  type CreateSchedulerTarget,
  type UpdateSchedulerSlackTarget,
  type UpdateSchedulerMsTeamsTarget,
  type UpdateSchedulerEmailTarget,
  type SchedulerSlackTarget,
  type SchedulerEmailTarget,
  type SchedulerMsTeamsTarget,
  type SchedulerCsvOptions,
  type SchedulerImageOptions,
  type SchedulerGsheetsOptions,
  type CreateSchedulerAndTargetsWithoutIds,
  type NotificationPayloadBase,
  type QueueTraceProperties,
  type ApiCsvUrlResponse,
  type ApiJobScheduledResponse,
  type ApiJobStatusResponse,
  type ApiScheduledJobsResponse,
  type ApiSchedulerAndTargetsResponse,
  type ApiSchedulersResponse,
  type ApiTestSchedulerResponse,
  type ThresholdOptions,
  LightdashPage,
  operatorActionValue
} from '@lightdash/common';

/**
 * Type guard to check if scheduler is for a chart (as opposed to dashboard)
 */
function isChartCreateScheduler(
  data: CreateSchedulerAndTargets
): data is ChartScheduler & { targets: CreateSchedulerTarget[] };

/**
 * Type guard to check if scheduler is for a dashboard (as opposed to chart)
 */
function isDashboardCreateScheduler(
  data: CreateSchedulerAndTargets
): data is DashboardScheduler & { targets: CreateSchedulerTarget[] };

/**
 * Type guard to check if data is a create scheduler payload
 */
function isCreateScheduler(
  data: ScheduledDeliveryPayload
): data is CreateSchedulerAndTargets & TraceTaskBase;

/**
 * Type guard for MS Teams create target
 */
function isCreateSchedulerMsTeamsTarget(
  target: Pick<SchedulerSlackTarget, 'channel'> |
          Pick<SchedulerEmailTarget, 'recipient'> |
          Pick<SchedulerMsTeamsTarget, 'webhook'>
): target is Pick<SchedulerMsTeamsTarget, 'webhook'>;

/**
 * Type guard for Slack create target
 */
function isCreateSchedulerSlackTarget(
  target: Pick<SchedulerSlackTarget, 'channel'> |
          Pick<SchedulerEmailTarget, 'recipient'> |
          Pick<SchedulerMsTeamsTarget, 'webhook'>
): target is Pick<SchedulerSlackTarget, 'channel'>;

/**
 * Type guard for email target
 */
function isEmailTarget(
  target: SchedulerSlackTarget | SchedulerEmailTarget | SchedulerMsTeamsTarget
): target is SchedulerEmailTarget;

/**
 * Type guard for MS Teams target
 */
function isMsTeamsTarget(
  target: SchedulerSlackTarget | SchedulerEmailTarget | SchedulerMsTeamsTarget
): target is SchedulerMsTeamsTarget;

/**
 * Type guard for Slack target
 */
function isSlackTarget(
  target: SchedulerSlackTarget | SchedulerEmailTarget | SchedulerMsTeamsTarget
): target is SchedulerSlackTarget;

/**
 * Type guard for CSV options
 */
function isSchedulerCsvOptions(
  options: SchedulerCsvOptions | SchedulerImageOptions | SchedulerGsheetsOptions
): options is SchedulerCsvOptions;

/**
 * Type guard for Google Sheets options
 */
function isSchedulerGsheetsOptions(
  options: SchedulerCsvOptions | SchedulerImageOptions | SchedulerGsheetsOptions
): options is SchedulerGsheetsOptions;

/**
 * Type guard for image options
 */
function isSchedulerImageOptions(
  options: SchedulerCsvOptions | SchedulerImageOptions | SchedulerGsheetsOptions
): options is SchedulerImageOptions;

/**
 * Type guard for update Slack target
 */
function isUpdateSchedulerSlackTarget(
  data: CreateSchedulerTarget | UpdateSchedulerSlackTarget
): data is UpdateSchedulerSlackTarget;

/**
 * Type guard for update MS Teams target
 */
function isUpdateSchedulerMsTeamsTarget(
  data: CreateSchedulerTarget | UpdateSchedulerMsTeamsTarget
): data is UpdateSchedulerMsTeamsTarget;

/**
 * Type guard for update email target
 */
function isUpdateSchedulerEmailTarget(
  data: CreateSchedulerTarget | UpdateSchedulerEmailTarget
): data is UpdateSchedulerEmailTarget;

/**
 * Get the UUID from a scheduler target
 */
function getSchedulerTargetUuid(
  target: SchedulerSlackTarget | SchedulerMsTeamsTarget | SchedulerEmailTarget | CreateSchedulerTarget
): string | undefined;

/**
 * Get the UUID from a scheduler
 */
function getSchedulerUuid(
  data: CreateSchedulerAndTargets | Pick<Scheduler, 'schedulerUuid'>
): string | undefined;

/**
 * Check if scheduler has a UUID (i.e., is a persisted scheduler)
 */
function hasSchedulerUuid(
  data: SchedulerAndTargets | CreateSchedulerAndTargets
): data is SchedulerAndTargets;

/**
 * Format the threshold operator and value for display
 * @param operator - The threshold operator
 * @param value - The threshold value
 * @param highlight - String to wrap the value with (default: '*')
 * @returns Formatted string describing the threshold condition
 */
function operatorActionValue(
  operator: ThresholdOperator,
  value: number | string,
  highlight?: string
): string;

/**
 * Enum for different Lightdash page types used in scheduling
 */
enum LightdashPage {
  DASHBOARD = 'dashboard',
  CHART = 'chart',
  EXPLORE = 'explore',
}

/**
 * Scheduler with target destinations included
 */
type SchedulerAndTargets = Scheduler & {
  targets: (SchedulerSlackTarget | SchedulerEmailTarget | SchedulerMsTeamsTarget)[];
  latestRun?: SchedulerRun | null;
};

/**
 * Type for creating a scheduler without IDs (user-facing API)
 */
type CreateSchedulerAndTargetsWithoutIds = Omit<
  CreateSchedulerAndTargets,
  'savedChartUuid' | 'dashboardUuid' | 'createdBy'
>;

/**
 * Target for creating a new scheduler delivery
 */
type CreateSchedulerTarget =
  | Pick<SchedulerSlackTarget, 'channel'>
  | Pick<SchedulerMsTeamsTarget, 'webhook'>
  | Pick<SchedulerEmailTarget, 'recipient'>;

/**
 * Base payload for notification delivery jobs
 */
type NotificationPayloadBase = {
  schedulerUuid?: string;
  scheduledTime: Date;
  jobGroup: string;
  page: {
    url: string;
    details: {
      name: string;
      description: string | undefined;
    };
    pageType: LightdashPage;
    organizationUuid: string;
    imageUrl?: string;
    csvUrl?: {
      path: string;
      filename: string;
      localPath: string;
      truncated: boolean;
    };
    csvUrls?: {
      path: string;
      filename: string;
      localPath: string;
      truncated: boolean;
    }[];
    pdfFile?: {
      source: string;
      fileName: string;
    };
    failures?: {
      chartName: string;
      error: string;
    }[];
  };
  scheduler: CreateSchedulerAndTargets;
};

/**
 * Properties for distributed tracing of jobs
 */
type QueueTraceProperties = {
  traceHeader?: string;
  baggageHeader?: string;
  sentryMessageId?: string;
};

/**
 * API response for CSV download URL
 */
type ApiCsvUrlResponse = {
  status: 'ok';
  results: {
    url: string;
    status: string;
    truncated: boolean;
  };
};

/**
 * API response when a job is scheduled
 */
type ApiJobScheduledResponse = {
  status: 'ok';
  results: {
    jobId: string;
  };
};

/**
 * API response for job status
 */
type ApiJobStatusResponse = {
  status: 'ok';
  results: {
    status: SchedulerJobStatus;
    details: Record<string, any> | null;
  };
};

/**
 * Scheduled job with date and ID
 */
type ScheduledJobs = {
  date: Date;
  id: string;
};

/**
 * API response for list of scheduled jobs
 */
type ApiScheduledJobsResponse = {
  status: 'ok';
  results: ScheduledJobs[];
};

/**
 * API response for single scheduler with targets
 */
type ApiSchedulerAndTargetsResponse = {
  status: 'ok';
  results: SchedulerAndTargets;
};

/**
 * API response for paginated list of schedulers
 */
type ApiSchedulersResponse = ApiSuccess<
  KnexPaginatedData<SchedulerAndTargets[]>
>;

/**
 * API response for testing a scheduler
 */
type ApiTestSchedulerResponse = {
  status: 'ok';
  results: {
    jobId: string;
  };
};

/**
 * Threshold configuration options
 */
type ThresholdOptions = {
  operator: ThresholdOperator;
  fieldId: string;
  value: number;
};

/**
 * Scheduled delivery with link to the job
 */
type ScheduledDeliveryWithJobLink = {
  schedulerUuid: string;
  scheduledTime: Date;
  jobId: string;
};

/**
 * Filter rule labels for scheduler configuration
 */
type SchedulerFilterRuleLabels = {
  target: string;
  operator: string;
  values: string[];
};

/**
 * Scheduler execution status enum
 */
enum SchedulerStatus {
  ENABLED = 'enabled',
  DISABLED = 'disabled',
}

/**
 * Scheduler settings for a project or organization
 */
type SchedulerSettings = {
  enabled: boolean;
  maxSchedulers: number;
  maxDeliveriesPerDay: number;
};

Scheduler Log Types

Types for tracking scheduler execution history, job status, and delivery logs.

/**
 * Target type for scheduled delivery
 */
type SchedulerTargetType = 'email' | 'slack' | 'gsheets' | 'msteams';

/**
 * Details about the scheduler execution context
 */
interface SchedulerDetails {
  projectUuid?: string;
  organizationUuid?: string;
  createdByUserUuid?: string;
  [key: string]: any;
}

/**
 * Log entry for a scheduler job execution
 */
interface SchedulerLog {
  jobId: string;
  task: SchedulerTaskName;
  status: SchedulerJobStatus;
  scheduledTime: Date;
  createdAt: Date;
  schedulerUuid?: string;
  jobGroup?: string;
  target?: string;
  targetType?: SchedulerTargetType;
  details: SchedulerDetails;
}

/**
 * Input type for creating a scheduler log (omits auto-generated fields)
 */
type CreateSchedulerLog = Omit<SchedulerLog, 'createdAt'>;

/**
 * Scheduler execution history with related metadata
 */
interface SchedulerWithLogs {
  schedulers: SchedulerAndTargets[];
  users: Array<{ firstName: string; lastName: string; userUuid: string }>;
  charts: Array<{ name: string; savedChartUuid: string }>;
  dashboards: Array<{ name: string; dashboardUuid: string }>;
  logs: SchedulerLog[];
}

/**
 * API response for scheduler logs with pagination
 */
interface ApiSchedulerLogsResponse {
  status: 'ok';
  results: KnexPaginatedData<SchedulerWithLogs>;
}

/**
 * Overall status for a scheduler run
 */
enum SchedulerRunStatus {
  COMPLETED = 'completed',
  PARTIAL_FAILURE = 'partial_failure',
  FAILED = 'failed',
  RUNNING = 'running',
  SCHEDULED = 'scheduled',
}

/**
 * Counts of log entries by status
 */
interface LogCounts {
  total: number;
  scheduled: number;
  started: number;
  completed: number;
  error: number;
}

/**
 * Aggregated view of a scheduler run with status and log counts
 */
interface SchedulerRun {
  runId: string;
  schedulerUuid: string;
  schedulerName: string;
  scheduledTime: Date;
  status: SchedulerJobStatus; // Parent job status from database
  runStatus: SchedulerRunStatus; // Computed status for entire run
  createdAt: Date;
  details: Record<string, any> | null;
  logCounts: LogCounts;
  // Metadata for filtering and display
  resourceType: 'chart' | 'dashboard';
  resourceUuid: string;
  resourceName: string;
  createdByUserUuid: string;
  createdByUserName: string;
  format: SchedulerFormat; // CSV, IMAGE, GSHEETS, etc.
}

/**
 * API response for scheduler runs with pagination
 */
interface ApiSchedulerRunsResponse {
  status: 'ok';
  results: KnexPaginatedData<SchedulerRun[]>;
}

/**
 * Detailed log entry for a specific run
 */
interface SchedulerRunLog {
  jobId: string;
  task: SchedulerTaskName;
  status: SchedulerJobStatus;
  scheduledTime: Date;
  createdAt: Date;
  jobGroup: string;
  target: string | null;
  targetType: SchedulerTargetType | null;
  details: SchedulerDetails | null;
  isParent: boolean;
}

/**
 * Complete log details for a specific scheduler run
 */
interface SchedulerRunLogsResponse {
  runId: string;
  schedulerUuid: string;
  schedulerName: string;
  scheduledTime: Date;
  logs: SchedulerRunLog[];
  // Metadata
  resourceType: 'chart' | 'dashboard';
  resourceUuid: string;
  resourceName: string;
  createdByUserUuid: string;
  createdByUserName: string;
}

/**
 * API response for scheduler run logs
 */
interface ApiSchedulerRunLogsResponse {
  status: 'ok';
  results: SchedulerRunLogsResponse;
}

Scheduler Task List Types

Types defining the available scheduler task names and their payload mappings for the job queue system.

/**
 * Enterprise edition scheduler tasks
 */
const EE_SCHEDULER_TASKS = {
  SLACK_AI_PROMPT: 'slackAiPrompt',
  AI_AGENT_EVAL_RESULT: 'aiAgentEvalResult',
  EMBED_ARTIFACT_VERSION: 'embedArtifactVersion',
  GENERATE_ARTIFACT_QUESTION: 'generateArtifactQuestion',
} as const;

/**
 * All scheduler task names (both OSS and EE)
 */
const SCHEDULER_TASKS = {
  HANDLE_SCHEDULED_DELIVERY: 'handleScheduledDelivery',
  SEND_SLACK_NOTIFICATION: 'sendSlackNotification',
  SEND_EMAIL_NOTIFICATION: 'sendEmailNotification',
  SEND_MSTEAMS_NOTIFICATION: 'sendMsTeamsNotification',
  UPLOAD_GSHEETS: 'uploadGsheets',
  DOWNLOAD_CSV: 'downloadCsv',
  UPLOAD_GSHEET_FROM_QUERY: 'uploadGsheetFromQuery',
  VALIDATE_PROJECT: 'validateProject',
  COMPILE_PROJECT: 'compileProject',
  CREATE_PROJECT_WITH_COMPILE: 'createProjectWithCompile',
  TEST_AND_COMPILE_PROJECT: 'testAndCompileProject',
  SQL_RUNNER: 'sqlRunner',
  SQL_RUNNER_PIVOT_QUERY: 'sqlRunnerPivotQuery',
  REPLACE_CUSTOM_FIELDS: 'replaceCustomFields',
  INDEX_CATALOG: 'indexCatalog',
  GENERATE_DAILY_JOBS: 'generateDailyJobs',
  EXPORT_CSV_DASHBOARD: 'exportCsvDashboard',
  RENAME_RESOURCES: 'renameResources',
  CLEAN_QUERY_HISTORY: 'cleanQueryHistory',
  DOWNLOAD_ASYNC_QUERY_RESULTS: 'downloadAsyncQueryResults',
  ...EE_SCHEDULER_TASKS,
} as const;

/**
 * Array of all valid task names
 */
const ALL_TASK_NAMES: SchedulerTaskName[];

/**
 * Maps each scheduler task to its specific payload type
 */
interface TaskPayloadMap {
  handleScheduledDelivery: ScheduledDeliveryPayload;
  sendSlackNotification: SlackNotificationPayload;
  sendEmailNotification: EmailNotificationPayload;
  sendMsTeamsNotification: MsTeamsNotificationPayload;
  uploadGsheets: GsheetsNotificationPayload;
  downloadCsv: DownloadCsvPayload;
  uploadGsheetFromQuery: UploadMetricGsheetPayload;
  validateProject: ValidateProjectPayload;
  compileProject: CompileProjectPayload;
  createProjectWithCompile: SchedulerCreateProjectWithCompilePayload;
  testAndCompileProject: CompileProjectPayload;
  sqlRunner: SqlRunnerPayload;
  sqlRunnerPivotQuery: SqlRunnerPivotQueryPayload;
  replaceCustomFields: ReplaceCustomFieldsPayload;
  indexCatalog: SchedulerIndexCatalogJobPayload;
  generateDailyJobs: TraceTaskBase;
  exportCsvDashboard: ExportCsvDashboardPayload;
  slackAiPrompt: SlackPromptJobPayload;
  renameResources: RenameResourcesPayload;
  cleanQueryHistory: TraceTaskBase;
  downloadAsyncQueryResults: DownloadAsyncQueryResultsPayload;
  aiAgentEvalResult: AiAgentEvalRunJobPayload;
  embedArtifactVersion: EmbedArtifactVersionJobPayload;
  generateArtifactQuestion: GenerateArtifactQuestionJobPayload;
}

/**
 * Maps enterprise edition tasks to their payload types
 */
interface EETaskPayloadMap {
  slackAiPrompt: SlackPromptJobPayload;
  aiAgentEvalResult: AiAgentEvalRunJobPayload;
  embedArtifactVersion: EmbedArtifactVersionJobPayload;
  generateArtifactQuestion: GenerateArtifactQuestionJobPayload;
}

/**
 * Union type of all valid scheduler task names
 */
type SchedulerTaskName = typeof SCHEDULER_TASKS[keyof typeof SCHEDULER_TASKS];

/**
 * Type guard to check if a string is a valid scheduler task name
 */
function isSchedulerTaskName(task: string): task is SchedulerTaskName;

Search

Search functionality for finding spaces, dashboards, charts, tables, and fields across Lightdash projects with filtering and ranking.

Search Result Types

type SpaceSearchResult = Pick<Space, 'uuid' | 'name'> & {
  search_rank: number;
};

type DashboardSearchResult = Pick<
  Dashboard,
  'uuid' | 'name' | 'description' | 'spaceUuid' | 'projectUuid'
> & {
  validationErrors: {
    validationId: ValidationErrorDashboardResponse['validationId'];
  }[];
  viewsCount: number;
  firstViewedAt: string | null;
  lastModified: string | null;
  createdBy: {
    firstName: string;
    lastName: string;
    userUuid: string;
  } | null;
  lastUpdatedBy: {
    firstName: string;
    lastName: string;
    userUuid: string;
  } | null;
  charts: {
    uuid: string;
    name: string;
    description?: string;
    chartType: ChartKind;
    viewsCount: number;
  }[];
  search_rank: number;
};

type SavedChartSearchResult = Pick<
  SavedChart,
  'uuid' | 'name' | 'description' | 'spaceUuid' | 'projectUuid'
> & {
  chartType: ChartKind;
  validationErrors: {
    validationId: ValidationErrorChartResponse['validationId'];
  }[];
  chartSource: 'saved';
  viewsCount: number;
  firstViewedAt: string | null;
  lastModified: string | null;
  createdBy: {
    firstName: string;
    lastName: string;
    userUuid: string;
  } | null;
  lastUpdatedBy: {
    firstName: string;
    lastName: string;
    userUuid: string;
  } | null;
  search_rank: number;
};

type SqlChartSearchResult = Pick<
  SqlChart,
  'name' | 'description' | 'slug'
> & {
  uuid: SqlChart['savedSqlUuid'];
  chartType: ChartKind;
  spaceUuid: SqlChart['space']['uuid'];
  projectUuid: SqlChart['project']['projectUuid'];
  chartSource: 'sql';
  viewsCount: number;
  firstViewedAt: string | null;
  lastModified: string | null;
  createdBy: {
    firstName: string;
    lastName: string;
    userUuid: string;
  } | null;
  lastUpdatedBy: {
    firstName: string;
    lastName: string;
    userUuid: string;
  } | null;
  search_rank: number;
};

type AllChartsSearchResult = Pick<
  SavedChartSearchResult,
  'uuid' | 'name' | 'description' | 'spaceUuid' | 'projectUuid'
> &
  Partial<Pick<SqlChartSearchResult, 'slug'>> & {
    chartType: ChartKind;
    chartSource: 'saved' | 'sql';
    viewsCount: number;
    firstViewedAt: string | null;
    lastModified: string | null;
    createdBy: {
      firstName: string;
      lastName: string;
      userUuid: string;
    } | null;
    lastUpdatedBy: {
      firstName: string;
      lastName: string;
      userUuid: string;
    } | null;
    search_rank: number;
  };

type TableSearchResult = Pick<
  Table,
  'name' | 'label' | 'description' | 'requiredAttributes'
> & {
  explore: string;
  exploreLabel: string;
  regexMatchCount: number;
};

type TableErrorSearchResult = Pick<
  TableSearchResult,
  'explore' | 'exploreLabel'
> & {
  validationErrors: {
    validationId: ValidationErrorTableResponse['validationId'];
  }[];
};

type FieldSearchResult = Pick<
  Dimension | Metric,
  | 'name'
  | 'label'
  | 'description'
  | 'type'
  | 'fieldType'
  | 'table'
  | 'tableLabel'
> & {
  requiredAttributes?: Record<string, string | string[]>;
  tablesRequiredAttributes?: Record<
    string,
    Record<string, string | string[]>
  >;
  explore: string;
  exploreLabel: string;
  regexMatchCount: number;
};

type DashboardTabResult = {
  uuid: string; // Tab uuid
  name: string; // Tab name
  dashboardUuid: string;
  dashboardName: string;
  spaceUuid: string;
};

type SearchResult =
  | SpaceSearchResult
  | DashboardSearchResult
  | DashboardTabResult
  | SavedChartSearchResult
  | SqlChartSearchResult
  | AllChartsSearchResult
  | TableErrorSearchResult
  | TableSearchResult
  | FieldSearchResult;

type SearchResults = {
  spaces: SpaceSearchResult[];
  dashboards: DashboardSearchResult[];
  savedCharts: SavedChartSearchResult[];
  sqlCharts: SqlChartSearchResult[];
  tables: (TableSearchResult | TableErrorSearchResult)[];
  fields: FieldSearchResult[];
  pages: PageResult[];
  dashboardTabs: DashboardTabResult[];
};

Search Item Types

enum SearchItemType {
  DASHBOARD = 'dashboard',
  DASHBOARD_TAB = 'dashboard_tab',
  CHART = 'saved_chart',
  SQL_CHART = 'sql_chart',
  SPACE = 'space',
  TABLE = 'table',
  FIELD = 'field',
  PAGE = 'page',
}

Search Filters

type SearchFilters = {
  type?: string; // the type filter can be any string, but it should be one of the EntityType to be valid
  fromDate?: string;
  toDate?: string;
  createdByUuid?: string;
};

Search Utility Functions

/**
 * Type guard to check if a search result is an explore result (table or field)
 */
function isExploreSearchResult(
  value: SearchResult
): value is TableSearchResult | FieldSearchResult;

/**
 * Type guard to check if a search result is a field result
 */
function isFieldSearchResult(
  value: SearchResult
): value is FieldSearchResult;

/**
 * Type guard to check if a search result is a table error result
 */
function isTableErrorSearchResult(
  value: SearchResult
): value is TableErrorSearchResult;

/**
 * Type guard to check if a search result is a saved chart
 */
function isSavedChartSearchResult(
  value: SearchResult
): value is SavedChartSearchResult;

/**
 * Type guard to check if a search result is a SQL chart
 */
function isSqlChartSearchResult(
  value: SearchResult
): value is SqlChartSearchResult;

/**
 * Type guard to check if a search result is a dashboard
 */
function isDashboardSearchResult(
  value: SearchResult
): value is DashboardSearchResult;

/**
 * Get the unique identifier for a search result
 */
function getSearchResultId(meta: SearchResult | undefined): string;

/**
 * Convert a SearchResults key to its corresponding SearchItemType
 */
function getSearchItemTypeFromResultKey(
  searchResultKey: keyof SearchResults
): SearchItemType;

Metrics Explorer Types

Types for the Metrics Explorer feature, which allows users to explore and compare metrics over time with segmentation and period-over-period comparison.

Metrics Explorer Comparison Types

enum MetricExplorerComparison {
  NONE = 'none',
  PREVIOUS_PERIOD = 'previous_period',
  DIFFERENT_METRIC = 'different_metric',
}

Metrics Explorer Query

type MetricExplorerPartialDateRange = [Date | null, Date | null];
type MetricExplorerDateRange = [Date, Date];

type MetricExplorerQuery =
  | {
      comparison: MetricExplorerComparison.NONE;
      segmentDimension: string | null;
    }
  | {
      comparison: MetricExplorerComparison.PREVIOUS_PERIOD;
    }
  | {
      comparison: MetricExplorerComparison.DIFFERENT_METRIC;
      metric: {
        label: string;
        table: string;
        name: string;
      };
    };

Metrics Explorer Data Points

type MetricExploreDataPoint = {
  date: Date;
  segment: string | null;
  metric: {
    value: number | null;
    label: string | null;
  };
  compareMetric: {
    value: number | null;
    label: string | null;
  };
};

type MetricExploreDataPointWithDateValue = MetricExploreDataPoint & {
  dateValue: number;
};

Metrics Explorer Results

type MetricsExplorerQueryResults = {
  metric: MetricWithAssociatedTimeDimension;
  compareMetric: MetricWithAssociatedTimeDimension | null;
  segmentDimension: Dimension | null;
  fields: ItemsMap;
  results: MetricExploreDataPointWithDateValue[];
  hasFilteredSeries: boolean;
};

type ApiMetricsExplorerQueryResults = {
  status: 'ok';
  results: MetricsExplorerQueryResults;
};

enum MetricTotalComparisonType {
  NONE = 'none',
  PREVIOUS_PERIOD = 'previous_period',
}

type MetricTotalResults = {
  value: number | null;
  comparisonValue: number | null;
  metric: MetricWithAssociatedTimeDimension;
};

type ApiMetricsExplorerTotalResults = {
  status: 'ok';
  results: MetricTotalResults;
};

Usage Example:

import {
  type MetricsExplorerQueryResults,
  type MetricExplorerQuery,
  MetricExplorerComparison,
} from '@lightdash/common';

// Query with no comparison
const query1: MetricExplorerQuery = {
  comparison: MetricExplorerComparison.NONE,
  segmentDimension: 'customers.region',
};

// Query with previous period comparison
const query2: MetricExplorerQuery = {
  comparison: MetricExplorerComparison.PREVIOUS_PERIOD,
};

// Query with different metric comparison
const query3: MetricExplorerQuery = {
  comparison: MetricExplorerComparison.DIFFERENT_METRIC,
  metric: {
    label: 'Total Orders',
    table: 'orders',
    name: 'total_orders',
  },
};

Install with Tessl CLI

npx tessl i tessl/npm-lightdash--common

docs

api

index.md

tile.json