Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 | 158x 158x 158x 158x 158x 158x 158x 158x 158x 51x 51x 45x 6x 7x 3x 4x 2x 2x 6x 158x 158x 158x 158x 158x 158x 158x 43x 5x 5x 5x 5x 38x 38x 5x 5x 5x 33x 43x 31x 31x 1x 1x 1x 1x 32x 1x 1x 1x 31x 32x 31x 31x 2x 8x 2x 6x 3x 3x 158x 53x 53x 53x 2x 2x 53x 5x 48x 47x 158x 158x 158x 158x 1107x 1107x 1107x 4077x 3x 4074x 4074x 2612x 4074x 7812x 24836x 1107x 4726x 5327x 8005x 4079x 647x 342x 342x 1350x 4420x 342x 765x 640x 640x 637x 765x 765x 765x 637x 637x 637x 305x 460x 1158x 51x 1107x 1158x 1158x 342x 765x 57x 8x 49x 5x 72x 24x 68x 6x 66x 20x 61x 7x 59x 72x 72x 7x 90x 94x 94x 91x 94x 47x 158x 158x 158x 158x 9x 1x 8x 158x 158x 158x 158x | /**
* Dashboard types and schemas
*
* Zod schemas and TypeScript types for Sentry Dashboard API responses.
* Includes utility functions for stripping server-generated fields
* before PUT requests, and strict input validation for user-authored widgets.
*/
import { z } from "zod";
import { ValidationError } from "../lib/errors.js";
import { logger } from "../lib/logger.js";
// ---------------------------------------------------------------------------
// Widget type and display type enums
//
// Source: sentry/src/sentry/models/dashboard_widget.py
// Also in: @sentry/api types (cli/node_modules/@sentry/api/dist/types.gen.d.ts)
// ---------------------------------------------------------------------------
/**
* Valid widget types (dataset selectors).
*
* Source: sentry/src/sentry/models/dashboard_widget.py DashboardWidgetTypes.TYPES
*/
export const WIDGET_TYPES = [
"discover",
"issue",
"error-events",
"transaction-like",
"spans",
"logs",
"tracemetrics",
"preprod-app-size",
] as const;
export type WidgetType = (typeof WIDGET_TYPES)[number];
/** Default widgetType — the modern spans dataset covers most use cases */
export const DEFAULT_WIDGET_TYPE: WidgetType = "spans";
/**
* Valid widget display types (visualization formats).
*
* Source: sentry/src/sentry/models/dashboard_widget.py DashboardWidgetDisplayTypes.TYPES
*/
export const DISPLAY_TYPES = [
"line",
"area",
"stacked_area",
"bar",
"table",
"big_number",
"top_n",
"details",
"categorical_bar",
"wheel",
"rage_and_dead_clicks",
"server_tree",
"text",
"agents_traces_table",
] as const;
export type DisplayType = (typeof DISPLAY_TYPES)[number];
// ---------------------------------------------------------------------------
// Schemas
// ---------------------------------------------------------------------------
/** Schema for a single query within a dashboard widget */
export const DashboardWidgetQuerySchema = z
.object({
id: z.string().optional(),
name: z.string().optional(),
conditions: z.string().optional(),
columns: z.array(z.string()).optional(),
aggregates: z.array(z.string()).optional(),
fieldAliases: z.array(z.string()).optional(),
orderby: z.string().optional(),
fields: z.array(z.string()).optional(),
widgetId: z.string().optional(),
dateCreated: z.string().optional(),
})
.passthrough();
/** Schema for widget layout position */
export const DashboardWidgetLayoutSchema = z
.object({
x: z.number(),
y: z.number(),
w: z.number(),
h: z.number(),
minH: z.number().optional(),
isResizable: z.boolean().optional(),
})
.passthrough();
/** Schema for a single dashboard widget */
export const DashboardWidgetSchema = z
.object({
id: z.string().optional(),
title: z.string(),
displayType: z.string(),
widgetType: z.string().optional(),
interval: z.string().optional(),
queries: z.array(DashboardWidgetQuerySchema).optional(),
layout: DashboardWidgetLayoutSchema.optional(),
thresholds: z.unknown().optional(),
limit: z.number().nullable().optional(),
dashboardId: z.string().optional(),
dateCreated: z.string().optional(),
})
.passthrough();
/** Schema for dashboard list items (lightweight, from GET /dashboards/) */
export const DashboardListItemSchema = z
.object({
id: z.string(),
title: z.string(),
dateCreated: z.string().optional(),
createdBy: z
.object({
name: z.string().optional(),
email: z.string().optional(),
})
.optional(),
widgetDisplay: z.array(z.string()).optional(),
})
.passthrough();
/** Schema for full dashboard detail (from GET /dashboards/{id}/) */
export const DashboardDetailSchema = z
.object({
id: z.string(),
title: z.string(),
widgets: z.array(DashboardWidgetSchema).optional(),
dateCreated: z.string().optional(),
createdBy: z
.object({
name: z.string().optional(),
email: z.string().optional(),
})
.optional(),
projects: z.array(z.number()).optional(),
environment: z.array(z.string()).optional(),
period: z.string().nullable().optional(),
})
.passthrough();
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type DashboardWidgetQuery = z.infer<typeof DashboardWidgetQuerySchema>;
export type DashboardWidgetLayout = z.infer<typeof DashboardWidgetLayoutSchema>;
export type DashboardWidget = z.infer<typeof DashboardWidgetSchema>;
export type DashboardListItem = z.infer<typeof DashboardListItemSchema>;
export type DashboardDetail = z.infer<typeof DashboardDetailSchema>;
// ---------------------------------------------------------------------------
// Strict input schema for user-authored widgets
// ---------------------------------------------------------------------------
/**
* Strict schema for user-authored widget JSON (create/add/edit input).
* Validates displayType and widgetType against known Sentry enums.
* Defaults widgetType to "spans" when not provided.
*
* Use DashboardWidgetSchema (permissive) for parsing server responses.
*/
export const DashboardWidgetInputSchema = z
.object({
title: z.string(),
displayType: z.enum(DISPLAY_TYPES),
widgetType: z.enum(WIDGET_TYPES).default(DEFAULT_WIDGET_TYPE),
interval: z.string().optional(),
queries: z.array(DashboardWidgetQuerySchema).optional(),
layout: DashboardWidgetLayoutSchema.optional(),
thresholds: z.unknown().optional(),
limit: z.number().nullable().optional(),
})
.passthrough();
/**
* Parse and validate user-authored widget JSON with strict enum checks.
* Throws ValidationError with actionable messages listing valid values.
*
* @param raw - Raw parsed JSON from user's widget file
* @returns Validated widget with widgetType defaulted to "spans" if omitted
*/
export function parseWidgetInput(raw: unknown): DashboardWidget {
const result = DashboardWidgetInputSchema.safeParse(raw);
if (result.success) {
return result.data;
}
const issues = result.error.issues.map((issue) => {
if (issue.path.includes("displayType")) {
return `Invalid displayType. Valid values: ${DISPLAY_TYPES.join(", ")}`;
}
if (issue.path.includes("widgetType")) {
return `Invalid widgetType. Valid values: ${WIDGET_TYPES.join(", ")}`;
}
return `${issue.path.join(".")}: ${issue.message}`;
});
throw new ValidationError(
`Invalid widget definition:\n${issues.join("\n")}`,
"widget-json"
);
}
// ---------------------------------------------------------------------------
// Aggregate functions & search filter enums
// ---------------------------------------------------------------------------
/**
* Aggregate function aliases resolved before validation.
*
* The Sentry events API silently resolves these, but the dashboard widget UI
* only understands canonical function names from AggregationKey. Resolving
* aliases here ensures widgets render correctly in the UI.
*
* Source: https://github.com/getsentry/sentry/blob/master/src/sentry/search/events/constants.py
* SPAN_FUNCTION_ALIASES: spm→epm, sps→eps
* FUNCTION_ALIASES: tpm→epm, tps→eps
*/
export const AGGREGATE_ALIASES: Record<string, string> = {
spm: "epm",
sps: "eps",
tpm: "epm",
tps: "eps",
};
/**
* Canonical aggregate functions for the spans dataset (default for dashboard widgets).
* These are the function names the dashboard UI can render in the "Visualize" dropdown.
*
* Source: https://github.com/getsentry/sentry/blob/master/static/app/utils/fields/index.ts (AggregationKey enum)
* Dataset: https://github.com/getsentry/sentry/blob/master/src/sentry/search/events/datasets/spans_indexed.py
*/
export const SPAN_AGGREGATE_FUNCTIONS = [
"count",
"count_unique",
"sum",
"avg",
"percentile",
"p50",
"p75",
"p90",
"p95",
"p99",
"p100",
"eps",
"epm",
"any",
"min",
"max",
] as const;
export type SpanAggregateFunction = (typeof SPAN_AGGREGATE_FUNCTIONS)[number];
/**
* Additional aggregate functions from the discover dataset.
* Available when widgetType is "discover" or "error-events".
*
* Source: https://github.com/getsentry/sentry/blob/master/static/app/utils/fields/index.ts (AggregationKey enum)
* Dataset: https://github.com/getsentry/sentry/blob/master/src/sentry/search/events/datasets/discover.py
*/
export const DISCOVER_AGGREGATE_FUNCTIONS = [
...SPAN_AGGREGATE_FUNCTIONS,
"failure_count",
"failure_rate",
"apdex",
"count_miserable",
"user_misery",
"count_web_vitals",
"count_if",
"count_at_least",
"last_seen",
"latest_event",
"var",
"stddev",
"cov",
"corr",
"performance_score",
"opportunity_score",
"count_scores",
] as const;
export type DiscoverAggregateFunction =
(typeof DISCOVER_AGGREGATE_FUNCTIONS)[number];
/** Zod schema for validating a span aggregate function name */
export const SpanAggregateFunctionSchema = z.enum(SPAN_AGGREGATE_FUNCTIONS);
/** Zod schema for validating a discover aggregate function name */
export const DiscoverAggregateFunctionSchema = z.enum(
DISCOVER_AGGREGATE_FUNCTIONS
);
/**
* Valid `is:` filter values for issue search conditions (--where flag).
* Only valid when widgetType is "issue". Other datasets don't support `is:`.
*
* Status values from GroupStatus:
* https://github.com/getsentry/sentry/blob/master/src/sentry/models/group.py#L196-L204
*
* Substatus values from SUBSTATUS_UPDATE_CHOICES:
* https://github.com/getsentry/sentry/blob/master/src/sentry/types/group.py#L33-L41
*
* Assignment/link filters from is_filter_translation:
* https://github.com/getsentry/sentry/blob/master/src/sentry/issues/issue_search.py#L45-L51
*/
export const IS_FILTER_VALUES = [
// Status (GroupStatus)
"resolved",
"unresolved",
"ignored",
"archived",
"muted",
"reprocessing",
// Substatus (GroupSubStatus)
"escalating",
"ongoing",
"regressed",
"new",
"archived_until_escalating",
"archived_until_condition_met",
"archived_forever",
// Assignment & linking
"assigned",
"unassigned",
"for_review",
"linked",
"unlinked",
] as const;
export type IsFilterValue = (typeof IS_FILTER_VALUES)[number];
/** Zod schema for validating an `is:` filter value */
export const IsFilterValueSchema = z.enum(IS_FILTER_VALUES);
// ---------------------------------------------------------------------------
// Aggregate & sort parsing (quote-free CLI shorthand)
// ---------------------------------------------------------------------------
/**
* Parse a shorthand aggregate expression into Sentry query syntax.
* Resolves aliases (spm→epm, tpm→epm, etc.) so widgets render in the dashboard UI.
*
* Accepts three formats:
* "count" → "count()"
* "p95:span.duration" → "p95(span.duration)"
* "count()" → "count()" (passthrough if already has parens)
* "spm" → "epm()" (alias resolved)
*/
export function parseAggregate(input: string): string {
if (input.includes("(")) {
// Resolve aliases even in paren form: spm() → epm(), tpm(x) → epm(x)
const parenIdx = input.indexOf("(");
const fn = input.slice(0, parenIdx);
const alias = AGGREGATE_ALIASES[fn];
return alias ? `${alias}${input.slice(parenIdx)}` : input;
}
const colonIdx = input.indexOf(":");
if (colonIdx > 0) {
const fn = input.slice(0, colonIdx);
const resolved = AGGREGATE_ALIASES[fn] ?? fn;
return `${resolved}(${input.slice(colonIdx + 1)})`;
}
const resolved = AGGREGATE_ALIASES[input] ?? input;
return `${resolved}()`;
}
/**
* Extract the function name from a parsed aggregate string.
* "count()" → "count"
* "p95(span.duration)" → "p95"
*/
function extractFunctionName(aggregate: string): string {
const parenIdx = aggregate.indexOf("(");
return parenIdx > 0 ? aggregate.slice(0, parenIdx) : aggregate;
}
/**
* Check whether a parsed aggregate uses the tracemetrics comma-separated format.
* Format: `aggregation(value,metric_name,metric_type,unit)`
* Example: `p50(value,completion.duration_ms,distribution,none)`
*/
function isTracemetricsAggregate(aggregate: string): boolean {
const parenIdx = aggregate.indexOf("(");
Iif (parenIdx < 0) {
return false;
}
const inner = aggregate.slice(parenIdx + 1, -1);
return inner.startsWith("value,") && inner.split(",").length === 4;
}
/**
* Validate that all aggregate function names in a list are known.
* Throws a ValidationError listing valid functions if any are invalid.
*
* For the `tracemetrics` dataset, aggregates must use the comma-separated
* format: `aggregation(value,metric_name,metric_type,unit)`. Standard
* span-style aggregates like `count()` or `p50(span.duration)` are
* invalid for tracemetrics.
*
* @param aggregates - Parsed aggregate strings (e.g. ["count()", "p95(span.duration)"])
* @param dataset - Widget dataset, determines which function list to validate against
*/
export function validateAggregateNames(
aggregates: string[],
dataset?: string
): void {
// tracemetrics uses a different aggregate format — validate structure, not function names
if (dataset === "tracemetrics") {
for (const agg of aggregates) {
Iif (!isTracemetricsAggregate(agg)) {
throw new ValidationError(
`Invalid tracemetrics aggregate "${agg}".\n\n` +
"tracemetrics queries must use the format: aggregation(value,metric_name,metric_type,unit)\n" +
"Example: p50(value,completion.duration_ms,distribution,none)\n\n" +
"Parameters:\n" +
" - aggregation: avg, sum, count, p50, p75, p90, p95, p99, min, max\n" +
` - value: literal string "value"\n` +
" - metric_name: the name passed to Sentry.metrics.distribution/gauge/count\n" +
" - metric_type: distribution, gauge, counter, set\n" +
" - unit: none, byte, second, millisecond, etc. (must match SDK emission)",
"query"
);
}
}
return;
}
const validFunctions: readonly string[] =
dataset === "discover" || dataset === "error-events"
? DISCOVER_AGGREGATE_FUNCTIONS
: SPAN_AGGREGATE_FUNCTIONS;
for (const agg of aggregates) {
const fn = extractFunctionName(agg);
if (!validFunctions.includes(fn)) {
const aliasList = Object.entries(AGGREGATE_ALIASES)
.map(([from, to]) => `${from}→${to}`)
.join(", ");
throw new ValidationError(
`Unknown aggregate function "${fn}".\n\n` +
`Valid functions: ${validFunctions.join(", ")}\n` +
`Aliases (auto-resolved): ${aliasList}`,
"query"
);
}
}
}
/**
* Parse a sort expression with optional `-` prefix for descending.
* Uses the same shorthand as {@link parseAggregate}.
* "-count" → "-count()"
* "p95:span.duration" → "p95(span.duration)"
* "-p95:span.duration" → "-p95(span.duration)"
*/
export function parseSortExpression(input: string): string {
if (input.startsWith("-")) {
return `-${parseAggregate(input.slice(1))}`;
}
return parseAggregate(input);
}
// ---------------------------------------------------------------------------
// Query preparation for Sentry API
// ---------------------------------------------------------------------------
/** Maximum result limits by display type */
const MAX_LIMITS: Partial<Record<string, number>> = {
table: 10,
bar: 10,
};
/**
* Prepare widget queries for the Sentry API.
* Auto-computes `fields` from columns + aggregates.
* Defaults `conditions` to "" when missing.
* Clamps per-display-type limits to their maximums with a warning.
*/
export function prepareWidgetQueries(
inputWidget: DashboardWidget
): DashboardWidget {
let widget = inputWidget;
// Clamp to per-display-type limit maximums
const maxLimit = MAX_LIMITS[widget.displayType];
if (
maxLimit !== undefined &&
widget.limit !== undefined &&
widget.limit !== null &&
widget.limit > maxLimit
) {
logger.warn(
`${widget.displayType} widgets support a maximum of ${maxLimit} rows. Clamping --limit from ${widget.limit} to ${maxLimit}.`
);
widget = { ...widget, limit: maxLimit };
}
if (!widget.queries) {
return widget;
}
return {
...widget,
queries: widget.queries.map((q) => ({
...q,
conditions: q.conditions ?? "",
fields: q.fields?.length
? q.fields
: [...(q.columns ?? []), ...(q.aggregates ?? [])],
})),
};
}
// ---------------------------------------------------------------------------
// Auto-layout utilities
// ---------------------------------------------------------------------------
/** Sentry dashboard grid column count */
export const GRID_COLUMNS = 6;
/**
* Controls how the auto-placer positions new widgets in the grid.
*
* - `sequential` — Cursor-based append: place after the last widget,
* wrap to a new row on overflow. Never backfills interior gaps.
* - `dense` — First-fit packing: scan top-to-bottom, left-to-right
* and place in the first available gap. Produces compact layouts.
*/
export type WidgetLayoutMode = "sequential" | "dense";
/** Default widget dimensions by displayType */
const DEFAULT_WIDGET_SIZE: Partial<
Record<DisplayType, { w: number; h: number; minH: number }>
> = {
big_number: { w: 2, h: 1, minH: 1 },
line: { w: 3, h: 2, minH: 2 },
area: { w: 3, h: 2, minH: 2 },
bar: { w: 3, h: 2, minH: 2 },
table: { w: 6, h: 2, minH: 2 },
};
const FALLBACK_SIZE = { w: 3, h: 2, minH: 2 };
/**
* Fallback layout for widgets without an existing layout.
* Used when merging explicit layout flags over a widget that has no layout set.
* Position defaults to origin (0,0) with standard 3×2 dimensions.
*/
export const FALLBACK_LAYOUT: DashboardWidgetLayout = {
x: 0,
y: 0,
...FALLBACK_SIZE,
};
/** Build a set of occupied grid cells and the max bottom edge from existing layouts. */
function buildOccupiedGrid(widgets: DashboardWidget[]): {
occupied: Set<string>;
maxY: number;
} {
const occupied = new Set<string>();
let maxY = 0;
for (const w of widgets) {
if (!w.layout) {
continue;
}
const bottom = w.layout.y + w.layout.h;
if (bottom > maxY) {
maxY = bottom;
}
for (let y = w.layout.y; y < bottom; y++) {
for (let x = w.layout.x; x < w.layout.x + w.layout.w; x++) {
occupied.add(`${x},${y}`);
}
}
}
return { occupied, maxY };
}
/** Check whether a rectangle fits at a position without overlapping occupied cells. */
function regionFits(
occupied: Set<string>,
rect: { px: number; py: number; w: number; h: number }
): boolean {
for (let dy = 0; dy < rect.h; dy++) {
for (let dx = 0; dx < rect.w; dx++) {
if (occupied.has(`${rect.px + dx},${rect.py + dy}`)) {
return false;
}
}
}
return true;
}
/** Grid state computed from existing widget layouts */
type OccupiedGrid = { occupied: Set<string>; maxY: number };
/** Widget dimensions resolved from displayType */
type WidgetSize = { w: number; h: number; minH: number };
/**
* Dense (first-fit) placement: scan the grid top-to-bottom, left-to-right
* and place the widget in the first gap where it fits.
*/
function assignLayoutDense(
widget: DashboardWidget,
size: WidgetSize,
grid: OccupiedGrid
): DashboardWidget {
const { w, h, minH } = size;
for (let y = 0; y <= grid.maxY; y++) {
for (let x = 0; x <= GRID_COLUMNS - w; x++) {
if (regionFits(grid.occupied, { px: x, py: y, w, h })) {
return { ...widget, layout: { x, y, w, h, minH } };
}
}
}
return { ...widget, layout: { x: 0, y: grid.maxY, w, h, minH } };
}
/**
* Find the layout of the last widget in the array that has one.
* Reverse-scans because the API preserves insertion order.
*/
function findLastLayout(
widgets: DashboardWidget[]
): DashboardWidgetLayout | undefined {
for (let i = widgets.length - 1; i >= 0; i--) {
const layout = widgets[i]?.layout;
if (layout) {
return layout;
}
}
}
/**
* Sequential (cursor-based) placement: place the widget immediately to the
* right of the last existing widget on the same row. When the row overflows
* or the position overlaps a manually-placed widget, wrap to a fresh row
* below all existing content.
*/
function assignLayoutSequential(
widget: DashboardWidget,
existingWidgets: DashboardWidget[],
size: WidgetSize,
grid: OccupiedGrid
): DashboardWidget {
const { w, h, minH } = size;
const lastLayout = findLastLayout(existingWidgets);
if (lastLayout) {
const cursorX = lastLayout.x + lastLayout.w;
const cursorY = lastLayout.y;
// Place at cursor if it fits within the grid and doesn't overlap
if (
cursorX + w <= GRID_COLUMNS &&
regionFits(grid.occupied, { px: cursorX, py: cursorY, w, h })
) {
return { ...widget, layout: { x: cursorX, y: cursorY, w, h, minH } };
}
}
// Wrap to a new row below all existing content
return { ...widget, layout: { x: 0, y: grid.maxY, w, h, minH } };
}
/**
* Assign a default layout to a widget if it doesn't already have one.
*
* Two placement modes are available:
* - `"sequential"` (default) — Cursor-based append: the widget is placed
* immediately after the last existing widget, wrapping to a new row when
* the current row overflows. Interior gaps are never backfilled.
* - `"dense"` — First-fit packing: the widget is placed in the first
* available gap, scanning top-to-bottom and left-to-right.
*
* @param widget - Widget that may be missing a layout
* @param existingWidgets - Widgets already in the dashboard (used to compute placement)
* @param mode - Layout strategy (`"sequential"` or `"dense"`)
* @returns Widget with layout guaranteed
*/
export function assignDefaultLayout(
widget: DashboardWidget,
existingWidgets: DashboardWidget[],
mode: WidgetLayoutMode = "sequential"
): DashboardWidget {
if (widget.layout) {
return widget;
}
const size =
DEFAULT_WIDGET_SIZE[widget.displayType as DisplayType] ?? FALLBACK_SIZE;
const grid = buildOccupiedGrid(existingWidgets);
if (mode === "dense") {
return assignLayoutDense(widget, size, grid);
}
return assignLayoutSequential(widget, existingWidgets, size, grid);
}
// ---------------------------------------------------------------------------
// Layout validation
// ---------------------------------------------------------------------------
/** Shared layout flags accepted by widget add and edit commands */
export type WidgetLayoutFlags = {
readonly col?: number;
readonly row?: number;
readonly width?: number;
readonly height?: number;
};
/** Assert a layout value is a non-negative integer within an optional upper bound */
function assertLayoutInt(
value: number,
flag: string,
min: number,
max?: number
): void {
if (!Number.isInteger(value) || value < min) {
throw new ValidationError(
`--${flag} must be ${min === 0 ? "a non-negative" : "a positive"} integer (got ${value}).`,
flag
);
}
if (max !== undefined && value > max) {
throw new ValidationError(
`--${flag} must be ${min}–${max} (dashboard grid is ${GRID_COLUMNS} columns wide).`,
flag
);
}
}
/**
* Validate layout flag values against the 6-column dashboard grid.
*
* Checks that position and size values are within the valid range and
* that the widget fits within the grid columns. Validates each provided
* flag independently, and cross-validates x + width when both are known.
*
* @param flags - Layout flags from the command
* @param existing - Existing widget layout (used for cross-validation when only one dimension is provided)
*/
export function validateWidgetLayout(
flags: WidgetLayoutFlags,
existing?: DashboardWidgetLayout
): void {
if (flags.col !== undefined) {
assertLayoutInt(flags.col, "col", 0, GRID_COLUMNS - 1);
}
if (flags.row !== undefined) {
assertLayoutInt(flags.row, "row", 0);
}
if (flags.width !== undefined) {
assertLayoutInt(flags.width, "width", 1, GRID_COLUMNS);
}
if (flags.height !== undefined) {
assertLayoutInt(flags.height, "height", 1);
}
// Cross-validate col + width doesn't overflow the grid
const effectiveX = flags.col ?? existing?.x;
const effectiveW = flags.width ?? existing?.w;
if (
effectiveX !== undefined &&
effectiveW !== undefined &&
effectiveX + effectiveW > GRID_COLUMNS
) {
throw new ValidationError(
`Widget overflows the grid: col(${effectiveX}) + width(${effectiveW}) = ${effectiveX + effectiveW}, but the grid is ${GRID_COLUMNS} columns wide.`,
"col"
);
}
}
// ---------------------------------------------------------------------------
// Server field stripping utilities
//
// The Sentry dashboard API returns many extra fields via GET that should NOT
// be sent back in PUT requests. Using an allowlist approach ensures only
// fields the API accepts are included, avoiding silent rejection of widgets.
// ---------------------------------------------------------------------------
/** Extract only the query fields the PUT API accepts */
function cleanQuery(q: DashboardWidgetQuery): DashboardWidgetQuery {
return {
name: q.name ?? "",
conditions: q.conditions ?? "",
columns: q.columns ?? [],
aggregates: q.aggregates ?? [],
fields: q.fields ?? [],
...(q.fieldAliases && { fieldAliases: q.fieldAliases }),
...(q.orderby && { orderby: q.orderby }),
};
}
/**
* Strip server-generated and passthrough fields from a widget for PUT requests.
*
* Uses an allowlist approach: only includes fields the dashboard PUT API
* accepts. The GET response includes many extra fields (description, thresholds,
* interval, axisRange, datasetSource, etc.) that cause silent failures if
* sent back in PUT.
*
* @param widget - Widget object from GET response
* @returns Widget safe for PUT (only API-accepted fields)
*/
export function stripWidgetServerFields(
widget: DashboardWidget
): DashboardWidget {
const cleaned: DashboardWidget = {
title: widget.title,
displayType: widget.displayType,
...(widget.widgetType && { widgetType: widget.widgetType }),
...(widget.queries && { queries: widget.queries.map(cleanQuery) }),
...(widget.limit !== undefined &&
widget.limit !== null && { limit: widget.limit }),
};
// Preserve layout (x, y, w, h, minH only — not isResizable)
if (widget.layout) {
cleaned.layout = {
x: widget.layout.x,
y: widget.layout.y,
w: widget.layout.w,
h: widget.layout.h,
...(widget.layout.minH !== undefined && { minH: widget.layout.minH }),
};
}
return cleaned;
}
/**
* Prepare a full dashboard for PUT update.
* Strips server-generated fields from all widgets while preserving
* widgetType, displayType, and layout.
*
* @param dashboard - Dashboard detail from GET response
* @returns Object with title and cleaned widgets, ready for PUT body
*/
export function prepareDashboardForUpdate(dashboard: DashboardDetail): {
title: string;
widgets: DashboardWidget[];
projects?: number[];
environment?: string[];
period?: string | null;
} {
return {
title: dashboard.title,
widgets: (dashboard.widgets ?? []).map(stripWidgetServerFields),
projects: dashboard.projects,
environment: dashboard.environment,
period: dashboard.period,
};
}
// ---------------------------------------------------------------------------
// Widget data query types
//
// Types for responses from the events-stats and events API endpoints
// used to fetch actual widget data for dashboard rendering.
// ---------------------------------------------------------------------------
/**
* Single data point from the events-stats API.
* Format: [timestamp_epoch_seconds, [{count: value}]]
*/
export const EventsStatsDataPointSchema = z.tuple([
z.number(),
z.array(z.object({ count: z.number() })),
]);
export type EventsStatsDataPoint = z.infer<typeof EventsStatsDataPointSchema>;
/**
* A single time-series from events-stats.
*
* In simple queries this is the top-level response.
* In grouped queries (`topEvents > 0`) each group key maps to one of these.
*/
export const EventsStatsSeriesSchema = z
.object({
data: z.array(EventsStatsDataPointSchema),
order: z.number().optional(),
start: z.union([z.string(), z.number()]).optional(),
end: z.union([z.string(), z.number()]).optional(),
meta: z
.object({
fields: z.record(z.string()).optional(),
units: z.record(z.string().nullable()).optional(),
})
.passthrough()
.optional(),
})
.passthrough();
export type EventsStatsSeries = z.infer<typeof EventsStatsSeriesSchema>;
/**
* Response from `GET /organizations/{org}/events/` (table format).
*
* Used by table, big_number, and top_n widget types.
*/
export const EventsTableResponseSchema = z.object({
data: z.array(z.record(z.unknown())),
meta: z
.object({
fields: z.record(z.string()).optional(),
units: z.record(z.string().nullable()).optional(),
})
.optional(),
});
export type EventsTableResponse = z.infer<typeof EventsTableResponseSchema>;
// ---------------------------------------------------------------------------
// Widget data result types — discriminated union for all widget outputs
// ---------------------------------------------------------------------------
/** Time-series data for chart widgets (line, area, bar) */
export type TimeseriesResult = {
type: "timeseries";
series: {
label: string;
values: { timestamp: number; value: number }[];
unit?: string | null;
}[];
};
/** Tabular data for table and top_n widgets */
export type TableResult = {
type: "table";
columns: { name: string; type?: string; unit?: string | null }[];
rows: Record<string, unknown>[];
};
/** Single scalar value for big_number widgets */
export type ScalarResult = {
type: "scalar";
value: number;
previousValue?: number;
unit?: string | null;
};
/** Markdown text content for text widgets (no API query — content from widget.description) */
export type TextResult = {
type: "text";
content: string;
};
/** Widget type not supported for data fetching */
export type UnsupportedResult = {
type: "unsupported";
reason: string;
};
/** Widget query failed */
export type ErrorResult = {
type: "error";
message: string;
};
/**
* Result of querying a widget's data.
*
* Discriminated on `type` to determine how to render:
* - `timeseries` → sparkline charts
* - `table` → text table
* - `scalar` → big number display
* - `text` → rendered markdown content
* - `unsupported` → placeholder message
* - `error` → error message
*/
export type WidgetDataResult =
| TimeseriesResult
| TableResult
| ScalarResult
| TextResult
| UnsupportedResult
| ErrorResult;
// ---------------------------------------------------------------------------
// Dataset mapping
// ---------------------------------------------------------------------------
/**
* Maps widget types to API dataset parameter values.
*
* Widget types that don't map to a dataset (issue, preprod-app-size, etc.)
* return null and are rendered as "unsupported".
*/
const WIDGET_TYPE_TO_DATASET: Record<string, string> = {
spans: "spans",
discover: "discover",
"error-events": "errors",
"transaction-like": "transactions",
logs: "logs",
tracemetrics: "tracemetrics",
};
/**
* Map a widget's `widgetType` to the API `dataset` parameter.
*
* @param widgetType - The widget's dataset type (e.g., "spans", "discover")
* @returns The API dataset string, or null if the type isn't queryable
*/
export function mapWidgetTypeToDataset(
widgetType: string | undefined
): string | null {
if (!widgetType) {
return null;
}
return WIDGET_TYPE_TO_DATASET[widgetType] ?? null;
}
/** Display types that use time-series data (events-stats endpoint) */
export const TIMESERIES_DISPLAY_TYPES = new Set([
"line",
"area",
"stacked_area",
"bar",
"categorical_bar",
]);
/** Display types that use tabular data (events endpoint) */
export const TABLE_DISPLAY_TYPES = new Set(["table", "top_n"]);
// ---------------------------------------------------------------------------
// Dashboard revision types
// ---------------------------------------------------------------------------
/** Schema for the createdBy field in a dashboard revision */
const DashboardRevisionCreatedBySchema = z
.object({
id: z.string().optional(),
name: z.string().nullish(),
email: z.string().nullish(),
avatarType: z.string().nullish(),
avatarUrl: z.string().nullish(),
})
.passthrough();
/** Schema for a dashboard revision (from GET /dashboards/{id}/revisions/) */
export const DashboardRevisionSchema = z
.object({
id: z.string(),
title: z.string(),
dateCreated: z.string(),
createdBy: DashboardRevisionCreatedBySchema.nullable(),
source: z.string(),
})
.passthrough();
export type DashboardRevision = z.infer<typeof DashboardRevisionSchema>;
|