import {z} from 'zod' export type PivotConfig = {hiddenDimensionFieldIds?: Array | undefined, rowTotals?: boolean | undefined, columnTotals?: boolean | undefined, visibleMetricFieldIds?: Array | undefined, hiddenMetricFieldIds?: Array | undefined, columnOrder?: Array | undefined, rowFieldIds?: Array | undefined, metricsAsRows: boolean, pivotDimensions: Array}; export type CustomLabel = {[key: string]: string}; export type PickCompiledDimensionLabelOrNameOrTable = {name: string, label: string, table: string}; export type CustomDimensionTypeBIN = 'bin'; export type FieldId = string; export type BinTypeFIXEDNUMBER = 'fixed_number'; export type FixedNumberBinDimension = {id: string, name: string, table: string, type: CustomDimensionTypeBIN, dimensionId: FieldId, binType: BinTypeFIXEDNUMBER, binNumber: number} | {[key: string]: unknown}; export type BinTypeFIXEDWIDTH = 'fixed_width'; export type FixedWidthBinDimension = {id: string, name: string, table: string, type: CustomDimensionTypeBIN, dimensionId: FieldId, binType: BinTypeFIXEDWIDTH, binWidth: number} | {[key: string]: unknown}; export type BinTypeCUSTOMRANGE = 'custom_range'; export type BinRange = {to?: number | undefined, from?: number | undefined}; export type CustomRangeBinDimension = {id: string, name: string, table: string, type: CustomDimensionTypeBIN, dimensionId: FieldId, binType: BinTypeCUSTOMRANGE, customRange: Array} | {[key: string]: unknown}; export type BinTypeCUSTOMGROUP = 'custom_group'; export type GroupValueMatchType = 'exact' | 'startsWith' | 'endsWith' | 'includes'; export type GroupValueRule = {value: string, matchType: GroupValueMatchType}; export type BinGroup = {values: Array, name: string}; export type CustomGroupBinDimension = {id: string, name: string, table: string, type: CustomDimensionTypeBIN, dimensionId: FieldId, binType: BinTypeCUSTOMGROUP, customGroups: Array} | {[key: string]: unknown}; export type CustomBinDimension = FixedNumberBinDimension | FixedWidthBinDimension | CustomRangeBinDimension | CustomGroupBinDimension; export type CustomDimensionTypeSQL = 'sql'; export type DimensionType = 'string' | 'number' | 'timestamp' | 'date' | 'boolean'; export type CustomSqlDimension = {id: string, name: string, table: string, type: CustomDimensionTypeSQL, sql: string, dimensionType: DimensionType} | {[key: string]: unknown}; export type CustomDimension = CustomBinDimension | CustomSqlDimension; export type MetricType = '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 type Compact = 'auto' | 'thousands' | 'millions' | 'billions' | 'trillions' | 'kilobytes' | 'megabytes' | 'gigabytes' | 'terabytes' | 'petabytes' | 'kibibytes' | 'mebibytes' | 'gibibytes' | 'tebibytes' | 'pebibytes'; export type CompactOrAlias = Compact | '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 type Format = 'km' | 'mi' | 'si' | 'usd' | 'gbp' | 'eur' | 'jpy' | 'dkk' | 'id' | 'percent'; export type NumberSeparator = 'default' | 'commaPeriod' | 'spacePeriod' | 'periodComma' | 'noSeparatorPeriod' | 'apostrophePeriod'; export type AnyType = unknown; export type FilterOperator = 'isNull' | 'notNull' | 'equals' | 'notEquals' | 'startsWith' | 'endsWith' | 'include' | 'doesNotInclude' | 'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'inThePast' | 'notInThePast' | 'inTheNext' | 'inTheCurrent' | 'notInTheCurrent' | 'inBetween' | 'notInBetween' | 'inPeriodToDate'; export type MetricFilterRule = {includeNull?: boolean | undefined, values?: Array | undefined, operator: FilterOperator, id: string, target: {fieldRef: string}, settings?: AnyType | undefined, disabled?: boolean | undefined, required?: boolean | undefined, caseSensitive?: boolean | undefined} | {[key: string]: unknown}; export type CustomFormatType = 'default' | 'percent' | 'currency' | 'number' | 'id' | 'date' | 'timestamp' | 'bytes_si' | 'bytes_iec' | 'custom'; export type TimeFrames = '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 type CustomFormat = {type: CustomFormatType, round?: number | undefined, separator?: NumberSeparator | undefined, currency?: string | undefined, compact?: CompactOrAlias | undefined, prefix?: string | undefined, suffix?: string | undefined, timeInterval?: TimeFrames | undefined, custom?: string | undefined} | {[key: string]: unknown}; export type AdditionalMetric = {label?: string | undefined, type: MetricType, description?: string | undefined, sql: string, hidden?: boolean | undefined, round?: number | undefined, compact?: CompactOrAlias | undefined, format?: (Format | string) | undefined, separator?: NumberSeparator | undefined, table: string, name: string, index?: number | undefined, filters?: Array | undefined, baseDimensionName?: string | undefined, baseMetricName?: string | undefined, uuid?: (string | null) | undefined, percentile?: number | undefined, distinctKeys?: Array | undefined, formatOptions?: CustomFormat | undefined, generationType?: 'periodOverPeriod' | undefined, baseMetricId?: FieldId | undefined, timeDimensionId?: FieldId | undefined, granularity?: TimeFrames | undefined, periodOffset?: number | undefined} | {[key: string]: unknown}; export type TableCalculationTotalMode = 'formula' | 'sum_of_rows' | 'none'; export type TableCalculationType = 'number' | 'string' | 'date' | 'timestamp' | 'boolean'; export type SqlTableCalculation = {totalMode?: TableCalculationTotalMode | undefined, type?: TableCalculationType | undefined, format?: CustomFormat | undefined, displayName: string, name: string, index?: number | undefined, sql: string}; export type TableCalculationTemplateTypePERCENTCHANGEFROMPREVIOUS = 'percent_change_from_previous'; export type TableCalculationTemplateTypePERCENTOFPREVIOUSVALUE = 'percent_of_previous_value'; export type TableCalculationTemplateTypePERCENTOFCOLUMNTOTAL = 'percent_of_column_total'; export type TableCalculationTemplateTypeRANKINCOLUMN = 'rank_in_column'; export type TableCalculationTemplateTypeRUNNINGTOTAL = 'running_total'; export type FrameBoundaryType = 'unbounded_preceding' | 'preceding' | 'current_row' | 'following' | 'unbounded_following'; export type FrameBoundary = {offset?: number | undefined, type: FrameBoundaryType}; export type FrameType = 'rows' | 'range'; export type FrameClause = {end: FrameBoundary, start?: FrameBoundary | undefined, frameType: FrameType}; export type WindowFunctionType = 'row_number' | 'percent_rank' | 'cume_dist' | 'rank' | 'sum' | 'avg' | 'count' | 'min' | 'max'; export type TableCalculationTemplateTypeWINDOWFUNCTION = 'window_function'; export type TableCalculationTemplate = {partitionBy?: Array | undefined, orderBy: Array<{order: 'asc' | 'desc' | 'null' | null, fieldId: string}>, fieldId: string, type: TableCalculationTemplateTypePERCENTCHANGEFROMPREVIOUS} | {partitionBy?: Array | undefined, orderBy: Array<{order: 'asc' | 'desc' | 'null' | null, fieldId: string}>, fieldId: string, type: TableCalculationTemplateTypePERCENTOFPREVIOUSVALUE} | {partitionBy?: Array | undefined, fieldId: string, type: TableCalculationTemplateTypePERCENTOFCOLUMNTOTAL} | {fieldId: string, type: TableCalculationTemplateTypeRANKINCOLUMN} | {fieldId: string, type: TableCalculationTemplateTypeRUNNINGTOTAL} | {frame?: FrameClause | undefined, partitionBy: Array, orderBy: Array<{order: 'asc' | 'desc' | 'null' | null, fieldId: string}>, fieldId: string | null, windowFunction: WindowFunctionType, type: TableCalculationTemplateTypeWINDOWFUNCTION}; export type TemplateTableCalculation = {totalMode?: TableCalculationTotalMode | undefined, type?: TableCalculationType | undefined, format?: CustomFormat | undefined, displayName: string, name: string, index?: number | undefined, template: TableCalculationTemplate}; export type FormulaTableCalculation = {totalMode?: TableCalculationTotalMode | undefined, type?: TableCalculationType | undefined, format?: CustomFormat | undefined, displayName: string, name: string, index?: number | undefined, formula: string}; export type TableCalculation = SqlTableCalculation | TemplateTableCalculation | FormulaTableCalculation; 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 FilterGroupResponse = {or: Array, id: string} | {and: Array, id: string}; export type FiltersResponse = {tableCalculations?: FilterGroupResponse | undefined, metrics?: FilterGroupResponse | undefined, dimensions?: FilterGroupResponse | undefined}; export type MetricQueryResponse = {metadata?: {hasADateDimension: PickCompiledDimensionLabelOrNameOrTable} | undefined, customDimensions?: Array | undefined, additionalMetrics?: Array | undefined, tableCalculations: Array, limit: number, sorts: Array, filters: FiltersResponse, metrics: Array, dimensions: Array, exploreName: string}; export type UploadMetricGsheet = {pivotConfig?: PivotConfig | undefined, hiddenFields?: Array | undefined, customLabels?: CustomLabel | undefined, columnOrder: Array, showTableNames: boolean, metricQuery: MetricQueryResponse, exploreId: string, projectUuid: string}; export type CreateApiApiV1GdriveUploadGsheetArgs = {body: UploadMetricGsheet}; export type CreateApiApiV1GdriveUploadGsheetOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const apiJobScheduledResponse = z.object({results: z.object({jobId: z.string()}), 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 }; /** * Upload to Google Sheet * * POST /api/v1/gdrive/upload-gsheet */ export const createApiApiV1GdriveUploadGsheet = async (args: CreateApiApiV1GdriveUploadGsheetArgs, options: CreateApiApiV1GdriveUploadGsheetOptions) => { 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/gdrive/upload-gsheet${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(apiJobScheduledResponse, await res.json()) };