import {z} from 'zod' export type DateGranularity = 'Second' | 'Minute' | 'Hour' | 'Day' | 'Week' | 'Month' | 'Quarter' | 'Year'; export type DateZoom = {xAxisFieldId?: string | undefined, granularity?: (DateGranularity | string) | undefined}; export type PivotSortAnchor = {value: string | number | boolean | null, reference: string}; export type SortField = {pivotValues?: Array | undefined, nullsFirst?: boolean | undefined, descending: boolean, fieldId: string}; export type AnyType = unknown; export type CreateApiApiV1SavedChartUuidChartAndResultsArgs = {chartUuid: string, body: {autoRefresh?: boolean | undefined, dateZoom?: DateZoom | undefined, dashboardUuid: string, dashboardSorts: Array, invalidateCache?: boolean | undefined, dashboardFilters: AnyType}}; export type CreateApiApiV1SavedChartUuidChartAndResultsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const tableCalculationTotalMode = z.enum(["formula", "sum_of_rows", "none"]); export const tableCalculationType = z.enum(["number", "string", "date", "timestamp", "boolean"]); export const customFormatType = z.enum(["default", "percent", "currency", "number", "id", "date", "timestamp", "bytes_si", "bytes_iec", "custom"]); export const numberSeparator = z.enum(["default", "commaPeriod", "spacePeriod", "periodComma", "noSeparatorPeriod", "apostrophePeriod"]); export const compact = z.enum(["auto", "thousands", "millions", "billions", "trillions", "kilobytes", "megabytes", "gigabytes", "terabytes", "petabytes", "kibibytes", "mebibytes", "gibibytes", "tebibytes", "pebibytes"]); export const compactOrAlias = z.union([compact, z.enum(["K", "thousand", "M", "million", "B", "billion", "T", "trillion", "KB", "kilobyte", "MB", "megabyte", "GB", "gigabyte", "TB", "terabyte", "PB", "petabyte", "KiB", "kibibyte", "MiB", "mebibyte", "GiB", "gibibyte", "TiB", "tebibyte", "PiB", "pebibyte"])]); export const timeFrames = z.enum(["RAW", "YEAR", "QUARTER", "MONTH", "WEEK", "DAY", "HOUR", "MINUTE", "SECOND", "MILLISECOND", "DAY_OF_WEEK_INDEX", "DAY_OF_MONTH_NUM", "DAY_OF_YEAR_NUM", "WEEK_NUM", "MONTH_NUM", "QUARTER_NUM", "YEAR_NUM", "DAY_OF_WEEK_NAME", "MONTH_NAME", "QUARTER_NAME", "HOUR_OF_DAY_NUM", "MINUTE_OF_HOUR_NUM"]); export const customFormat = z.object({type: customFormatType, round: z.number().optional(), separator: numberSeparator.optional(), currency: z.string().optional(), compact: compactOrAlias.optional(), prefix: z.string().optional(), suffix: z.string().optional(), timeInterval: timeFrames.optional(), custom: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const sqlTableCalculation = z.object({totalMode: tableCalculationTotalMode.optional(), type: tableCalculationType.optional(), format: customFormat.optional(), displayName: z.string(), name: z.string(), index: z.number().optional(), sql: z.string()}); export const tableCalculationTemplateTypePERCENTCHANGEFROMPREVIOUS = z.literal("percent_change_from_previous"); export const tableCalculationTemplateTypePERCENTOFPREVIOUSVALUE = z.literal("percent_of_previous_value"); export const tableCalculationTemplateTypePERCENTOFCOLUMNTOTAL = z.literal("percent_of_column_total"); export const tableCalculationTemplateTypeRANKINCOLUMN = z.literal("rank_in_column"); export const tableCalculationTemplateTypeRUNNINGTOTAL = z.literal("running_total"); export const frameBoundaryType = z.enum(["unbounded_preceding", "preceding", "current_row", "following", "unbounded_following"]); export const frameBoundary = z.object({offset: z.number().optional(), type: frameBoundaryType}); export const frameType = z.enum(["rows", "range"]); export const frameClause = z.object({end: frameBoundary, start: frameBoundary.optional(), frameType: frameType}); export const windowFunctionType = z.enum(["row_number", "percent_rank", "cume_dist", "rank", "sum", "avg", "count", "min", "max"]); export const tableCalculationTemplateTypeWINDOWFUNCTION = z.literal("window_function"); export const tableCalculationTemplate = z.union([z.object({partitionBy: z.array(z.string()).optional(), orderBy: z.array(z.object({order: z.enum(["asc", "desc", "null"]).nullable(), fieldId: z.string()})), fieldId: z.string(), type: tableCalculationTemplateTypePERCENTCHANGEFROMPREVIOUS}), z.object({partitionBy: z.array(z.string()).optional(), orderBy: z.array(z.object({order: z.enum(["asc", "desc", "null"]).nullable(), fieldId: z.string()})), fieldId: z.string(), type: tableCalculationTemplateTypePERCENTOFPREVIOUSVALUE}), z.object({partitionBy: z.array(z.string()).optional(), fieldId: z.string(), type: tableCalculationTemplateTypePERCENTOFCOLUMNTOTAL}), z.object({fieldId: z.string(), type: tableCalculationTemplateTypeRANKINCOLUMN}), z.object({fieldId: z.string(), type: tableCalculationTemplateTypeRUNNINGTOTAL}), z.object({frame: frameClause.optional(), partitionBy: z.array(z.string()), orderBy: z.array(z.object({order: z.enum(["asc", "desc", "null"]).nullable(), fieldId: z.string()})), fieldId: z.string().nullable(), windowFunction: windowFunctionType, type: tableCalculationTemplateTypeWINDOWFUNCTION})]); export const templateTableCalculation = z.object({totalMode: tableCalculationTotalMode.optional(), type: tableCalculationType.optional(), format: customFormat.optional(), displayName: z.string(), name: z.string(), index: z.number().optional(), template: tableCalculationTemplate}); export const formulaTableCalculation = z.object({totalMode: tableCalculationTotalMode.optional(), type: tableCalculationType.optional(), format: customFormat.optional(), displayName: z.string(), name: z.string(), index: z.number().optional(), formula: z.string()}); export const tableCalculation = z.union([sqlTableCalculation, templateTableCalculation, formulaTableCalculation]); export const metricType = z.enum(["percentile", "average", "count", "count_distinct", "sum", "sum_distinct", "average_distinct", "min", "max", "percent_of_previous", "percent_of_total", "running_total", "number", "median", "string", "date", "timestamp", "boolean"]); export const format = z.enum(["km", "mi", "si", "usd", "gbp", "eur", "jpy", "dkk", "id", "percent"]); export const anyType = z.unknown(); export const filterOperator = z.enum(["isNull", "notNull", "equals", "notEquals", "startsWith", "endsWith", "include", "doesNotInclude", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "inThePast", "notInThePast", "inTheNext", "inTheCurrent", "notInTheCurrent", "inBetween", "notInBetween", "inPeriodToDate"]); export const metricFilterRule = z.object({includeNull: z.boolean().optional(), values: z.array(anyType).optional(), operator: filterOperator, id: z.string(), target: z.object({fieldRef: z.string()}), settings: anyType.optional(), disabled: z.boolean().optional(), required: z.boolean().optional(), caseSensitive: z.boolean().optional()}).and(z.record(z.string(), z.unknown())); export const fieldId = z.string(); export const additionalMetric = z.object({label: z.string().optional(), type: metricType, description: z.string().optional(), sql: z.string(), hidden: z.boolean().optional(), round: z.number().optional(), compact: compactOrAlias.optional(), format: z.union([format, z.string()]).optional(), separator: numberSeparator.optional(), table: z.string(), name: z.string(), index: z.number().optional(), filters: z.array(metricFilterRule).optional(), baseDimensionName: z.string().optional(), baseMetricName: z.string().optional(), uuid: z.string().nullable().optional(), percentile: z.number().optional(), distinctKeys: z.array(z.string()).optional(), formatOptions: customFormat.optional(), generationType: z.literal("periodOverPeriod").optional(), baseMetricId: fieldId.optional(), timeDimensionId: fieldId.optional(), granularity: timeFrames.optional(), periodOffset: z.number().optional()}).and(z.record(z.string(), z.unknown())); export const customDimensionTypeBIN = z.literal("bin"); export const binTypeFIXEDNUMBER = z.literal("fixed_number"); export const fixedNumberBinDimension = z.object({id: z.string(), name: z.string(), table: z.string(), type: customDimensionTypeBIN, dimensionId: fieldId, binType: binTypeFIXEDNUMBER, binNumber: z.number()}).and(z.record(z.string(), z.unknown())); export const binTypeFIXEDWIDTH = z.literal("fixed_width"); export const fixedWidthBinDimension = z.object({id: z.string(), name: z.string(), table: z.string(), type: customDimensionTypeBIN, dimensionId: fieldId, binType: binTypeFIXEDWIDTH, binWidth: z.number()}).and(z.record(z.string(), z.unknown())); export const binTypeCUSTOMRANGE = z.literal("custom_range"); export const binRange = z.object({to: z.number().optional(), from: z.number().optional()}); export const customRangeBinDimension = z.object({id: z.string(), name: z.string(), table: z.string(), type: customDimensionTypeBIN, dimensionId: fieldId, binType: binTypeCUSTOMRANGE, customRange: z.array(binRange)}).and(z.record(z.string(), z.unknown())); export const binTypeCUSTOMGROUP = z.literal("custom_group"); export const groupValueMatchType = z.enum(["exact", "startsWith", "endsWith", "includes"]); export const groupValueRule = z.object({value: z.string(), matchType: groupValueMatchType}); export const binGroup = z.object({values: z.array(groupValueRule), name: z.string()}); export const customGroupBinDimension = z.object({id: z.string(), name: z.string(), table: z.string(), type: customDimensionTypeBIN, dimensionId: fieldId, binType: binTypeCUSTOMGROUP, customGroups: z.array(binGroup)}).and(z.record(z.string(), z.unknown())); export const customBinDimension = z.union([fixedNumberBinDimension, fixedWidthBinDimension, customRangeBinDimension, customGroupBinDimension]); export const customDimensionTypeSQL = z.literal("sql"); export const dimensionType = z.enum(["string", "number", "timestamp", "date", "boolean"]); export const customSqlDimension = z.object({id: z.string(), name: z.string(), table: z.string(), type: customDimensionTypeSQL, sql: z.string(), dimensionType: dimensionType}).and(z.record(z.string(), z.unknown())); export const customDimension = z.union([customBinDimension, customSqlDimension]); export const fieldTypeMETRIC = z.literal("metric"); export const sourcePosition = z.object({character: z.number(), line: z.number()}); export const source = z.object({content: z.string(), highlight: z.object({end: sourcePosition, start: sourcePosition}).optional(), range: z.object({end: sourcePosition, start: sourcePosition}), path: z.string()}); export const fieldUrl = z.object({label: z.string(), url: z.string()}); export const recordStringStringOrStringArray = z.record(z.string(), z.union([z.string(), z.array(z.string())])); export const defaultTimeDimension = z.object({interval: timeFrames, field: z.string()}); export const metric = z.object({fieldType: fieldTypeMETRIC, type: metricType, name: z.string(), label: z.string(), table: z.string(), tableLabel: z.string(), sql: z.string(), description: z.string().optional(), source: source.optional(), hidden: z.boolean(), compact: compactOrAlias.optional(), round: z.number().optional(), format: z.union([format, z.string()]).optional(), separator: numberSeparator.optional(), groupLabel: z.string().optional(), groups: z.array(z.string()).optional(), urls: z.array(fieldUrl).optional(), index: z.number().optional(), tags: z.array(z.string()).optional(), parameterReferences: z.array(z.string()).optional(), showUnderlyingValues: z.array(z.string()).optional(), filters: z.array(metricFilterRule).optional(), percentile: z.number().optional(), distinctKeys: z.array(z.string()).optional(), formatOptions: customFormat.optional(), dimensionReference: z.string().optional(), baseDimensionType: dimensionType.optional(), baseDimensionTimeInterval: timeFrames.optional(), requiredAttributes: recordStringStringOrStringArray.optional(), anyAttributes: recordStringStringOrStringArray.optional(), defaultTimeDimension: defaultTimeDimension.optional(), spotlight: z.object({owner: z.string().optional(), defaultFilter: metricFilterRule.optional(), defaultSegment: z.string().optional(), segmentBy: z.array(z.string()).optional(), filterBy: z.array(z.string()).optional(), categories: z.array(z.string()).optional(), visibility: z.enum(["show", "hide"])}).optional(), drivers: z.array(z.string()).optional(), aiHint: z.union([z.string(), z.array(z.string())]).optional(), richText: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const fieldType = z.enum(["metric", "dimension"]); export const field = z.object({fieldType: fieldType, type: z.string(), name: z.string(), label: z.string(), table: z.string(), tableLabel: z.string(), sql: z.string(), description: z.string().optional(), source: source.optional(), hidden: z.boolean(), compact: compactOrAlias.optional(), round: z.number().optional(), format: z.union([format, z.string()]).optional(), separator: numberSeparator.optional(), groupLabel: z.string().optional(), groups: z.array(z.string()).optional(), urls: z.array(fieldUrl).optional(), index: z.number().optional(), tags: z.array(z.string()).optional(), parameterReferences: z.array(z.string()).optional()}).and(z.record(z.string(), z.unknown())); export const recordStringItemOrAdditionalMetric = z.record(z.string(), z.union([tableCalculation, additionalMetric, customDimension, metric, field])); export const preAggregateMissReasonNOPREAGGREGATESDEFINED = z.literal("no_pre_aggregates_defined"); export const preAggregateMissReasonDIMENSIONNOTINPREAGGREGATE = z.literal("dimension_not_in_pre_aggregate"); export const preAggregateMissReasonMETRICNOTINPREAGGREGATE = z.literal("metric_not_in_pre_aggregate"); export const preAggregateMissReasonNONADDITIVEMETRIC = z.literal("non_additive_metric"); export const preAggregateMissReasonCUSTOMSQLMETRIC = z.literal("custom_sql_metric"); export const preAggregateMissReasonFILTERDIMENSIONNOTINPREAGGREGATE = z.literal("filter_dimension_not_in_pre_aggregate"); export const preAggregateMissReasonPREAGGREGATEFILTERNOTSATISFIED = z.literal("pre_aggregate_filter_not_satisfied"); export const preAggregateMissReasonGRANULARITYTOOFINE = z.literal("granularity_too_fine"); export const preAggregateMissReasonCUSTOMDIMENSIONPRESENT = z.literal("custom_dimension_present"); export const preAggregateMissReasonCUSTOMMETRICPRESENT = z.literal("custom_metric_present"); export const preAggregateMissReasonTABLECALCULATIONPRESENT = z.literal("table_calculation_present"); export const preAggregateMissReasonUSERBYPASS = z.literal("user_bypass"); export const preAggregateMissReasonEXPLORERESOLUTIONERROR = z.literal("explore_resolution_error"); export const preAggregateMissReasonNOACTIVEMATERIALIZATION = z.literal("no_active_materialization"); export const preAggregateMatchMiss = z.union([z.object({reason: preAggregateMissReasonNOPREAGGREGATESDEFINED}), z.object({fieldId: fieldId, reason: preAggregateMissReasonDIMENSIONNOTINPREAGGREGATE}), z.object({fieldId: fieldId, reason: preAggregateMissReasonMETRICNOTINPREAGGREGATE}), z.object({fieldId: fieldId, reason: preAggregateMissReasonNONADDITIVEMETRIC}), z.object({fieldId: fieldId, reason: preAggregateMissReasonCUSTOMSQLMETRIC}), z.object({fieldId: fieldId, reason: preAggregateMissReasonFILTERDIMENSIONNOTINPREAGGREGATE}), z.object({fieldId: fieldId, reason: preAggregateMissReasonPREAGGREGATEFILTERNOTSATISFIED}), z.object({preAggregateTimeDimension: z.string(), preAggregateGranularity: timeFrames, queryGranularity: timeFrames, fieldId: fieldId, reason: preAggregateMissReasonGRANULARITYTOOFINE}), z.object({reason: preAggregateMissReasonCUSTOMDIMENSIONPRESENT}), z.object({fieldId: fieldId, reason: preAggregateMissReasonCUSTOMMETRICPRESENT}), z.object({fieldId: fieldId, reason: preAggregateMissReasonTABLECALCULATIONPRESENT}), z.object({preAggregateName: z.string(), reason: preAggregateMissReasonUSERBYPASS}), z.object({reason: preAggregateMissReasonEXPLORERESOLUTIONERROR}), z.object({reason: preAggregateMissReasonNOACTIVEMATERIALIZATION})]); export const cacheMetadata = z.object({preAggregate: z.object({reason: preAggregateMatchMiss.optional(), name: z.string().optional(), hit: z.boolean()}).optional(), cacheHit: z.boolean(), cacheKey: z.string().optional(), cacheExpiresAt: z.string().optional(), cacheUpdatedTime: z.string().optional()}); export const pickCompiledDimensionLabelOrNameOrTable = z.object({name: z.string(), label: z.string(), table: z.string()}); export const pivotSortAnchor = z.object({value: z.union([z.string(), z.number(), z.boolean()]).nullable(), reference: z.string()}); export const sortField = z.object({pivotValues: z.array(pivotSortAnchor).optional(), nullsFirst: z.boolean().optional(), descending: z.boolean(), fieldId: z.string()}); export const filterGroupResponse = z.union([z.object({or: z.array(anyType), id: z.string()}), z.object({and: z.array(anyType), id: z.string()})]); export const filtersResponse = z.object({tableCalculations: filterGroupResponse.optional(), metrics: filterGroupResponse.optional(), dimensions: filterGroupResponse.optional()}); export const metricQueryResponse = z.object({metadata: z.object({hasADateDimension: pickCompiledDimensionLabelOrNameOrTable}).optional(), customDimensions: z.array(customDimension).optional(), additionalMetrics: z.array(additionalMetric).optional(), tableCalculations: z.array(tableCalculation), limit: z.number(), sorts: z.array(sortField), filters: filtersResponse, metrics: z.array(fieldId), dimensions: z.array(fieldId), exploreName: z.string()}); export const apiRunQueryResponse = z.object({results: z.object({fields: recordStringItemOrAdditionalMetric.optional(), rows: z.array(anyType), cacheMetadata: cacheMetadata, metricQuery: metricQueryResponse}), status: z.literal("ok")}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get chart and results * * POST /api/v1/saved/{chartUuid}/chart-and-results */ export const createApiApiV1SavedChartUuidChartAndResults = async (args: CreateApiApiV1SavedChartUuidChartAndResultsArgs, options: CreateApiApiV1SavedChartUuidChartAndResultsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/saved/${encodeURIComponent(String(args.chartUuid))}/chart-and-results${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(apiRunQueryResponse, await res.json()) };