UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

196 lines (195 loc) • 10.2 kB
import { ConstructableOrderBy } from "./filter.js"; import { DateFieldType, NumberFieldType, SortSet } from "./fields.js"; import { DatasourceAction, FieldTypeOf, ReadShape, SoftrDatasources } from "../action.js"; import { WhereCallback } from "./record.js"; //#region src/datasource/chart.d.ts declare const dimensionValue: unique symbol; declare const measureValue: unique symbol; /** A chart column that groups rows. The brand carries the value type the column reads back as. */ type Dimension<TValue$1> = { readonly [dimensionValue]: TValue$1; }; /** A chart column that aggregates rows. The brand carries the value type the column reads back as. */ type Measure<TValue$1> = { readonly [measureValue]: TValue$1; }; type ColumnValue<T> = T extends Dimension<infer TValue> ? TValue : T extends Measure<infer TValue> ? TValue : never; type DateBuckets = { /** Groups by calendar day. The value reads as `"2025-06-14"`. */ readonly byDay: Dimension<string | null>; /** * Groups by calendar week. The value is the ISO date of the week's Monday. Monday-based, * while `byDayOfWeek` counts from Sunday: the server disagrees with itself, so the two * cannot be lined up by arithmetic alone. */ readonly byWeek: Dimension<string | null>; /** Groups by calendar month. The value reads as `"2025-06"`. */ readonly byMonth: Dimension<string | null>; /** Groups by calendar quarter. The value is a display string like `"Q2 2025"`, not a parseable date. */ readonly byQuarter: Dimension<string | null>; /** Groups by calendar year. The value is the year as a number. */ readonly byYear: Dimension<number | null>; /** * Groups by day of week, 1 through 7 with 1 as Sunday. Sunday-based, while `byWeek` is * Monday-based: the server disagrees with itself, so the two cannot be lined up by * arithmetic alone. */ readonly byDayOfWeek: Dimension<number | null>; /** Groups by month of year, 1 through 12. */ readonly byMonthOfYear: Dimension<number | null>; /** Groups by quarter of year, 1 through 4. */ readonly byQuarterOfYear: Dimension<number | null>; }; type DatetimeBuckets = DateBuckets & { /** Groups by hour of day, 0 through 23. */ readonly byHourOfDay: Dimension<number | null>; }; type DateDimension = Dimension<string | null> & DateBuckets; type DatetimeDimension = Dimension<string | null> & DatetimeBuckets; type NumericMeasures = { /** Adds the group's values. `null` when the group has none. */ readonly sum: Measure<number | null>; /** Averages the group's values, rounded to two decimals. `null` when the group has none. */ readonly avg: Measure<number | null>; /** The group's smallest value. `null` when the group has none. */ readonly min: Measure<number | null>; /** The group's largest value. `null` when the group has none. */ readonly max: Measure<number | null>; /** Counts the group's distinct values. */ readonly distinct: Measure<number>; }; type DateMeasures = { /** The group's earliest date, as `"2025-06-14"`. `null` when the group has none. */ readonly min: Measure<string | null>; /** The group's latest date, as `"2025-06-14"`. `null` when the group has none. */ readonly max: Measure<string | null>; /** Counts the group's distinct values. */ readonly distinct: Measure<number>; }; type AnyDimension = Dimension<unknown> & DatetimeBuckets; type AnyMeasures = { readonly sum: Measure<number | null>; readonly avg: Measure<number | null>; readonly min: Measure<unknown>; readonly max: Measure<unknown>; readonly distinct: Measure<number>; }; /** A field a chart cannot use for this: the missing leaves are the compile error saying so. */ type Unusable = { readonly [dimensionValue]?: never; }; /** * The handles a `groupBy` callback is handed: one per alias. The bare handle groups by the * field's value; a date field also carries bucket leaves. A multi-value field has no handle * body, because exploding it would count each record once per value and inflate every metric. */ type DimensionSet<TShape extends ReadShape> = keyof SoftrDatasources extends never ? Record<string, AnyDimension> : { [Alias in keyof TShape["fields"]]: DimensionFor<FieldTypeOf<TShape["datasourceId"], TShape["fields"][Alias]>> }; type DimensionFor<TFieldType> = [TFieldType] extends [never] ? AnyDimension : TFieldType extends `${string}[]` | "ATTACHMENT" | "DATE_RANGE" ? Unusable : TFieldType extends "DATE" ? DateDimension : TFieldType extends DateFieldType ? DatetimeDimension : TFieldType extends NumberFieldType ? Dimension<number | null> : TFieldType extends "CHECKBOX" ? Dimension<boolean | null> : Dimension<string | null>; /** * The handles a `metrics` callback is handed: aggregation leaves per alias, gated by the * field's declared type, plus `$count`. A field whose aggregate would come back as a * coerced non-number has no leaves at all. */ type MeasureSet<TShape extends ReadShape> = (keyof SoftrDatasources extends never ? Record<string, AnyMeasures> : { [Alias in keyof TShape["fields"]]: MeasureFor<FieldTypeOf<TShape["datasourceId"], TShape["fields"][Alias]>> }) & { /** Counts the rows in each group. Takes no field: every row counts once. */ readonly $count: Measure<number>; }; type MeasureFor<TFieldType> = [TFieldType] extends [never] ? AnyMeasures : TFieldType extends `${string}[]` ? Unusable : TFieldType extends NumberFieldType ? NumericMeasures : TFieldType extends DateFieldType ? DateMeasures : Unusable; type IsUnion<T, TAll = T> = [T] extends [never] ? false : T extends unknown ? [TAll] extends [T] ? false : true : never; type MoreThanTwo<TKeys, TAll = TKeys> = TKeys extends unknown ? IsUnion<Exclude<TAll, TKeys>> : never; type GroupByBounds<TGroups> = [keyof TGroups] extends [never] ? { __error: "a chart needs at least one column to group by"; } : true extends MoreThanTwo<keyof TGroups> ? { __error: "a chart may group by at most two columns"; } : unknown; type MetricBounds<TMetrics, TGroups> = [Extract<keyof TMetrics, keyof TGroups>] extends [never] ? unknown : { __error: "a metric key must not collide with a group key"; }; /** One row, keyed by the caller's own `groupBy` and `metrics` keys. */ type ChartRow<TGroups, TMetrics> = { [K in keyof TGroups | keyof TMetrics]: ColumnValue<(TGroups & TMetrics)[K]> }; interface ChartResult<TRow> { data: Array<TRow>; executionTimestamp: Date; } /** A chart before `groupBy`. It cannot be awaited: an un-grouped chart is not a request. */ type ChartSeed<TShape extends ReadShape> = { /** * Names the group columns: one or two entries, each a handle from the callback, keyed by * the name the row will carry. A bare handle groups by the field's value; a bucket leaf * such as `q.closedAt.byMonth` groups a date field by the bucket. * * @example * ds.chart(sales).groupBy((q) => ({ month: q.closedAt.byMonth, region: q.region })) */ groupBy<TGroups extends Record<string, Dimension<unknown>>>(build: (q: DimensionSet<TShape>) => TGroups & GroupByBounds<TGroups>): ChartBuilder<TShape, TGroups, Record<never, never>>; /** * Narrows which records the chart aggregates. Same filters as `ds.list`. */ where(build: WhereCallback<TShape>): ChartSeed<TShape>; }; type ChartBuilder<TShape extends ReadShape, TGroups, TMetrics> = { /** * Names the aggregated columns, keyed by the name the row will carry. Omit the call for a * distinct-values query: the rows then hold the group columns alone. * * @example * ds.chart(sales) * .groupBy((q) => ({ region: q.region })) * .metrics((q) => ({ revenue: q.amount.sum, orders: q.$count })) */ metrics<TNext extends Record<string, Measure<unknown>>>(build: (q: MeasureSet<TShape>) => TNext & MetricBounds<TNext, TGroups>): ChartBuilder<TShape, TGroups, TNext>; /** * Narrows which records the chart aggregates. Same filters as `ds.list`. */ where(build: WhereCallback<TShape>): ChartBuilder<TShape, TGroups, TMetrics>; /** * Sorts the rows by the chart's own keys. Call it last: it sees the keys declared so far, * so placed before `metrics` a metric key is not yet a column. Without a sort the rows come * back by the first bucket ascending, else by the first metric descending. * * @example * ds.chart(sales) * .groupBy((q) => ({ month: q.closedAt.byMonth })) * .metrics((q) => ({ revenue: q.amount.sum })) * .orderBy((q) => [q.month.asc, q.revenue.desc]) */ orderBy(build: (q: SortSet<ChartRow<TGroups, TMetrics>>) => ConstructableOrderBy | Array<ConstructableOrderBy>): ChartBuilder<TShape, TGroups, TMetrics>; } & Promise<ChartResult<ChartRow<TGroups, TMetrics>>>; interface MetricResult<TValue$1> { value: TValue$1; executionTimestamp: Date; } type MetricBuilder<TShape extends ReadShape, TValue$1> = { /** * Narrows which records the metric aggregates. Same filters as `ds.list`. */ where(build: WhereCallback<TShape>): MetricBuilder<TShape, TValue$1>; } & Promise<MetricResult<TValue$1>>; /** * Aggregates records into chart rows: one row per group, keyed by the caller's own names. * * `groupBy` is required and takes one or two columns. `metrics` is optional; without it the * rows hold the distinct group values. `orderBy` comes last, over the chart's own keys. * * @example * const { data } = await ds * .chart(sales) * .groupBy((q) => ({ month: q.closedAt.byMonth })) * .metrics((q) => ({ revenue: q.amount.sum, orders: q.$count })) * .where((q) => q.status.is("paid")) * .orderBy((q) => q.month.asc) * // data: Array<{ month: string | null; revenue: number | null; orders: number }> */ declare function chart<TShape extends ReadShape>(query: DatasourceAction<TShape>): ChartSeed<TShape>; /** * Aggregates records into one value, with no grouping. * * @example * const { value } = await ds * .metric(sales, (q) => q.amount.sum) * .where((q) => q.status.is("paid")) * // value: number | null */ declare function metric<TShape extends ReadShape, TMeasure extends Measure<unknown>>(query: DatasourceAction<TShape>, pick: (q: MeasureSet<TShape>) => TMeasure): MetricBuilder<TShape, ColumnValue<TMeasure>>; //#endregion export { chart, metric };