@smallwebco/tinypivot-mcp 0.6.1 → 0.7.1

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.
@@ -7369,6 +7369,1148 @@ function parseKey(key) {
7369
7369
  return key.split("|||");
7370
7370
  }
7371
7371
 
7372
+ // ../core/dist/chart/registry.js
7373
+ var DIMENSION_X = { xAxis: "X-Axis (dimension)", xAxisPlaceholder: "Drop a dimension" };
7374
+ var MEASURE_Y = { yAxis: "Y-Axis (measure)", yAxisPlaceholder: "Drop a measure" };
7375
+ var GROUP_SERIES = { slot: "seriesField", label: "Color / Series (optional)", placeholder: "Group by dimension" };
7376
+ var CHART_TYPES = [
7377
+ {
7378
+ type: "bar",
7379
+ defaults: { sortOrder: "value-desc" },
7380
+ label: "Bar Chart",
7381
+ icon: "M3 3v18h18V3H3zm4 14H5v-6h2v6zm4 0H9V7h2v10zm4 0h-2V9h2v8zm4 0h-2v-4h2v4z",
7382
+ description: "Compare values across categories",
7383
+ renderer: "apex",
7384
+ apexType: "bar",
7385
+ aliases: ["bars", "column", "columns", "column chart", "histogram", "ranking"],
7386
+ zones: { ...DIMENSION_X, ...MEASURE_Y, extra: GROUP_SERIES },
7387
+ requiredFields: ["dimension", "measure"],
7388
+ optionalFields: ["dimension"],
7389
+ guidance: "Drag a category to X-axis and a number to Y-axis",
7390
+ bestFor: ["Comparing categories", "Ranking", "Part-to-whole"]
7391
+ },
7392
+ {
7393
+ type: "stackedBar",
7394
+ defaults: { sortOrder: "value-desc" },
7395
+ label: "Stacked Bar",
7396
+ icon: "M3 3v18h18V3H3zm4 14H5v-3h2v3zm0-4H5v-3h2v3zm4 4H9v-5h2v5zm0-6H9v-4h2v4zm4 6h-2v-3h2v3zm0-4h-2v-5h2v5zm4 4h-2v-2h2v2zm0-3h-2v-2h2v2z",
7397
+ description: "Compare composition across categories",
7398
+ renderer: "apex",
7399
+ apexType: "bar",
7400
+ aliases: ["stacked", "stacked column", "stacked bars", "composition"],
7401
+ zones: { ...DIMENSION_X, ...MEASURE_Y, extra: { slot: "seriesField", label: "Series (stacking field)", placeholder: "Drop a dimension to stack by" } },
7402
+ requiredFields: ["dimension", "measure"],
7403
+ optionalFields: ["dimension"],
7404
+ guidance: "Drag a category to X-axis, a number to Y-axis, and a grouping field to Series",
7405
+ bestFor: ["Part-to-whole comparison", "Composition over categories", "Cumulative totals"]
7406
+ },
7407
+ {
7408
+ type: "line",
7409
+ label: "Line Chart",
7410
+ icon: "M3.5 18.5l6-6 4 4 8-8M14.5 8.5h6v6",
7411
+ description: "Show trends over time or sequence",
7412
+ renderer: "apex",
7413
+ apexType: "line",
7414
+ aliases: ["trend", "time series", "timeseries", "lines", "sparkline"],
7415
+ zones: { ...DIMENSION_X, ...MEASURE_Y, extra: GROUP_SERIES },
7416
+ requiredFields: ["dimension", "measure"],
7417
+ optionalFields: ["dimension"],
7418
+ guidance: "Best with time/date on X-axis and numbers on Y-axis",
7419
+ bestFor: ["Trends over time", "Continuous data", "Multiple series"]
7420
+ },
7421
+ {
7422
+ type: "area",
7423
+ label: "Area Chart",
7424
+ icon: "M3 17l6-6 4 4 8-8v10H3z",
7425
+ description: "Show magnitude and trends",
7426
+ renderer: "apex",
7427
+ apexType: "area",
7428
+ aliases: ["filled line", "mountain", "stacked area"],
7429
+ zones: { ...DIMENSION_X, ...MEASURE_Y, extra: GROUP_SERIES },
7430
+ requiredFields: ["dimension", "measure"],
7431
+ optionalFields: ["dimension"],
7432
+ guidance: "Like line charts but emphasizes volume. Great for stacked comparisons.",
7433
+ bestFor: ["Cumulative totals", "Part-to-whole over time", "Volume trends"]
7434
+ },
7435
+ {
7436
+ type: "pie",
7437
+ defaults: { sortOrder: "value-desc" },
7438
+ label: "Pie Chart",
7439
+ icon: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8v8l5.66 5.66C14.28 19.04 13.18 20 12 20z",
7440
+ description: "Show proportions of a whole",
7441
+ renderer: "apex",
7442
+ apexType: "pie",
7443
+ aliases: ["share", "proportion"],
7444
+ zones: { xAxis: "Slices (dimension)", xAxisPlaceholder: "Drop a dimension", yAxis: "Values (measure)", yAxisPlaceholder: "Drop a measure" },
7445
+ requiredFields: ["dimension", "measure"],
7446
+ optionalFields: [],
7447
+ guidance: "Drag a category and a number. Best with 2-6 categories.",
7448
+ bestFor: ["Part-to-whole", "Proportions", "Simple distributions"]
7449
+ },
7450
+ {
7451
+ type: "donut",
7452
+ defaults: { sortOrder: "value-desc" },
7453
+ label: "Donut Chart",
7454
+ icon: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z",
7455
+ description: "Proportions with center space for metrics",
7456
+ renderer: "apex",
7457
+ apexType: "donut",
7458
+ aliases: ["doughnut", "ring"],
7459
+ zones: { xAxis: "Slices (dimension)", xAxisPlaceholder: "Drop a dimension", yAxis: "Values (measure)", yAxisPlaceholder: "Drop a measure" },
7460
+ requiredFields: ["dimension", "measure"],
7461
+ optionalFields: [],
7462
+ guidance: "Like pie but allows showing a total in the center",
7463
+ bestFor: ["Part-to-whole", "Showing total", "Dashboard KPIs"]
7464
+ },
7465
+ {
7466
+ type: "scatter",
7467
+ label: "Scatter Plot",
7468
+ icon: "M7 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm5-6a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm5 8a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm-3 4a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",
7469
+ description: "Show relationships between two variables",
7470
+ renderer: "apex",
7471
+ apexType: "scatter",
7472
+ aliases: ["scatterplot", "scatter plot", "xy", "correlation", "dot plot", "points"],
7473
+ zones: {
7474
+ xAxis: "X-Axis (measure)",
7475
+ xAxisPlaceholder: "Drop a measure",
7476
+ ...MEASURE_Y,
7477
+ extra: { slot: "seriesField", label: "Color by (optional)", placeholder: "Group points by dimension" }
7478
+ },
7479
+ requiredFields: ["measure", "measure"],
7480
+ optionalFields: ["dimension"],
7481
+ guidance: "Drag a number to X-axis and another number to Y-axis",
7482
+ bestFor: ["Correlation", "Outlier detection", "Distribution"]
7483
+ },
7484
+ {
7485
+ type: "bubble",
7486
+ label: "Bubble Chart",
7487
+ icon: "M7 14a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm5-5a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm5 7a4 4 0 1 0 0-8 4 4 0 0 0 0 8z",
7488
+ description: "Three-dimensional comparison",
7489
+ renderer: "apex",
7490
+ apexType: "bubble",
7491
+ aliases: ["bubbles"],
7492
+ zones: {
7493
+ xAxis: "X-Axis (measure)",
7494
+ xAxisPlaceholder: "Drop a measure",
7495
+ ...MEASURE_Y,
7496
+ extra: { slot: "seriesField", label: "Color by (optional)", placeholder: "Group points by dimension" },
7497
+ size: { slot: "sizeField", label: "Size (number)", placeholder: "Drop a number for bubble size" }
7498
+ },
7499
+ requiredFields: ["measure", "measure"],
7500
+ optionalFields: ["measure", "dimension"],
7501
+ guidance: "Like scatter, plus drag a third number to Size for bubble size",
7502
+ bestFor: ["Multi-variable comparison", "Weighted relationships"]
7503
+ },
7504
+ {
7505
+ type: "heatmap",
7506
+ label: "Heatmap",
7507
+ icon: "M3 3h4v4H3V3zm6 0h4v4H9V3zm6 0h4v4h-4V3zM3 9h4v4H3V9zm6 0h4v4H9V9zm6 0h4v4h-4V9zM3 15h4v4H3v-4zm6 0h4v4H9v-4zm6 0h4v4h-4v-4z",
7508
+ description: "Visualize density or intensity",
7509
+ renderer: "apex",
7510
+ apexType: "heatmap",
7511
+ aliases: ["heat map", "matrix", "cross tab", "crosstab", "grid"],
7512
+ zones: {
7513
+ ...DIMENSION_X,
7514
+ yAxis: "Y-Axis (dimension)",
7515
+ yAxisPlaceholder: "Drop a dimension",
7516
+ extra: { slot: "colorField", label: "Value / Intensity", placeholder: "Drop a measure for color intensity" }
7517
+ },
7518
+ requiredFields: ["dimension", "dimension", "measure"],
7519
+ optionalFields: [],
7520
+ guidance: "Drag two categories (X and Y) and a number to Color",
7521
+ bestFor: ["Patterns", "Density", "Cross-tabulation"]
7522
+ },
7523
+ {
7524
+ type: "radar",
7525
+ label: "Radar Chart",
7526
+ icon: "M12 2L4 6v6c0 5.55 3.84 10.74 8 12 4.16-1.26 8-6.45 8-12V6l-8-4zm0 3.18l6 3v5.09c0 4.08-2.76 7.91-6 9.14V5.18z",
7527
+ description: "Compare multiple variables",
7528
+ renderer: "apex",
7529
+ apexType: "radar",
7530
+ aliases: ["spider", "web", "star", "spider web"],
7531
+ zones: {
7532
+ xAxis: "Axes (dimension)",
7533
+ xAxisPlaceholder: "Drop a dimension",
7534
+ yAxis: "Values (measure)",
7535
+ yAxisPlaceholder: "Drop a measure",
7536
+ extra: { slot: "seriesField", label: "Compare by (optional)", placeholder: "Group by dimension" }
7537
+ },
7538
+ requiredFields: ["dimension", "measure"],
7539
+ optionalFields: ["dimension"],
7540
+ guidance: "Best for comparing items across multiple metrics",
7541
+ bestFor: ["Multi-metric comparison", "Performance profiles", "Balanced scorecards"]
7542
+ },
7543
+ {
7544
+ type: "choropleth",
7545
+ label: "Map",
7546
+ icon: "M3 6.5L9 4l6 2.5L21 4v13.5L15 20l-6-2.5L3 20V6.5zm7 .9v8.8l4 1.6V9z",
7547
+ description: "Shade countries, US states or sales regions by value",
7548
+ renderer: "d3",
7549
+ aliases: ["map", "maps", "geo", "geomap", "filled map", "region map", "world map", "us map", "state map", "country map"],
7550
+ zones: {
7551
+ xAxis: "Region (country, state or region)",
7552
+ xAxisPlaceholder: "Drop a name or ISO / postal code",
7553
+ yAxis: "Value (measure)",
7554
+ yAxisPlaceholder: "Drop a measure"
7555
+ },
7556
+ defaults: { geography: "auto", showLegend: true },
7557
+ terminalFallback: { as: "bar", note: "Map drawn in TinyPivot; this text card ranks the regions instead." },
7558
+ requiredFields: ["dimension", "measure"],
7559
+ optionalFields: [],
7560
+ guidance: "Drag a country, US state or region (e.g. EMEA, APAC) and a number",
7561
+ bestFor: ["Regional comparison", "Geographic spread", "Territory performance"]
7562
+ },
7563
+ {
7564
+ type: "bullet",
7565
+ label: "Bullet",
7566
+ icon: "M3 5h14v4H3V5zm0 10h10v4H3v-4zm16-11h2v6h-2V4zm-4 10h2v6h-2v-6z",
7567
+ description: "Actual against target with qualitative bands",
7568
+ renderer: "d3",
7569
+ aliases: ["bullets", "target", "actual vs target", "vs target", "kpi", "progress", "goal", "quota"],
7570
+ zones: {
7571
+ xAxis: "Rows (dimension)",
7572
+ xAxisPlaceholder: "Drop a dimension",
7573
+ yAxis: "Actual (measure)",
7574
+ yAxisPlaceholder: "Drop a measure",
7575
+ size: { slot: "targetField", label: "Target (measure, optional)", placeholder: "Drop a target measure" }
7576
+ },
7577
+ defaults: { sortOrder: "value-desc" },
7578
+ terminalFallback: { as: "bar", note: "Bullet chart drawn in TinyPivot; this text card shows actuals as bars." },
7579
+ requiredFields: ["dimension", "measure"],
7580
+ optionalFields: ["measure"],
7581
+ guidance: "Drag a category and an actual; add a target measure for the marker",
7582
+ bestFor: ["Actual vs target", "Quota attainment", "KPI scorecards"]
7583
+ },
7584
+ {
7585
+ type: "radialBar",
7586
+ label: "Radial Bar",
7587
+ icon: "M12 2a10 10 0 0 1 10 10h-3a7 7 0 0 0-7-7V2zm0 5a5 5 0 0 1 5 5h-3a2 2 0 0 0-2-2V7zM2 12h3a7 7 0 0 0 7 7v3A10 10 0 0 1 2 12z",
7588
+ description: "Bars wrapped around a circle",
7589
+ renderer: "d3",
7590
+ aliases: ["radial", "radial bars", "circular bar", "circular bars", "polar bar", "gauge", "rose", "nightingale", "wind rose"],
7591
+ zones: {
7592
+ xAxis: "Bars (dimension)",
7593
+ xAxisPlaceholder: "Drop a dimension",
7594
+ yAxis: "Length (measure)",
7595
+ yAxisPlaceholder: "Drop a measure",
7596
+ extra: { slot: "seriesField", label: "Stack by (optional)", placeholder: "Group by dimension" }
7597
+ },
7598
+ defaults: { sortOrder: "value-desc" },
7599
+ terminalFallback: { as: "bar", note: "Radial bars drawn in TinyPivot; this text card shows them as straight bars." },
7600
+ requiredFields: ["dimension", "measure"],
7601
+ optionalFields: ["dimension"],
7602
+ guidance: "Drag a category and a number; add a series to stack",
7603
+ bestFor: ["Cyclical categories", "Ranking at a glance", "Compact dashboards"]
7604
+ },
7605
+ {
7606
+ type: "radialArea",
7607
+ label: "Radial Area",
7608
+ icon: "M12 2l3 7 7 1-5 5 2 7-7-4-7 4 2-7-5-5 7-1z",
7609
+ description: "A filled line around a circle, for cycles like months or hours",
7610
+ renderer: "d3",
7611
+ aliases: ["polar area", "radial line", "circular area", "radial area chart", "seasonality", "clock"],
7612
+ zones: {
7613
+ xAxis: "Angle (dimension, e.g. month)",
7614
+ xAxisPlaceholder: "Drop a dimension",
7615
+ yAxis: "Radius (measure)",
7616
+ yAxisPlaceholder: "Drop a measure",
7617
+ extra: { slot: "seriesField", label: "Compare by (optional)", placeholder: "Group by dimension" }
7618
+ },
7619
+ defaults: { sortOrder: "label-asc" },
7620
+ terminalFallback: { as: "line", note: "Radial area drawn in TinyPivot; this text card unrolls it into a line." },
7621
+ requiredFields: ["dimension", "measure"],
7622
+ optionalFields: ["dimension"],
7623
+ guidance: "Best with an ordered cycle (months, weekdays, hours) and a number",
7624
+ bestFor: ["Seasonality", "Cyclical patterns", "Year-over-year cycles"]
7625
+ },
7626
+ {
7627
+ type: "treemap",
7628
+ label: "Treemap",
7629
+ icon: "M3 3h10v10H3V3zm12 0h6v6h-6V3zm0 8h6v10h-6V11zM3 15h10v6H3v-6z",
7630
+ description: "Nested rectangles sized by value",
7631
+ renderer: "d3",
7632
+ aliases: ["tree map", "tiles", "mosaic", "hierarchy", "blocks"],
7633
+ zones: {
7634
+ xAxis: "Tiles (dimension)",
7635
+ xAxisPlaceholder: "Drop a dimension",
7636
+ yAxis: "Size (measure)",
7637
+ yAxisPlaceholder: "Drop a measure",
7638
+ extra: { slot: "seriesField", label: "Group by (optional parent)", placeholder: "Drop a parent dimension" }
7639
+ },
7640
+ defaults: { sortOrder: "value-desc" },
7641
+ terminalFallback: { as: "bar", note: "Treemap drawn in TinyPivot; this text card ranks the tiles instead." },
7642
+ requiredFields: ["dimension", "measure"],
7643
+ optionalFields: ["dimension"],
7644
+ guidance: "Drag a category and a number; add a parent group to nest tiles",
7645
+ bestFor: ["Part-to-whole with many items", "Nested breakdowns", "Spotting the big few"]
7646
+ },
7647
+ {
7648
+ type: "sunburst",
7649
+ label: "Sunburst",
7650
+ icon: "M12 2a10 10 0 1 0 10 10h-4a6 6 0 1 1-6-6V2zm0 6a4 4 0 1 0 4 4h-4V8z",
7651
+ description: "Rings of a hierarchy, parent inside, children outside",
7652
+ renderer: "d3",
7653
+ aliases: ["sun burst", "multi-level pie", "multilevel pie", "nested donut", "radial tree"],
7654
+ zones: {
7655
+ xAxis: "Outer ring (dimension)",
7656
+ xAxisPlaceholder: "Drop a dimension",
7657
+ yAxis: "Size (measure)",
7658
+ yAxisPlaceholder: "Drop a measure",
7659
+ extra: { slot: "seriesField", label: "Inner ring (optional parent)", placeholder: "Drop a parent dimension" }
7660
+ },
7661
+ defaults: { sortOrder: "value-desc" },
7662
+ terminalFallback: { as: "bar", note: "Sunburst drawn in TinyPivot; this text card ranks the outer ring instead." },
7663
+ requiredFields: ["dimension", "measure"],
7664
+ optionalFields: ["dimension"],
7665
+ guidance: "Drag a category and a number; add a parent for the inner ring",
7666
+ bestFor: ["Two-level part-to-whole", "Category \u2192 subcategory mix"]
7667
+ },
7668
+ {
7669
+ type: "slope",
7670
+ label: "Slope",
7671
+ icon: "M4 4v16M20 4v16M4 15l16-9M4 8l16 6M4 18l16-2",
7672
+ description: "Who grew and who shrank between two periods",
7673
+ renderer: "d3",
7674
+ aliases: ["slopegraph", "slope graph", "slope chart", "before after", "before and after", "change", "period comparison", "yoy", "year over year"],
7675
+ zones: {
7676
+ xAxis: "Lines (dimension)",
7677
+ xAxisPlaceholder: "Drop a dimension",
7678
+ yAxis: "Value (measure)",
7679
+ yAxisPlaceholder: "Drop a measure",
7680
+ extra: { slot: "seriesField", label: "Periods (first vs last, e.g. year)", placeholder: "Drop a period dimension" }
7681
+ },
7682
+ defaults: { sortOrder: "value-desc" },
7683
+ terminalFallback: { as: "bar", note: "Slope chart drawn in TinyPivot; this text card shows totals as bars." },
7684
+ requiredFields: ["dimension", "measure", "dimension"],
7685
+ optionalFields: [],
7686
+ guidance: "Drag a category, a number, and a period field (e.g. year) to compare first vs last",
7687
+ bestFor: ["Year-over-year change", "Before and after", "Rank shifts"]
7688
+ }
7689
+ ];
7690
+ var TYPE_BY_ID = new Map(CHART_TYPES.map((t) => [t.type, t]));
7691
+ function normalizeTypeName(name) {
7692
+ return name.toLowerCase().replace(/[\s_\-]+/g, "");
7693
+ }
7694
+ var TYPE_BY_NAME = /* @__PURE__ */ new Map();
7695
+ for (const info of CHART_TYPES) {
7696
+ for (const name of [info.type, info.label, ...info.aliases])
7697
+ TYPE_BY_NAME.set(normalizeTypeName(name), info.type);
7698
+ }
7699
+ var CHART_TYPE_IDS = CHART_TYPES.map((t) => t.type);
7700
+ function resolveChartType(name) {
7701
+ if (!name)
7702
+ return null;
7703
+ return TYPE_BY_NAME.get(normalizeTypeName(name)) ?? null;
7704
+ }
7705
+ function getChartTypeInfo(type) {
7706
+ return TYPE_BY_ID.get(type);
7707
+ }
7708
+ function getEffectiveChartOptions(config) {
7709
+ const defaults = TYPE_BY_ID.get(config.type)?.defaults ?? {};
7710
+ const options = { ...defaults };
7711
+ for (const [key, value2] of Object.entries(config.options ?? {})) {
7712
+ if (value2 !== void 0)
7713
+ options[key] = value2;
7714
+ }
7715
+ return options;
7716
+ }
7717
+
7718
+ // ../core/dist/chart/geo-codes.js
7719
+ var COUNTRY_ROWS = [
7720
+ ["AD", "AND", "020", "EU", "Andorra"],
7721
+ ["AE", "ARE", "784", "AS", "United Arab Emirates", "UAE"],
7722
+ ["AF", "AFG", "004", "AS", "Afghanistan"],
7723
+ ["AG", "ATG", "028", "NA", "Antigua and Barbuda"],
7724
+ ["AI", "AIA", "660", "NA", "Anguilla"],
7725
+ ["AL", "ALB", "008", "EU", "Albania"],
7726
+ ["AM", "ARM", "051", "AS", "Armenia"],
7727
+ ["AO", "AGO", "024", "AF", "Angola"],
7728
+ ["AQ", "ATA", "010", "AN", "Antarctica"],
7729
+ ["AR", "ARG", "032", "SA", "Argentina"],
7730
+ ["AS", "ASM", "016", "OC", "American Samoa"],
7731
+ ["AT", "AUT", "040", "EU", "Austria"],
7732
+ ["AU", "AUS", "036", "OC", "Australia"],
7733
+ ["AW", "ABW", "533", "NA", "Aruba"],
7734
+ ["AX", "ALA", "248", "EU", "\xC5land Islands", "Aland Islands"],
7735
+ ["AZ", "AZE", "031", "AS", "Azerbaijan"],
7736
+ ["BA", "BIH", "070", "EU", "Bosnia and Herzegovina", "Bosnia and Herz."],
7737
+ ["BB", "BRB", "052", "NA", "Barbados"],
7738
+ ["BD", "BGD", "050", "AS", "Bangladesh"],
7739
+ ["BE", "BEL", "056", "EU", "Belgium"],
7740
+ ["BF", "BFA", "854", "AF", "Burkina Faso"],
7741
+ ["BG", "BGR", "100", "EU", "Bulgaria"],
7742
+ ["BH", "BHR", "048", "AS", "Bahrain"],
7743
+ ["BI", "BDI", "108", "AF", "Burundi"],
7744
+ ["BJ", "BEN", "204", "AF", "Benin"],
7745
+ ["BL", "BLM", "652", "NA", "Saint Barth\xE9lemy"],
7746
+ ["BM", "BMU", "060", "NA", "Bermuda"],
7747
+ ["BN", "BRN", "096", "AS", "Brunei Darussalam", "Brunei"],
7748
+ ["BO", "BOL", "068", "SA", "Bolivia"],
7749
+ ["BQ", "BES", "535", "NA", "Bonaire, Sint Eustatius and Saba"],
7750
+ ["BR", "BRA", "076", "SA", "Brazil"],
7751
+ ["BS", "BHS", "044", "NA", "Bahamas"],
7752
+ ["BT", "BTN", "064", "AS", "Bhutan"],
7753
+ ["BV", "BVT", "074", "AN", "Bouvet Island"],
7754
+ ["BW", "BWA", "072", "AF", "Botswana"],
7755
+ ["BY", "BLR", "112", "EU", "Belarus"],
7756
+ ["BZ", "BLZ", "084", "NA", "Belize"],
7757
+ ["CA", "CAN", "124", "NA", "Canada"],
7758
+ ["CC", "CCK", "166", "AS", "Cocos (Keeling) Islands"],
7759
+ ["CD", "COD", "180", "AF", "Democratic Republic of the Congo", "Congo", "Dem. Rep. Congo"],
7760
+ ["CF", "CAF", "140", "AF", "Central African Republic", "Central African Rep."],
7761
+ ["CG", "COG", "178", "AF", "Republic of the Congo", "Congo"],
7762
+ ["CH", "CHE", "756", "EU", "Switzerland"],
7763
+ ["CI", "CIV", "384", "AF", "Cote d'Ivoire", "C\xF4te d'Ivoire", "Ivory Coast"],
7764
+ ["CK", "COK", "184", "OC", "Cook Islands"],
7765
+ ["CL", "CHL", "152", "SA", "Chile"],
7766
+ ["CM", "CMR", "120", "AF", "Cameroon"],
7767
+ ["CN", "CHN", "156", "AS", "People's Republic of China", "China"],
7768
+ ["CO", "COL", "170", "SA", "Colombia"],
7769
+ ["CR", "CRI", "188", "NA", "Costa Rica"],
7770
+ ["CU", "CUB", "192", "NA", "Cuba"],
7771
+ ["CV", "CPV", "132", "AF", "Cape Verde"],
7772
+ ["CW", "CUW", "531", "NA", "Cura\xE7ao"],
7773
+ ["CX", "CXR", "162", "AS", "Christmas Island"],
7774
+ ["CY", "CYP", "196", "EU", "Cyprus"],
7775
+ ["CZ", "CZE", "203", "EU", "Czech Republic", "Czechia"],
7776
+ ["DE", "DEU", "276", "EU", "Germany"],
7777
+ ["DJ", "DJI", "262", "AF", "Djibouti"],
7778
+ ["DK", "DNK", "208", "EU", "Denmark"],
7779
+ ["DM", "DMA", "212", "NA", "Dominica"],
7780
+ ["DO", "DOM", "214", "NA", "Dominican Republic", "Dominican Rep."],
7781
+ ["DZ", "DZA", "012", "AF", "Algeria"],
7782
+ ["EC", "ECU", "218", "SA", "Ecuador"],
7783
+ ["EE", "EST", "233", "EU", "Estonia"],
7784
+ ["EG", "EGY", "818", "AF", "Egypt"],
7785
+ ["EH", "ESH", "732", "AF", "Western Sahara", "W. Sahara"],
7786
+ ["ER", "ERI", "232", "AF", "Eritrea"],
7787
+ ["ES", "ESP", "724", "EU", "Spain"],
7788
+ ["ET", "ETH", "231", "AF", "Ethiopia"],
7789
+ ["FI", "FIN", "246", "EU", "Finland"],
7790
+ ["FJ", "FJI", "242", "OC", "Fiji"],
7791
+ ["FK", "FLK", "238", "SA", "Falkland Islands (Malvinas)", "Falkland Is."],
7792
+ ["FM", "FSM", "583", "OC", "Micronesia, Federated States of"],
7793
+ ["FO", "FRO", "234", "EU", "Faroe Islands"],
7794
+ ["FR", "FRA", "250", "EU", "France"],
7795
+ ["GA", "GAB", "266", "AF", "Gabon"],
7796
+ ["GB", "GBR", "826", "EU", "United Kingdom", "UK", "Great Britain"],
7797
+ ["GD", "GRD", "308", "NA", "Grenada"],
7798
+ ["GE", "GEO", "268", "AS", "Georgia"],
7799
+ ["GF", "GUF", "254", "SA", "French Guiana"],
7800
+ ["GG", "GGY", "831", "EU", "Guernsey"],
7801
+ ["GH", "GHA", "288", "AF", "Ghana"],
7802
+ ["GI", "GIB", "292", "EU", "Gibraltar"],
7803
+ ["GL", "GRL", "304", "NA", "Greenland"],
7804
+ ["GM", "GMB", "270", "AF", "Republic of The Gambia", "The Gambia", "Gambia"],
7805
+ ["GN", "GIN", "324", "AF", "Guinea"],
7806
+ ["GP", "GLP", "312", "NA", "Guadeloupe"],
7807
+ ["GQ", "GNQ", "226", "AF", "Equatorial Guinea", "Eq. Guinea"],
7808
+ ["GR", "GRC", "300", "EU", "Greece"],
7809
+ ["GS", "SGS", "239", "AN", "South Georgia and the South Sandwich Islands"],
7810
+ ["GT", "GTM", "320", "NA", "Guatemala"],
7811
+ ["GU", "GUM", "316", "OC", "Guam"],
7812
+ ["GW", "GNB", "624", "AF", "Guinea-Bissau"],
7813
+ ["GY", "GUY", "328", "SA", "Guyana"],
7814
+ ["HK", "HKG", "344", "AS", "Hong Kong"],
7815
+ ["HM", "HMD", "334", "AN", "Heard Island and McDonald Islands"],
7816
+ ["HN", "HND", "340", "NA", "Honduras"],
7817
+ ["HR", "HRV", "191", "EU", "Croatia"],
7818
+ ["HT", "HTI", "332", "NA", "Haiti"],
7819
+ ["HU", "HUN", "348", "EU", "Hungary"],
7820
+ ["ID", "IDN", "360", "AS", "Indonesia"],
7821
+ ["IE", "IRL", "372", "EU", "Ireland"],
7822
+ ["IL", "ISR", "376", "AS", "Israel"],
7823
+ ["IM", "IMN", "833", "EU", "Isle of Man"],
7824
+ ["IN", "IND", "356", "AS", "India"],
7825
+ ["IO", "IOT", "086", "AS", "British Indian Ocean Territory"],
7826
+ ["IQ", "IRQ", "368", "AS", "Iraq"],
7827
+ ["IR", "IRN", "364", "AS", "Islamic Republic of Iran", "Iran"],
7828
+ ["IS", "ISL", "352", "EU", "Iceland"],
7829
+ ["IT", "ITA", "380", "EU", "Italy"],
7830
+ ["JE", "JEY", "832", "EU", "Jersey"],
7831
+ ["JM", "JAM", "388", "NA", "Jamaica"],
7832
+ ["JO", "JOR", "400", "AS", "Jordan"],
7833
+ ["JP", "JPN", "392", "AS", "Japan"],
7834
+ ["KE", "KEN", "404", "AF", "Kenya"],
7835
+ ["KG", "KGZ", "417", "AS", "Kyrgyzstan"],
7836
+ ["KH", "KHM", "116", "AS", "Cambodia"],
7837
+ ["KI", "KIR", "296", "OC", "Kiribati"],
7838
+ ["KM", "COM", "174", "AF", "Comoros"],
7839
+ ["KN", "KNA", "659", "NA", "Saint Kitts and Nevis"],
7840
+ ["KP", "PRK", "408", "AS", "North Korea"],
7841
+ ["KR", "KOR", "410", "AS", "South Korea", "Korea, Republic of", "Republic of Korea"],
7842
+ ["KW", "KWT", "414", "AS", "Kuwait"],
7843
+ ["KY", "CYM", "136", "NA", "Cayman Islands"],
7844
+ ["KZ", "KAZ", "398", "AS", "Kazakhstan"],
7845
+ ["LA", "LAO", "418", "AS", "Lao People's Democratic Republic", "Laos"],
7846
+ ["LB", "LBN", "422", "AS", "Lebanon"],
7847
+ ["LC", "LCA", "662", "NA", "Saint Lucia"],
7848
+ ["LI", "LIE", "438", "EU", "Liechtenstein"],
7849
+ ["LK", "LKA", "144", "AS", "Sri Lanka"],
7850
+ ["LR", "LBR", "430", "AF", "Liberia"],
7851
+ ["LS", "LSO", "426", "AF", "Lesotho"],
7852
+ ["LT", "LTU", "440", "EU", "Lithuania"],
7853
+ ["LU", "LUX", "442", "EU", "Luxembourg"],
7854
+ ["LV", "LVA", "428", "EU", "Latvia"],
7855
+ ["LY", "LBY", "434", "AF", "Libya"],
7856
+ ["MA", "MAR", "504", "AF", "Morocco"],
7857
+ ["MC", "MCO", "492", "EU", "Monaco"],
7858
+ ["MD", "MDA", "498", "EU", "Moldova, Republic of", "Moldova"],
7859
+ ["ME", "MNE", "499", "EU", "Montenegro"],
7860
+ ["MF", "MAF", "663", "NA", "Saint Martin (French part)"],
7861
+ ["MG", "MDG", "450", "AF", "Madagascar"],
7862
+ ["MH", "MHL", "584", "OC", "Marshall Islands"],
7863
+ ["MK", "MKD", "807", "EU", "The Republic of North Macedonia", "North Macedonia", "Macedonia"],
7864
+ ["ML", "MLI", "466", "AF", "Mali"],
7865
+ ["MM", "MMR", "104", "AS", "Myanmar"],
7866
+ ["MN", "MNG", "496", "AS", "Mongolia"],
7867
+ ["MO", "MAC", "446", "AS", "Macao"],
7868
+ ["MP", "MNP", "580", "OC", "Northern Mariana Islands"],
7869
+ ["MQ", "MTQ", "474", "NA", "Martinique"],
7870
+ ["MR", "MRT", "478", "AF", "Mauritania"],
7871
+ ["MS", "MSR", "500", "NA", "Montserrat"],
7872
+ ["MT", "MLT", "470", "EU", "Malta"],
7873
+ ["MU", "MUS", "480", "AF", "Mauritius"],
7874
+ ["MV", "MDV", "462", "AS", "Maldives"],
7875
+ ["MW", "MWI", "454", "AF", "Malawi"],
7876
+ ["MX", "MEX", "484", "NA", "Mexico"],
7877
+ ["MY", "MYS", "458", "AS", "Malaysia"],
7878
+ ["MZ", "MOZ", "508", "AF", "Mozambique"],
7879
+ ["NA", "NAM", "516", "AF", "Namibia"],
7880
+ ["NC", "NCL", "540", "OC", "New Caledonia"],
7881
+ ["NE", "NER", "562", "AF", "Niger"],
7882
+ ["NF", "NFK", "574", "OC", "Norfolk Island"],
7883
+ ["NG", "NGA", "566", "AF", "Nigeria"],
7884
+ ["NI", "NIC", "558", "NA", "Nicaragua"],
7885
+ ["NL", "NLD", "528", "EU", "Netherlands", "The Netherlands", "Netherlands (Kingdom of the)"],
7886
+ ["NO", "NOR", "578", "EU", "Norway"],
7887
+ ["NP", "NPL", "524", "AS", "Nepal"],
7888
+ ["NR", "NRU", "520", "OC", "Nauru"],
7889
+ ["NU", "NIU", "570", "OC", "Niue"],
7890
+ ["NZ", "NZL", "554", "OC", "New Zealand"],
7891
+ ["OM", "OMN", "512", "AS", "Oman"],
7892
+ ["PA", "PAN", "591", "NA", "Panama"],
7893
+ ["PE", "PER", "604", "SA", "Peru"],
7894
+ ["PF", "PYF", "258", "OC", "French Polynesia"],
7895
+ ["PG", "PNG", "598", "OC", "Papua New Guinea"],
7896
+ ["PH", "PHL", "608", "AS", "Philippines"],
7897
+ ["PK", "PAK", "586", "AS", "Pakistan"],
7898
+ ["PL", "POL", "616", "EU", "Poland"],
7899
+ ["PM", "SPM", "666", "NA", "Saint Pierre and Miquelon"],
7900
+ ["PN", "PCN", "612", "OC", "Pitcairn", "Pitcairn Islands"],
7901
+ ["PR", "PRI", "630", "NA", "Puerto Rico"],
7902
+ ["PS", "PSE", "275", "AS", "State of Palestine", "Palestine"],
7903
+ ["PT", "PRT", "620", "EU", "Portugal"],
7904
+ ["PW", "PLW", "585", "OC", "Palau"],
7905
+ ["PY", "PRY", "600", "SA", "Paraguay"],
7906
+ ["QA", "QAT", "634", "AS", "Qatar"],
7907
+ ["RE", "REU", "638", "AF", "Reunion"],
7908
+ ["RO", "ROU", "642", "EU", "Romania"],
7909
+ ["RS", "SRB", "688", "EU", "Serbia"],
7910
+ ["RU", "RUS", "643", "AS", "Russian Federation", "Russia"],
7911
+ ["RW", "RWA", "646", "AF", "Rwanda"],
7912
+ ["SA", "SAU", "682", "AS", "Saudi Arabia"],
7913
+ ["SB", "SLB", "090", "OC", "Solomon Islands", "Solomon Is."],
7914
+ ["SC", "SYC", "690", "AF", "Seychelles"],
7915
+ ["SD", "SDN", "729", "AF", "Sudan"],
7916
+ ["SE", "SWE", "752", "EU", "Sweden"],
7917
+ ["SG", "SGP", "702", "AS", "Singapore"],
7918
+ ["SH", "SHN", "654", "AF", "Saint Helena"],
7919
+ ["SI", "SVN", "705", "EU", "Slovenia"],
7920
+ ["SJ", "SJM", "744", "EU", "Svalbard and Jan Mayen"],
7921
+ ["SK", "SVK", "703", "EU", "Slovakia"],
7922
+ ["SL", "SLE", "694", "AF", "Sierra Leone"],
7923
+ ["SM", "SMR", "674", "EU", "San Marino"],
7924
+ ["SN", "SEN", "686", "AF", "Senegal"],
7925
+ ["SO", "SOM", "706", "AF", "Somalia"],
7926
+ ["SR", "SUR", "740", "SA", "Suriname"],
7927
+ ["SS", "SSD", "728", "AF", "South Sudan", "S. Sudan"],
7928
+ ["ST", "STP", "678", "AF", "Sao Tome and Principe"],
7929
+ ["SV", "SLV", "222", "NA", "El Salvador"],
7930
+ ["SX", "SXM", "534", "NA", "Sint Maarten (Dutch part)"],
7931
+ ["SY", "SYR", "760", "AS", "Syrian Arab Republic", "Syria"],
7932
+ ["SZ", "SWZ", "748", "AF", "Eswatini", "eSwatini"],
7933
+ ["TC", "TCA", "796", "NA", "Turks and Caicos Islands"],
7934
+ ["TD", "TCD", "148", "AF", "Chad"],
7935
+ ["TF", "ATF", "260", "AN", "French Southern Territories", "Fr. S. Antarctic Lands"],
7936
+ ["TG", "TGO", "768", "AF", "Togo"],
7937
+ ["TH", "THA", "764", "AS", "Thailand"],
7938
+ ["TJ", "TJK", "762", "AS", "Tajikistan"],
7939
+ ["TK", "TKL", "772", "OC", "Tokelau"],
7940
+ ["TL", "TLS", "626", "OC", "Timor-Leste"],
7941
+ ["TM", "TKM", "795", "AS", "Turkmenistan"],
7942
+ ["TN", "TUN", "788", "AF", "Tunisia"],
7943
+ ["TO", "TON", "776", "OC", "Tonga"],
7944
+ ["TR", "TUR", "792", "AS", "T\xFCrkiye", "Turkey"],
7945
+ ["TT", "TTO", "780", "NA", "Trinidad and Tobago"],
7946
+ ["TV", "TUV", "798", "OC", "Tuvalu"],
7947
+ ["TW", "TWN", "158", "AS", "Taiwan, Province of China", "Taiwan"],
7948
+ ["TZ", "TZA", "834", "AF", "United Republic of Tanzania", "Tanzania"],
7949
+ ["UA", "UKR", "804", "EU", "Ukraine"],
7950
+ ["UG", "UGA", "800", "AF", "Uganda"],
7951
+ ["UM", "UMI", "581", "OC", "United States Minor Outlying Islands"],
7952
+ ["US", "USA", "840", "NA", "United States of America", "United States", "USA", "U.S.A.", "US", "U.S."],
7953
+ ["UY", "URY", "858", "SA", "Uruguay"],
7954
+ ["UZ", "UZB", "860", "AS", "Uzbekistan"],
7955
+ ["VA", "VAT", "336", "EU", "Holy See (Vatican City State)"],
7956
+ ["VC", "VCT", "670", "NA", "Saint Vincent and the Grenadines"],
7957
+ ["VE", "VEN", "862", "SA", "Venezuela"],
7958
+ ["VG", "VGB", "092", "NA", "Virgin Islands, British"],
7959
+ ["VI", "VIR", "850", "NA", "Virgin Islands, U.S."],
7960
+ ["VN", "VNM", "704", "AS", "Vietnam"],
7961
+ ["VU", "VUT", "548", "OC", "Vanuatu"],
7962
+ ["WF", "WLF", "876", "OC", "Wallis and Futuna"],
7963
+ ["WS", "WSM", "882", "OC", "Samoa"],
7964
+ ["XK", "XKK", "983", "EU", "Kosovo"],
7965
+ ["YE", "YEM", "887", "AS", "Yemen"],
7966
+ ["YT", "MYT", "175", "AF", "Mayotte"],
7967
+ ["ZA", "ZAF", "710", "AF", "South Africa"],
7968
+ ["ZM", "ZMB", "894", "AF", "Zambia"],
7969
+ ["ZW", "ZWE", "716", "AF", "Zimbabwe"]
7970
+ ];
7971
+
7972
+ // ../core/dist/chart/geo.js
7973
+ var US_STATE_ROWS = [
7974
+ ["01", "AL", "Alabama"],
7975
+ ["02", "AK", "Alaska"],
7976
+ ["04", "AZ", "Arizona"],
7977
+ ["05", "AR", "Arkansas"],
7978
+ ["06", "CA", "California"],
7979
+ ["08", "CO", "Colorado"],
7980
+ ["09", "CT", "Connecticut"],
7981
+ ["10", "DE", "Delaware"],
7982
+ ["11", "DC", "District of Columbia"],
7983
+ ["12", "FL", "Florida"],
7984
+ ["13", "GA", "Georgia"],
7985
+ ["15", "HI", "Hawaii"],
7986
+ ["16", "ID", "Idaho"],
7987
+ ["17", "IL", "Illinois"],
7988
+ ["18", "IN", "Indiana"],
7989
+ ["19", "IA", "Iowa"],
7990
+ ["20", "KS", "Kansas"],
7991
+ ["21", "KY", "Kentucky"],
7992
+ ["22", "LA", "Louisiana"],
7993
+ ["23", "ME", "Maine"],
7994
+ ["24", "MD", "Maryland"],
7995
+ ["25", "MA", "Massachusetts"],
7996
+ ["26", "MI", "Michigan"],
7997
+ ["27", "MN", "Minnesota"],
7998
+ ["28", "MS", "Mississippi"],
7999
+ ["29", "MO", "Missouri"],
8000
+ ["30", "MT", "Montana"],
8001
+ ["31", "NE", "Nebraska"],
8002
+ ["32", "NV", "Nevada"],
8003
+ ["33", "NH", "New Hampshire"],
8004
+ ["34", "NJ", "New Jersey"],
8005
+ ["35", "NM", "New Mexico"],
8006
+ ["36", "NY", "New York"],
8007
+ ["37", "NC", "North Carolina"],
8008
+ ["38", "ND", "North Dakota"],
8009
+ ["39", "OH", "Ohio"],
8010
+ ["40", "OK", "Oklahoma"],
8011
+ ["41", "OR", "Oregon"],
8012
+ ["42", "PA", "Pennsylvania"],
8013
+ ["44", "RI", "Rhode Island"],
8014
+ ["45", "SC", "South Carolina"],
8015
+ ["46", "SD", "South Dakota"],
8016
+ ["47", "TN", "Tennessee"],
8017
+ ["48", "TX", "Texas"],
8018
+ ["49", "UT", "Utah"],
8019
+ ["50", "VT", "Vermont"],
8020
+ ["51", "VA", "Virginia"],
8021
+ ["53", "WA", "Washington"],
8022
+ ["54", "WV", "West Virginia"],
8023
+ ["55", "WI", "Wisconsin"],
8024
+ ["56", "WY", "Wyoming"],
8025
+ ["72", "PR", "Puerto Rico"]
8026
+ ];
8027
+ var US_STATE_ALIASES = {
8028
+ "washington dc": "DC",
8029
+ "washington d c": "DC",
8030
+ "d c": "DC",
8031
+ "dist of columbia": "DC",
8032
+ "washington state": "WA",
8033
+ "new york state": "NY"
8034
+ };
8035
+ function normalizeRegionName(name) {
8036
+ return name.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim().replace(/^the /, "");
8037
+ }
8038
+ var MIDDLE_EAST = ["AE", "BH", "IL", "IQ", "IR", "JO", "KW", "LB", "OM", "PS", "QA", "SA", "SY", "TR", "YE"];
8039
+ var NORTH_AFRICA = ["DZ", "EG", "EH", "LY", "MA", "TN"];
8040
+ var CENTRAL_AMERICA = ["BZ", "CR", "GT", "HN", "NI", "PA", "SV"];
8041
+ var ANGLO_NORTH_AMERICA = ["US", "CA", "GL", "BM", "PM"];
8042
+ var EU_MEMBERS = ["AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "ES", "FI", "FR", "GR", "HR", "HU", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "PT", "RO", "SE", "SI", "SK"];
8043
+ function continent(code) {
8044
+ return COUNTRY_ROWS.filter((r) => r[3] === code).map((r) => r[0]);
8045
+ }
8046
+ function without(list, drop) {
8047
+ const dropSet = new Set(drop);
8048
+ return list.filter((c) => !dropSet.has(c));
8049
+ }
8050
+ var latinAmerica = () => [...without(continent("NA"), ANGLO_NORTH_AMERICA), ...continent("SA")];
8051
+ var REGION_GROUPS = [
8052
+ { names: ["africa"], members: () => continent("AF") },
8053
+ { names: ["asia"], members: () => continent("AS") },
8054
+ { names: ["europe", "eur"], members: () => continent("EU") },
8055
+ { names: ["south america", "samer"], members: () => continent("SA") },
8056
+ { names: ["oceania", "australia and oceania"], members: () => continent("OC") },
8057
+ { names: ["antarctica"], members: () => continent("AN") },
8058
+ { names: ["americas", "the americas", "amer", "amers"], members: () => [...continent("NA"), ...continent("SA")] },
8059
+ { names: ["latin america", "latam", "lac", "latin america and caribbean", "latin america and the caribbean"], members: latinAmerica },
8060
+ { names: ["central america"], members: () => CENTRAL_AMERICA },
8061
+ { names: ["caribbean"], members: () => without(continent("NA"), [...ANGLO_NORTH_AMERICA, "MX", ...CENTRAL_AMERICA]) },
8062
+ { names: ["middle east"], members: () => MIDDLE_EAST },
8063
+ { names: ["mena", "middle east and north africa"], members: () => [...MIDDLE_EAST, ...NORTH_AFRICA] },
8064
+ { names: ["north africa"], members: () => NORTH_AFRICA },
8065
+ { names: ["sub saharan africa", "ssa"], members: () => without(continent("AF"), NORTH_AFRICA) },
8066
+ { names: ["emea", "europe middle east and africa"], members: () => [...continent("EU"), ...continent("AF"), ...MIDDLE_EAST] },
8067
+ { names: ["apac", "asia pacific", "apj", "asia pacific and japan", "apjc"], members: () => [...without(continent("AS"), MIDDLE_EAST), ...continent("OC")] },
8068
+ { names: ["european union", "eu27", "eu 27"], members: () => EU_MEMBERS },
8069
+ { names: ["dach"], members: () => ["DE", "AT", "CH"] },
8070
+ { names: ["benelux"], members: () => ["BE", "NL", "LU"] },
8071
+ { names: ["nordics", "nordic", "nordic countries"], members: () => ["DK", "FI", "IS", "NO", "SE"] },
8072
+ { names: ["scandinavia"], members: () => ["DK", "NO", "SE"] },
8073
+ { names: ["uk and ireland", "uki", "uk and i", "british isles"], members: () => ["GB", "IE"] },
8074
+ { names: ["anz", "australia and new zealand", "australasia"], members: () => ["AU", "NZ"] },
8075
+ { names: ["gcc", "gulf", "gulf states"], members: () => ["AE", "BH", "KW", "OM", "QA", "SA"] },
8076
+ { names: ["southeast asia", "south east asia", "sea", "asean"], members: () => ["BN", "ID", "KH", "LA", "MM", "MY", "PH", "SG", "TH", "VN"] },
8077
+ { names: ["east asia"], members: () => ["CN", "HK", "JP", "KP", "KR", "MN", "MO", "TW"] },
8078
+ { names: ["south asia"], members: () => ["AF", "BD", "BT", "IN", "LK", "MV", "NP", "PK"] },
8079
+ { names: ["cee", "central and eastern europe", "eastern europe"], members: () => ["AL", "BA", "BG", "BY", "CZ", "EE", "HR", "HU", "LT", "LV", "MD", "ME", "MK", "PL", "RO", "RS", "SI", "SK", "UA", "XK"] }
8080
+ ];
8081
+ var NORTH_AMERICA_NAMES = ["north america", "namer", "noram", "nam", "us and canada"];
8082
+ var indexes = null;
8083
+ function buildIndexes() {
8084
+ const country = /* @__PURE__ */ new Map();
8085
+ for (const [alpha2, alpha3, numeric, , ...names] of COUNTRY_ROWS) {
8086
+ for (const key of [alpha2, alpha3, numeric, String(Number(numeric)), ...names])
8087
+ country.set(normalizeRegionName(key), alpha2);
8088
+ }
8089
+ for (const [alias, alpha2] of [["uk", "GB"], ["england", "GB"], ["britain", "GB"], ["great britain", "GB"], ["holland", "NL"], ["korea", "KR"], ["russia", "RU"], ["czech republic", "CZ"], ["turkiye", "TR"], ["uae", "AE"], ["dr congo", "CD"], ["drc", "CD"]])
8090
+ country.set(alias, alpha2);
8091
+ const group = /* @__PURE__ */ new Map();
8092
+ for (const g of REGION_GROUPS) {
8093
+ for (const name of g.names)
8094
+ group.set(normalizeRegionName(name), g.members);
8095
+ }
8096
+ const state = /* @__PURE__ */ new Map();
8097
+ for (const [fips, postal, name] of US_STATE_ROWS) {
8098
+ for (const key of [fips, postal, name, String(Number(fips))])
8099
+ state.set(normalizeRegionName(key), postal);
8100
+ }
8101
+ for (const [alias, postal] of Object.entries(US_STATE_ALIASES))
8102
+ state.set(alias, postal);
8103
+ return { country, group, state };
8104
+ }
8105
+ function getIndexes() {
8106
+ indexes ?? (indexes = buildIndexes());
8107
+ return indexes;
8108
+ }
8109
+ function matchWorld(norm, ctx) {
8110
+ const { country, group } = getIndexes();
8111
+ if (NORTH_AMERICA_NAMES.includes(norm))
8112
+ return { kind: "region", codes: ctx.hasLatinAmerica ? ["US", "CA"] : continent("NA") };
8113
+ const alpha2 = country.get(norm);
8114
+ if (alpha2)
8115
+ return { kind: "country", codes: [alpha2] };
8116
+ const members = group.get(norm);
8117
+ return members ? { kind: "region", codes: members() } : null;
8118
+ }
8119
+ function matchUsState(norm) {
8120
+ const postal = getIndexes().state.get(norm);
8121
+ return postal ? { kind: "state", codes: [postal] } : null;
8122
+ }
8123
+ function matchRegion(label, geography, ctx = { hasLatinAmerica: false }) {
8124
+ const norm = normalizeRegionName(label);
8125
+ if (!norm)
8126
+ return null;
8127
+ return geography === "us-states" ? matchUsState(norm) : matchWorld(norm, ctx);
8128
+ }
8129
+ function contextFor(labels) {
8130
+ const { group } = getIndexes();
8131
+ const latam = group.get("latin america");
8132
+ return { hasLatinAmerica: labels.some((l) => group.get(normalizeRegionName(l)) === latam) };
8133
+ }
8134
+ function detectGeography(labels) {
8135
+ const ctx = contextFor(labels);
8136
+ let states = 0;
8137
+ let world = 0;
8138
+ for (const label of labels) {
8139
+ if (matchRegion(label, "us-states"))
8140
+ states++;
8141
+ if (matchRegion(label, "world", ctx))
8142
+ world++;
8143
+ }
8144
+ return states > world ? "us-states" : "world";
8145
+ }
8146
+ function matchRegions(entries, geography = "auto") {
8147
+ const labels = entries.map((e) => e.label);
8148
+ const resolved = geography === "auto" ? detectGeography(labels) : geography;
8149
+ const ctx = contextFor(labels);
8150
+ const regions = [];
8151
+ const unmatched = [];
8152
+ for (const entry of entries) {
8153
+ const match = matchRegion(entry.label, resolved, ctx);
8154
+ if (match)
8155
+ regions.push({ ...match, label: entry.label, value: entry.value });
8156
+ else
8157
+ unmatched.push(entry.label);
8158
+ }
8159
+ const byCode = /* @__PURE__ */ new Map();
8160
+ for (const region of [...regions].sort((a, b) => Number(a.kind !== "region") - Number(b.kind !== "region"))) {
8161
+ for (const code of region.codes)
8162
+ byCode.set(code, region);
8163
+ }
8164
+ return { geography: resolved, regions, unmatched, byCode };
8165
+ }
8166
+ var STATE_NAME_BY_POSTAL = new Map(US_STATE_ROWS.map(([, postal, name]) => [postal, name]));
8167
+ function regionDisplayName(region) {
8168
+ return region.kind === "state" ? STATE_NAME_BY_POSTAL.get(region.codes[0]) ?? region.label : region.label;
8169
+ }
8170
+
8171
+ // ../core/dist/chart/d3-data.js
8172
+ var BULLET_NEAR_RATIO = 0.8;
8173
+ var BULLET_MAX_ROWS = 40;
8174
+ function bulletStatus(value2, target) {
8175
+ if (target === null || target <= 0)
8176
+ return null;
8177
+ if (value2 >= target)
8178
+ return "met";
8179
+ return value2 >= target * BULLET_NEAR_RATIO ? "near" : "below";
8180
+ }
8181
+ function quantile(sorted, p) {
8182
+ if (sorted.length === 0)
8183
+ return 0;
8184
+ const pos = (sorted.length - 1) * p;
8185
+ const lo = Math.floor(pos);
8186
+ const hi = Math.ceil(pos);
8187
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
8188
+ }
8189
+ function processChartDataForBullet(data, config) {
8190
+ const empty = { rows: [], max: 0, hasTarget: false, truncated: 0 };
8191
+ if (!config.xAxis || !config.yAxis || data.length === 0)
8192
+ return empty;
8193
+ const actuals = sortCategoryEntries(config, aggregateByCategory(data, config.xAxis.field, config.yAxis.field, config.yAxis.aggregation));
8194
+ const targetField = config.targetField;
8195
+ const targets = targetField ? new Map(aggregateByCategory(data, config.xAxis.field, targetField.field, targetField.aggregation).map((e) => [e.category, e.value])) : null;
8196
+ const kept = actuals.slice(0, BULLET_MAX_ROWS);
8197
+ const max = Math.max(0, ...kept.map((e) => Math.max(e.value, targets?.get(e.category) ?? 0))) * 1.05;
8198
+ const sorted = kept.map((e) => e.value).sort((a, b) => a - b);
8199
+ const terciles = [quantile(sorted, 1 / 3), quantile(sorted, 2 / 3), max];
8200
+ const rows = kept.map((entry) => {
8201
+ const target = targets?.get(entry.category) ?? null;
8202
+ const bands = target !== null && target > 0 ? [target * BULLET_NEAR_RATIO, target, max] : terciles;
8203
+ return { label: entry.category, value: entry.value, target, bands, status: bulletStatus(entry.value, target) };
8204
+ });
8205
+ return { rows, max, hasTarget: targets !== null, truncated: actuals.length - kept.length };
8206
+ }
8207
+ var HIERARCHY_MAX_LEAVES = 300;
8208
+ function collectLeaves(data, config) {
8209
+ const parentField = config.seriesField?.field;
8210
+ const groups = /* @__PURE__ */ new Map();
8211
+ for (const row of data) {
8212
+ const parent = parentField ? String(row[parentField] ?? "(blank)") : "";
8213
+ const bucket = groups.get(parent);
8214
+ if (bucket)
8215
+ bucket.push(row);
8216
+ else
8217
+ groups.set(parent, [row]);
8218
+ }
8219
+ const leaves = [];
8220
+ for (const [parent, rows] of groups) {
8221
+ for (const entry of aggregateByCategory(rows, config.xAxis.field, config.yAxis.field, config.yAxis.aggregation))
8222
+ leaves.push({ parent, ...entry });
8223
+ }
8224
+ return leaves;
8225
+ }
8226
+ function foldSmallLeaves(leaves) {
8227
+ if (leaves.length <= HIERARCHY_MAX_LEAVES)
8228
+ return { kept: leaves, folded: 0 };
8229
+ const ranked = [...leaves].sort((a, b) => b.value - a.value);
8230
+ const kept = ranked.slice(0, HIERARCHY_MAX_LEAVES - 1);
8231
+ const other = /* @__PURE__ */ new Map();
8232
+ for (const leaf of ranked.slice(HIERARCHY_MAX_LEAVES - 1)) {
8233
+ const acc = other.get(leaf.parent) ?? { value: 0, count: 0 };
8234
+ acc.value += leaf.value;
8235
+ acc.count++;
8236
+ other.set(leaf.parent, acc);
8237
+ }
8238
+ for (const [parent, acc] of other)
8239
+ kept.push({ parent, category: `Other (${acc.count})`, value: acc.value });
8240
+ return { kept, folded: ranked.length - (HIERARCHY_MAX_LEAVES - 1) };
8241
+ }
8242
+ function processChartDataForHierarchy(data, config) {
8243
+ const rootName = config.yAxis ? formatFieldLabel(config.yAxis.field) : "Total";
8244
+ if (!config.xAxis || !config.yAxis || data.length === 0)
8245
+ return { root: { name: rootName, children: [] }, dropped: [], folded: 0 };
8246
+ const all = collectLeaves(data, config);
8247
+ const dropped = all.filter((l) => !(l.value > 0)).map((l) => l.parent ? `${l.parent} / ${l.category}` : l.category);
8248
+ const { kept, folded } = foldSmallLeaves(all.filter((l) => l.value > 0));
8249
+ const byParent = /* @__PURE__ */ new Map();
8250
+ for (const leaf of kept) {
8251
+ const node = { name: leaf.category, value: leaf.value };
8252
+ const siblings = byParent.get(leaf.parent);
8253
+ if (siblings)
8254
+ siblings.push(node);
8255
+ else
8256
+ byParent.set(leaf.parent, [node]);
8257
+ }
8258
+ const children = config.seriesField ? Array.from(byParent, ([name, leaves]) => ({ name, children: leaves })) : byParent.get("") ?? [];
8259
+ return { root: { name: rootName, children }, dropped, folded };
8260
+ }
8261
+ function processChartDataForChoropleth(data, config) {
8262
+ const geography = getEffectiveChartOptions(config).geography ?? "auto";
8263
+ const entries = config.xAxis && config.yAxis ? aggregateByCategory(data, config.xAxis.field, config.yAxis.field, config.yAxis.aggregation) : [];
8264
+ const result = matchRegions(entries.map((e) => ({ label: e.category, value: e.value })), geography);
8265
+ const values = result.regions.map((r) => r.value);
8266
+ return {
8267
+ ...result,
8268
+ min: values.length ? Math.min(...values) : 0,
8269
+ max: values.length ? Math.max(...values) : 0
8270
+ };
8271
+ }
8272
+ function describeUnmatchedRegions(result, limit = 5) {
8273
+ const { unmatched, geography } = result;
8274
+ if (unmatched.length === 0)
8275
+ return null;
8276
+ const map = geography === "us-states" ? "US states map" : "world map";
8277
+ const shown = unmatched.slice(0, limit).map((l) => `"${l}"`).join(", ");
8278
+ const more = unmatched.length > limit ? ` and ${unmatched.length - limit} more` : "";
8279
+ const noun = unmatched.length === 1 ? "label" : "labels";
8280
+ return `${unmatched.length} ${noun} not found on the ${map}: ${shown}${more}. Use country or state names, ISO / postal codes, or regions like EMEA, APAC, LATAM.`;
8281
+ }
8282
+ function processChartDataForSlope(data, config) {
8283
+ if (!config.xAxis || !config.yAxis || !config.seriesField)
8284
+ return null;
8285
+ const chart = processChartData(data, { ...config, options: { ...config.options, sortOrder: "label-asc" } });
8286
+ const periods = chart.series.map((s) => s.name).sort(compareLabels);
8287
+ if (periods.length < 2)
8288
+ return null;
8289
+ const first = chart.series.find((s) => s.name === periods[0]);
8290
+ const last = chart.series.find((s) => s.name === periods.at(-1));
8291
+ const rows = chart.categories.map((label, i) => {
8292
+ const start = first.data[i] ?? 0;
8293
+ const end = last.data[i] ?? 0;
8294
+ return { label, start, end, change: start !== 0 ? end / start - 1 : null };
8295
+ }).filter((r) => r.start !== 0 || r.end !== 0).sort((a, b) => b.end - a.end);
8296
+ return { from: first.name, to: last.name, rows, skippedPeriods: periods.slice(1, -1) };
8297
+ }
8298
+
8299
+ // ../core/dist/chart/d3-theme.js
8300
+ function formatCompactChartValue(val, format) {
8301
+ if (format === "percent")
8302
+ return `${Number.isInteger(val) ? val : val.toFixed(1)}%`;
8303
+ const abs = Math.abs(val);
8304
+ let text;
8305
+ if (abs >= 1e9)
8306
+ text = `${(abs / 1e9).toFixed(1)}B`;
8307
+ else if (abs >= 1e6)
8308
+ text = `${(abs / 1e6).toFixed(1)}M`;
8309
+ else if (abs >= 1e3)
8310
+ text = `${(abs / 1e3).toFixed(abs >= 1e4 ? 0 : 1)}K`;
8311
+ else
8312
+ text = Number.isInteger(abs) ? String(abs) : abs.toFixed(1);
8313
+ const sign = val < 0 ? "-" : "";
8314
+ return format === "currency" ? `${sign}$${text}` : `${sign}${text}`;
8315
+ }
8316
+
8317
+ // ../core/dist/chart/story.js
8318
+ function measureNoun(config) {
8319
+ const field = config.yAxis;
8320
+ if (!field)
8321
+ return "value";
8322
+ return (field.label || formatFieldLabel(field.field)).toLowerCase();
8323
+ }
8324
+ function categoryNoun(config, count) {
8325
+ const field = config.xAxis;
8326
+ const word2 = field ? (field.label || formatFieldLabel(field.field)).toLowerCase() : "item";
8327
+ if (count === 1 || word2.endsWith("s"))
8328
+ return word2;
8329
+ if (/[^aeiou]y$/.test(word2))
8330
+ return `${word2.slice(0, -1)}ies`;
8331
+ return /(?:x|ch|sh)$/.test(word2) ? `${word2}es` : `${word2}s`;
8332
+ }
8333
+ function pct(part, whole) {
8334
+ return whole > 0 ? `${Math.round(part / whole * 100)}%` : "0%";
8335
+ }
8336
+ function compact(config, value2) {
8337
+ return formatCompactChartValue(value2, config.options?.valueFormat);
8338
+ }
8339
+ function rankedTotals(data, config) {
8340
+ const chart = processChartData(data, config);
8341
+ return chart.categories.map((label, i) => ({ label, value: chart.series.reduce((sum, s) => sum + (s.data[i] ?? 0), 0) })).sort((a, b) => b.value - a.value);
8342
+ }
8343
+ function choroplethStory(data, config) {
8344
+ const map = processChartDataForChoropleth(data, config);
8345
+ const ranked = [...map.regions].sort((a, b) => b.value - a.value);
8346
+ if (ranked.length === 0)
8347
+ return null;
8348
+ const noun = measureNoun(config);
8349
+ const [top] = ranked;
8350
+ const low = ranked.at(-1);
8351
+ const topName = regionDisplayName(top);
8352
+ const total = ranked.reduce((sum, r) => sum + r.value, 0);
8353
+ const headline = ranked.length === 1 ? `${topName}: ${compact(config, top.value)} ${noun}` : low.value > 0 && top.value / low.value >= 1.5 ? `${topName} leads with ${compact(config, top.value)} ${noun}, ${(top.value / low.value).toFixed(1)}\xD7 ${regionDisplayName(low)}` : `${topName} leads with ${compact(config, top.value)} ${noun}, ${pct(top.value, total)} of the total`;
8354
+ const place = map.geography === "us-states" ? "states" : ranked.some((r) => r.kind === "region") ? "regions" : "countries";
8355
+ return {
8356
+ headline,
8357
+ dek: `${ranked.length} ${place} shaded by ${noun}; darker means more.`,
8358
+ callouts: ranked.slice(0, 3).map((r) => r.label)
8359
+ };
8360
+ }
8361
+ function bulletStory(data, config) {
8362
+ const bullet = processChartDataForBullet(data, config);
8363
+ if (bullet.rows.length === 0)
8364
+ return null;
8365
+ const noun = measureNoun(config);
8366
+ const withTarget = bullet.rows.filter((r) => r.target !== null && r.target > 0);
8367
+ if (withTarget.length === 0) {
8368
+ const [top] = bullet.rows;
8369
+ return {
8370
+ headline: `${top.label} leads with ${compact(config, top.value)} ${noun}`,
8371
+ dek: "Bands mark the bottom, middle and top thirds of all rows.",
8372
+ callouts: [top.label]
8373
+ };
8374
+ }
8375
+ const attainment = withTarget.map((r) => ({ label: r.label, ratio: r.value / r.target })).sort((a, b) => b.ratio - a.ratio);
8376
+ const met = attainment.filter((a) => a.ratio >= 1).length;
8377
+ const best = attainment[0];
8378
+ const worst = attainment.at(-1);
8379
+ const head = `${met} of ${attainment.length} beat target`;
8380
+ const detail = attainment.length > 1 ? `${best.label} leads at ${pct(best.ratio, 1)}; ${worst.label} trails at ${pct(worst.ratio, 1)}` : `${best.label} is at ${pct(best.ratio, 1)}`;
8381
+ return {
8382
+ headline: `${head}. ${detail}`,
8383
+ dek: `Bars show ${noun}, ticks the target; bands mark under 80%, 80\u2013100% and over target.`,
8384
+ callouts: attainment.length > 1 ? [best.label, worst.label] : [best.label]
8385
+ };
8386
+ }
8387
+ function radialBarStory(data, config) {
8388
+ const ranked = rankedTotals(data, config);
8389
+ if (ranked.length === 0)
8390
+ return null;
8391
+ const total = ranked.reduce((sum, r) => sum + r.value, 0);
8392
+ const [top] = ranked;
8393
+ return {
8394
+ headline: `${top.label} leads: ${pct(top.value, total)} of ${measureNoun(config)} across ${ranked.length} ${categoryNoun(config, ranked.length)}`,
8395
+ dek: config.seriesField ? `Each bar stacks ${formatFieldLabel(config.seriesField.field).toLowerCase()}; longer is more.` : "Longer bars are larger; sorted clockwise from the top.",
8396
+ callouts: [top.label]
8397
+ };
8398
+ }
8399
+ function radialAreaStory(data, config) {
8400
+ const chart = processChartData(data, config);
8401
+ if (chart.categories.length < 3)
8402
+ return null;
8403
+ const totals = chart.categories.map((label, i) => ({ label, value: chart.series.reduce((sum, s) => sum + (s.data[i] ?? 0), 0) }));
8404
+ const peak = totals.reduce((a, b) => b.value > a.value ? b : a);
8405
+ const trough = totals.reduce((a, b) => b.value < a.value ? b : a);
8406
+ const noun = measureNoun(config);
8407
+ const drop = peak.value > 0 ? Math.round((1 - trough.value / peak.value) * 100) : 0;
8408
+ let dek = `Each spoke is a ${formatFieldLabel(config.xAxis.field).toLowerCase()}; distance from the centre is ${noun}.`;
8409
+ if (chart.series.length > 1)
8410
+ dek += " Peak and low are for all series combined.";
8411
+ if (chart.series.length === 2) {
8412
+ const [a, b] = chart.series.map((s) => s.data.reduce((x, y) => x + (y ?? 0), 0));
8413
+ const change = b > 0 ? Math.round((a - b) / b * 100) : 0;
8414
+ dek += ` ${chart.series[0].name} vs ${chart.series[1].name}: ${change >= 0 ? "+" : ""}${change}% overall.`;
8415
+ }
8416
+ return {
8417
+ headline: `${formatFieldLabel(noun)} peak in ${peak.label} and bottom out in ${trough.label}, ${drop}% lower`,
8418
+ dek,
8419
+ callouts: [peak.label, trough.label]
8420
+ };
8421
+ }
8422
+ function hierarchyStory(data, config) {
8423
+ const { root } = processChartDataForHierarchy(data, config);
8424
+ const branches = root.children ?? [];
8425
+ if (branches.length === 0)
8426
+ return null;
8427
+ const noun = measureNoun(config);
8428
+ const sizeOf = (n) => n.value ?? (n.children ?? []).reduce((s, c) => s + (c.value ?? 0), 0);
8429
+ const total = branches.reduce((s, b) => s + sizeOf(b), 0);
8430
+ if (config.seriesField) {
8431
+ const top = [...branches].sort((a, b) => sizeOf(b) - sizeOf(a))[0];
8432
+ const leaf = [...top.children ?? []].sort((a, b) => (b.value ?? 0) - (a.value ?? 0))[0];
8433
+ return {
8434
+ headline: `${top.name} is ${pct(sizeOf(top), total)} of ${noun}${leaf ? `; ${leaf.name} alone is ${pct(leaf.value ?? 0, total)}` : ""}`,
8435
+ dek: `Area is ${noun}, grouped by ${formatFieldLabel(config.seriesField.field).toLowerCase()}.`,
8436
+ callouts: [top.name, ...leaf ? [leaf.name] : []]
8437
+ };
8438
+ }
8439
+ const ranked = [...branches].sort((a, b) => sizeOf(b) - sizeOf(a));
8440
+ const topN = Math.min(3, ranked.length);
8441
+ const share = pct(ranked.slice(0, topN).reduce((s, b) => s + sizeOf(b), 0), total);
8442
+ return {
8443
+ headline: `The top ${topN} of ${ranked.length} ${categoryNoun(config, ranked.length)} make up ${share} of ${noun}`,
8444
+ dek: `Area is ${noun}.`,
8445
+ callouts: ranked.slice(0, topN).map((b) => b.name)
8446
+ };
8447
+ }
8448
+ function signedPct(change) {
8449
+ const rounded = Math.round(change * 100);
8450
+ return `${rounded >= 0 ? "+" : ""}${rounded}%`;
8451
+ }
8452
+ function slopeStory(data, config) {
8453
+ const slope = processChartDataForSlope(data, config);
8454
+ if (!slope || slope.rows.length === 0)
8455
+ return null;
8456
+ const comparable = slope.rows.filter((r) => r.change !== null);
8457
+ const grew = slope.rows.filter((r) => r.end > r.start).length;
8458
+ const ranked = [...comparable].sort((a, b) => b.change - a.change);
8459
+ const best = ranked[0];
8460
+ const worst = ranked.at(-1);
8461
+ let headline = `${grew} of ${slope.rows.length} grew from ${slope.from} to ${slope.to}`;
8462
+ if (best && best.change > 0)
8463
+ headline += `; ${best.label} rose most (${signedPct(best.change)})`;
8464
+ if (worst && worst !== best && worst.change < 0)
8465
+ headline += `, ${worst.label} fell most (${signedPct(worst.change)})`;
8466
+ const skipped = slope.skippedPeriods.length ? ` ${slope.skippedPeriods.length} periods in between are not shown.` : "";
8467
+ return {
8468
+ headline,
8469
+ dek: `${formatFieldLabel(measureNoun(config))} in ${slope.from} (left) and ${slope.to} (right); rising lines are highlighted.${skipped}`,
8470
+ callouts: [...new Set([best?.label, worst?.label].filter((l) => Boolean(l)))]
8471
+ };
8472
+ }
8473
+ var STORIES = {
8474
+ choropleth: choroplethStory,
8475
+ bullet: bulletStory,
8476
+ radialBar: radialBarStory,
8477
+ radialArea: radialAreaStory,
8478
+ treemap: hierarchyStory,
8479
+ sunburst: hierarchyStory,
8480
+ slope: slopeStory
8481
+ };
8482
+ var fieldName = (field) => field ? field.label || formatFieldLabel(field.field) : "";
8483
+ function chartKicker(config) {
8484
+ const measure = fieldName(config.yAxis);
8485
+ const dimension = fieldName(config.xAxis).toLowerCase();
8486
+ if (config.type === "bullet" && config.targetField)
8487
+ return `${measure} vs ${fieldName(config.targetField).toLowerCase()} by ${dimension}`;
8488
+ if ((config.type === "treemap" || config.type === "sunburst") && config.seriesField)
8489
+ return `${measure} by ${fieldName(config.seriesField).toLowerCase()} and ${dimension}`;
8490
+ return `${measure} by ${dimension}`;
8491
+ }
8492
+ function chartFootnote(config) {
8493
+ const parts = [];
8494
+ const describe2 = (field) => `${fieldName(field)}: ${field.aggregation ?? "sum"} of ${field.field}`;
8495
+ parts.push(describe2(config.yAxis));
8496
+ if (config.targetField)
8497
+ parts.push(describe2(config.targetField));
8498
+ return parts.join(" \xB7 ");
8499
+ }
8500
+ function buildChartStory(data, config) {
8501
+ if (!config.xAxis || !config.yAxis || data.length === 0)
8502
+ return null;
8503
+ const body = STORIES[config.type]?.(data, config) ?? null;
8504
+ if (!body)
8505
+ return null;
8506
+ return {
8507
+ ...body,
8508
+ headline: config.options?.title || body.headline,
8509
+ kicker: chartKicker(config),
8510
+ footnote: chartFootnote(config)
8511
+ };
8512
+ }
8513
+
7372
8514
  // ../core/dist/chart/index.js
7373
8515
  var CHART_THEME_PRESETS = {
7374
8516
  "code": {
@@ -7476,9 +8618,7 @@ function resolveChartSortOrder(config, categories) {
7476
8618
  return config.options.sortOrder;
7477
8619
  if (isTemporalCategories(config, categories))
7478
8620
  return "label-asc";
7479
- if (config.type === "bar" || config.type === "stackedBar" || config.type === "pie" || config.type === "donut")
7480
- return "value-desc";
7481
- return "label-asc";
8621
+ return getChartTypeInfo(config.type)?.defaults?.sortOrder ?? "label-asc";
7482
8622
  }
7483
8623
  var MONTH_INDEX = {
7484
8624
  jan: 0,
@@ -7620,6 +8760,40 @@ function processChartData(data, config) {
7620
8760
  }
7621
8761
  return { categories, series };
7622
8762
  }
8763
+ function aggregateByCategory(data, categoryField, measureField, aggregation = "sum") {
8764
+ const readMeasure = createMeasureReader(aggregation);
8765
+ const grouped = /* @__PURE__ */ new Map();
8766
+ for (const row of data) {
8767
+ const raw = row[measureField];
8768
+ if (raw === null || raw === void 0 || raw === "")
8769
+ continue;
8770
+ const value2 = readMeasure(raw);
8771
+ if (Number.isNaN(value2))
8772
+ continue;
8773
+ const category = String(row[categoryField] ?? "(blank)");
8774
+ const bucket = grouped.get(category);
8775
+ if (bucket)
8776
+ bucket.push(value2);
8777
+ else
8778
+ grouped.set(category, [value2]);
8779
+ }
8780
+ return Array.from(grouped, ([category, values]) => ({ category, value: aggregateValues(values, aggregation) }));
8781
+ }
8782
+ function sortCategoryEntries(config, entries) {
8783
+ const sortOrder = resolveChartSortOrder(config, entries.map((e) => e.category));
8784
+ switch (sortOrder) {
8785
+ case "value-desc":
8786
+ return [...entries].sort((a, b) => b.value - a.value || compareLabels(a.category, b.category));
8787
+ case "value-asc":
8788
+ return [...entries].sort((a, b) => a.value - b.value || compareLabels(a.category, b.category));
8789
+ case "label-asc":
8790
+ return [...entries].sort((a, b) => compareLabels(a.category, b.category));
8791
+ case "label-desc":
8792
+ return [...entries].sort((a, b) => compareLabels(b.category, a.category));
8793
+ default:
8794
+ return entries;
8795
+ }
8796
+ }
7623
8797
  function processChartDataForScatter(data, config) {
7624
8798
  if (!config.xAxis || !config.yAxis || data.length === 0) {
7625
8799
  return { series: [] };
@@ -8383,6 +9557,11 @@ function renderPreciseBar(ratio, width) {
8383
9557
  const rem = totalEighths % 8;
8384
9558
  return `${"\u2588".repeat(full)}${SUB_BLOCKS[rem]}`;
8385
9559
  }
9560
+ var SPACED_BAR = "\u2586";
9561
+ function renderSpacedBar(ratio, width) {
9562
+ const clamped = Math.max(0, Math.min(1, ratio));
9563
+ return clamped > 0 ? SPACED_BAR.repeat(Math.max(1, Math.round(clamped * width))) : "";
9564
+ }
8386
9565
  function renderSparkline(values) {
8387
9566
  if (values.length === 0)
8388
9567
  return "";
@@ -9234,9 +10413,9 @@ function formatTrendDelta(values) {
9234
10413
  const last = values[values.length - 1];
9235
10414
  if (!Number.isFinite(first) || !Number.isFinite(last) || first <= 0)
9236
10415
  return "";
9237
- const pct = (last - first) / first * 100;
9238
- const sign = pct >= 0 ? "+" : "";
9239
- return `${sign}${pct.toFixed(1)}%`;
10416
+ const pct2 = (last - first) / first * 100;
10417
+ const sign = pct2 >= 0 ? "+" : "";
10418
+ return `${sign}${pct2.toFixed(1)}%`;
9240
10419
  }
9241
10420
  function paint(ctx, rgb, text) {
9242
10421
  return ctx.pal ? ansiFg(ctx.pal[rgb], text) : text;
@@ -9246,6 +10425,8 @@ function paintSeries(ctx, index, text) {
9246
10425
  }
9247
10426
  function frame(ctx, badge, body, kind, stats = ctx.statsLine) {
9248
10427
  body.push(CARD_DIVIDER, paint(ctx, "muted", stats));
10428
+ if (ctx.note)
10429
+ body.push(paint(ctx, "muted", `\u24D8 ${ctx.note}`));
9249
10430
  if (ctx.liveRow)
9250
10431
  body.push(ctx.liveRow);
9251
10432
  const footerRight = `${ctx.dataset.rows.length.toLocaleString()} rows \xB7 ${kind}`;
@@ -9257,13 +10438,13 @@ function totalBadge(ctx) {
9257
10438
  }
9258
10439
  function paintPlotRow(ctx, row, owners, multiSeries) {
9259
10440
  const axisAt = Math.max(row.indexOf("\u2524"), row.indexOf("\u2502"));
9260
- const cells = [...row.slice(axisAt + 1)];
10441
+ const cells2 = [...row.slice(axisAt + 1)];
9261
10442
  let out = `${paint(ctx, "muted", row.slice(0, axisAt))}${paint(ctx, "border", row[axisAt])}`;
9262
10443
  let start = 0;
9263
- for (let i = 1; i <= cells.length; i++) {
9264
- if (i < cells.length && owners[i] === owners[start])
10444
+ for (let i = 1; i <= cells2.length; i++) {
10445
+ if (i < cells2.length && owners[i] === owners[start])
9265
10446
  continue;
9266
- const run = cells.slice(start, i).join("");
10447
+ const run = cells2.slice(start, i).join("");
9267
10448
  out += owners[start] < 0 ? run : multiSeries ? paintSeries(ctx, owners[start], run) : paint(ctx, "accent", run);
9268
10449
  start = i;
9269
10450
  }
@@ -9311,10 +10492,10 @@ function lineCard(ctx) {
9311
10492
  }
9312
10493
  var MAX_BAR_ENTRIES = 14;
9313
10494
  var BAR_WIDTH = 34;
9314
- function barRow(ctx, label, labelWidth, bar, barPlainWidth, value2, valWidth, pct) {
10495
+ function barRow(ctx, label, labelWidth, bar, barPlainWidth, value2, valWidth, pct2) {
9315
10496
  const labelText = paint(ctx, "text", padEndVisual(truncateVisual(label, labelWidth), labelWidth));
9316
10497
  const valueText = padStartVisual(formatCompactNumber(value2), valWidth);
9317
- const pctText = pct === void 0 ? "" : ` ${paint(ctx, "muted", `${pct.toFixed(1).padStart(5)}%`)}`;
10498
+ const pctText = pct2 === void 0 ? "" : ` ${paint(ctx, "muted", `${pct2.toFixed(1).padStart(5)}%`)}`;
9318
10499
  return `${labelText} ${paint(ctx, "border", "\u2502")} ${bar}${" ".repeat(Math.max(0, BAR_WIDTH - barPlainWidth))} ${ctx.pal ? ansiFgBold(ctx.pal.text, valueText) : valueText}${pctText}`;
9319
10500
  }
9320
10501
  function seriesLegend(ctx) {
@@ -9348,8 +10529,8 @@ function stackedCard(ctx) {
9348
10529
  used += len;
9349
10530
  }
9350
10531
  });
9351
- const pct = !ctx.nonAdditive && ctx.grandTotal > 0 ? entry.total / ctx.grandTotal * 100 : void 0;
9352
- body.push(barRow(ctx, entry.label, labelWidth, bar, used, entry.total, valWidth, pct));
10532
+ const pct2 = !ctx.nonAdditive && ctx.grandTotal > 0 ? entry.total / ctx.grandTotal * 100 : void 0;
10533
+ body.push(barRow(ctx, entry.label, labelWidth, bar, used, entry.total, valWidth, pct2));
9353
10534
  }
9354
10535
  body.push(...moreCategoriesNote(ctx, entries.length));
9355
10536
  return frame(ctx, totalBadge(ctx), body, "Stacked Bar");
@@ -9390,9 +10571,9 @@ function barCard(ctx) {
9390
10571
  const labelWidth = Math.min(20, Math.max(...entries.map((e) => visualWidth(e.label)), 6));
9391
10572
  const valWidth = Math.max(...entries.map((e) => visualWidth(formatCompactNumber(e.total))), 5);
9392
10573
  const body = entries.map((entry) => {
9393
- const plain = renderPreciseBar(Math.abs(entry.total) / maxVal, BAR_WIDTH);
9394
- const pct = !ctx.nonAdditive && ctx.grandTotal > 0 ? entry.total / ctx.grandTotal * 100 : void 0;
9395
- return barRow(ctx, entry.label, labelWidth, paint(ctx, "accent", plain), visualWidth(plain), entry.total, valWidth, pct);
10574
+ const plain = renderSpacedBar(Math.abs(entry.total) / maxVal, BAR_WIDTH);
10575
+ const pct2 = !ctx.nonAdditive && ctx.grandTotal > 0 ? entry.total / ctx.grandTotal * 100 : void 0;
10576
+ return barRow(ctx, entry.label, labelWidth, paint(ctx, "accent", plain), visualWidth(plain), entry.total, valWidth, pct2);
9396
10577
  });
9397
10578
  body.push(...moreCategoriesNote(ctx, entries.length));
9398
10579
  return frame(ctx, totalBadge(ctx), body, "Bar");
@@ -9408,7 +10589,7 @@ function shareCard(ctx) {
9408
10589
  const labelWidth = Math.min(20, Math.max(...shown.map((s) => visualWidth(s.label)), 6));
9409
10590
  const valWidth = Math.max(...shown.map((s) => visualWidth(formatCompactNumber(s.value))), 5);
9410
10591
  const body = shown.map((slice, i) => {
9411
- const plain = renderPreciseBar(slice.value / total, BAR_WIDTH);
10592
+ const plain = renderSpacedBar(slice.value / total, BAR_WIDTH);
9412
10593
  return barRow(ctx, slice.label, labelWidth, paintSeries(ctx, i, plain), visualWidth(plain), slice.value, valWidth, slice.value / total * 100);
9413
10594
  });
9414
10595
  const top = shown[0];
@@ -9429,11 +10610,11 @@ function heatmapCard(ctx) {
9429
10610
  const header = `${" ".repeat(labelWidth)} ${cols.map((c) => padEndVisual(truncateVisual(c.name, HEAT_CELL - 1), HEAT_CELL)).join("")}`;
9430
10611
  const body = [paint(ctx, "muted", header)];
9431
10612
  rows.forEach((row, r) => {
9432
- const cells = cols.map((c) => {
10613
+ const cells2 = cols.map((c) => {
9433
10614
  const level = Math.round(((Number(c.data[r]) || 0) - min) / span * (HEAT_SHADES.length - 1));
9434
10615
  return `${paint(ctx, "accent", HEAT_SHADES[level].repeat(HEAT_CELL - 1))} `;
9435
10616
  });
9436
- body.push(`${paint(ctx, "text", padEndVisual(truncateVisual(row, labelWidth), labelWidth))} ${cells.join("")}`);
10617
+ body.push(`${paint(ctx, "text", padEndVisual(truncateVisual(row, labelWidth), labelWidth))} ${cells2.join("")}`);
9437
10618
  });
9438
10619
  body.push("", paint(ctx, "muted", `\xB7 low ${formatCompactNumber(min)} \u2588 high ${formatCompactNumber(min + span)}`));
9439
10620
  return frame(ctx, totalBadge(ctx), body, "Heatmap");
@@ -9460,9 +10641,9 @@ function scatterCard(ctx) {
9460
10641
  const yWidth = Math.max(visualWidth(formatCompactNumber(yMax)), visualWidth(formatCompactNumber(yMin)), 6);
9461
10642
  const multi = data.series.length > 1;
9462
10643
  const body = multi ? [data.series.slice(0, 4).map((s, i) => paintSeries(ctx, i, `\u25CF ${truncateVisual(s.name, 14)}`)).join(" "), ""] : [];
9463
- grid.forEach((cells, r) => {
10644
+ grid.forEach((cells2, r) => {
9464
10645
  const tick = r === 0 ? formatCompactNumber(yMax) : r === rows - 1 ? formatCompactNumber(yMin) : "";
9465
- const row = `${padStartVisual(tick, yWidth)} \u2524${cells.map((mask) => String.fromCharCode(10240 + mask)).join("")}`;
10646
+ const row = `${padStartVisual(tick, yWidth)} \u2524${cells2.map((mask) => String.fromCharCode(10240 + mask)).join("")}`;
9466
10647
  body.push(ctx.pal ? paintPlotRow(ctx, row, owners[r], multi) : row);
9467
10648
  });
9468
10649
  body.push(paint(ctx, "border", `${" ".repeat(yWidth)} \u2514${"\u2500".repeat(cols)}`));
@@ -9491,8 +10672,10 @@ function chartCard(ctx) {
9491
10672
  function formatTerminalChart(dataset, chartConfig, options = {}) {
9492
10673
  if (!chartConfig?.xAxis || !chartConfig?.yAxis || dataset.rows.length === 0)
9493
10674
  return "";
10675
+ const requested = chartConfig.type ?? "bar";
10676
+ const fallback = getChartTypeInfo(requested)?.terminalFallback;
9494
10677
  const config = {
9495
- type: chartConfig.type ?? "bar",
10678
+ type: fallback?.as ?? requested,
9496
10679
  xAxis: chartConfig.xAxis,
9497
10680
  yAxis: chartConfig.yAxis,
9498
10681
  seriesField: chartConfig.seriesField,
@@ -9527,6 +10710,7 @@ function formatTerminalChart(dataset, chartConfig, options = {}) {
9527
10710
  pal,
9528
10711
  liveRow: live && pal ? ansiFg(pal.accent, live) : live,
9529
10712
  statsLine: `\u25B2 Peak: ${truncateVisual(String(processed.categories[peak]), 14)} (${formatCompactNumber(totalsPerCat[peak])}) \xB7 \u25BC Low: ${truncateVisual(String(processed.categories[low]), 14)} (${formatCompactNumber(totalsPerCat[low])}) \xB7 \u25C6 Avg: ${formatCompactNumber(grandTotal / totalsPerCat.length)}`,
10713
+ note: fallback?.note,
9530
10714
  footerLeft: options.showBranding !== false ? "tiny-pivot.com" : "",
9531
10715
  raw: options.raw
9532
10716
  };
@@ -9605,10 +10789,13 @@ function formatColumnNotes(columns) {
9605
10789
  return `Columns: ${notes.join(" \xB7 ") || "none"}`;
9606
10790
  }
9607
10791
  var REPRINT_NOTE = "Show the card above to the user verbatim.";
9608
- var WIDGET_NOTE = "The user already sees this in the TinyPivot view in the chat: do not repeat the card or a table of it. Reply with the takeaways.";
10792
+ var SHOWN_NOTES = {
10793
+ widget: "The user already sees this in the TinyPivot view in the chat: do not repeat the card or a table of it. Reply with the takeaways.",
10794
+ pi: "TinyPivot's pi extension already shows the user this card: do not repeat it or a table of it. Reply with the takeaways and the Studio link."
10795
+ };
9609
10796
  function cardNote(companionUrl, options) {
9610
- if (options.shownInWidget)
9611
- return WIDGET_NOTE;
10797
+ if (options.shownBy)
10798
+ return SHOWN_NOTES[options.shownBy];
9612
10799
  return companionUrl && options.reprintNote !== false ? REPRINT_NOTE : null;
9613
10800
  }
9614
10801
  function datasetCard(dataset, options = {}) {
@@ -9617,6 +10804,21 @@ function datasetCard(dataset, options = {}) {
9617
10804
  function cardTitle(card) {
9618
10805
  return /╭─ (.+?) ─/.exec(card.replace(/\x1B\[[0-9;]*m/g, ""))?.[1] ?? null;
9619
10806
  }
10807
+ function describeChartForText(rows, config) {
10808
+ if (!config?.type || !config.xAxis || !config.yAxis)
10809
+ return [];
10810
+ const full = config;
10811
+ const lines = [];
10812
+ const story = full.options?.annotations === false ? null : buildChartStory(rows, full);
10813
+ if (story)
10814
+ lines.push(`Takeaway (computed from the data): ${story.headline}.`);
10815
+ if (full.type === "choropleth") {
10816
+ const unmatched = describeUnmatchedRegions(processChartDataForChoropleth(rows, full));
10817
+ if (unmatched)
10818
+ lines.push(`> **Map warning**: ${unmatched}`);
10819
+ }
10820
+ return lines;
10821
+ }
9620
10822
  function formatDatasetSummary(dataset, companionUrl, options = {}) {
9621
10823
  const cardOptions = { ...options, companionUrl: options.companionUrl ?? companionUrl };
9622
10824
  const chartBlock = smallGridTable(dataset) ?? datasetCard(dataset, cardOptions);
@@ -9634,6 +10836,9 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
9634
10836
  if (integrityWarning) {
9635
10837
  parts.push("", integrityWarning);
9636
10838
  }
10839
+ const chartText = describeChartForText(dataset.rows, dataset.chartConfig);
10840
+ if (chartText.length > 0)
10841
+ parts.push("", ...chartText);
9637
10842
  if (chartBlock) {
9638
10843
  parts.push("", chartBlock);
9639
10844
  const note = cardNote(companionUrl, options);
@@ -9710,7 +10915,7 @@ function formatPivotSummary(dataset, config, companionUrl, options = {}) {
9710
10915
  const topColsRule = `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u252C\u2500")}\u2500\u2524`;
9711
10916
  const midRule = `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`;
9712
10917
  const botColsRule = `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u2534\u2500")}\u2500\u2524`;
9713
- const formatRow = (cells) => `\u2502 ${cells.map((c, i) => i === 0 ? padEndVisual(c, widths[i]) : padStartVisual(c, widths[i])).join(" \u2502 ")} \u2502`;
10918
+ const formatRow = (cells2) => `\u2502 ${cells2.map((c, i) => i === 0 ? padEndVisual(c, widths[i]) : padStartVisual(c, widths[i])).join(" \u2502 ")} \u2502`;
9714
10919
  const showBranding = options.showBranding !== false;
9715
10920
  const metaRight = `${dataset.rows.length.toLocaleString()} rows \xB7 ${result.rowHeaders.length} groups`;
9716
10921
  const metaLeft = showBranding ? "tiny-pivot.com" : "";
@@ -10008,8 +11213,8 @@ function renderChartView(payload, pal, innerWidth, height, overrideChartType) {
10008
11213
  barOut = fg(pal.accent, rawBar) + " ".repeat(Math.max(0, barW - visualWidth(rawBar)));
10009
11214
  }
10010
11215
  const valStr = fgBold(pal.text, padStartVisual(fmtNum(e.total), valW));
10011
- const pct = grandTotal > 0 ? fg(pal.muted, `${(e.total / grandTotal * 100).toFixed(1).padStart(5)}%`) : "";
10012
- lines.push(`${label} ${fg(pal.border, "\u2502")} ${barOut} ${valStr} ${pct}`);
11216
+ const pct2 = grandTotal > 0 ? fg(pal.muted, `${(e.total / grandTotal * 100).toFixed(1).padStart(5)}%`) : "";
11217
+ lines.push(`${label} ${fg(pal.border, "\u2502")} ${barOut} ${valStr} ${pct2}`);
10013
11218
  }
10014
11219
  if (processed.categories.length > entries.length) {
10015
11220
  lines.push(fg(pal.muted, `\u2026 +${processed.categories.length - entries.length} more categories`));
@@ -10082,8 +11287,8 @@ function renderPivotView(payload, pal, innerWidth, height) {
10082
11287
  const topRule = fg(pal.border, `\u256D\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u252C\u2500")}\u2500\u256E`);
10083
11288
  const midRule = fg(pal.border, `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`);
10084
11289
  const botRule = fg(pal.border, `\u2570\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u2534\u2500")}\u2500\u256F`);
10085
- const formatRow = (cells, isHeader = false, isTotal = false) => {
10086
- const rendered = cells.map((cell, i) => {
11290
+ const formatRow = (cells2, isHeader = false, isTotal = false) => {
11291
+ const rendered = cells2.map((cell, i) => {
10087
11292
  const padded = i === 0 ? padEndVisual(cell, widths[i]) : padStartVisual(cell, widths[i]);
10088
11293
  if (isHeader)
10089
11294
  return fgBold(pal.accent, padded);
@@ -10303,6 +11508,7 @@ var INTERACTIVE_ROW_LIMIT = 1e5;
10303
11508
  var ROW_PAGE_SIZE = 25e3;
10304
11509
 
10305
11510
  // src/companion.ts
11511
+ var STUDIO_IDLE_STOP_MS = 2 * 60 * 1e3;
10306
11512
  function isAllowedRequest(request, port) {
10307
11513
  const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
10308
11514
  if (!request.host || !allowedHosts.includes(request.host))
@@ -10467,14 +11673,22 @@ data: ${JSON.stringify(payload)}
10467
11673
  const text = typeof body.text === "string" ? body.text.trim() : "";
10468
11674
  if (!text || text.length > MAX_NOTE_CHARS)
10469
11675
  return sendJson(res, 400, { error: `Write a note of up to ${MAX_NOTE_CHARS.toLocaleString("en-US")} characters.` });
10470
- const note = studio.addNote(text, {
10471
- stepId: typeof body.stepId === "string" ? body.stepId : void 0,
10472
- attachment: parseAttachment(body.attachment)
10473
- });
10474
- return sendJson(res, 200, { note });
11676
+ try {
11677
+ const note = studio.addNote(text, {
11678
+ stepId: typeof body.stepId === "string" ? body.stepId : void 0,
11679
+ attachment: parseAttachment(body.attachment)
11680
+ });
11681
+ return sendJson(res, 200, { note });
11682
+ } catch (error) {
11683
+ return sendJson(res, 409, { error: errorMessage(error) });
11684
+ }
10475
11685
  }
10476
- if (pathname === "/api/studio/note/delete") {
10477
- return sendJson(res, 200, { removed: typeof body.id === "string" && studio.removeNote(body.id) });
11686
+ if (pathname === "/api/studio/verify") {
11687
+ try {
11688
+ return sendJson(res, 200, { checks: await studio.verifyStep(String(body.stepId ?? "")) });
11689
+ } catch (error) {
11690
+ return sendJson(res, 400, { error: errorMessage(error) });
11691
+ }
10478
11692
  }
10479
11693
  if (pathname === "/api/studio/reply") {
10480
11694
  const text = typeof body.text === "string" ? body.text.trim() : "";
@@ -10489,7 +11703,8 @@ data: ${JSON.stringify(payload)}
10489
11703
  }
10490
11704
  if (pathname === "/api/studio/show") {
10491
11705
  try {
10492
- const dataset = await studio.showStep(String(body.stepId ?? ""));
11706
+ const viewMode = body.viewMode === "grid" || body.viewMode === "chart" || body.viewMode === "pivot" ? body.viewMode : void 0;
11707
+ const dataset = await studio.showStep(String(body.stepId ?? ""), { viewMode });
10493
11708
  broadcastUpdate();
10494
11709
  return sendJson(res, 200, { datasetId: dataset.id });
10495
11710
  } catch (error) {
@@ -10508,6 +11723,8 @@ data: ${JSON.stringify(payload)}
10508
11723
  return sendJson(res, 404, { error: "Not found" });
10509
11724
  };
10510
11725
  let listenPort = 0;
11726
+ let closePromise = null;
11727
+ let idleTimer;
10511
11728
  const server = http.createServer(async (req, res) => {
10512
11729
  const urlObj = new URL(req.url || "/", "http://127.0.0.1");
10513
11730
  const pathname = urlObj.pathname;
@@ -10539,7 +11756,16 @@ data: ${JSON.stringify(studio.snapshot())}
10539
11756
 
10540
11757
  `);
10541
11758
  sseClients.add(res);
10542
- req.on("close", () => sseClients.delete(res));
11759
+ clearTimeout(idleTimer);
11760
+ req.on("close", () => {
11761
+ sseClients.delete(res);
11762
+ armIdleStop();
11763
+ });
11764
+ return;
11765
+ }
11766
+ if (req.method === "POST" && pathname === "/api/studio/stop") {
11767
+ sendJson(res, 200, { stopped: true });
11768
+ setImmediate(() => void stopSelf("stopped"));
10543
11769
  return;
10544
11770
  }
10545
11771
  if (req.method === "GET" && pathname === "/api/studio/agent-stream") {
@@ -10619,38 +11845,50 @@ data: ${JSON.stringify(studio.snapshot())}
10619
11845
  `, "utf8");
10620
11846
  } catch {
10621
11847
  }
10622
- let closePromise = null;
11848
+ function closeServer() {
11849
+ if (closePromise)
11850
+ return closePromise;
11851
+ clearTimeout(idleTimer);
11852
+ closePromise = (async () => {
11853
+ for (const client of sseClients) {
11854
+ try {
11855
+ client.end();
11856
+ } catch {
11857
+ }
11858
+ }
11859
+ sseClients.clear();
11860
+ await new Promise((resolve) => {
11861
+ server.close(() => resolve());
11862
+ server.closeAllConnections();
11863
+ });
11864
+ try {
11865
+ const raw = await fs3.readFile(sessionFile, "utf8");
11866
+ const parsed = JSON.parse(raw);
11867
+ if (parsed.pid === process.pid) {
11868
+ await fs3.unlink(sessionFile);
11869
+ }
11870
+ } catch {
11871
+ }
11872
+ })();
11873
+ return closePromise;
11874
+ }
11875
+ async function stopSelf(reason) {
11876
+ await closeServer();
11877
+ options.onStopped?.(reason);
11878
+ }
11879
+ function armIdleStop() {
11880
+ clearTimeout(idleTimer);
11881
+ if (!options.idleStopMs || sseClients.size > 0 || closePromise)
11882
+ return;
11883
+ idleTimer = setTimeout(() => void stopSelf("idle"), options.idleStopMs);
11884
+ idleTimer.unref();
11885
+ }
10623
11886
  return {
10624
11887
  url,
10625
11888
  port: address.port,
10626
11889
  broadcastUpdate,
10627
11890
  clientCount: () => sseClients.size,
10628
- close: () => {
10629
- if (closePromise)
10630
- return closePromise;
10631
- closePromise = (async () => {
10632
- for (const client of sseClients) {
10633
- try {
10634
- client.end();
10635
- } catch {
10636
- }
10637
- }
10638
- sseClients.clear();
10639
- await new Promise((resolve) => {
10640
- server.close(() => resolve());
10641
- server.closeAllConnections();
10642
- });
10643
- try {
10644
- const raw = await fs3.readFile(sessionFile, "utf8");
10645
- const parsed = JSON.parse(raw);
10646
- if (parsed.pid === process.pid) {
10647
- await fs3.unlink(sessionFile);
10648
- }
10649
- } catch {
10650
- }
10651
- })();
10652
- return closePromise;
10653
- }
11891
+ close: closeServer
10654
11892
  };
10655
11893
  }
10656
11894
 
@@ -12055,9 +13293,127 @@ async function executeReadOnlyPostgresQuery(config, sql) {
12055
13293
  }
12056
13294
 
12057
13295
  // src/studio.ts
13296
+ import crypto from "crypto";
12058
13297
  import fs7 from "fs";
12059
13298
  import path7 from "path";
12060
13299
 
13300
+ // src/claims.ts
13301
+ var NUMBER_RE = /(?<![\w.-])([$€£]?)(-?)(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?\s?([KMB])?(%)?(?![\w-])/g;
13302
+ var SCALE = { K: 1e3, M: 1e6, B: 1e9 };
13303
+ var MIN_PLAIN_VALUE = 10;
13304
+ var MAX_ROWS_PER_SOURCE = 2e4;
13305
+ var MAX_CLAIMS = 40;
13306
+ function parseNumber(match) {
13307
+ const [text, currency, minus, whole, fraction = "", suffix, percent2] = match;
13308
+ const isYear = !currency && !suffix && !percent2 && !fraction && /^(?:19|20)\d{2}$/.test(whole);
13309
+ if (isYear)
13310
+ return null;
13311
+ const scale = suffix ? SCALE[suffix] : 1;
13312
+ const unsigned = Number(`${whole.replace(/,/g, "")}.${fraction || "0"}`);
13313
+ const value2 = (minus ? -1 : 1) * unsigned * scale;
13314
+ if (!percent2 && !suffix && Math.abs(value2) < MIN_PLAIN_VALUE)
13315
+ return null;
13316
+ const tolerance = 0.5 * 10 ** -fraction.length * scale;
13317
+ return { text: text.trim(), value: value2, tolerance, percent: Boolean(percent2) };
13318
+ }
13319
+ function extractNumbers(text) {
13320
+ const seen = /* @__PURE__ */ new Set();
13321
+ const out = [];
13322
+ for (const match of text.matchAll(NUMBER_RE)) {
13323
+ const parsed = parseNumber(match);
13324
+ if (parsed && !seen.has(parsed.text)) {
13325
+ seen.add(parsed.text);
13326
+ out.push(parsed);
13327
+ }
13328
+ if (out.length >= MAX_CLAIMS)
13329
+ break;
13330
+ }
13331
+ return out;
13332
+ }
13333
+ var SUMMARY_MAX_ROWS = 1e3;
13334
+ var MAX_GROUPS = 50;
13335
+ var PERCENT_COLUMN_RE = /pct|percent|share|rate|ratio|%/i;
13336
+ function rowLabel(row) {
13337
+ const label = Object.values(row).find((value2) => typeof value2 === "string" && value2.trim() !== "");
13338
+ return typeof label === "string" ? label : "";
13339
+ }
13340
+ var IS_TYPE = {
13341
+ number: (value2) => typeof value2 === "number",
13342
+ string: (value2) => typeof value2 === "string"
13343
+ };
13344
+ function columnsOf(rows, type) {
13345
+ const first = rows.find((row) => row && typeof row === "object") ?? {};
13346
+ return Object.keys(first).filter((column) => rows.some((row) => IS_TYPE[type](row[column])));
13347
+ }
13348
+ function sumOf(rows, column) {
13349
+ return rows.reduce((sum, row) => sum + (typeof row[column] === "number" ? row[column] : 0), 0);
13350
+ }
13351
+ function groupTotals(rows, dimensions, measure, total, pool) {
13352
+ for (const dimension of dimensions) {
13353
+ const groups = /* @__PURE__ */ new Map();
13354
+ for (const row of rows) {
13355
+ const key = row[dimension];
13356
+ if (typeof key === "string" && typeof row[measure] === "number")
13357
+ groups.set(key, (groups.get(key) ?? 0) + row[measure]);
13358
+ if (groups.size > MAX_GROUPS)
13359
+ break;
13360
+ }
13361
+ if (groups.size > MAX_GROUPS)
13362
+ continue;
13363
+ for (const [key, sum] of groups) {
13364
+ pool.values.push({ value: sum, where: `${measure} \xB7 ${key} (all ${dimension})` });
13365
+ if (total !== 0)
13366
+ pool.percents.push({ value: sum / total * 100, where: `share of ${measure} \xB7 ${key}` });
13367
+ }
13368
+ }
13369
+ }
13370
+ function cells(rows, measure, total, pool) {
13371
+ const isPercent = PERCENT_COLUMN_RE.test(measure);
13372
+ for (const row of rows) {
13373
+ const cell = row[measure];
13374
+ if (typeof cell !== "number")
13375
+ continue;
13376
+ const label = rowLabel(row);
13377
+ const where = label ? `${measure} \xB7 ${label}` : measure;
13378
+ pool.values.push({ value: cell, where });
13379
+ if (isPercent)
13380
+ pool.percents.push({ value: cell, where });
13381
+ else if (total !== 0)
13382
+ pool.percents.push({ value: cell / total * 100, where: `share of ${measure} \xB7 ${label || "total"}` });
13383
+ }
13384
+ }
13385
+ function candidatesFor(source) {
13386
+ const pool = { values: [], percents: [] };
13387
+ const rows = source.rows.slice(0, MAX_ROWS_PER_SOURCE);
13388
+ const summary = source.rows.length <= SUMMARY_MAX_ROWS;
13389
+ const dimensions = summary ? columnsOf(rows, "string") : source.dimensions ?? [];
13390
+ for (const measure of columnsOf(rows, "number")) {
13391
+ const total = sumOf(rows, measure);
13392
+ if (summary)
13393
+ cells(rows, measure, total, pool);
13394
+ pool.values.push({ value: total, where: `${measure} \xB7 total of ${source.name}` });
13395
+ groupTotals(rows, dimensions, measure, total, pool);
13396
+ }
13397
+ return pool;
13398
+ }
13399
+ function closest(claim, candidates) {
13400
+ return candidates.find((candidate) => Math.abs(candidate.value - claim.value) <= claim.tolerance + 1e-9);
13401
+ }
13402
+ function checkClaims(text, sources) {
13403
+ const claims = extractNumbers(text);
13404
+ if (claims.length === 0 || sources.length === 0)
13405
+ return [];
13406
+ const pools = sources.map(candidatesFor);
13407
+ const values = pools.flatMap((pool) => pool.values);
13408
+ const percents = pools.flatMap((pool) => pool.percents);
13409
+ return claims.map((claim) => {
13410
+ const match = closest(claim, claim.percent ? percents : values);
13411
+ if (match)
13412
+ return { text: claim.text, status: "found", where: match.where };
13413
+ return { text: claim.text, status: claim.percent ? "unchecked" : "not-found" };
13414
+ });
13415
+ }
13416
+
12061
13417
  // src/duckdb.ts
12062
13418
  import { spawn } from "child_process";
12063
13419
  import fs5 from "fs";
@@ -12206,6 +13562,7 @@ import path6 from "path";
12206
13562
  import zlib from "zlib";
12207
13563
  var HISTORY_MAX_SAVED_ROWS = 2e5;
12208
13564
  var DEFAULT_RETENTION_DAYS = 30;
13565
+ var SESSIONS_DIR = "sessions";
12209
13566
  function defaultHistoryDir() {
12210
13567
  const base = process.env.XDG_DATA_HOME || path6.join(os5.homedir(), ".local", "share");
12211
13568
  return path6.join(base, "tinypivot", "history");
@@ -12287,11 +13644,24 @@ var HistoryStore = class {
12287
13644
  throw new Error(`History entry ${entry.id} has no saved rows.`);
12288
13645
  return zlib.gunzipSync(fs6.readFileSync(file)).toString("utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
12289
13646
  }
12290
- /** Deletes entries older than the retention window. Returns how many were removed. */
13647
+ /** Removes conversation traces last written before `cutoff`, and the old trace every session shared. */
13648
+ pruneTraces(cutoff) {
13649
+ fs6.rmSync(path6.join(this.dir, "trace.jsonl"), { force: true });
13650
+ const sessions = path6.join(this.dir, SESSIONS_DIR);
13651
+ if (!fs6.existsSync(sessions))
13652
+ return;
13653
+ for (const file of fs6.readdirSync(sessions)) {
13654
+ const full = path6.join(sessions, file);
13655
+ if (fs6.statSync(full).mtimeMs < cutoff)
13656
+ fs6.rmSync(full, { force: true });
13657
+ }
13658
+ }
13659
+ /** Deletes entries and conversation traces older than the retention window. Returns how many entries were removed. */
12291
13660
  prune(now = /* @__PURE__ */ new Date()) {
12292
13661
  if (!fs6.existsSync(this.dir))
12293
13662
  return 0;
12294
13663
  const cutoff = now.getTime() - this.retentionDays * 24 * 60 * 60 * 1e3;
13664
+ this.pruneTraces(cutoff);
12295
13665
  let removed = 0;
12296
13666
  for (const entry of this.list()) {
12297
13667
  if (new Date(entry.createdAt).getTime() >= cutoff)
@@ -12319,6 +13689,7 @@ function formatHistoryList(entries) {
12319
13689
  var STEPS_IN_MEMORY = 300;
12320
13690
  var HISTORY_IN_SNAPSHOT = 50;
12321
13691
  var ATTACHMENT_MAX_CHARS = 6e3;
13692
+ var ASK_MAX_CHARS = 500;
12322
13693
  var AGENT_NAMES = {
12323
13694
  "claude-code": "Claude Code",
12324
13695
  "claude-ai": "Claude Desktop",
@@ -12348,6 +13719,11 @@ function describeView(dataset) {
12348
13719
  }
12349
13720
  return "table";
12350
13721
  }
13722
+ function viewDimensions(dataset) {
13723
+ const chart = dataset.chartConfig;
13724
+ const pivot = dataset.pivotConfig;
13725
+ return [chart?.xAxis?.field, chart?.seriesField?.field, ...pivot?.rowFields ?? [], ...pivot?.columnFields ?? []].filter((field) => Boolean(field));
13726
+ }
12351
13727
  function whereSql(where) {
12352
13728
  return where.map((filter) => `CAST(${quoteIdentifier(filter.field)} AS VARCHAR) IN (${filter.equals.map((value2) => quoteLiteral(String(value2))).join(", ")})`).join(" AND ");
12353
13729
  }
@@ -12379,7 +13755,31 @@ function withoutCards(text) {
12379
13755
  const stripped = text.replace(/```text\n[\s\S]*?```\n?/g, (block) => /[╭╰│┤├]/.test(block) ? "" : block);
12380
13756
  return stripped.replace(/\n{3,}/g, "\n\n").trim() || text.trim();
12381
13757
  }
13758
+ function fingerprintRows(rows) {
13759
+ const rowHashes = rows.map((row) => crypto.createHash("sha1").update(JSON.stringify(row, (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2)).digest("hex"));
13760
+ rowHashes.sort();
13761
+ return { rows: rows.length, hash: crypto.createHash("sha256").update(rowHashes.join("")).digest("hex").slice(0, 16) };
13762
+ }
13763
+ function sourceFile(file) {
13764
+ try {
13765
+ const stat = fs7.statSync(file);
13766
+ return { file, bytes: stat.size, modifiedAt: stat.mtime.toISOString() };
13767
+ } catch {
13768
+ return void 0;
13769
+ }
13770
+ }
13771
+ function checkSource(then) {
13772
+ const now = sourceFile(then.file);
13773
+ if (!now)
13774
+ return { kind: "source", ok: false, detail: "The file is gone or cannot be read." };
13775
+ const ok = now.bytes === then.bytes && now.modifiedAt === then.modifiedAt;
13776
+ return { kind: "source", ok, detail: ok ? "The file is unchanged since this step." : `The file changed: ${now.bytes.toLocaleString("en-US")} bytes, saved ${now.modifiedAt}.` };
13777
+ }
12382
13778
  var sequence = 0;
13779
+ function newSessionId() {
13780
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
13781
+ return `${stamp}-${process.pid.toString(36)}${Math.random().toString(36).slice(2, 6)}`;
13782
+ }
12383
13783
  function nextId(prefix) {
12384
13784
  sequence += 1;
12385
13785
  return `${prefix}-${Date.now().toString(36)}-${sequence.toString(36)}`;
@@ -12389,12 +13789,12 @@ var Studio = class {
12389
13789
  this.store = store;
12390
13790
  this.history = options.history ?? new HistoryStore();
12391
13791
  this.duck = options.duck ?? new DuckDbRunner();
13792
+ this.sessionId = options.sessionId ?? newSessionId();
12392
13793
  this.steps = this.readTraceFile();
12393
13794
  }
12394
13795
  history;
12395
13796
  duck;
12396
13797
  steps = [];
12397
- notes = [];
12398
13798
  pullsByDataset = /* @__PURE__ */ new Map();
12399
13799
  listeners = /* @__PURE__ */ new Set();
12400
13800
  changeQueued = false;
@@ -12403,6 +13803,11 @@ var Studio = class {
12403
13803
  agentName;
12404
13804
  agentBusy = false;
12405
13805
  agentHint;
13806
+ /**
13807
+ * Which conversation this Studio belongs to. Each server process is one conversation, so its
13808
+ * trace is its own: other sessions, harnesses and tools running on the machine never show up here.
13809
+ */
13810
+ sessionId;
12406
13811
  /** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
12407
13812
  subscribe(listener) {
12408
13813
  this.listeners.add(listener);
@@ -12424,7 +13829,6 @@ var Studio = class {
12424
13829
  ...step,
12425
13830
  editableSql: step.sql ?? (step.file ? fileStepSql(step.file, step.where) : void 0)
12426
13831
  })),
12427
- notes: this.pendingNotes(),
12428
13832
  history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
12429
13833
  historyEnabled: this.history.enabled,
12430
13834
  loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id),
@@ -12449,7 +13853,7 @@ var Studio = class {
12449
13853
  this.changed();
12450
13854
  }
12451
13855
  get traceFile() {
12452
- return path7.join(this.history.dir, "trace.jsonl");
13856
+ return path7.join(this.history.dir, SESSIONS_DIR, `${this.sessionId}.jsonl`);
12453
13857
  }
12454
13858
  readTraceFile() {
12455
13859
  if (!this.history.enabled || !fs7.existsSync(this.traceFile))
@@ -12466,7 +13870,7 @@ var Studio = class {
12466
13870
  if (!this.history.enabled)
12467
13871
  return;
12468
13872
  try {
12469
- fs7.mkdirSync(this.history.dir, { recursive: true });
13873
+ fs7.mkdirSync(path7.dirname(this.traceFile), { recursive: true });
12470
13874
  fs7.appendFileSync(this.traceFile, `${JSON.stringify(step)}
12471
13875
  `);
12472
13876
  if (fs7.statSync(this.traceFile).size > TRACE_FILE_MAX_BYTES)
@@ -12486,13 +13890,18 @@ var Studio = class {
12486
13890
  this.changed();
12487
13891
  return full;
12488
13892
  }
12489
- /** Records a step about a dataset, filling in its name, size, view and saved pull. */
13893
+ /** Records a step about a dataset, filling in its name, size, columns, fingerprint, view and saved pull. */
12490
13894
  recordDatasetStep(dataset, step) {
13895
+ const source = step.file ? sourceFile(step.file) : void 0;
12491
13896
  return this.record({
12492
13897
  ...step,
13898
+ ...step.ask?.trim() ? { ask: step.ask.trim().slice(0, ASK_MAX_CHARS) } : { ask: void 0 },
12493
13899
  datasetId: dataset.id,
12494
13900
  datasetName: dataset.name,
12495
13901
  rows: dataset.rows.length,
13902
+ columns: dataset.columns.map((column) => column.name),
13903
+ fingerprint: fingerprintRows(dataset.rows),
13904
+ ...source ? { source } : {},
12496
13905
  view: describeView(dataset),
12497
13906
  viewMode: dataset.viewMode,
12498
13907
  ...dataset.chartConfig ? { chartConfig: structuredClone(dataset.chartConfig) } : {},
@@ -12502,9 +13911,11 @@ var Studio = class {
12502
13911
  }
12503
13912
  /**
12504
13913
  * Shows a step's dataset as it was right after the step, reopening it from history when it is
12505
- * no longer loaded. Looking is not a step, so nothing is recorded.
13914
+ * no longer loaded; `viewMode` shows it another way, e.g. its rows. Looking is not a step, so
13915
+ * nothing is recorded.
12506
13916
  */
12507
- async showStep(stepId, sessionKey = DEFAULT_SESSION_KEY) {
13917
+ async showStep(stepId, options = {}) {
13918
+ const sessionKey = options.sessionKey ?? DEFAULT_SESSION_KEY;
12508
13919
  const step = this.steps.find((s) => s.id === stepId);
12509
13920
  if (!step?.datasetId)
12510
13921
  throw new Error("That step has no data to show.");
@@ -12514,8 +13925,9 @@ var Studio = class {
12514
13925
  throw new Error("That data is no longer loaded and was not saved to history.");
12515
13926
  dataset = await this.reopen(step.historyId, { actor: "user", sessionKey, record: false });
12516
13927
  }
13928
+ const viewMode = options.viewMode ?? step.viewMode;
12517
13929
  return this.store.updateView(dataset.id, {
12518
- ...step.viewMode ? { viewMode: step.viewMode } : {},
13930
+ ...viewMode ? { viewMode } : {},
12519
13931
  ...step.chartConfig ? { chartConfig: { ...step.chartConfig, seriesField: step.chartConfig.seriesField } } : {},
12520
13932
  ...step.pivotConfig ? { pivotConfig: step.pivotConfig } : {}
12521
13933
  }, sessionKey) ?? dataset;
@@ -12555,7 +13967,7 @@ var Studio = class {
12555
13967
  });
12556
13968
  const shown = this.keepViewOf(input.viewFromStepId, dataset, sessionKey) ?? dataset;
12557
13969
  this.remember(shown, { kind: "query", source: input.sql });
12558
- this.recordDatasetStep(shown, { actor: input.actor, tool: "query", why: input.why, sql: input.sql });
13970
+ this.recordDatasetStep(shown, { actor: input.actor, tool: "query", why: input.why, ask: input.ask, sql: input.sql });
12559
13971
  return { dataset: shown, truncated: result.truncated };
12560
13972
  }
12561
13973
  /** Gives `dataset` the view of the step's dataset when every field that view uses is in the result. */
@@ -12598,8 +14010,8 @@ var Studio = class {
12598
14010
  return dataset;
12599
14011
  }
12600
14012
  /**
12601
- * Sends the user's message to the agent: straight into its conversation when a live connector
12602
- * takes it, otherwise queued for its next TinyPivot reply.
14013
+ * Sends the user's message straight into the agent's conversation. Throws when no live
14014
+ * connector takes it: the Studio only offers to send when the agent can receive.
12603
14015
  */
12604
14016
  addNote(text, options = {}) {
12605
14017
  const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
@@ -12607,57 +14019,73 @@ var Studio = class {
12607
14019
  id: nextId("note"),
12608
14020
  at: (/* @__PURE__ */ new Date()).toISOString(),
12609
14021
  text: text.trim(),
12610
- delivery: "queued",
12611
14022
  ...options.stepId ? { stepId: options.stepId } : {},
12612
14023
  ...attachment ? { attachment } : {}
12613
14024
  };
12614
- if (this.agent.push(note, this.describeNote(note, { withSource: true })))
12615
- note.delivery = "live";
12616
- else
12617
- this.notes.push(note);
14025
+ if (!this.agent.push(note, this.describeNote(note)))
14026
+ throw new Error(`${this.agentName ? agentLabel(this.agentName) : "Your agent"} cannot receive messages from the Studio. Ask in your terminal instead.`);
12618
14027
  this.record({ actor: "user", tool: "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
12619
14028
  return note;
12620
14029
  }
12621
- /**
12622
- * How a message reads to the agent: the text, the step it is about, and any attached data.
12623
- * `withSource` says where it came from, for messages that arrive on their own in the conversation.
12624
- */
12625
- describeNote(note, { withSource = false } = {}) {
14030
+ /** How a message reads to the agent: where it came from, the text, the step it is about, and any attached data. */
14031
+ describeNote(note) {
12626
14032
  const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
12627
- const source = withSource ? "Message from the user in TinyPivot Studio: " : "";
12628
- const lines = [`${source}${note.text}`];
14033
+ const lines = [`Message from the user in TinyPivot Studio: ${note.text}`];
12629
14034
  if (step)
12630
14035
  lines.push(`About the step "${step.why ?? step.view ?? step.tool}"${step.datasetId ? ` on dataset \`${step.datasetId}\`` : ""}${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""}`);
12631
14036
  if (note.attachment)
12632
14037
  lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
12633
14038
  return lines.join("\n");
12634
14039
  }
12635
- /** The agent's answer to a Studio message, recorded in the trace where the user reads it. */
12636
- reply(text) {
12637
- return this.record({ actor: "agent", tool: "reply", why: withoutCards(text) });
12638
- }
12639
- /** Drops a queued note the user no longer wants sent. */
12640
- removeNote(id) {
12641
- const before = this.notes.length;
12642
- this.notes = this.notes.filter((note) => note.id !== id);
12643
- if (this.notes.length !== before)
12644
- this.changed();
12645
- return this.notes.length !== before;
12646
- }
12647
- pendingNotes() {
12648
- return [...this.notes];
12649
- }
12650
- /** The queued notes as text for the agent, emptying the queue. Empty when there are none. */
12651
- takeNotes() {
12652
- if (this.notes.length === 0)
12653
- return "";
12654
- const lines = this.notes.map((note) => `- ${this.describeNote(note).replace(/\n/g, "\n ")}`);
12655
- this.notes = [];
12656
- this.changed();
12657
- return `
12658
-
12659
- **Notes from the user in TinyPivot Studio** (act on these):
12660
- ${lines.join("\n")}`;
14040
+ /**
14041
+ * The agent's answer to a Studio message, recorded where the user reads it, with each number it
14042
+ * quotes checked against the data loaded since the user last asked something.
14043
+ */
14044
+ reply(text, sessionKey = DEFAULT_SESSION_KEY) {
14045
+ const answer = withoutCards(text);
14046
+ const claims = checkClaims(answer, this.datasetsSinceLastAsk(sessionKey));
14047
+ return this.record({ actor: "agent", tool: "reply", why: answer, ...claims.length ? { claims } : {} });
14048
+ }
14049
+ /** The datasets the current question has used and that are still loaded, newest first. */
14050
+ datasetsSinceLastAsk(sessionKey) {
14051
+ let lastAsk = this.steps.length - 1;
14052
+ while (lastAsk > 0 && !(this.steps[lastAsk].actor === "user" && (this.steps[lastAsk].tool === "note" || this.steps[lastAsk].tool === "query")))
14053
+ lastAsk--;
14054
+ const ids = new Set(this.steps.slice(Math.max(0, lastAsk)).flatMap((step) => step.datasetId ? [step.datasetId] : []));
14055
+ return [...ids].reverse().flatMap((id) => {
14056
+ const dataset = this.store.get(id, sessionKey);
14057
+ return dataset ? [{ name: dataset.name, rows: dataset.rows, dimensions: viewDimensions(dataset) }] : [];
14058
+ });
14059
+ }
14060
+ /**
14061
+ * Re-checks a step: whether its source file is unchanged, and whether running its SQL again gives
14062
+ * the same rows. Results of queries are compared value by value (row order ignored); a file load
14063
+ * is compared by row count, since the file reader and SQL may type the same column differently.
14064
+ */
14065
+ async verifyStep(stepId, sessionKey = DEFAULT_SESSION_KEY) {
14066
+ const step = this.steps.find((s) => s.id === stepId);
14067
+ if (!step)
14068
+ throw new Error("That step is no longer in the trace.");
14069
+ const checks = [];
14070
+ if (step.source)
14071
+ checks.push(checkSource(step.source));
14072
+ const sql = step.sql ?? (step.file ? fileStepSql(step.file, step.where) : void 0);
14073
+ if (sql && step.fingerprint)
14074
+ checks.push(await this.checkRerun(sql, step, sessionKey));
14075
+ return checks;
14076
+ }
14077
+ async checkRerun(sql, step, sessionKey) {
14078
+ const expected = step.fingerprint;
14079
+ try {
14080
+ const result = await this.duck.run(sql, this.queryViews(sessionKey));
14081
+ const again = fingerprintRows(result.rows);
14082
+ if (step.tool !== "query" && step.tool !== "query_postgres")
14083
+ return { kind: "rerun", ok: again.rows === expected.rows, detail: `The SQL gives ${again.rows.toLocaleString("en-US")} rows again; the load had ${expected.rows.toLocaleString("en-US")}.` };
14084
+ const ok = again.rows === expected.rows && again.hash === expected.hash;
14085
+ return { kind: "rerun", ok, detail: ok ? `Same ${again.rows.toLocaleString("en-US")} rows, same values.` : `Different result: ${again.rows.toLocaleString("en-US")} rows now, ${expected.rows.toLocaleString("en-US")} then${again.rows === expected.rows ? ", with changed values" : ""}.` };
14086
+ } catch (error) {
14087
+ return { kind: "rerun", ok: false, detail: `Could not run it again: ${error instanceof Error ? error.message : String(error)}` };
14088
+ }
12661
14089
  }
12662
14090
  };
12663
14091
 
@@ -12666,6 +14094,7 @@ import fsSync3 from "fs";
12666
14094
  import fs8 from "fs/promises";
12667
14095
  import path9 from "path";
12668
14096
  import { fileURLToPath as fileURLToPath2 } from "url";
14097
+ import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
12669
14098
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12670
14099
  import { z } from "zod";
12671
14100
 
@@ -12769,12 +14198,12 @@ function formatProfile(dataset) {
12769
14198
  }
12770
14199
 
12771
14200
  // src/telemetry.ts
12772
- import crypto from "crypto";
14201
+ import crypto2 from "crypto";
12773
14202
  import fsSync2 from "fs";
12774
14203
  import os6 from "os";
12775
14204
  import path8 from "path";
12776
14205
  var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
12777
- var PACKAGE_VERSION = "0.6.1";
14206
+ var PACKAGE_VERSION = "0.7.1";
12778
14207
  function isTelemetryEnabled() {
12779
14208
  if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
12780
14209
  return false;
@@ -12810,7 +14239,7 @@ function getAnonymousId() {
12810
14239
  }
12811
14240
  } catch {
12812
14241
  }
12813
- const fresh = crypto.randomUUID();
14242
+ const fresh = crypto2.randomUUID();
12814
14243
  cachedAnonId = fresh;
12815
14244
  try {
12816
14245
  fsSync2.mkdirSync(path8.dirname(prefPath), { recursive: true });
@@ -12856,11 +14285,12 @@ var LOAD_DATA_ROW_GUIDE = 50;
12856
14285
  function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
12857
14286
  const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link, except in pi, which already shows it. Where TinyPivot shows its view in the chat, never repeat the card." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
12858
14287
  return [
12859
- "Show figures through TinyPivot: any ranking, breakdown, comparison, trend, chart or pivot, instead of Markdown tables, HTML, SVG or matplotlib, passing chartConfig or pivotConfig in the same call.",
14288
+ "Show figures through TinyPivot: any ranking, breakdown, comparison, trend, map, chart or pivot, instead of Markdown tables, HTML, SVG or matplotlib, passing chartConfig or pivotConfig in the same call.",
12860
14289
  `For files use load_file, so the rows stay out of your context; to filter, join or aggregate files first, use query with SQL. Use load_data only for rows you already have, up to about ${LOAD_DATA_ROW_GUIDE}; write larger sets to a file first. history lists and reopens earlier pulls.`,
14290
+ `Chart types: ${CHART_TYPES.map((t) => t.type).join(", ")}; names like map also work. seriesField: slope period, treemap parent; targetField: bullet target.`,
12861
14291
  "Totals are exact. Compute ratios, shares and rates as numerator / denominator, one row per chart point, before loading; never add up percentage columns, and do not use percentOfTotal for a share within a period.",
12862
14292
  "Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
12863
- "Pass why on every data call: one short sentence the user sees in the TinyPivot Studio trace. Replies may end with notes the user wrote in the Studio; act on them.",
14293
+ "On every data call pass why (one short sentence for TinyPivot Studio); when loading or querying, also ask (the user's request, verbatim).",
12864
14294
  ...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply.'] : [],
12865
14295
  cards
12866
14296
  ].join(" ");
@@ -12878,21 +14308,17 @@ var AGGREGATION_VALUES = [
12878
14308
  "stdDev",
12879
14309
  "percentOfTotal"
12880
14310
  ];
12881
- var CHART_TYPE_VALUES = [
12882
- "bar",
12883
- "stackedBar",
12884
- "line",
12885
- "area",
12886
- "pie",
12887
- "donut",
12888
- "scatter",
12889
- "bubble",
12890
- "heatmap",
12891
- "radar"
12892
- ];
14311
+ var chartTypeSchema = z.string().optional().superRefine((value2, ctx) => {
14312
+ if (value2 !== void 0 && !resolveChartType(value2))
14313
+ ctx.addIssue({ code: "custom", message: `Unknown chart type "${value2}". Use one of: ${CHART_TYPES.map((t) => t.type).join(", ")}.` });
14314
+ });
14315
+ var GEOGRAPHY_VALUES = ["auto", "world", "us-states"];
12893
14316
  var CHART_AGG_VALUES = ["sum", "avg", "count", "min", "max"];
12894
14317
  var VIEW_MODE_VALUES = ["grid", "pivot", "chart"];
12895
14318
  var VISUAL_THEME_VALUES = CHART_THEME_IDS;
14319
+ function optionalCompletable(complete) {
14320
+ return completable(completable(z.string(), complete).optional(), complete);
14321
+ }
12896
14322
  var pivotValueSchema = z.object({
12897
14323
  field: z.string(),
12898
14324
  aggregation: z.enum(AGGREGATION_VALUES).default("sum")
@@ -12908,14 +14334,22 @@ var pivotConfigSchema = z.object({
12908
14334
  showRowTotals: z.boolean().default(true),
12909
14335
  showColumnTotals: z.boolean().default(true)
12910
14336
  });
12911
- var chartConfigSchema = z.object({
12912
- type: z.enum(CHART_TYPE_VALUES).default("bar"),
14337
+ var chartFieldShape = {
14338
+ type: chartTypeSchema,
12913
14339
  xAxisField: z.string().describe("Category or date column"),
12914
- yAxisField: z.string().describe("Column to aggregate"),
14340
+ yAxisField: z.string(),
12915
14341
  aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
12916
- seriesField: z.string().optional().describe("Column to split into series"),
14342
+ seriesField: z.string().optional(),
14343
+ targetField: z.string().optional(),
12917
14344
  title: z.string().optional()
12918
- });
14345
+ };
14346
+ var chartStyleShape = {
14347
+ geography: z.enum(GEOGRAPHY_VALUES).optional(),
14348
+ annotations: z.boolean().optional(),
14349
+ variant: z.enum(["editorial", "deck"]).optional(),
14350
+ footnote: z.string().optional()
14351
+ };
14352
+ var loadChartSchema = z.object(chartFieldShape);
12919
14353
  function extractSessionKey(extra) {
12920
14354
  if (!extra || typeof extra !== "object")
12921
14355
  return void 0;
@@ -12951,29 +14385,38 @@ function normalizePivot(pivotConfig) {
12951
14385
  function extensionHint(agent, status) {
12952
14386
  const name = agentLabel(agent);
12953
14387
  if (status === "updated")
12954
- return `TinyPivot's ${name} extension was just updated. Restart ${name} to send messages live.`;
14388
+ return { text: `TinyPivot's ${name} extension was just updated. Restart ${name} to send messages live.` };
12955
14389
  if (status === "absent")
12956
- return `Run npx @smallwebco/tinypivot-mcp@latest init --targets=${agent}, then restart ${name}, to send messages live.`;
14390
+ return { text: `Install TinyPivot's ${name} extension, then restart ${name}, to send messages live:`, command: `npx @smallwebco/tinypivot-mcp@latest init --targets=${agent}` };
12957
14391
  return void 0;
12958
14392
  }
14393
+ var CLAUDE_CHANNEL_HINT = {
14394
+ text: "To send messages live, restart Claude Code into this same conversation with TinyPivot's channel:",
14395
+ command: "claude --continue --dangerously-load-development-channels server:tinypivot"
14396
+ };
12959
14397
  var whyParam = z.string().max(240).optional();
14398
+ var askParam = z.string().optional();
12960
14399
  var DUCKDB_WAIT_MS = 45e3;
12961
- function toCoreChartConfig(input) {
14400
+ function toCoreChartConfig(input, source) {
14401
+ const type = resolveChartType(input.type ?? "bar") ?? "bar";
14402
+ const aggregation = input.aggregation;
12962
14403
  return {
12963
- type: input.type,
14404
+ type,
12964
14405
  xAxis: { field: input.xAxisField, role: "dimension" },
12965
- yAxis: {
12966
- field: input.yAxisField,
12967
- role: "measure",
12968
- aggregation: input.aggregation
12969
- },
14406
+ yAxis: { field: input.yAxisField, role: "measure", aggregation },
12970
14407
  seriesField: input.seriesField ? { field: input.seriesField, role: "dimension" } : void 0,
14408
+ targetField: input.targetField ? { field: input.targetField, role: "measure", aggregation } : void 0,
12971
14409
  options: {
12972
14410
  title: input.title ?? "",
12973
14411
  showLegend: true,
12974
14412
  showDataLabels: false,
12975
14413
  showGrid: true,
12976
- stacked: input.type === "stackedBar"
14414
+ stacked: type === "stackedBar",
14415
+ ...input.geography ? { geography: input.geography } : {},
14416
+ ...input.annotations === void 0 ? {} : { annotations: input.annotations },
14417
+ ...source ? { source } : {},
14418
+ ...input.variant ? { variant: input.variant } : {},
14419
+ ...input.footnote ? { footnote: input.footnote } : {}
12977
14420
  }
12978
14421
  };
12979
14422
  }
@@ -13099,7 +14542,7 @@ function createTinyPivotMcpServer(options = {}) {
13099
14542
  const server = new McpServer(
13100
14543
  {
13101
14544
  name: "tinypivot",
13102
- version: "0.6.1"
14545
+ version: "0.7.1"
13103
14546
  },
13104
14547
  {
13105
14548
  capabilities: {
@@ -13111,7 +14554,11 @@ function createTinyPivotMcpServer(options = {}) {
13111
14554
  }
13112
14555
  );
13113
14556
  const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
13114
- const cardFormat = () => ({ showBranding: !isPro2, reprintNote: reprintCards, shownInWidget: clientRendersWidget() });
14557
+ const cardFormat = () => ({
14558
+ showBranding: !isPro2,
14559
+ reprintNote: reprintCards,
14560
+ shownBy: clientRendersWidget() ? "widget" : getClientName() === "pi" ? "pi" : void 0
14561
+ });
13115
14562
  const resolveCompanionUrlForTool = async (forceCompanion = false) => {
13116
14563
  if (activeCompanionUrl)
13117
14564
  return activeCompanionUrl;
@@ -13128,7 +14575,7 @@ function createTinyPivotMcpServer(options = {}) {
13128
14575
  };
13129
14576
  const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
13130
14577
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13131
- const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`);
14578
+ const summaryText = `${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`;
13132
14579
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
13133
14580
  recordTelemetry({
13134
14581
  event: "tool_call",
@@ -13147,7 +14594,6 @@ function createTinyPivotMcpServer(options = {}) {
13147
14594
  } catch (error) {
13148
14595
  console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
13149
14596
  }
13150
- const withNotes = (text) => `${text}${studio.takeNotes()}`;
13151
14597
  const connectAgent = () => {
13152
14598
  const clientName = server.server.getClientVersion()?.name;
13153
14599
  studio.setAgentName(clientName);
@@ -13155,7 +14601,7 @@ function createTinyPivotMcpServer(options = {}) {
13155
14601
  void refreshAgentExtension(clientName).then((status) => studio.setAgentHint(extensionHint(clientName, status))).catch(() => {
13156
14602
  });
13157
14603
  if (clientName === "claude-code" && !claudeChannel)
13158
- studio.setAgentHint("Start Claude Code with --dangerously-load-development-channels server:tinypivot to send messages live.");
14604
+ studio.setAgentHint(CLAUDE_CHANNEL_HINT);
13159
14605
  if (claudeChannel) {
13160
14606
  studio.agent.connect({
13161
14607
  name: "Claude Code channel",
@@ -13320,20 +14766,21 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13320
14766
  filePath: z.string(),
13321
14767
  name: z.string().optional(),
13322
14768
  why: whyParam,
14769
+ ask: askParam,
13323
14770
  where: z.array(rowFilterSchema).optional().describe('Keep only matching rows, e.g. [{"field":"year","equals":[2026]}]'),
13324
14771
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13325
14772
  pivotConfig: pivotConfigSchema.optional(),
13326
- chartConfig: chartConfigSchema.optional(),
14773
+ chartConfig: loadChartSchema.optional(),
13327
14774
  keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
13328
14775
  },
13329
14776
  _meta: INLINE_UI_META
13330
14777
  },
13331
- async ({ filePath, name, why, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
14778
+ async ({ filePath, name, why, ask, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13332
14779
  try {
13333
14780
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
13334
14781
  const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
13335
14782
  studio.remember(ds, { kind: "file", source: ds.source, where });
13336
- const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
14783
+ const explicitChart = chartConfig ? toCoreChartConfig(chartConfig, ds.name) : void 0;
13337
14784
  if (pivotConfig) {
13338
14785
  const normalizedPivot = normalizePivot(pivotConfig);
13339
14786
  store.updateView(ds.id, {
@@ -13347,7 +14794,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13347
14794
  ...explicitChart ? { chartConfig: explicitChart } : {}
13348
14795
  }, sessionKey);
13349
14796
  }
13350
- studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, file: ds.source, where });
14797
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, ask, file: ds.source, where });
13351
14798
  return replyWithDataset(ds, sessionKey, "load_file");
13352
14799
  } catch (err) {
13353
14800
  return {
@@ -13365,16 +14812,17 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13365
14812
  inputSchema: {
13366
14813
  name: z.string(),
13367
14814
  why: whyParam,
14815
+ ask: askParam,
13368
14816
  rows: z.array(z.record(z.string(), z.unknown())),
13369
14817
  source: z.string().optional(),
13370
14818
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13371
14819
  pivotConfig: pivotConfigSchema.optional(),
13372
- chartConfig: chartConfigSchema.optional(),
14820
+ chartConfig: loadChartSchema.optional(),
13373
14821
  keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
13374
14822
  },
13375
14823
  _meta: INLINE_UI_META
13376
14824
  },
13377
- async ({ name, why, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
14825
+ async ({ name, why, ask, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13378
14826
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
13379
14827
  const ds = store.register({
13380
14828
  name,
@@ -13383,12 +14831,12 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13383
14831
  rows,
13384
14832
  viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
13385
14833
  pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
13386
- chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
14834
+ chartConfig: chartConfig ? toCoreChartConfig(chartConfig, source ? `${name} (${source})` : name) : void 0,
13387
14835
  sessionKey,
13388
14836
  keepExisting: shouldKeep
13389
14837
  });
13390
14838
  studio.remember(ds, { kind: "data", source: source ?? "inline JSON" });
13391
- studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why });
14839
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why, ask });
13392
14840
  return replyWithDataset(ds, sessionKey, "load_data");
13393
14841
  }
13394
14842
  );
@@ -13433,7 +14881,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13433
14881
  chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
13434
14882
  }, sessionKey);
13435
14883
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13436
- const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat()));
14884
+ const summary = formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat());
13437
14885
  studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
13438
14886
  const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
13439
14887
  const payload = buildAppPayload(ds, store, {
@@ -13462,18 +14910,15 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13462
14910
  description: "Chart the active dataset.",
13463
14911
  inputSchema: {
13464
14912
  datasetId: z.string().optional(),
13465
- type: z.enum(CHART_TYPE_VALUES).default("bar"),
13466
- xAxisField: z.string(),
13467
- yAxisField: z.string(),
13468
- aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
13469
- seriesField: z.string().optional(),
13470
- title: z.string().optional(),
14913
+ ...chartFieldShape,
14914
+ ...chartStyleShape,
13471
14915
  why: whyParam,
13472
14916
  chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
13473
14917
  },
13474
14918
  _meta: INLINE_UI_META
13475
14919
  },
13476
- async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, why, chartTheme }, extra) => {
14920
+ async ({ datasetId, chartTheme, why, ...chartInput }, extra) => {
14921
+ const { xAxisField, yAxisField, aggregation, seriesField } = chartInput;
13477
14922
  const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
13478
14923
  const ds = store.get(datasetId, sessionKey);
13479
14924
  if (!ds) {
@@ -13485,7 +14930,8 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13485
14930
  if (chartTheme && (isPro2 || chartTheme === "code")) {
13486
14931
  store.setVisualTheme(chartTheme);
13487
14932
  }
13488
- const chartConfig = toCoreChartConfig({ type, xAxisField, yAxisField, aggregation, seriesField, title });
14933
+ const chartConfig = toCoreChartConfig(chartInput, ds.name);
14934
+ const type = chartConfig.type;
13489
14935
  store.updateView(ds.id, {
13490
14936
  viewMode: "chart",
13491
14937
  chartConfig
@@ -13503,14 +14949,15 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13503
14949
  summaryParts.push(integrityWarning, "");
13504
14950
  }
13505
14951
  summaryParts.push(
13506
- `Configured **${type}** chart on **${ds.name}**: X = \`${xAxisField}\`, Y = \`${aggregation}(${yAxisField})\`${seriesField ? `, series = \`${seriesField}\`` : ""}.`
14952
+ `Configured **${type}** chart on **${ds.name}**: X = \`${xAxisField}\`, Y = \`${aggregation}(${yAxisField})\`${seriesField ? `, series = \`${seriesField}\`` : ""}${chartInput.targetField ? `, target = \`${chartInput.targetField}\`` : ""}.`,
14953
+ ...describeChartForText(ds.rows, chartConfig)
13507
14954
  );
13508
14955
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13509
14956
  if (asciiChart)
13510
14957
  summaryParts.push("", asciiChart);
13511
14958
  if (liveCompanionUrl)
13512
14959
  summaryParts.push(`Studio: ${liveCompanionUrl}`);
13513
- const summaryText = withNotes(summaryParts.join("\n"));
14960
+ const summaryText = summaryParts.join("\n");
13514
14961
  studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_chart", why });
13515
14962
  const chartTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summaryText, "utf8") / 4));
13516
14963
  const payload = buildAppPayload(ds, store, {
@@ -13541,6 +14988,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13541
14988
  inputSchema: {
13542
14989
  sql: z.string(),
13543
14990
  why: whyParam,
14991
+ ask: askParam,
13544
14992
  name: z.string().optional(),
13545
14993
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13546
14994
  pivotConfig: pivotConfigSchema.optional(),
@@ -13548,7 +14996,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13548
14996
  },
13549
14997
  _meta: INLINE_UI_META
13550
14998
  },
13551
- async ({ sql, why, name, viewMode, pivotConfig, keepExisting }, extra) => {
14999
+ async ({ sql, why, ask, name, viewMode, pivotConfig, keepExisting }, extra) => {
13552
15000
  if (!isPro2) {
13553
15001
  return {
13554
15002
  isError: true,
@@ -13572,7 +15020,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13572
15020
  keepExisting: shouldKeep
13573
15021
  });
13574
15022
  studio.remember(ds, { kind: "postgres", source: sql });
13575
- studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, sql });
15023
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, ask, sql });
13576
15024
  return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
13577
15025
  } catch (err) {
13578
15026
  return {
@@ -13591,15 +15039,16 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13591
15039
  inputSchema: {
13592
15040
  sql: z.string(),
13593
15041
  why: whyParam,
15042
+ ask: askParam,
13594
15043
  name: z.string().optional(),
13595
15044
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13596
15045
  pivotConfig: pivotConfigSchema.optional(),
13597
- chartConfig: chartConfigSchema.optional(),
15046
+ chartConfig: loadChartSchema.optional(),
13598
15047
  keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
13599
15048
  },
13600
15049
  _meta: INLINE_UI_META
13601
15050
  },
13602
- async ({ sql, why, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
15051
+ async ({ sql, why, ask, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13603
15052
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
13604
15053
  try {
13605
15054
  if (await withinBudget(studio.duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
@@ -13609,6 +15058,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13609
15058
  sql,
13610
15059
  name,
13611
15060
  why,
15061
+ ask,
13612
15062
  actor: "agent",
13613
15063
  sessionKey,
13614
15064
  keepExisting: shouldKeep,
@@ -13640,7 +15090,7 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13640
15090
  if (!ds)
13641
15091
  return { isError: true, content: [{ type: "text", text: `Dataset "${datasetId ?? "(active)"}" not found.` }] };
13642
15092
  studio.recordDatasetStep(ds, { actor: "agent", tool: "profile", why });
13643
- return { content: [{ type: "text", text: withNotes(formatProfile(ds)) }] };
15093
+ return { content: [{ type: "text", text: formatProfile(ds) }] };
13644
15094
  }
13645
15095
  );
13646
15096
  server.registerTool(
@@ -13660,7 +15110,7 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13660
15110
  if (!history.enabled)
13661
15111
  return { content: [{ type: "text", text: "History is off (TINYPIVOT_HISTORY=0)." }] };
13662
15112
  if (!open)
13663
- return { content: [{ type: "text", text: withNotes(formatHistoryList(history.list(limit ?? 15))) }] };
15113
+ return { content: [{ type: "text", text: formatHistoryList(history.list(limit ?? 15)) }] };
13664
15114
  const { sessionKey } = resolveSessionContext(extra, true);
13665
15115
  try {
13666
15116
  const ds = await studio.reopen(open, { actor: "agent", why, sessionKey });
@@ -13831,6 +15281,13 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13831
15281
  };
13832
15282
  }
13833
15283
  ));
15284
+ const applyVisualTheme = (theme) => {
15285
+ if (!isPro2 && theme !== "code")
15286
+ return { theme: "code", proRequired: true, text: "Additional chart themes require TinyPivot Pro (https://tiny-pivot.com/pricing)." };
15287
+ const active = store.setVisualTheme(theme);
15288
+ notifyCompanion();
15289
+ return { theme: active, text: `TinyPivot theme set to **${active}** (saved to ~/.config/tinypivot/preferences.json).` };
15290
+ };
13834
15291
  server.registerTool(
13835
15292
  "set_visual_theme",
13836
15293
  {
@@ -13844,20 +15301,28 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13844
15301
  }
13845
15302
  },
13846
15303
  async ({ theme }) => {
13847
- if (!isPro2 && theme !== "code") {
13848
- return {
13849
- content: [{ type: "text", text: "Additional chart themes require TinyPivot Pro (https://tiny-pivot.com/pricing)." }],
13850
- structuredContent: { chartTheme: "code", proRequired: true }
13851
- };
13852
- }
13853
- const activeTheme = store.setVisualTheme(theme);
13854
- notifyCompanion();
15304
+ const result = applyVisualTheme(theme);
13855
15305
  return {
13856
- content: [{ type: "text", text: `TinyPivot theme set to **${activeTheme}** (saved to ~/.config/tinypivot/preferences.json).` }],
13857
- structuredContent: { chartTheme: activeTheme }
15306
+ content: [{ type: "text", text: result.text }],
15307
+ structuredContent: result.proRequired ? { chartTheme: "code", proRequired: true } : { chartTheme: result.theme }
13858
15308
  };
13859
15309
  }
13860
15310
  );
15311
+ server.registerPrompt(
15312
+ "theme",
15313
+ {
15314
+ title: "TinyPivot theme",
15315
+ description: `Switch TinyPivot's theme for terminal cards, charts and the Studio: ${CHART_THEME_IDS.join(", ")}.`,
15316
+ argsSchema: {
15317
+ name: optionalCompletable((value2) => CHART_THEME_IDS.filter((id) => id.startsWith(value2 ?? "")))
15318
+ }
15319
+ },
15320
+ ({ name }) => {
15321
+ const theme = CHART_THEME_IDS.find((id) => id === name?.trim().toLowerCase());
15322
+ const text = theme ? `${applyVisualTheme(theme).text} Confirm it to the user in one short line; no tool call is needed.` : `TinyPivot's theme is **${store.getVisualTheme()}**. Tell the user, in one short line, that they can pick one of: ${CHART_THEME_IDS.join(", ")} (for example /mcp__tinypivot__theme paper).`;
15323
+ return { messages: [{ role: "user", content: { type: "text", text } }] };
15324
+ }
15325
+ );
13861
15326
  widgetOnly(server.registerTool(
13862
15327
  "get_datasets_state",
13863
15328
  {
@@ -13903,6 +15368,7 @@ export {
13903
15368
  isProcessAlive,
13904
15369
  resolveCompanionUrl,
13905
15370
  runTuiCommand,
15371
+ STUDIO_IDLE_STOP_MS,
13906
15372
  startCompanionServer,
13907
15373
  buildPiExtensionSource,
13908
15374
  TINYPIVOT_CLAUDE_RULE_BLOCK,