measurr 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/shapes.d.ts CHANGED
@@ -85,7 +85,7 @@ export declare function toTimeseries<R extends AnyResult>(result: R, options: {
85
85
  bucket: DimensionOf<R>;
86
86
  unit: 'day' | 'week' | 'month';
87
87
  measure: MeasureOf<R>;
88
- series?: DimensionOf<R>;
88
+ series?: DimensionOf<R> | undefined;
89
89
  fill?: number | null;
90
90
  }): TimeseriesShape;
91
91
  export declare function toDistribution<R extends AnyResult>(result: R, options: {
@@ -108,4 +108,149 @@ export declare function toLeaderboard<R extends AnyResult>(result: R, options: {
108
108
  by: DimensionOf<R>;
109
109
  measure: MeasureOf<R>;
110
110
  }): LeaderboardShape;
111
+ export type TimeGranularity = 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';
112
+ /** Scalar values a series or a leaderboard row can carry along. */
113
+ export type ScalarMeta = Record<string, string | number | boolean | null>;
114
+ export type KpiOutput = {
115
+ kind: 'kpi';
116
+ value: number;
117
+ label?: string;
118
+ /** A currency code, or `'PERCENTAGE'` for a share (`percent: true`). */
119
+ unit?: string;
120
+ prefix?: string;
121
+ suffix?: string;
122
+ trend?: 'up' | 'down' | 'flat';
123
+ };
124
+ export type TimeSeriesPoint = {
125
+ /** The bucket's local start date as UTC midnight (`2026-10-01T00:00:00.000Z`). */
126
+ ts: Date;
127
+ value: number;
128
+ label?: string;
129
+ };
130
+ export type TimeSeriesSeries<SeriesKey extends string = string, Meta = ScalarMeta | undefined> = {
131
+ key: SeriesKey;
132
+ label?: string;
133
+ points: TimeSeriesPoint[];
134
+ chartType?: 'line' | 'bar';
135
+ axis?: 'left' | 'right';
136
+ meta?: Meta;
137
+ };
138
+ export type TimeSeriesOutput<SeriesKey extends string = string, Meta = ScalarMeta | undefined> = {
139
+ kind: 'timeseries';
140
+ granularity: TimeGranularity;
141
+ series: TimeSeriesSeries<SeriesKey, Meta>[];
142
+ };
143
+ export type DistributionSegment<Key extends string = string> = {
144
+ key: Key;
145
+ label: string;
146
+ value: number;
147
+ /** 0-100. */
148
+ percent?: number;
149
+ };
150
+ export type DistributionChartType = 'bar' | 'donut' | 'pie' | 'funnel';
151
+ export type DistributionOutput<Key extends string = string> = {
152
+ kind: 'distribution';
153
+ total: number;
154
+ segments: DistributionSegment<Key>[];
155
+ chartType?: DistributionChartType;
156
+ };
157
+ export type TableColumn<Key extends string = string> = {
158
+ key: Key;
159
+ label: string;
160
+ type?: 'string' | 'number' | 'date' | 'boolean';
161
+ nullable?: boolean;
162
+ };
163
+ export type TableOutput<Row = Record<string, unknown>, ColumnKey extends string = string> = {
164
+ kind: 'table';
165
+ columns: TableColumn<ColumnKey>[];
166
+ rows: Row[];
167
+ total?: number;
168
+ };
169
+ export type PivotOutput = {
170
+ kind: 'pivot';
171
+ rowDimension: {
172
+ key: string;
173
+ label: string;
174
+ };
175
+ columnDimension: {
176
+ key: string;
177
+ label: string;
178
+ };
179
+ rows: string[];
180
+ columns: string[];
181
+ /** `values[row][column]`. */
182
+ values: number[][];
183
+ /** Same shape as `values`; empty strings for cells without one. */
184
+ cellTooltips?: string[][];
185
+ totals?: {
186
+ rowTotals?: number[];
187
+ columnTotals?: number[];
188
+ grandTotal?: number;
189
+ };
190
+ };
191
+ export type LeaderboardItem<Meta = ScalarMeta | undefined> = {
192
+ rank: number;
193
+ id: string;
194
+ label: string;
195
+ value: number;
196
+ meta?: Meta;
197
+ };
198
+ export type LeaderboardOutput<Meta = ScalarMeta | undefined> = {
199
+ kind: 'leaderboard';
200
+ items: LeaderboardItem<Meta>[];
201
+ total?: number;
202
+ };
203
+ export interface OutputKindMap {
204
+ kpi: KpiOutput;
205
+ timeseries: TimeSeriesOutput;
206
+ distribution: DistributionOutput;
207
+ table: TableOutput;
208
+ leaderboard: LeaderboardOutput;
209
+ pivot: PivotOutput;
210
+ }
211
+ export type OutputKind = keyof OutputKindMap;
212
+ export type OutputForKind<K extends OutputKind> = OutputKindMap[K];
213
+ export type MetricOutput = OutputKindMap[OutputKind];
214
+ export declare const isKpi: (output: MetricOutput) => output is KpiOutput;
215
+ export declare const isTimeSeries: (output: MetricOutput) => output is TimeSeriesOutput;
216
+ export declare const isDistribution: (output: MetricOutput) => output is DistributionOutput;
217
+ export declare const isTable: (output: MetricOutput) => output is TableOutput;
218
+ export declare const isLeaderboard: (output: MetricOutput) => output is LeaderboardOutput;
219
+ export declare const isPivot: (output: MetricOutput) => output is PivotOutput;
220
+ /** Wire keys by key (`String(key)`, so `'null'` names the empty group). */
221
+ type Renames = Readonly<Record<string, string>>;
222
+ export declare function presentKpi<R extends AnyResult>(result: R, measure: MeasureOf<R>, display?: Omit<KpiOutput, 'kind' | 'value'> & {
223
+ /** A 0-1 share, drawn as 0-100 with the unit `'PERCENTAGE'`. */
224
+ percent?: boolean;
225
+ }): KpiOutput;
226
+ export declare function presentTimeseries<R extends AnyResult>(result: R, options: {
227
+ bucket: DimensionOf<R> & ('day' | 'week' | 'month');
228
+ measure: MeasureOf<R>;
229
+ /** The dimension each series is; one series named after the measure without it. */
230
+ series?: DimensionOf<R> | undefined;
231
+ /** Wire keys for series keys (or the measure). */
232
+ keys?: Renames;
233
+ /** Labels by wire key, where the dataset's are not the ones to show. */
234
+ labels?: Renames;
235
+ chartType?: 'line' | 'bar';
236
+ }): TimeSeriesOutput;
237
+ /**
238
+ * Segments in query order (or `order`), with a `total` the segments add up to, so a
239
+ * many-to-many split still has percentages that sum to 100.
240
+ */
241
+ export declare function presentDistribution<R extends AnyResult>(result: R, options: {
242
+ by: DimensionOf<R>;
243
+ measure: MeasureOf<R>;
244
+ chartType?: DistributionChartType;
245
+ keys?: Renames;
246
+ labels?: Renames;
247
+ /** Segment order by wire key; keys it does not list go last. */
248
+ order?: readonly string[];
249
+ }): DistributionOutput;
250
+ export declare function presentLeaderboard<R extends AnyResult>(result: R, options: {
251
+ by: DimensionOf<R>;
252
+ measure: MeasureOf<R>;
253
+ /** What each row carries besides its value, from every measure of the row. */
254
+ meta?: (values: Measures) => ScalarMeta;
255
+ }): LeaderboardOutput;
111
256
  export {};
package/dist/shapes.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bucketStarts
3
- } from "./index-g255jb1s.js";
3
+ } from "./index-115syy01.js";
4
4
 
5
5
  // src/shapes.ts
6
6
  function toKpi(result, measure) {
@@ -125,7 +125,90 @@ function distinct(values) {
125
125
  function sortNumeric(values) {
126
126
  return values.every((value) => typeof value.key === "number") ? [...values].sort((a, b) => Number(a.key) - Number(b.key)) : values;
127
127
  }
128
+ var isKpi = (output) => output.kind === "kpi";
129
+ var isTimeSeries = (output) => output.kind === "timeseries";
130
+ var isDistribution = (output) => output.kind === "distribution";
131
+ var isTable = (output) => output.kind === "table";
132
+ var isLeaderboard = (output) => output.kind === "leaderboard";
133
+ var isPivot = (output) => output.kind === "pivot";
134
+ var rename = (renames, key) => renames?.[String(key)] ?? String(key);
135
+ function presentKpi(result, measure, display = {}) {
136
+ const { percent, ...rest } = display;
137
+ const value = toKpi(result, measure).value ?? 0;
138
+ return percent ? { kind: "kpi", value: value * 100, unit: "PERCENTAGE", ...rest } : { kind: "kpi", value, ...rest };
139
+ }
140
+ function presentTimeseries(result, options) {
141
+ const shape = toTimeseries(result, {
142
+ bucket: options.bucket,
143
+ unit: options.bucket,
144
+ measure: options.measure,
145
+ series: options.series
146
+ });
147
+ return {
148
+ kind: "timeseries",
149
+ granularity: options.bucket,
150
+ series: shape.series.map((series) => {
151
+ const key = rename(options.keys, series.key);
152
+ return {
153
+ key,
154
+ label: options.labels?.[key] ?? series.label,
155
+ points: series.points.map((point) => ({
156
+ ts: new Date(`${point.bucket}T00:00:00.000Z`),
157
+ value: point.value ?? 0
158
+ })),
159
+ ...options.chartType && { chartType: options.chartType }
160
+ };
161
+ })
162
+ };
163
+ }
164
+ function presentDistribution(result, options) {
165
+ const segments = toDistribution(result, options).segments.map((segment) => {
166
+ const key = rename(options.keys, segment.key);
167
+ return {
168
+ key,
169
+ label: options.labels?.[key] ?? segment.label,
170
+ value: segment.value ?? 0
171
+ };
172
+ });
173
+ const { order } = options;
174
+ if (order) {
175
+ const rank = (key) => order.includes(key) ? order.indexOf(key) : order.length;
176
+ segments.sort((a, b) => rank(a.key) - rank(b.key));
177
+ }
178
+ const total = segments.reduce((sum, segment) => sum + segment.value, 0);
179
+ return {
180
+ kind: "distribution",
181
+ total,
182
+ segments: segments.map((segment) => ({
183
+ ...segment,
184
+ percent: total > 0 ? segment.value / total * 100 : 0
185
+ })),
186
+ ...options.chartType && { chartType: options.chartType }
187
+ };
188
+ }
189
+ function presentLeaderboard(result, options) {
190
+ return {
191
+ kind: "leaderboard",
192
+ items: toLeaderboard(result, options).items.map((item) => ({
193
+ rank: item.rank,
194
+ id: String(item.key),
195
+ label: item.label,
196
+ value: item.value ?? 0,
197
+ ...options.meta && { meta: options.meta(item.values) }
198
+ }))
199
+ };
200
+ }
128
201
  export {
202
+ isDistribution,
203
+ isKpi,
204
+ isLeaderboard,
205
+ isPivot,
206
+ isTable,
207
+ isTimeSeries,
208
+ presentDistribution,
209
+ presentKpi,
210
+ presentLeaderboard,
211
+ presentTimeseries,
129
212
  toDistribution,
130
213
  toKpi,
131
214
  toLeaderboard,
package/dist/testing.js CHANGED
@@ -3,11 +3,11 @@ import {
3
3
  allTenants2,
4
4
  isAnalyticsError2,
5
5
  createAnalytics2
6
- } from "./index-zgb1e89d.js";
6
+ } from "./index-z5xv3ffk.js";
7
7
  import {
8
8
  measure2,
9
9
  dimension2
10
- } from "./index-g2mjqx4f.js";
10
+ } from "./index-pgccd363.js";
11
11
 
12
12
  // src/testing.ts
13
13
  var COUNT = "__contractCount";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "measurr",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "A small typed semantic layer: datasets of measures and dimensions compiled to one SQL statement per dialect.",
5
5
  "type": "module",
6
6
  "module": "./dist/index.js",
@@ -57,6 +57,12 @@
57
57
  "import": "./dist/handler.js",
58
58
  "default": "./dist/handler.js"
59
59
  },
60
+ "./metrics": {
61
+ "types": "./dist/metrics.d.ts",
62
+ "bun": "./src/metrics.ts",
63
+ "import": "./dist/metrics.js",
64
+ "default": "./dist/metrics.js"
65
+ },
60
66
  "./testing": {
61
67
  "types": "./dist/testing.d.ts",
62
68
  "bun": "./src/testing.ts",
@@ -66,7 +72,7 @@
66
72
  },
67
73
  "scripts": {
68
74
  "build": "rm -rf dist && bun run build:js && bun run build:types",
69
- "build:js": "bun build ./src/index.ts ./src/dialects/postgres.ts ./src/shapes.ts ./src/handler.ts ./src/testing.ts --root ./src --outdir ./dist --target node --packages external --splitting",
75
+ "build:js": "bun build ./src/index.ts ./src/dialects/postgres.ts ./src/shapes.ts ./src/handler.ts ./src/metrics.ts ./src/testing.ts --root ./src --outdir ./dist --target node --packages external --splitting",
70
76
  "build:types": "tsgo -p tsconfig.build.json",
71
77
  "prepublishOnly": "bun run build",
72
78
  "test": "bun test",
package/src/analytics.ts CHANGED
@@ -255,6 +255,11 @@ export type Analytics<DS extends readonly AnyDataset[], Ctx> = {
255
255
  }): Promise<z.ZodType<DatasetQuery<DS[number]>>>
256
256
  /** The result schema for one dataset. */
257
257
  resultSchema(dataset: DS[number]['key']): z.ZodType<QueryResult<Row, Row>>
258
+ /**
259
+ * The timezone `ctx`'s periods and buckets resolve in: the `timezone` hook's answer, UTC
260
+ * when it has none. Rejects with `invalid_timezone` for a name the runtime does not know.
261
+ */
262
+ timezone(ctx: Ctx): Promise<string>
258
263
  /** The datasets `ctx` may query, with the measures and dimensions it may use. */
259
264
  listDatasets(ctx: Ctx): Promise<DatasetCatalogEntry<DS[number]['key']>[]>
260
265
  }
@@ -419,6 +424,17 @@ export function createAnalytics<const DS extends readonly AnyDataset[], Ctx>(
419
424
  }
420
425
 
421
426
  /** Parse, authorize, and resolve everything that comes from hooks. */
427
+ const timezoneOf = async (ctx: Ctx) => {
428
+ const timezone = (await options.timezone?.(ctx)) || 'UTC'
429
+ if (!isValidTimezone(timezone)) {
430
+ throw new AnalyticsError(
431
+ 'invalid_timezone',
432
+ `Unknown timezone ${timezone}`
433
+ )
434
+ }
435
+ return timezone
436
+ }
437
+
422
438
  const prepare = async (input: unknown, ctx: Ctx): Promise<Prepared> => {
423
439
  const parsed = querySchemaFor(datasets).safeParse(input)
424
440
  if (!parsed.success) {
@@ -471,14 +487,7 @@ export function createAnalytics<const DS extends readonly AnyDataset[], Ctx>(
471
487
  )
472
488
  }
473
489
 
474
- const timezone = (await options.timezone?.(ctx)) || 'UTC'
475
- if (!isValidTimezone(timezone)) {
476
- throw new AnalyticsError(
477
- 'invalid_timezone',
478
- `Unknown timezone ${timezone}`
479
- )
480
- }
481
-
490
+ const timezone = await timezoneOf(ctx)
482
491
  const query = normalizeQuery(dataset, parsedQuery)
483
492
  const at = now()
484
493
  let period: ResolvedPeriod | null
@@ -678,6 +687,7 @@ export function createAnalytics<const DS extends readonly AnyDataset[], Ctx>(
678
687
  schemaOptions?.datasets?.map(datasetOf) ?? datasets
679
688
  )) as Analytics<DS, Ctx>['querySchema'],
680
689
  resultSchema: (key) => resultSchemaFor(key) as z.ZodType<ShapedResult>,
690
+ timezone: timezoneOf,
681
691
  listDatasets: async (ctx) =>
682
692
  (await allowedDatasets(ctx)).map(
683
693
  (dataset) =>