@smallwebco/tinypivot-mcp 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  };
@@ -9617,6 +10801,21 @@ function datasetCard(dataset, options = {}) {
9617
10801
  function cardTitle(card) {
9618
10802
  return /╭─ (.+?) ─/.exec(card.replace(/\x1B\[[0-9;]*m/g, ""))?.[1] ?? null;
9619
10803
  }
10804
+ function describeChartForText(rows, config) {
10805
+ if (!config?.type || !config.xAxis || !config.yAxis)
10806
+ return [];
10807
+ const full = config;
10808
+ const lines = [];
10809
+ const story = full.options?.annotations === false ? null : buildChartStory(rows, full);
10810
+ if (story)
10811
+ lines.push(`Takeaway (computed from the data): ${story.headline}.`);
10812
+ if (full.type === "choropleth") {
10813
+ const unmatched = describeUnmatchedRegions(processChartDataForChoropleth(rows, full));
10814
+ if (unmatched)
10815
+ lines.push(`> **Map warning**: ${unmatched}`);
10816
+ }
10817
+ return lines;
10818
+ }
9620
10819
  function formatDatasetSummary(dataset, companionUrl, options = {}) {
9621
10820
  const cardOptions = { ...options, companionUrl: options.companionUrl ?? companionUrl };
9622
10821
  const chartBlock = smallGridTable(dataset) ?? datasetCard(dataset, cardOptions);
@@ -9634,6 +10833,9 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
9634
10833
  if (integrityWarning) {
9635
10834
  parts.push("", integrityWarning);
9636
10835
  }
10836
+ const chartText = describeChartForText(dataset.rows, dataset.chartConfig);
10837
+ if (chartText.length > 0)
10838
+ parts.push("", ...chartText);
9637
10839
  if (chartBlock) {
9638
10840
  parts.push("", chartBlock);
9639
10841
  const note = cardNote(companionUrl, options);
@@ -9710,7 +10912,7 @@ function formatPivotSummary(dataset, config, companionUrl, options = {}) {
9710
10912
  const topColsRule = `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u252C\u2500")}\u2500\u2524`;
9711
10913
  const midRule = `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`;
9712
10914
  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`;
10915
+ const formatRow = (cells2) => `\u2502 ${cells2.map((c, i) => i === 0 ? padEndVisual(c, widths[i]) : padStartVisual(c, widths[i])).join(" \u2502 ")} \u2502`;
9714
10916
  const showBranding = options.showBranding !== false;
9715
10917
  const metaRight = `${dataset.rows.length.toLocaleString()} rows \xB7 ${result.rowHeaders.length} groups`;
9716
10918
  const metaLeft = showBranding ? "tiny-pivot.com" : "";
@@ -10008,8 +11210,8 @@ function renderChartView(payload, pal, innerWidth, height, overrideChartType) {
10008
11210
  barOut = fg(pal.accent, rawBar) + " ".repeat(Math.max(0, barW - visualWidth(rawBar)));
10009
11211
  }
10010
11212
  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}`);
11213
+ const pct2 = grandTotal > 0 ? fg(pal.muted, `${(e.total / grandTotal * 100).toFixed(1).padStart(5)}%`) : "";
11214
+ lines.push(`${label} ${fg(pal.border, "\u2502")} ${barOut} ${valStr} ${pct2}`);
10013
11215
  }
10014
11216
  if (processed.categories.length > entries.length) {
10015
11217
  lines.push(fg(pal.muted, `\u2026 +${processed.categories.length - entries.length} more categories`));
@@ -10082,8 +11284,8 @@ function renderPivotView(payload, pal, innerWidth, height) {
10082
11284
  const topRule = fg(pal.border, `\u256D\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u252C\u2500")}\u2500\u256E`);
10083
11285
  const midRule = fg(pal.border, `\u251C\u2500${widths.map((w) => "\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`);
10084
11286
  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) => {
11287
+ const formatRow = (cells2, isHeader = false, isTotal = false) => {
11288
+ const rendered = cells2.map((cell, i) => {
10087
11289
  const padded = i === 0 ? padEndVisual(cell, widths[i]) : padStartVisual(cell, widths[i]);
10088
11290
  if (isHeader)
10089
11291
  return fgBold(pal.accent, padded);
@@ -10303,6 +11505,7 @@ var INTERACTIVE_ROW_LIMIT = 1e5;
10303
11505
  var ROW_PAGE_SIZE = 25e3;
10304
11506
 
10305
11507
  // src/companion.ts
11508
+ var STUDIO_IDLE_STOP_MS = 2 * 60 * 1e3;
10306
11509
  function isAllowedRequest(request, port) {
10307
11510
  const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
10308
11511
  if (!request.host || !allowedHosts.includes(request.host))
@@ -10467,14 +11670,22 @@ data: ${JSON.stringify(payload)}
10467
11670
  const text = typeof body.text === "string" ? body.text.trim() : "";
10468
11671
  if (!text || text.length > MAX_NOTE_CHARS)
10469
11672
  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 });
11673
+ try {
11674
+ const note = studio.addNote(text, {
11675
+ stepId: typeof body.stepId === "string" ? body.stepId : void 0,
11676
+ attachment: parseAttachment(body.attachment)
11677
+ });
11678
+ return sendJson(res, 200, { note });
11679
+ } catch (error) {
11680
+ return sendJson(res, 409, { error: errorMessage(error) });
11681
+ }
10475
11682
  }
10476
- if (pathname === "/api/studio/note/delete") {
10477
- return sendJson(res, 200, { removed: typeof body.id === "string" && studio.removeNote(body.id) });
11683
+ if (pathname === "/api/studio/verify") {
11684
+ try {
11685
+ return sendJson(res, 200, { checks: await studio.verifyStep(String(body.stepId ?? "")) });
11686
+ } catch (error) {
11687
+ return sendJson(res, 400, { error: errorMessage(error) });
11688
+ }
10478
11689
  }
10479
11690
  if (pathname === "/api/studio/reply") {
10480
11691
  const text = typeof body.text === "string" ? body.text.trim() : "";
@@ -10489,7 +11700,8 @@ data: ${JSON.stringify(payload)}
10489
11700
  }
10490
11701
  if (pathname === "/api/studio/show") {
10491
11702
  try {
10492
- const dataset = await studio.showStep(String(body.stepId ?? ""));
11703
+ const viewMode = body.viewMode === "grid" || body.viewMode === "chart" || body.viewMode === "pivot" ? body.viewMode : void 0;
11704
+ const dataset = await studio.showStep(String(body.stepId ?? ""), { viewMode });
10493
11705
  broadcastUpdate();
10494
11706
  return sendJson(res, 200, { datasetId: dataset.id });
10495
11707
  } catch (error) {
@@ -10508,6 +11720,8 @@ data: ${JSON.stringify(payload)}
10508
11720
  return sendJson(res, 404, { error: "Not found" });
10509
11721
  };
10510
11722
  let listenPort = 0;
11723
+ let closePromise = null;
11724
+ let idleTimer;
10511
11725
  const server = http.createServer(async (req, res) => {
10512
11726
  const urlObj = new URL(req.url || "/", "http://127.0.0.1");
10513
11727
  const pathname = urlObj.pathname;
@@ -10539,7 +11753,16 @@ data: ${JSON.stringify(studio.snapshot())}
10539
11753
 
10540
11754
  `);
10541
11755
  sseClients.add(res);
10542
- req.on("close", () => sseClients.delete(res));
11756
+ clearTimeout(idleTimer);
11757
+ req.on("close", () => {
11758
+ sseClients.delete(res);
11759
+ armIdleStop();
11760
+ });
11761
+ return;
11762
+ }
11763
+ if (req.method === "POST" && pathname === "/api/studio/stop") {
11764
+ sendJson(res, 200, { stopped: true });
11765
+ setImmediate(() => void stopSelf("stopped"));
10543
11766
  return;
10544
11767
  }
10545
11768
  if (req.method === "GET" && pathname === "/api/studio/agent-stream") {
@@ -10619,38 +11842,50 @@ data: ${JSON.stringify(studio.snapshot())}
10619
11842
  `, "utf8");
10620
11843
  } catch {
10621
11844
  }
10622
- let closePromise = null;
11845
+ function closeServer() {
11846
+ if (closePromise)
11847
+ return closePromise;
11848
+ clearTimeout(idleTimer);
11849
+ closePromise = (async () => {
11850
+ for (const client of sseClients) {
11851
+ try {
11852
+ client.end();
11853
+ } catch {
11854
+ }
11855
+ }
11856
+ sseClients.clear();
11857
+ await new Promise((resolve) => {
11858
+ server.close(() => resolve());
11859
+ server.closeAllConnections();
11860
+ });
11861
+ try {
11862
+ const raw = await fs3.readFile(sessionFile, "utf8");
11863
+ const parsed = JSON.parse(raw);
11864
+ if (parsed.pid === process.pid) {
11865
+ await fs3.unlink(sessionFile);
11866
+ }
11867
+ } catch {
11868
+ }
11869
+ })();
11870
+ return closePromise;
11871
+ }
11872
+ async function stopSelf(reason) {
11873
+ await closeServer();
11874
+ options.onStopped?.(reason);
11875
+ }
11876
+ function armIdleStop() {
11877
+ clearTimeout(idleTimer);
11878
+ if (!options.idleStopMs || sseClients.size > 0 || closePromise)
11879
+ return;
11880
+ idleTimer = setTimeout(() => void stopSelf("idle"), options.idleStopMs);
11881
+ idleTimer.unref();
11882
+ }
10623
11883
  return {
10624
11884
  url,
10625
11885
  port: address.port,
10626
11886
  broadcastUpdate,
10627
11887
  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
- }
11888
+ close: closeServer
10654
11889
  };
10655
11890
  }
10656
11891
 
@@ -12055,9 +13290,127 @@ async function executeReadOnlyPostgresQuery(config, sql) {
12055
13290
  }
12056
13291
 
12057
13292
  // src/studio.ts
13293
+ import crypto from "crypto";
12058
13294
  import fs7 from "fs";
12059
13295
  import path7 from "path";
12060
13296
 
13297
+ // src/claims.ts
13298
+ var NUMBER_RE = /(?<![\w.-])([$€£]?)(-?)(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?\s?([KMB])?(%)?(?![\w-])/g;
13299
+ var SCALE = { K: 1e3, M: 1e6, B: 1e9 };
13300
+ var MIN_PLAIN_VALUE = 10;
13301
+ var MAX_ROWS_PER_SOURCE = 2e4;
13302
+ var MAX_CLAIMS = 40;
13303
+ function parseNumber(match) {
13304
+ const [text, currency, minus, whole, fraction = "", suffix, percent2] = match;
13305
+ const isYear = !currency && !suffix && !percent2 && !fraction && /^(?:19|20)\d{2}$/.test(whole);
13306
+ if (isYear)
13307
+ return null;
13308
+ const scale = suffix ? SCALE[suffix] : 1;
13309
+ const unsigned = Number(`${whole.replace(/,/g, "")}.${fraction || "0"}`);
13310
+ const value2 = (minus ? -1 : 1) * unsigned * scale;
13311
+ if (!percent2 && !suffix && Math.abs(value2) < MIN_PLAIN_VALUE)
13312
+ return null;
13313
+ const tolerance = 0.5 * 10 ** -fraction.length * scale;
13314
+ return { text: text.trim(), value: value2, tolerance, percent: Boolean(percent2) };
13315
+ }
13316
+ function extractNumbers(text) {
13317
+ const seen = /* @__PURE__ */ new Set();
13318
+ const out = [];
13319
+ for (const match of text.matchAll(NUMBER_RE)) {
13320
+ const parsed = parseNumber(match);
13321
+ if (parsed && !seen.has(parsed.text)) {
13322
+ seen.add(parsed.text);
13323
+ out.push(parsed);
13324
+ }
13325
+ if (out.length >= MAX_CLAIMS)
13326
+ break;
13327
+ }
13328
+ return out;
13329
+ }
13330
+ var SUMMARY_MAX_ROWS = 1e3;
13331
+ var MAX_GROUPS = 50;
13332
+ var PERCENT_COLUMN_RE = /pct|percent|share|rate|ratio|%/i;
13333
+ function rowLabel(row) {
13334
+ const label = Object.values(row).find((value2) => typeof value2 === "string" && value2.trim() !== "");
13335
+ return typeof label === "string" ? label : "";
13336
+ }
13337
+ var IS_TYPE = {
13338
+ number: (value2) => typeof value2 === "number",
13339
+ string: (value2) => typeof value2 === "string"
13340
+ };
13341
+ function columnsOf(rows, type) {
13342
+ const first = rows.find((row) => row && typeof row === "object") ?? {};
13343
+ return Object.keys(first).filter((column) => rows.some((row) => IS_TYPE[type](row[column])));
13344
+ }
13345
+ function sumOf(rows, column) {
13346
+ return rows.reduce((sum, row) => sum + (typeof row[column] === "number" ? row[column] : 0), 0);
13347
+ }
13348
+ function groupTotals(rows, dimensions, measure, total, pool) {
13349
+ for (const dimension of dimensions) {
13350
+ const groups = /* @__PURE__ */ new Map();
13351
+ for (const row of rows) {
13352
+ const key = row[dimension];
13353
+ if (typeof key === "string" && typeof row[measure] === "number")
13354
+ groups.set(key, (groups.get(key) ?? 0) + row[measure]);
13355
+ if (groups.size > MAX_GROUPS)
13356
+ break;
13357
+ }
13358
+ if (groups.size > MAX_GROUPS)
13359
+ continue;
13360
+ for (const [key, sum] of groups) {
13361
+ pool.values.push({ value: sum, where: `${measure} \xB7 ${key} (all ${dimension})` });
13362
+ if (total !== 0)
13363
+ pool.percents.push({ value: sum / total * 100, where: `share of ${measure} \xB7 ${key}` });
13364
+ }
13365
+ }
13366
+ }
13367
+ function cells(rows, measure, total, pool) {
13368
+ const isPercent = PERCENT_COLUMN_RE.test(measure);
13369
+ for (const row of rows) {
13370
+ const cell = row[measure];
13371
+ if (typeof cell !== "number")
13372
+ continue;
13373
+ const label = rowLabel(row);
13374
+ const where = label ? `${measure} \xB7 ${label}` : measure;
13375
+ pool.values.push({ value: cell, where });
13376
+ if (isPercent)
13377
+ pool.percents.push({ value: cell, where });
13378
+ else if (total !== 0)
13379
+ pool.percents.push({ value: cell / total * 100, where: `share of ${measure} \xB7 ${label || "total"}` });
13380
+ }
13381
+ }
13382
+ function candidatesFor(source) {
13383
+ const pool = { values: [], percents: [] };
13384
+ const rows = source.rows.slice(0, MAX_ROWS_PER_SOURCE);
13385
+ const summary = source.rows.length <= SUMMARY_MAX_ROWS;
13386
+ const dimensions = summary ? columnsOf(rows, "string") : source.dimensions ?? [];
13387
+ for (const measure of columnsOf(rows, "number")) {
13388
+ const total = sumOf(rows, measure);
13389
+ if (summary)
13390
+ cells(rows, measure, total, pool);
13391
+ pool.values.push({ value: total, where: `${measure} \xB7 total of ${source.name}` });
13392
+ groupTotals(rows, dimensions, measure, total, pool);
13393
+ }
13394
+ return pool;
13395
+ }
13396
+ function closest(claim, candidates) {
13397
+ return candidates.find((candidate) => Math.abs(candidate.value - claim.value) <= claim.tolerance + 1e-9);
13398
+ }
13399
+ function checkClaims(text, sources) {
13400
+ const claims = extractNumbers(text);
13401
+ if (claims.length === 0 || sources.length === 0)
13402
+ return [];
13403
+ const pools = sources.map(candidatesFor);
13404
+ const values = pools.flatMap((pool) => pool.values);
13405
+ const percents = pools.flatMap((pool) => pool.percents);
13406
+ return claims.map((claim) => {
13407
+ const match = closest(claim, claim.percent ? percents : values);
13408
+ if (match)
13409
+ return { text: claim.text, status: "found", where: match.where };
13410
+ return { text: claim.text, status: claim.percent ? "unchecked" : "not-found" };
13411
+ });
13412
+ }
13413
+
12061
13414
  // src/duckdb.ts
12062
13415
  import { spawn } from "child_process";
12063
13416
  import fs5 from "fs";
@@ -12206,6 +13559,7 @@ import path6 from "path";
12206
13559
  import zlib from "zlib";
12207
13560
  var HISTORY_MAX_SAVED_ROWS = 2e5;
12208
13561
  var DEFAULT_RETENTION_DAYS = 30;
13562
+ var SESSIONS_DIR = "sessions";
12209
13563
  function defaultHistoryDir() {
12210
13564
  const base = process.env.XDG_DATA_HOME || path6.join(os5.homedir(), ".local", "share");
12211
13565
  return path6.join(base, "tinypivot", "history");
@@ -12287,11 +13641,24 @@ var HistoryStore = class {
12287
13641
  throw new Error(`History entry ${entry.id} has no saved rows.`);
12288
13642
  return zlib.gunzipSync(fs6.readFileSync(file)).toString("utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
12289
13643
  }
12290
- /** Deletes entries older than the retention window. Returns how many were removed. */
13644
+ /** Removes conversation traces last written before `cutoff`, and the old trace every session shared. */
13645
+ pruneTraces(cutoff) {
13646
+ fs6.rmSync(path6.join(this.dir, "trace.jsonl"), { force: true });
13647
+ const sessions = path6.join(this.dir, SESSIONS_DIR);
13648
+ if (!fs6.existsSync(sessions))
13649
+ return;
13650
+ for (const file of fs6.readdirSync(sessions)) {
13651
+ const full = path6.join(sessions, file);
13652
+ if (fs6.statSync(full).mtimeMs < cutoff)
13653
+ fs6.rmSync(full, { force: true });
13654
+ }
13655
+ }
13656
+ /** Deletes entries and conversation traces older than the retention window. Returns how many entries were removed. */
12291
13657
  prune(now = /* @__PURE__ */ new Date()) {
12292
13658
  if (!fs6.existsSync(this.dir))
12293
13659
  return 0;
12294
13660
  const cutoff = now.getTime() - this.retentionDays * 24 * 60 * 60 * 1e3;
13661
+ this.pruneTraces(cutoff);
12295
13662
  let removed = 0;
12296
13663
  for (const entry of this.list()) {
12297
13664
  if (new Date(entry.createdAt).getTime() >= cutoff)
@@ -12319,6 +13686,7 @@ function formatHistoryList(entries) {
12319
13686
  var STEPS_IN_MEMORY = 300;
12320
13687
  var HISTORY_IN_SNAPSHOT = 50;
12321
13688
  var ATTACHMENT_MAX_CHARS = 6e3;
13689
+ var ASK_MAX_CHARS = 500;
12322
13690
  var AGENT_NAMES = {
12323
13691
  "claude-code": "Claude Code",
12324
13692
  "claude-ai": "Claude Desktop",
@@ -12348,6 +13716,11 @@ function describeView(dataset) {
12348
13716
  }
12349
13717
  return "table";
12350
13718
  }
13719
+ function viewDimensions(dataset) {
13720
+ const chart = dataset.chartConfig;
13721
+ const pivot = dataset.pivotConfig;
13722
+ return [chart?.xAxis?.field, chart?.seriesField?.field, ...pivot?.rowFields ?? [], ...pivot?.columnFields ?? []].filter((field) => Boolean(field));
13723
+ }
12351
13724
  function whereSql(where) {
12352
13725
  return where.map((filter) => `CAST(${quoteIdentifier(filter.field)} AS VARCHAR) IN (${filter.equals.map((value2) => quoteLiteral(String(value2))).join(", ")})`).join(" AND ");
12353
13726
  }
@@ -12379,7 +13752,31 @@ function withoutCards(text) {
12379
13752
  const stripped = text.replace(/```text\n[\s\S]*?```\n?/g, (block) => /[╭╰│┤├]/.test(block) ? "" : block);
12380
13753
  return stripped.replace(/\n{3,}/g, "\n\n").trim() || text.trim();
12381
13754
  }
13755
+ function fingerprintRows(rows) {
13756
+ const rowHashes = rows.map((row) => crypto.createHash("sha1").update(JSON.stringify(row, (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2)).digest("hex"));
13757
+ rowHashes.sort();
13758
+ return { rows: rows.length, hash: crypto.createHash("sha256").update(rowHashes.join("")).digest("hex").slice(0, 16) };
13759
+ }
13760
+ function sourceFile(file) {
13761
+ try {
13762
+ const stat = fs7.statSync(file);
13763
+ return { file, bytes: stat.size, modifiedAt: stat.mtime.toISOString() };
13764
+ } catch {
13765
+ return void 0;
13766
+ }
13767
+ }
13768
+ function checkSource(then) {
13769
+ const now = sourceFile(then.file);
13770
+ if (!now)
13771
+ return { kind: "source", ok: false, detail: "The file is gone or cannot be read." };
13772
+ const ok = now.bytes === then.bytes && now.modifiedAt === then.modifiedAt;
13773
+ 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}.` };
13774
+ }
12382
13775
  var sequence = 0;
13776
+ function newSessionId() {
13777
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
13778
+ return `${stamp}-${process.pid.toString(36)}${Math.random().toString(36).slice(2, 6)}`;
13779
+ }
12383
13780
  function nextId(prefix) {
12384
13781
  sequence += 1;
12385
13782
  return `${prefix}-${Date.now().toString(36)}-${sequence.toString(36)}`;
@@ -12389,12 +13786,12 @@ var Studio = class {
12389
13786
  this.store = store;
12390
13787
  this.history = options.history ?? new HistoryStore();
12391
13788
  this.duck = options.duck ?? new DuckDbRunner();
13789
+ this.sessionId = options.sessionId ?? newSessionId();
12392
13790
  this.steps = this.readTraceFile();
12393
13791
  }
12394
13792
  history;
12395
13793
  duck;
12396
13794
  steps = [];
12397
- notes = [];
12398
13795
  pullsByDataset = /* @__PURE__ */ new Map();
12399
13796
  listeners = /* @__PURE__ */ new Set();
12400
13797
  changeQueued = false;
@@ -12403,6 +13800,11 @@ var Studio = class {
12403
13800
  agentName;
12404
13801
  agentBusy = false;
12405
13802
  agentHint;
13803
+ /**
13804
+ * Which conversation this Studio belongs to. Each server process is one conversation, so its
13805
+ * trace is its own: other sessions, harnesses and tools running on the machine never show up here.
13806
+ */
13807
+ sessionId;
12406
13808
  /** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
12407
13809
  subscribe(listener) {
12408
13810
  this.listeners.add(listener);
@@ -12424,7 +13826,6 @@ var Studio = class {
12424
13826
  ...step,
12425
13827
  editableSql: step.sql ?? (step.file ? fileStepSql(step.file, step.where) : void 0)
12426
13828
  })),
12427
- notes: this.pendingNotes(),
12428
13829
  history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
12429
13830
  historyEnabled: this.history.enabled,
12430
13831
  loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id),
@@ -12449,7 +13850,7 @@ var Studio = class {
12449
13850
  this.changed();
12450
13851
  }
12451
13852
  get traceFile() {
12452
- return path7.join(this.history.dir, "trace.jsonl");
13853
+ return path7.join(this.history.dir, SESSIONS_DIR, `${this.sessionId}.jsonl`);
12453
13854
  }
12454
13855
  readTraceFile() {
12455
13856
  if (!this.history.enabled || !fs7.existsSync(this.traceFile))
@@ -12466,7 +13867,7 @@ var Studio = class {
12466
13867
  if (!this.history.enabled)
12467
13868
  return;
12468
13869
  try {
12469
- fs7.mkdirSync(this.history.dir, { recursive: true });
13870
+ fs7.mkdirSync(path7.dirname(this.traceFile), { recursive: true });
12470
13871
  fs7.appendFileSync(this.traceFile, `${JSON.stringify(step)}
12471
13872
  `);
12472
13873
  if (fs7.statSync(this.traceFile).size > TRACE_FILE_MAX_BYTES)
@@ -12486,13 +13887,18 @@ var Studio = class {
12486
13887
  this.changed();
12487
13888
  return full;
12488
13889
  }
12489
- /** Records a step about a dataset, filling in its name, size, view and saved pull. */
13890
+ /** Records a step about a dataset, filling in its name, size, columns, fingerprint, view and saved pull. */
12490
13891
  recordDatasetStep(dataset, step) {
13892
+ const source = step.file ? sourceFile(step.file) : void 0;
12491
13893
  return this.record({
12492
13894
  ...step,
13895
+ ...step.ask?.trim() ? { ask: step.ask.trim().slice(0, ASK_MAX_CHARS) } : { ask: void 0 },
12493
13896
  datasetId: dataset.id,
12494
13897
  datasetName: dataset.name,
12495
13898
  rows: dataset.rows.length,
13899
+ columns: dataset.columns.map((column) => column.name),
13900
+ fingerprint: fingerprintRows(dataset.rows),
13901
+ ...source ? { source } : {},
12496
13902
  view: describeView(dataset),
12497
13903
  viewMode: dataset.viewMode,
12498
13904
  ...dataset.chartConfig ? { chartConfig: structuredClone(dataset.chartConfig) } : {},
@@ -12502,9 +13908,11 @@ var Studio = class {
12502
13908
  }
12503
13909
  /**
12504
13910
  * 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.
13911
+ * no longer loaded; `viewMode` shows it another way, e.g. its rows. Looking is not a step, so
13912
+ * nothing is recorded.
12506
13913
  */
12507
- async showStep(stepId, sessionKey = DEFAULT_SESSION_KEY) {
13914
+ async showStep(stepId, options = {}) {
13915
+ const sessionKey = options.sessionKey ?? DEFAULT_SESSION_KEY;
12508
13916
  const step = this.steps.find((s) => s.id === stepId);
12509
13917
  if (!step?.datasetId)
12510
13918
  throw new Error("That step has no data to show.");
@@ -12514,8 +13922,9 @@ var Studio = class {
12514
13922
  throw new Error("That data is no longer loaded and was not saved to history.");
12515
13923
  dataset = await this.reopen(step.historyId, { actor: "user", sessionKey, record: false });
12516
13924
  }
13925
+ const viewMode = options.viewMode ?? step.viewMode;
12517
13926
  return this.store.updateView(dataset.id, {
12518
- ...step.viewMode ? { viewMode: step.viewMode } : {},
13927
+ ...viewMode ? { viewMode } : {},
12519
13928
  ...step.chartConfig ? { chartConfig: { ...step.chartConfig, seriesField: step.chartConfig.seriesField } } : {},
12520
13929
  ...step.pivotConfig ? { pivotConfig: step.pivotConfig } : {}
12521
13930
  }, sessionKey) ?? dataset;
@@ -12555,7 +13964,7 @@ var Studio = class {
12555
13964
  });
12556
13965
  const shown = this.keepViewOf(input.viewFromStepId, dataset, sessionKey) ?? dataset;
12557
13966
  this.remember(shown, { kind: "query", source: input.sql });
12558
- this.recordDatasetStep(shown, { actor: input.actor, tool: "query", why: input.why, sql: input.sql });
13967
+ this.recordDatasetStep(shown, { actor: input.actor, tool: "query", why: input.why, ask: input.ask, sql: input.sql });
12559
13968
  return { dataset: shown, truncated: result.truncated };
12560
13969
  }
12561
13970
  /** Gives `dataset` the view of the step's dataset when every field that view uses is in the result. */
@@ -12598,8 +14007,8 @@ var Studio = class {
12598
14007
  return dataset;
12599
14008
  }
12600
14009
  /**
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.
14010
+ * Sends the user's message straight into the agent's conversation. Throws when no live
14011
+ * connector takes it: the Studio only offers to send when the agent can receive.
12603
14012
  */
12604
14013
  addNote(text, options = {}) {
12605
14014
  const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
@@ -12607,57 +14016,73 @@ var Studio = class {
12607
14016
  id: nextId("note"),
12608
14017
  at: (/* @__PURE__ */ new Date()).toISOString(),
12609
14018
  text: text.trim(),
12610
- delivery: "queued",
12611
14019
  ...options.stepId ? { stepId: options.stepId } : {},
12612
14020
  ...attachment ? { attachment } : {}
12613
14021
  };
12614
- if (this.agent.push(note, this.describeNote(note, { withSource: true })))
12615
- note.delivery = "live";
12616
- else
12617
- this.notes.push(note);
14022
+ if (!this.agent.push(note, this.describeNote(note)))
14023
+ throw new Error(`${this.agentName ? agentLabel(this.agentName) : "Your agent"} cannot receive messages from the Studio. Ask in your terminal instead.`);
12618
14024
  this.record({ actor: "user", tool: "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
12619
14025
  return note;
12620
14026
  }
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 } = {}) {
14027
+ /** How a message reads to the agent: where it came from, the text, the step it is about, and any attached data. */
14028
+ describeNote(note) {
12626
14029
  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}`];
14030
+ const lines = [`Message from the user in TinyPivot Studio: ${note.text}`];
12629
14031
  if (step)
12630
14032
  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
14033
  if (note.attachment)
12632
14034
  lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
12633
14035
  return lines.join("\n");
12634
14036
  }
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")}`;
14037
+ /**
14038
+ * The agent's answer to a Studio message, recorded where the user reads it, with each number it
14039
+ * quotes checked against the data loaded since the user last asked something.
14040
+ */
14041
+ reply(text, sessionKey = DEFAULT_SESSION_KEY) {
14042
+ const answer = withoutCards(text);
14043
+ const claims = checkClaims(answer, this.datasetsSinceLastAsk(sessionKey));
14044
+ return this.record({ actor: "agent", tool: "reply", why: answer, ...claims.length ? { claims } : {} });
14045
+ }
14046
+ /** The datasets the current question has used and that are still loaded, newest first. */
14047
+ datasetsSinceLastAsk(sessionKey) {
14048
+ let lastAsk = this.steps.length - 1;
14049
+ while (lastAsk > 0 && !(this.steps[lastAsk].actor === "user" && (this.steps[lastAsk].tool === "note" || this.steps[lastAsk].tool === "query")))
14050
+ lastAsk--;
14051
+ const ids = new Set(this.steps.slice(Math.max(0, lastAsk)).flatMap((step) => step.datasetId ? [step.datasetId] : []));
14052
+ return [...ids].reverse().flatMap((id) => {
14053
+ const dataset = this.store.get(id, sessionKey);
14054
+ return dataset ? [{ name: dataset.name, rows: dataset.rows, dimensions: viewDimensions(dataset) }] : [];
14055
+ });
14056
+ }
14057
+ /**
14058
+ * Re-checks a step: whether its source file is unchanged, and whether running its SQL again gives
14059
+ * the same rows. Results of queries are compared value by value (row order ignored); a file load
14060
+ * is compared by row count, since the file reader and SQL may type the same column differently.
14061
+ */
14062
+ async verifyStep(stepId, sessionKey = DEFAULT_SESSION_KEY) {
14063
+ const step = this.steps.find((s) => s.id === stepId);
14064
+ if (!step)
14065
+ throw new Error("That step is no longer in the trace.");
14066
+ const checks = [];
14067
+ if (step.source)
14068
+ checks.push(checkSource(step.source));
14069
+ const sql = step.sql ?? (step.file ? fileStepSql(step.file, step.where) : void 0);
14070
+ if (sql && step.fingerprint)
14071
+ checks.push(await this.checkRerun(sql, step, sessionKey));
14072
+ return checks;
14073
+ }
14074
+ async checkRerun(sql, step, sessionKey) {
14075
+ const expected = step.fingerprint;
14076
+ try {
14077
+ const result = await this.duck.run(sql, this.queryViews(sessionKey));
14078
+ const again = fingerprintRows(result.rows);
14079
+ if (step.tool !== "query" && step.tool !== "query_postgres")
14080
+ 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")}.` };
14081
+ const ok = again.rows === expected.rows && again.hash === expected.hash;
14082
+ 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" : ""}.` };
14083
+ } catch (error) {
14084
+ return { kind: "rerun", ok: false, detail: `Could not run it again: ${error instanceof Error ? error.message : String(error)}` };
14085
+ }
12661
14086
  }
12662
14087
  };
12663
14088
 
@@ -12666,6 +14091,7 @@ import fsSync3 from "fs";
12666
14091
  import fs8 from "fs/promises";
12667
14092
  import path9 from "path";
12668
14093
  import { fileURLToPath as fileURLToPath2 } from "url";
14094
+ import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
12669
14095
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12670
14096
  import { z } from "zod";
12671
14097
 
@@ -12769,12 +14195,12 @@ function formatProfile(dataset) {
12769
14195
  }
12770
14196
 
12771
14197
  // src/telemetry.ts
12772
- import crypto from "crypto";
14198
+ import crypto2 from "crypto";
12773
14199
  import fsSync2 from "fs";
12774
14200
  import os6 from "os";
12775
14201
  import path8 from "path";
12776
14202
  var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
12777
- var PACKAGE_VERSION = "0.6.1";
14203
+ var PACKAGE_VERSION = "0.7.0";
12778
14204
  function isTelemetryEnabled() {
12779
14205
  if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
12780
14206
  return false;
@@ -12810,7 +14236,7 @@ function getAnonymousId() {
12810
14236
  }
12811
14237
  } catch {
12812
14238
  }
12813
- const fresh = crypto.randomUUID();
14239
+ const fresh = crypto2.randomUUID();
12814
14240
  cachedAnonId = fresh;
12815
14241
  try {
12816
14242
  fsSync2.mkdirSync(path8.dirname(prefPath), { recursive: true });
@@ -12856,11 +14282,12 @@ var LOAD_DATA_ROW_GUIDE = 50;
12856
14282
  function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
12857
14283
  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
14284
  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.",
14285
+ "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
14286
  `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.`,
14287
+ `Chart types: ${CHART_TYPES.map((t) => t.type).join(", ")}; names like map also work. seriesField: slope period, treemap parent; targetField: bullet target.`,
12861
14288
  "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
14289
  "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.",
14290
+ "On every data call pass why (one short sentence for TinyPivot Studio); when loading or querying, also ask (the user's request, verbatim).",
12864
14291
  ...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply.'] : [],
12865
14292
  cards
12866
14293
  ].join(" ");
@@ -12878,21 +14305,17 @@ var AGGREGATION_VALUES = [
12878
14305
  "stdDev",
12879
14306
  "percentOfTotal"
12880
14307
  ];
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
- ];
14308
+ var chartTypeSchema = z.string().optional().superRefine((value2, ctx) => {
14309
+ if (value2 !== void 0 && !resolveChartType(value2))
14310
+ ctx.addIssue({ code: "custom", message: `Unknown chart type "${value2}". Use one of: ${CHART_TYPES.map((t) => t.type).join(", ")}.` });
14311
+ });
14312
+ var GEOGRAPHY_VALUES = ["auto", "world", "us-states"];
12893
14313
  var CHART_AGG_VALUES = ["sum", "avg", "count", "min", "max"];
12894
14314
  var VIEW_MODE_VALUES = ["grid", "pivot", "chart"];
12895
14315
  var VISUAL_THEME_VALUES = CHART_THEME_IDS;
14316
+ function optionalCompletable(complete) {
14317
+ return completable(completable(z.string(), complete).optional(), complete);
14318
+ }
12896
14319
  var pivotValueSchema = z.object({
12897
14320
  field: z.string(),
12898
14321
  aggregation: z.enum(AGGREGATION_VALUES).default("sum")
@@ -12908,14 +14331,22 @@ var pivotConfigSchema = z.object({
12908
14331
  showRowTotals: z.boolean().default(true),
12909
14332
  showColumnTotals: z.boolean().default(true)
12910
14333
  });
12911
- var chartConfigSchema = z.object({
12912
- type: z.enum(CHART_TYPE_VALUES).default("bar"),
14334
+ var chartFieldShape = {
14335
+ type: chartTypeSchema,
12913
14336
  xAxisField: z.string().describe("Category or date column"),
12914
- yAxisField: z.string().describe("Column to aggregate"),
14337
+ yAxisField: z.string(),
12915
14338
  aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
12916
- seriesField: z.string().optional().describe("Column to split into series"),
14339
+ seriesField: z.string().optional(),
14340
+ targetField: z.string().optional(),
12917
14341
  title: z.string().optional()
12918
- });
14342
+ };
14343
+ var chartStyleShape = {
14344
+ geography: z.enum(GEOGRAPHY_VALUES).optional(),
14345
+ annotations: z.boolean().optional(),
14346
+ variant: z.enum(["editorial", "deck"]).optional(),
14347
+ footnote: z.string().optional()
14348
+ };
14349
+ var loadChartSchema = z.object(chartFieldShape);
12919
14350
  function extractSessionKey(extra) {
12920
14351
  if (!extra || typeof extra !== "object")
12921
14352
  return void 0;
@@ -12951,29 +14382,38 @@ function normalizePivot(pivotConfig) {
12951
14382
  function extensionHint(agent, status) {
12952
14383
  const name = agentLabel(agent);
12953
14384
  if (status === "updated")
12954
- return `TinyPivot's ${name} extension was just updated. Restart ${name} to send messages live.`;
14385
+ return { text: `TinyPivot's ${name} extension was just updated. Restart ${name} to send messages live.` };
12955
14386
  if (status === "absent")
12956
- return `Run npx @smallwebco/tinypivot-mcp@latest init --targets=${agent}, then restart ${name}, to send messages live.`;
14387
+ return { text: `Install TinyPivot's ${name} extension, then restart ${name}, to send messages live:`, command: `npx @smallwebco/tinypivot-mcp@latest init --targets=${agent}` };
12957
14388
  return void 0;
12958
14389
  }
14390
+ var CLAUDE_CHANNEL_HINT = {
14391
+ text: "To send messages live, restart Claude Code into this same conversation with TinyPivot's channel:",
14392
+ command: "claude --continue --dangerously-load-development-channels server:tinypivot"
14393
+ };
12959
14394
  var whyParam = z.string().max(240).optional();
14395
+ var askParam = z.string().optional();
12960
14396
  var DUCKDB_WAIT_MS = 45e3;
12961
- function toCoreChartConfig(input) {
14397
+ function toCoreChartConfig(input, source) {
14398
+ const type = resolveChartType(input.type ?? "bar") ?? "bar";
14399
+ const aggregation = input.aggregation;
12962
14400
  return {
12963
- type: input.type,
14401
+ type,
12964
14402
  xAxis: { field: input.xAxisField, role: "dimension" },
12965
- yAxis: {
12966
- field: input.yAxisField,
12967
- role: "measure",
12968
- aggregation: input.aggregation
12969
- },
14403
+ yAxis: { field: input.yAxisField, role: "measure", aggregation },
12970
14404
  seriesField: input.seriesField ? { field: input.seriesField, role: "dimension" } : void 0,
14405
+ targetField: input.targetField ? { field: input.targetField, role: "measure", aggregation } : void 0,
12971
14406
  options: {
12972
14407
  title: input.title ?? "",
12973
14408
  showLegend: true,
12974
14409
  showDataLabels: false,
12975
14410
  showGrid: true,
12976
- stacked: input.type === "stackedBar"
14411
+ stacked: type === "stackedBar",
14412
+ ...input.geography ? { geography: input.geography } : {},
14413
+ ...input.annotations === void 0 ? {} : { annotations: input.annotations },
14414
+ ...source ? { source } : {},
14415
+ ...input.variant ? { variant: input.variant } : {},
14416
+ ...input.footnote ? { footnote: input.footnote } : {}
12977
14417
  }
12978
14418
  };
12979
14419
  }
@@ -13099,7 +14539,7 @@ function createTinyPivotMcpServer(options = {}) {
13099
14539
  const server = new McpServer(
13100
14540
  {
13101
14541
  name: "tinypivot",
13102
- version: "0.6.1"
14542
+ version: "0.7.0"
13103
14543
  },
13104
14544
  {
13105
14545
  capabilities: {
@@ -13128,7 +14568,7 @@ function createTinyPivotMcpServer(options = {}) {
13128
14568
  };
13129
14569
  const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
13130
14570
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13131
- const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`);
14571
+ const summaryText = `${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`;
13132
14572
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
13133
14573
  recordTelemetry({
13134
14574
  event: "tool_call",
@@ -13147,7 +14587,6 @@ function createTinyPivotMcpServer(options = {}) {
13147
14587
  } catch (error) {
13148
14588
  console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
13149
14589
  }
13150
- const withNotes = (text) => `${text}${studio.takeNotes()}`;
13151
14590
  const connectAgent = () => {
13152
14591
  const clientName = server.server.getClientVersion()?.name;
13153
14592
  studio.setAgentName(clientName);
@@ -13155,7 +14594,7 @@ function createTinyPivotMcpServer(options = {}) {
13155
14594
  void refreshAgentExtension(clientName).then((status) => studio.setAgentHint(extensionHint(clientName, status))).catch(() => {
13156
14595
  });
13157
14596
  if (clientName === "claude-code" && !claudeChannel)
13158
- studio.setAgentHint("Start Claude Code with --dangerously-load-development-channels server:tinypivot to send messages live.");
14597
+ studio.setAgentHint(CLAUDE_CHANNEL_HINT);
13159
14598
  if (claudeChannel) {
13160
14599
  studio.agent.connect({
13161
14600
  name: "Claude Code channel",
@@ -13320,20 +14759,21 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13320
14759
  filePath: z.string(),
13321
14760
  name: z.string().optional(),
13322
14761
  why: whyParam,
14762
+ ask: askParam,
13323
14763
  where: z.array(rowFilterSchema).optional().describe('Keep only matching rows, e.g. [{"field":"year","equals":[2026]}]'),
13324
14764
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13325
14765
  pivotConfig: pivotConfigSchema.optional(),
13326
- chartConfig: chartConfigSchema.optional(),
14766
+ chartConfig: loadChartSchema.optional(),
13327
14767
  keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
13328
14768
  },
13329
14769
  _meta: INLINE_UI_META
13330
14770
  },
13331
- async ({ filePath, name, why, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
14771
+ async ({ filePath, name, why, ask, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13332
14772
  try {
13333
14773
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
13334
14774
  const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
13335
14775
  studio.remember(ds, { kind: "file", source: ds.source, where });
13336
- const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
14776
+ const explicitChart = chartConfig ? toCoreChartConfig(chartConfig, ds.name) : void 0;
13337
14777
  if (pivotConfig) {
13338
14778
  const normalizedPivot = normalizePivot(pivotConfig);
13339
14779
  store.updateView(ds.id, {
@@ -13347,7 +14787,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13347
14787
  ...explicitChart ? { chartConfig: explicitChart } : {}
13348
14788
  }, sessionKey);
13349
14789
  }
13350
- studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, file: ds.source, where });
14790
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, ask, file: ds.source, where });
13351
14791
  return replyWithDataset(ds, sessionKey, "load_file");
13352
14792
  } catch (err) {
13353
14793
  return {
@@ -13365,16 +14805,17 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13365
14805
  inputSchema: {
13366
14806
  name: z.string(),
13367
14807
  why: whyParam,
14808
+ ask: askParam,
13368
14809
  rows: z.array(z.record(z.string(), z.unknown())),
13369
14810
  source: z.string().optional(),
13370
14811
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13371
14812
  pivotConfig: pivotConfigSchema.optional(),
13372
- chartConfig: chartConfigSchema.optional(),
14813
+ chartConfig: loadChartSchema.optional(),
13373
14814
  keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
13374
14815
  },
13375
14816
  _meta: INLINE_UI_META
13376
14817
  },
13377
- async ({ name, why, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
14818
+ async ({ name, why, ask, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13378
14819
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
13379
14820
  const ds = store.register({
13380
14821
  name,
@@ -13383,12 +14824,12 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13383
14824
  rows,
13384
14825
  viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
13385
14826
  pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
13386
- chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
14827
+ chartConfig: chartConfig ? toCoreChartConfig(chartConfig, source ? `${name} (${source})` : name) : void 0,
13387
14828
  sessionKey,
13388
14829
  keepExisting: shouldKeep
13389
14830
  });
13390
14831
  studio.remember(ds, { kind: "data", source: source ?? "inline JSON" });
13391
- studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why });
14832
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why, ask });
13392
14833
  return replyWithDataset(ds, sessionKey, "load_data");
13393
14834
  }
13394
14835
  );
@@ -13433,7 +14874,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13433
14874
  chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
13434
14875
  }, sessionKey);
13435
14876
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13436
- const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat()));
14877
+ const summary = formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat());
13437
14878
  studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
13438
14879
  const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
13439
14880
  const payload = buildAppPayload(ds, store, {
@@ -13462,18 +14903,15 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13462
14903
  description: "Chart the active dataset.",
13463
14904
  inputSchema: {
13464
14905
  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(),
14906
+ ...chartFieldShape,
14907
+ ...chartStyleShape,
13471
14908
  why: whyParam,
13472
14909
  chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
13473
14910
  },
13474
14911
  _meta: INLINE_UI_META
13475
14912
  },
13476
- async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, why, chartTheme }, extra) => {
14913
+ async ({ datasetId, chartTheme, why, ...chartInput }, extra) => {
14914
+ const { xAxisField, yAxisField, aggregation, seriesField } = chartInput;
13477
14915
  const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
13478
14916
  const ds = store.get(datasetId, sessionKey);
13479
14917
  if (!ds) {
@@ -13485,7 +14923,8 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13485
14923
  if (chartTheme && (isPro2 || chartTheme === "code")) {
13486
14924
  store.setVisualTheme(chartTheme);
13487
14925
  }
13488
- const chartConfig = toCoreChartConfig({ type, xAxisField, yAxisField, aggregation, seriesField, title });
14926
+ const chartConfig = toCoreChartConfig(chartInput, ds.name);
14927
+ const type = chartConfig.type;
13489
14928
  store.updateView(ds.id, {
13490
14929
  viewMode: "chart",
13491
14930
  chartConfig
@@ -13503,14 +14942,15 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13503
14942
  summaryParts.push(integrityWarning, "");
13504
14943
  }
13505
14944
  summaryParts.push(
13506
- `Configured **${type}** chart on **${ds.name}**: X = \`${xAxisField}\`, Y = \`${aggregation}(${yAxisField})\`${seriesField ? `, series = \`${seriesField}\`` : ""}.`
14945
+ `Configured **${type}** chart on **${ds.name}**: X = \`${xAxisField}\`, Y = \`${aggregation}(${yAxisField})\`${seriesField ? `, series = \`${seriesField}\`` : ""}${chartInput.targetField ? `, target = \`${chartInput.targetField}\`` : ""}.`,
14946
+ ...describeChartForText(ds.rows, chartConfig)
13507
14947
  );
13508
14948
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13509
14949
  if (asciiChart)
13510
14950
  summaryParts.push("", asciiChart);
13511
14951
  if (liveCompanionUrl)
13512
14952
  summaryParts.push(`Studio: ${liveCompanionUrl}`);
13513
- const summaryText = withNotes(summaryParts.join("\n"));
14953
+ const summaryText = summaryParts.join("\n");
13514
14954
  studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_chart", why });
13515
14955
  const chartTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summaryText, "utf8") / 4));
13516
14956
  const payload = buildAppPayload(ds, store, {
@@ -13541,6 +14981,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13541
14981
  inputSchema: {
13542
14982
  sql: z.string(),
13543
14983
  why: whyParam,
14984
+ ask: askParam,
13544
14985
  name: z.string().optional(),
13545
14986
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13546
14987
  pivotConfig: pivotConfigSchema.optional(),
@@ -13548,7 +14989,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13548
14989
  },
13549
14990
  _meta: INLINE_UI_META
13550
14991
  },
13551
- async ({ sql, why, name, viewMode, pivotConfig, keepExisting }, extra) => {
14992
+ async ({ sql, why, ask, name, viewMode, pivotConfig, keepExisting }, extra) => {
13552
14993
  if (!isPro2) {
13553
14994
  return {
13554
14995
  isError: true,
@@ -13572,7 +15013,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13572
15013
  keepExisting: shouldKeep
13573
15014
  });
13574
15015
  studio.remember(ds, { kind: "postgres", source: sql });
13575
- studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, sql });
15016
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, ask, sql });
13576
15017
  return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
13577
15018
  } catch (err) {
13578
15019
  return {
@@ -13591,15 +15032,16 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13591
15032
  inputSchema: {
13592
15033
  sql: z.string(),
13593
15034
  why: whyParam,
15035
+ ask: askParam,
13594
15036
  name: z.string().optional(),
13595
15037
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
13596
15038
  pivotConfig: pivotConfigSchema.optional(),
13597
- chartConfig: chartConfigSchema.optional(),
15039
+ chartConfig: loadChartSchema.optional(),
13598
15040
  keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
13599
15041
  },
13600
15042
  _meta: INLINE_UI_META
13601
15043
  },
13602
- async ({ sql, why, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
15044
+ async ({ sql, why, ask, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13603
15045
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
13604
15046
  try {
13605
15047
  if (await withinBudget(studio.duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
@@ -13609,6 +15051,7 @@ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13609
15051
  sql,
13610
15052
  name,
13611
15053
  why,
15054
+ ask,
13612
15055
  actor: "agent",
13613
15056
  sessionKey,
13614
15057
  keepExisting: shouldKeep,
@@ -13640,7 +15083,7 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13640
15083
  if (!ds)
13641
15084
  return { isError: true, content: [{ type: "text", text: `Dataset "${datasetId ?? "(active)"}" not found.` }] };
13642
15085
  studio.recordDatasetStep(ds, { actor: "agent", tool: "profile", why });
13643
- return { content: [{ type: "text", text: withNotes(formatProfile(ds)) }] };
15086
+ return { content: [{ type: "text", text: formatProfile(ds) }] };
13644
15087
  }
13645
15088
  );
13646
15089
  server.registerTool(
@@ -13660,7 +15103,7 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13660
15103
  if (!history.enabled)
13661
15104
  return { content: [{ type: "text", text: "History is off (TINYPIVOT_HISTORY=0)." }] };
13662
15105
  if (!open)
13663
- return { content: [{ type: "text", text: withNotes(formatHistoryList(history.list(limit ?? 15))) }] };
15106
+ return { content: [{ type: "text", text: formatHistoryList(history.list(limit ?? 15)) }] };
13664
15107
  const { sessionKey } = resolveSessionContext(extra, true);
13665
15108
  try {
13666
15109
  const ds = await studio.reopen(open, { actor: "agent", why, sessionKey });
@@ -13831,6 +15274,13 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13831
15274
  };
13832
15275
  }
13833
15276
  ));
15277
+ const applyVisualTheme = (theme) => {
15278
+ if (!isPro2 && theme !== "code")
15279
+ return { theme: "code", proRequired: true, text: "Additional chart themes require TinyPivot Pro (https://tiny-pivot.com/pricing)." };
15280
+ const active = store.setVisualTheme(theme);
15281
+ notifyCompanion();
15282
+ return { theme: active, text: `TinyPivot theme set to **${active}** (saved to ~/.config/tinypivot/preferences.json).` };
15283
+ };
13834
15284
  server.registerTool(
13835
15285
  "set_visual_theme",
13836
15286
  {
@@ -13844,20 +15294,28 @@ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
13844
15294
  }
13845
15295
  },
13846
15296
  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();
15297
+ const result = applyVisualTheme(theme);
13855
15298
  return {
13856
- content: [{ type: "text", text: `TinyPivot theme set to **${activeTheme}** (saved to ~/.config/tinypivot/preferences.json).` }],
13857
- structuredContent: { chartTheme: activeTheme }
15299
+ content: [{ type: "text", text: result.text }],
15300
+ structuredContent: result.proRequired ? { chartTheme: "code", proRequired: true } : { chartTheme: result.theme }
13858
15301
  };
13859
15302
  }
13860
15303
  );
15304
+ server.registerPrompt(
15305
+ "theme",
15306
+ {
15307
+ title: "TinyPivot theme",
15308
+ description: `Switch TinyPivot's theme for terminal cards, charts and the Studio: ${CHART_THEME_IDS.join(", ")}.`,
15309
+ argsSchema: {
15310
+ name: optionalCompletable((value2) => CHART_THEME_IDS.filter((id) => id.startsWith(value2 ?? "")))
15311
+ }
15312
+ },
15313
+ ({ name }) => {
15314
+ const theme = CHART_THEME_IDS.find((id) => id === name?.trim().toLowerCase());
15315
+ 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).`;
15316
+ return { messages: [{ role: "user", content: { type: "text", text } }] };
15317
+ }
15318
+ );
13861
15319
  widgetOnly(server.registerTool(
13862
15320
  "get_datasets_state",
13863
15321
  {
@@ -13903,6 +15361,7 @@ export {
13903
15361
  isProcessAlive,
13904
15362
  resolveCompanionUrl,
13905
15363
  runTuiCommand,
15364
+ STUDIO_IDLE_STOP_MS,
13906
15365
  startCompanionServer,
13907
15366
  buildPiExtensionSource,
13908
15367
  TINYPIVOT_CLAUDE_RULE_BLOCK,