@contractspec/example.analytics-dashboard 3.7.6 → 3.9.2

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.
Files changed (72) hide show
  1. package/README.md +66 -271
  2. package/dist/browser/dashboard.feature.js +592 -0
  3. package/dist/browser/docs/analytics-dashboard.docblock.js +2 -1
  4. package/dist/browser/docs/index.js +2 -1
  5. package/dist/browser/events.js +1 -1
  6. package/dist/browser/index.js +1260 -627
  7. package/dist/browser/ui/AnalyticsDashboard.js +915 -194
  8. package/dist/browser/ui/AnalyticsDashboard.widgets.js +94 -0
  9. package/dist/browser/ui/AnalyticsQueriesTable.js +188 -0
  10. package/dist/browser/ui/hooks/index.js +594 -3
  11. package/dist/browser/ui/hooks/useAnalyticsData.js +594 -3
  12. package/dist/browser/ui/index.js +1053 -440
  13. package/dist/browser/ui/renderers/analytics.markdown.js +620 -138
  14. package/dist/browser/ui/renderers/index.js +620 -138
  15. package/dist/browser/visualizations/catalog.js +457 -0
  16. package/dist/browser/visualizations/index.js +611 -0
  17. package/dist/browser/visualizations/specs.breakdown.js +140 -0
  18. package/dist/browser/visualizations/specs.performance.js +198 -0
  19. package/dist/browser/visualizations/widgets.js +595 -0
  20. package/dist/dashboard/index.d.ts +3 -3
  21. package/dist/dashboard.feature.js +592 -0
  22. package/dist/docs/analytics-dashboard.docblock.js +2 -1
  23. package/dist/docs/index.js +2 -1
  24. package/dist/events.js +1 -1
  25. package/dist/index.d.ts +4 -3
  26. package/dist/index.js +1260 -627
  27. package/dist/node/dashboard.feature.js +592 -0
  28. package/dist/node/docs/analytics-dashboard.docblock.js +2 -1
  29. package/dist/node/docs/index.js +2 -1
  30. package/dist/node/events.js +1 -1
  31. package/dist/node/index.js +1260 -627
  32. package/dist/node/ui/AnalyticsDashboard.js +915 -194
  33. package/dist/node/ui/AnalyticsDashboard.widgets.js +94 -0
  34. package/dist/node/ui/AnalyticsQueriesTable.js +188 -0
  35. package/dist/node/ui/hooks/index.js +594 -3
  36. package/dist/node/ui/hooks/useAnalyticsData.js +594 -3
  37. package/dist/node/ui/index.js +1053 -440
  38. package/dist/node/ui/renderers/analytics.markdown.js +620 -138
  39. package/dist/node/ui/renderers/index.js +620 -138
  40. package/dist/node/visualizations/catalog.js +457 -0
  41. package/dist/node/visualizations/index.js +611 -0
  42. package/dist/node/visualizations/specs.breakdown.js +140 -0
  43. package/dist/node/visualizations/specs.performance.js +198 -0
  44. package/dist/node/visualizations/widgets.js +595 -0
  45. package/dist/query/index.d.ts +1 -1
  46. package/dist/query-engine/index.d.ts +1 -1
  47. package/dist/ui/AnalyticsDashboard.js +915 -194
  48. package/dist/ui/AnalyticsDashboard.widgets.d.ts +5 -0
  49. package/dist/ui/AnalyticsDashboard.widgets.js +95 -0
  50. package/dist/ui/AnalyticsQueriesTable.d.ts +4 -0
  51. package/dist/ui/AnalyticsQueriesTable.js +189 -0
  52. package/dist/ui/AnalyticsQueriesTable.smoke.test.d.ts +1 -0
  53. package/dist/ui/hooks/index.d.ts +1 -1
  54. package/dist/ui/hooks/index.js +594 -3
  55. package/dist/ui/hooks/useAnalyticsData.js +594 -3
  56. package/dist/ui/index.d.ts +1 -1
  57. package/dist/ui/index.js +1053 -440
  58. package/dist/ui/renderers/analytics.markdown.d.ts +0 -9
  59. package/dist/ui/renderers/analytics.markdown.js +620 -138
  60. package/dist/ui/renderers/index.js +620 -138
  61. package/dist/visualizations/catalog.d.ts +9 -0
  62. package/dist/visualizations/catalog.js +458 -0
  63. package/dist/visualizations/index.d.ts +4 -0
  64. package/dist/visualizations/index.js +612 -0
  65. package/dist/visualizations/specs.breakdown.d.ts +4 -0
  66. package/dist/visualizations/specs.breakdown.js +141 -0
  67. package/dist/visualizations/specs.performance.d.ts +5 -0
  68. package/dist/visualizations/specs.performance.js +199 -0
  69. package/dist/visualizations/widgets.d.ts +24 -0
  70. package/dist/visualizations/widgets.js +596 -0
  71. package/dist/visualizations/widgets.test.d.ts +1 -0
  72. package/package.json +111 -11
package/dist/index.js CHANGED
@@ -1,4 +1,595 @@
1
1
  // @bun
2
+ // src/visualizations/specs.breakdown.ts
3
+ import { defineVisualization } from "@contractspec/lib.contracts-spec/visualizations";
4
+ var QUERY_REF = { key: "analytics.query.execute", version: "1.0.0" };
5
+ var META = {
6
+ version: "1.0.0",
7
+ domain: "analytics",
8
+ stability: "experimental",
9
+ owners: ["@example.analytics-dashboard"],
10
+ tags: ["analytics", "dashboard", "visualization"]
11
+ };
12
+ var ChannelMixVisualization = defineVisualization({
13
+ meta: {
14
+ ...META,
15
+ key: "analytics.visualization.channel-mix",
16
+ title: "Channel Mix",
17
+ description: "Session distribution across acquisition channels.",
18
+ goal: "Explain which channels currently drive the largest share of traffic.",
19
+ context: "Marketing attribution dashboard."
20
+ },
21
+ source: { primary: QUERY_REF, resultPath: "data" },
22
+ visualization: {
23
+ kind: "pie",
24
+ nameDimension: "channel",
25
+ valueMeasure: "sessions",
26
+ dimensions: [
27
+ {
28
+ key: "channel",
29
+ label: "Channel",
30
+ dataPath: "channel",
31
+ type: "category"
32
+ }
33
+ ],
34
+ measures: [{ key: "sessions", label: "Sessions", dataPath: "sessions" }],
35
+ table: { caption: "Sessions by acquisition channel." }
36
+ }
37
+ });
38
+ var EngagementHeatmapVisualization = defineVisualization({
39
+ meta: {
40
+ ...META,
41
+ key: "analytics.visualization.engagement-heatmap",
42
+ title: "Engagement Heatmap",
43
+ description: "Average engagement score by weekday and time band.",
44
+ goal: "Reveal the highest-engagement time windows for product activity.",
45
+ context: "Usage analytics dashboard."
46
+ },
47
+ source: { primary: QUERY_REF, resultPath: "data" },
48
+ visualization: {
49
+ kind: "heatmap",
50
+ xDimension: "timeBand",
51
+ yDimension: "weekday",
52
+ valueMeasure: "engagementScore",
53
+ dimensions: [
54
+ {
55
+ key: "timeBand",
56
+ label: "Time Band",
57
+ dataPath: "timeBand",
58
+ type: "category"
59
+ },
60
+ {
61
+ key: "weekday",
62
+ label: "Weekday",
63
+ dataPath: "weekday",
64
+ type: "category"
65
+ }
66
+ ],
67
+ measures: [
68
+ {
69
+ key: "engagementScore",
70
+ label: "Engagement",
71
+ dataPath: "engagementScore"
72
+ }
73
+ ],
74
+ table: { caption: "Engagement score by weekday and time band." }
75
+ }
76
+ });
77
+ var ConversionFunnelVisualization = defineVisualization({
78
+ meta: {
79
+ ...META,
80
+ key: "analytics.visualization.conversion-funnel",
81
+ title: "Conversion Funnel",
82
+ description: "Progression through the main acquisition funnel.",
83
+ goal: "Show where the product is losing the largest share of prospects.",
84
+ context: "Growth dashboard."
85
+ },
86
+ source: { primary: QUERY_REF, resultPath: "data" },
87
+ visualization: {
88
+ kind: "funnel",
89
+ nameDimension: "stage",
90
+ valueMeasure: "users",
91
+ sort: "descending",
92
+ dimensions: [
93
+ { key: "stage", label: "Stage", dataPath: "stage", type: "category" }
94
+ ],
95
+ measures: [{ key: "users", label: "Users", dataPath: "users" }],
96
+ table: { caption: "Users per conversion stage." }
97
+ }
98
+ });
99
+ var AccountCoverageGeoVisualization = defineVisualization({
100
+ meta: {
101
+ ...META,
102
+ key: "analytics.visualization.account-coverage-geo",
103
+ title: "Account Coverage",
104
+ description: "High-value accounts plotted on a slippy-map surface.",
105
+ goal: "Locate where active commercial concentration is strongest.",
106
+ context: "Territory coverage dashboard."
107
+ },
108
+ source: { primary: QUERY_REF, resultPath: "data" },
109
+ visualization: {
110
+ kind: "geo",
111
+ mode: "slippy-map",
112
+ variant: "scatter",
113
+ nameDimension: "city",
114
+ latitudeDimension: "latitude",
115
+ longitudeDimension: "longitude",
116
+ valueMeasure: "accounts",
117
+ dimensions: [
118
+ { key: "city", label: "City", dataPath: "city", type: "category" },
119
+ {
120
+ key: "latitude",
121
+ label: "Latitude",
122
+ dataPath: "latitude",
123
+ type: "latitude"
124
+ },
125
+ {
126
+ key: "longitude",
127
+ label: "Longitude",
128
+ dataPath: "longitude",
129
+ type: "longitude"
130
+ }
131
+ ],
132
+ measures: [{ key: "accounts", label: "Accounts", dataPath: "accounts" }],
133
+ table: { caption: "Account concentration by city." }
134
+ }
135
+ });
136
+
137
+ // src/visualizations/specs.performance.ts
138
+ import { defineVisualization as defineVisualization2 } from "@contractspec/lib.contracts-spec/visualizations";
139
+ var QUERY_REF2 = { key: "analytics.query.execute", version: "1.0.0" };
140
+ var META2 = {
141
+ version: "1.0.0",
142
+ domain: "analytics",
143
+ stability: "experimental",
144
+ owners: ["@example.analytics-dashboard"],
145
+ tags: ["analytics", "dashboard", "visualization"]
146
+ };
147
+ var RevenueMetricVisualization = defineVisualization2({
148
+ meta: {
149
+ ...META2,
150
+ key: "analytics.visualization.revenue-metric",
151
+ title: "Revenue Snapshot",
152
+ description: "Current recurring revenue with prior-period comparison.",
153
+ goal: "Highlight the headline commercial metric for the dashboard.",
154
+ context: "Executive revenue overview."
155
+ },
156
+ source: { primary: QUERY_REF2, resultPath: "data" },
157
+ visualization: {
158
+ kind: "metric",
159
+ measure: "totalRevenue",
160
+ comparisonMeasure: "priorRevenue",
161
+ dimensions: [
162
+ { key: "period", label: "Period", dataPath: "period", type: "time" }
163
+ ],
164
+ measures: [
165
+ {
166
+ key: "totalRevenue",
167
+ label: "Revenue",
168
+ dataPath: "totalRevenue",
169
+ format: "currency"
170
+ },
171
+ {
172
+ key: "priorRevenue",
173
+ label: "Prior Revenue",
174
+ dataPath: "priorRevenue",
175
+ format: "currency"
176
+ }
177
+ ],
178
+ sparkline: { dimension: "period", measure: "totalRevenue" },
179
+ table: { caption: "Revenue trend and prior period values." }
180
+ }
181
+ });
182
+ var RevenueTrendVisualization = defineVisualization2({
183
+ meta: {
184
+ ...META2,
185
+ key: "analytics.visualization.revenue-trend",
186
+ title: "Revenue Trend",
187
+ description: "Monthly revenue progression for the current quarter.",
188
+ goal: "Track whether revenue growth is accelerating or stalling.",
189
+ context: "Quarterly commercial dashboard."
190
+ },
191
+ source: { primary: QUERY_REF2, resultPath: "data" },
192
+ visualization: {
193
+ kind: "cartesian",
194
+ variant: "line",
195
+ xDimension: "date",
196
+ yMeasures: ["revenue"],
197
+ dimensions: [
198
+ { key: "date", label: "Month", dataPath: "date", type: "time" }
199
+ ],
200
+ measures: [
201
+ {
202
+ key: "revenue",
203
+ label: "Revenue",
204
+ dataPath: "revenue",
205
+ format: "currency",
206
+ color: "#0f766e"
207
+ }
208
+ ],
209
+ thresholds: [
210
+ { key: "target", value: 140000, label: "Target", color: "#dc2626" }
211
+ ],
212
+ table: { caption: "Monthly revenue values." }
213
+ }
214
+ });
215
+ var RegionalRevenueVisualization = defineVisualization2({
216
+ meta: {
217
+ ...META2,
218
+ key: "analytics.visualization.regional-revenue",
219
+ title: "Regional Revenue",
220
+ description: "Revenue split by sales territory.",
221
+ goal: "Compare the strongest and weakest performing territories.",
222
+ context: "Territory planning and commercial comparison."
223
+ },
224
+ source: { primary: QUERY_REF2, resultPath: "data" },
225
+ visualization: {
226
+ kind: "cartesian",
227
+ variant: "bar",
228
+ xDimension: "region",
229
+ yMeasures: ["revenue"],
230
+ dimensions: [
231
+ { key: "region", label: "Region", dataPath: "region", type: "category" }
232
+ ],
233
+ measures: [
234
+ {
235
+ key: "revenue",
236
+ label: "Revenue",
237
+ dataPath: "revenue",
238
+ format: "currency",
239
+ color: "#1d4ed8"
240
+ }
241
+ ],
242
+ table: { caption: "Revenue by region." }
243
+ }
244
+ });
245
+ var RetentionAreaVisualization = defineVisualization2({
246
+ meta: {
247
+ ...META2,
248
+ key: "analytics.visualization.retention-area",
249
+ title: "Retention Curve",
250
+ description: "Weekly retention progression across the active cohort.",
251
+ goal: "Show whether user retention remains above the desired floor.",
252
+ context: "Product health dashboard."
253
+ },
254
+ source: { primary: QUERY_REF2, resultPath: "data" },
255
+ visualization: {
256
+ kind: "cartesian",
257
+ variant: "area",
258
+ xDimension: "week",
259
+ yMeasures: ["retentionRate"],
260
+ dimensions: [
261
+ { key: "week", label: "Week", dataPath: "week", type: "category" }
262
+ ],
263
+ measures: [
264
+ {
265
+ key: "retentionRate",
266
+ label: "Retention",
267
+ dataPath: "retentionRate",
268
+ format: "percentage",
269
+ color: "#16a34a"
270
+ }
271
+ ],
272
+ thresholds: [
273
+ { key: "floor", value: 0.5, label: "Floor", color: "#f59e0b" }
274
+ ],
275
+ table: { caption: "Weekly retention rate." }
276
+ }
277
+ });
278
+ var PipelineScatterVisualization = defineVisualization2({
279
+ meta: {
280
+ ...META2,
281
+ key: "analytics.visualization.pipeline-scatter",
282
+ title: "Pipeline Velocity",
283
+ description: "Deal-cycle length against win rate for active accounts.",
284
+ goal: "Spot outliers where the sales cycle is long but conversion remains weak.",
285
+ context: "Commercial operations dashboard."
286
+ },
287
+ source: { primary: QUERY_REF2, resultPath: "data" },
288
+ visualization: {
289
+ kind: "cartesian",
290
+ variant: "scatter",
291
+ xDimension: "cycleDays",
292
+ yMeasures: ["winRate"],
293
+ dimensions: [
294
+ {
295
+ key: "cycleDays",
296
+ label: "Cycle Days",
297
+ dataPath: "cycleDays",
298
+ type: "number"
299
+ }
300
+ ],
301
+ measures: [
302
+ {
303
+ key: "winRate",
304
+ label: "Win Rate",
305
+ dataPath: "winRate",
306
+ format: "percentage",
307
+ color: "#7c3aed"
308
+ },
309
+ {
310
+ key: "arr",
311
+ label: "ARR",
312
+ dataPath: "arr",
313
+ format: "currency"
314
+ }
315
+ ],
316
+ series: [
317
+ {
318
+ key: "pipeline",
319
+ label: "Accounts",
320
+ measure: "winRate",
321
+ type: "scatter",
322
+ color: "#7c3aed"
323
+ }
324
+ ],
325
+ table: { caption: "Sales cycle and win rate per account." }
326
+ }
327
+ });
328
+
329
+ // src/visualizations/catalog.ts
330
+ import { VisualizationRegistry } from "@contractspec/lib.contracts-spec/visualizations";
331
+ var AnalyticsVisualizationSpecs = [
332
+ RevenueMetricVisualization,
333
+ RevenueTrendVisualization,
334
+ RegionalRevenueVisualization,
335
+ RetentionAreaVisualization,
336
+ PipelineScatterVisualization,
337
+ ChannelMixVisualization,
338
+ EngagementHeatmapVisualization,
339
+ ConversionFunnelVisualization,
340
+ AccountCoverageGeoVisualization
341
+ ];
342
+ var AnalyticsVisualizationRegistry = new VisualizationRegistry([
343
+ ...AnalyticsVisualizationSpecs
344
+ ]);
345
+ var AnalyticsVisualizationRefs = AnalyticsVisualizationSpecs.map((spec) => refOf(spec));
346
+ var AnalyticsVisualizationSpecMap = new Map(AnalyticsVisualizationSpecs.map((spec) => [
347
+ visualizationRefKey(spec.meta),
348
+ spec
349
+ ]));
350
+ var AnalyticsVisualizationSampleData = {
351
+ [visualizationRefKey(RevenueMetricVisualization.meta)]: {
352
+ data: [
353
+ { period: "2025-11-01", totalRevenue: 112000, priorRevenue: 103000 },
354
+ { period: "2025-12-01", totalRevenue: 119000, priorRevenue: 110000 },
355
+ { period: "2026-01-01", totalRevenue: 126500, priorRevenue: 116000 },
356
+ { period: "2026-02-01", totalRevenue: 133000, priorRevenue: 124000 },
357
+ { period: "2026-03-01", totalRevenue: 145500, priorRevenue: 133000 }
358
+ ]
359
+ },
360
+ [visualizationRefKey(RevenueTrendVisualization.meta)]: {
361
+ data: [
362
+ { date: "2025-11-01", revenue: 112000 },
363
+ { date: "2025-12-01", revenue: 119000 },
364
+ { date: "2026-01-01", revenue: 126500 },
365
+ { date: "2026-02-01", revenue: 133000 },
366
+ { date: "2026-03-01", revenue: 145500 }
367
+ ]
368
+ },
369
+ [visualizationRefKey(RegionalRevenueVisualization.meta)]: {
370
+ data: [
371
+ { region: "North America", revenue: 210000 },
372
+ { region: "EMEA", revenue: 174000 },
373
+ { region: "APAC", revenue: 132000 },
374
+ { region: "LATAM", revenue: 88000 }
375
+ ]
376
+ },
377
+ [visualizationRefKey(RetentionAreaVisualization.meta)]: {
378
+ data: [
379
+ { week: "Week 1", retentionRate: 0.71 },
380
+ { week: "Week 2", retentionRate: 0.66 },
381
+ { week: "Week 3", retentionRate: 0.62 },
382
+ { week: "Week 4", retentionRate: 0.58 },
383
+ { week: "Week 5", retentionRate: 0.55 },
384
+ { week: "Week 6", retentionRate: 0.53 }
385
+ ]
386
+ },
387
+ [visualizationRefKey(PipelineScatterVisualization.meta)]: {
388
+ data: [
389
+ { cycleDays: 18, winRate: 0.31, arr: 82000 },
390
+ { cycleDays: 26, winRate: 0.44, arr: 65000 },
391
+ { cycleDays: 33, winRate: 0.27, arr: 91000 },
392
+ { cycleDays: 14, winRate: 0.56, arr: 47000 },
393
+ { cycleDays: 21, winRate: 0.48, arr: 59000 },
394
+ { cycleDays: 39, winRate: 0.22, arr: 114000 }
395
+ ]
396
+ },
397
+ [visualizationRefKey(ChannelMixVisualization.meta)]: {
398
+ data: [
399
+ { channel: "Direct", sessions: 4200 },
400
+ { channel: "Organic Search", sessions: 3600 },
401
+ { channel: "Paid Search", sessions: 2100 },
402
+ { channel: "Partner", sessions: 1400 },
403
+ { channel: "Referral", sessions: 900 }
404
+ ]
405
+ },
406
+ [visualizationRefKey(EngagementHeatmapVisualization.meta)]: {
407
+ data: [
408
+ { weekday: "Mon", timeBand: "09:00", engagementScore: 74 },
409
+ { weekday: "Mon", timeBand: "13:00", engagementScore: 82 },
410
+ { weekday: "Tue", timeBand: "09:00", engagementScore: 69 },
411
+ { weekday: "Tue", timeBand: "13:00", engagementScore: 88 },
412
+ { weekday: "Wed", timeBand: "09:00", engagementScore: 77 },
413
+ { weekday: "Wed", timeBand: "13:00", engagementScore: 91 },
414
+ { weekday: "Thu", timeBand: "09:00", engagementScore: 72 },
415
+ { weekday: "Thu", timeBand: "13:00", engagementScore: 86 },
416
+ { weekday: "Fri", timeBand: "09:00", engagementScore: 65 },
417
+ { weekday: "Fri", timeBand: "13:00", engagementScore: 79 }
418
+ ]
419
+ },
420
+ [visualizationRefKey(ConversionFunnelVisualization.meta)]: {
421
+ data: [
422
+ { stage: "Visited Site", users: 12000 },
423
+ { stage: "Started Trial", users: 4200 },
424
+ { stage: "Activated Workspace", users: 2400 },
425
+ { stage: "Requested Demo", users: 980 },
426
+ { stage: "Closed Won", users: 310 }
427
+ ]
428
+ },
429
+ [visualizationRefKey(AccountCoverageGeoVisualization.meta)]: {
430
+ data: [
431
+ { city: "Paris", latitude: 48.8566, longitude: 2.3522, accounts: 48 },
432
+ { city: "London", latitude: 51.5072, longitude: -0.1276, accounts: 62 },
433
+ { city: "New York", latitude: 40.7128, longitude: -74.006, accounts: 71 },
434
+ { city: "Toronto", latitude: 43.6532, longitude: -79.3832, accounts: 36 },
435
+ {
436
+ city: "Singapore",
437
+ latitude: 1.3521,
438
+ longitude: 103.8198,
439
+ accounts: 29
440
+ }
441
+ ]
442
+ }
443
+ };
444
+ function refOf(spec) {
445
+ return { key: spec.meta.key, version: spec.meta.version };
446
+ }
447
+ function visualizationRefKey(ref) {
448
+ return `${ref.key}.v${ref.version}`;
449
+ }
450
+
451
+ // src/visualizations/widgets.ts
452
+ var LEGACY_VISUALIZATION_REFS = {
453
+ METRIC: refOf(RevenueMetricVisualization),
454
+ LINE_CHART: refOf(RevenueTrendVisualization),
455
+ BAR_CHART: refOf(RegionalRevenueVisualization),
456
+ AREA_CHART: refOf(RetentionAreaVisualization),
457
+ SCATTER_PLOT: refOf(PipelineScatterVisualization),
458
+ PIE_CHART: refOf(ChannelMixVisualization),
459
+ HEATMAP: refOf(EngagementHeatmapVisualization),
460
+ FUNNEL: refOf(ConversionFunnelVisualization),
461
+ MAP: refOf(AccountCoverageGeoVisualization)
462
+ };
463
+ function createExampleWidgets(dashboardId) {
464
+ return [
465
+ widget(dashboardId, "widget_revenue_metric", "Revenue Snapshot", "METRIC", 0, 0, 4, 2, {
466
+ layout: "single",
467
+ bindings: [binding(RevenueMetricVisualization, 200)]
468
+ }),
469
+ widget(dashboardId, "widget_revenue_trend", "Revenue Trend", "LINE_CHART", 4, 0, 8, 4, {
470
+ layout: "single",
471
+ bindings: [binding(RevenueTrendVisualization)]
472
+ }),
473
+ widget(dashboardId, "widget_regional_revenue", "Regional Revenue", "BAR_CHART", 0, 2, 6, 4, {
474
+ layout: "single",
475
+ bindings: [binding(RegionalRevenueVisualization)]
476
+ }),
477
+ widget(dashboardId, "widget_channel_mix", "Channel Mix", "PIE_CHART", 6, 2, 6, 4, {
478
+ layout: "single",
479
+ bindings: [binding(ChannelMixVisualization)]
480
+ }),
481
+ widget(dashboardId, "widget_retention", "Retention Curve", "AREA_CHART", 0, 6, 6, 4, {
482
+ layout: "single",
483
+ bindings: [binding(RetentionAreaVisualization)]
484
+ }),
485
+ widget(dashboardId, "widget_pipeline", "Pipeline Velocity", "SCATTER_PLOT", 6, 6, 6, 4, {
486
+ layout: "single",
487
+ bindings: [binding(PipelineScatterVisualization)]
488
+ }),
489
+ widget(dashboardId, "widget_heatmap", "Engagement Heatmap", "HEATMAP", 0, 10, 8, 4, {
490
+ layout: "single",
491
+ bindings: [binding(EngagementHeatmapVisualization)]
492
+ }),
493
+ widget(dashboardId, "widget_funnel", "Conversion Funnel", "FUNNEL", 8, 10, 4, 4, {
494
+ layout: "single",
495
+ bindings: [binding(ConversionFunnelVisualization)]
496
+ }),
497
+ widget(dashboardId, "widget_geo", "Account Coverage", "MAP", 0, 14, 12, 5, {
498
+ layout: "single",
499
+ bindings: [binding(AccountCoverageGeoVisualization, 360)]
500
+ }),
501
+ widget(dashboardId, "widget_comparison", "Commercial Comparison", "EMBED", 0, 19, 12, 6, {
502
+ layout: "comparison",
503
+ description: "Compare regional distribution, channel balance, and funnel shape.",
504
+ bindings: [
505
+ binding(RegionalRevenueVisualization, 240),
506
+ binding(ChannelMixVisualization, 240),
507
+ binding(ConversionFunnelVisualization, 240)
508
+ ]
509
+ }),
510
+ widget(dashboardId, "widget_timeline", "Growth Timeline", "EMBED", 0, 25, 12, 6, {
511
+ layout: "timeline",
512
+ description: "Track revenue and retention over the same reporting cadence.",
513
+ bindings: [
514
+ binding(RevenueTrendVisualization, 220),
515
+ binding(RetentionAreaVisualization, 220)
516
+ ]
517
+ })
518
+ ];
519
+ }
520
+ function resolveAnalyticsWidget(widget) {
521
+ const config = parseWidgetConfig(widget);
522
+ const bindings = config.bindings.map((binding) => {
523
+ const spec = AnalyticsVisualizationSpecMap.get(visualizationRefKey(binding.ref));
524
+ if (!spec)
525
+ return null;
526
+ return {
527
+ key: `${widget.id}:${visualizationRefKey(binding.ref)}`,
528
+ spec,
529
+ data: binding.data,
530
+ title: binding.title ?? spec.meta.title,
531
+ description: binding.description ?? spec.meta.description,
532
+ height: binding.height
533
+ };
534
+ }).filter((binding) => Boolean(binding));
535
+ if (!bindings.length)
536
+ return null;
537
+ return {
538
+ id: widget.id,
539
+ name: widget.name,
540
+ description: config.description,
541
+ layout: config.layout,
542
+ gridX: widget.gridX,
543
+ gridY: widget.gridY,
544
+ gridWidth: widget.gridWidth,
545
+ gridHeight: widget.gridHeight,
546
+ bindings
547
+ };
548
+ }
549
+ function parseWidgetConfig(widget) {
550
+ if (isAnalyticsWidgetConfig(widget.config)) {
551
+ return widget.config;
552
+ }
553
+ const legacyRef = LEGACY_VISUALIZATION_REFS[widget.type];
554
+ return legacyRef ? {
555
+ layout: "single",
556
+ bindings: [
557
+ {
558
+ ref: legacyRef,
559
+ data: AnalyticsVisualizationSampleData[visualizationRefKey(legacyRef)]
560
+ }
561
+ ]
562
+ } : { layout: "single", bindings: [] };
563
+ }
564
+ function binding(spec, height = 280) {
565
+ return {
566
+ ref: refOf(spec),
567
+ data: AnalyticsVisualizationSampleData[visualizationRefKey(spec.meta)],
568
+ height
569
+ };
570
+ }
571
+ function widget(dashboardId, id, name, type, gridX, gridY, gridWidth, gridHeight, config) {
572
+ const now = new Date;
573
+ return {
574
+ id,
575
+ dashboardId,
576
+ name,
577
+ type,
578
+ gridX,
579
+ gridY,
580
+ gridWidth,
581
+ gridHeight,
582
+ config,
583
+ createdAt: now,
584
+ updatedAt: now
585
+ };
586
+ }
587
+ function isAnalyticsWidgetConfig(value) {
588
+ if (!value || typeof value !== "object")
589
+ return false;
590
+ const candidate = value;
591
+ return (candidate.layout === "single" || candidate.layout === "comparison" || candidate.layout === "timeline") && Array.isArray(candidate.bindings);
592
+ }
2
593
  // src/dashboard.feature.ts
3
594
  import { defineFeature } from "@contractspec/lib.contracts-spec";
4
595
  var AnalyticsDashboardFeature = defineFeature({
@@ -32,6 +623,7 @@ var AnalyticsDashboardFeature = defineFeature({
32
623
  { key: "analytics.query.list", version: "1.0.0" },
33
624
  { key: "analytics.query.builder", version: "1.0.0" }
34
625
  ],
626
+ visualizations: [...AnalyticsVisualizationRefs],
35
627
  opToPresentation: [
36
628
  {
37
629
  op: { key: "analytics.dashboard.list", version: "1.0.0" },
@@ -800,279 +1392,486 @@ var ExecuteQueryContract = defineQuery({
800
1392
  ]
801
1393
  }
802
1394
  });
803
- // src/ui/renderers/analytics.markdown.ts
804
- var mockDashboards = [
805
- {
806
- id: "dash-1",
807
- name: "Sales Overview",
808
- slug: "sales-overview",
809
- status: "PUBLISHED",
810
- widgetCount: 8,
811
- viewCount: 1250,
812
- lastViewedAt: "2024-01-16T12:00:00Z"
813
- },
814
- {
815
- id: "dash-2",
816
- name: "User Engagement",
817
- slug: "user-engagement",
818
- status: "PUBLISHED",
819
- widgetCount: 6,
820
- viewCount: 890,
821
- lastViewedAt: "2024-01-16T10:00:00Z"
822
- },
823
- {
824
- id: "dash-3",
825
- name: "Product Analytics",
826
- slug: "product-analytics",
827
- status: "PUBLISHED",
828
- widgetCount: 10,
829
- viewCount: 560,
830
- lastViewedAt: "2024-01-15T14:00:00Z"
831
- },
832
- {
833
- id: "dash-4",
834
- name: "Finance Report",
835
- slug: "finance-report",
836
- status: "DRAFT",
837
- widgetCount: 4,
838
- viewCount: 0,
839
- lastViewedAt: null
840
- }
841
- ];
842
- var mockWidgets = [
843
- {
844
- id: "w-1",
845
- dashboardId: "dash-1",
846
- name: "Total Revenue",
847
- type: "METRIC",
848
- value: 125000,
849
- change: 12.5
850
- },
851
- {
852
- id: "w-2",
853
- dashboardId: "dash-1",
854
- name: "Active Users",
855
- type: "METRIC",
856
- value: 4500,
857
- change: 8.2
858
- },
859
- {
860
- id: "w-3",
861
- dashboardId: "dash-1",
862
- name: "Revenue Trend",
863
- type: "LINE_CHART",
864
- dataPoints: 30
865
- },
866
- {
867
- id: "w-4",
868
- dashboardId: "dash-1",
869
- name: "Top Products",
870
- type: "BAR_CHART",
871
- dataPoints: 10
872
- },
873
- {
874
- id: "w-5",
875
- dashboardId: "dash-2",
876
- name: "Daily Active Users",
877
- type: "LINE_CHART",
878
- dataPoints: 30
879
- },
880
- {
881
- id: "w-6",
882
- dashboardId: "dash-2",
883
- name: "Session Duration",
884
- type: "METRIC",
885
- value: 245,
886
- change: -3.1
887
- }
888
- ];
889
- var mockQueries = [
890
- {
891
- id: "q-1",
892
- name: "Monthly Revenue",
893
- type: "AGGREGATION",
894
- isShared: true,
895
- executionCount: 1500
896
- },
897
- {
898
- id: "q-2",
899
- name: "User Growth",
900
- type: "METRIC",
901
- isShared: true,
902
- executionCount: 890
903
- },
904
- {
905
- id: "q-3",
906
- name: "Product Sales",
907
- type: "SQL",
908
- isShared: false,
909
- executionCount: 340
910
- },
911
- {
912
- id: "q-4",
913
- name: "Conversion Funnel",
914
- type: "AGGREGATION",
915
- isShared: true,
916
- executionCount: 450
1395
+ // src/query-engine/index.ts
1396
+ class InMemoryQueryCache {
1397
+ cache = new Map;
1398
+ async get(key) {
1399
+ const entry = this.cache.get(key);
1400
+ if (!entry)
1401
+ return null;
1402
+ if (entry.expiresAt < new Date) {
1403
+ this.cache.delete(key);
1404
+ return null;
1405
+ }
1406
+ return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
917
1407
  }
918
- ];
919
- function formatNumber(value) {
920
- if (value >= 1e6) {
921
- return `${(value / 1e6).toFixed(1)}M`;
1408
+ async set(key, result, ttlSeconds) {
1409
+ const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1410
+ this.cache.set(key, { result, expiresAt });
922
1411
  }
923
- if (value >= 1000) {
924
- return `${(value / 1000).toFixed(1)}K`;
1412
+ async invalidate(pattern) {
1413
+ const regex = new RegExp(pattern);
1414
+ for (const key of this.cache.keys()) {
1415
+ if (regex.test(key)) {
1416
+ this.cache.delete(key);
1417
+ }
1418
+ }
925
1419
  }
926
- return value.toString();
927
- }
928
- function formatChange(change) {
929
- const icon = change >= 0 ? "\uD83D\uDCC8" : "\uD83D\uDCC9";
930
- const sign = change >= 0 ? "+" : "";
931
- return `${icon} ${sign}${change.toFixed(1)}%`;
932
1420
  }
933
- var analyticsDashboardMarkdownRenderer = {
934
- target: "markdown",
935
- render: async (desc) => {
936
- if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
937
- throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
938
- }
939
- const dashboards = mockDashboards;
940
- const widgets = mockWidgets;
941
- const queries = mockQueries;
942
- const dashboard = dashboards[0];
943
- if (!dashboard) {
944
- return {
945
- mimeType: "text/markdown",
946
- body: `# No Dashboards
947
1421
 
948
- No dashboards available.`
1422
+ class BasicQueryEngine {
1423
+ cache;
1424
+ constructor(cache) {
1425
+ this.cache = cache ?? new InMemoryQueryCache;
1426
+ }
1427
+ async execute(definition, params) {
1428
+ const startTime = Date.now();
1429
+ const validation = this.validateQuery(definition);
1430
+ if (!validation.valid) {
1431
+ return {
1432
+ data: [],
1433
+ columns: [],
1434
+ rowCount: 0,
1435
+ executionTimeMs: Date.now() - startTime,
1436
+ cached: false,
1437
+ error: validation.errors.join(", ")
949
1438
  };
950
1439
  }
951
- const dashboardWidgets = widgets.filter((w) => w.dashboardId === dashboard.id);
952
- const publishedDashboards = dashboards.filter((d) => d.status === "PUBLISHED");
953
- const totalViews = dashboards.reduce((sum, d) => sum + d.viewCount, 0);
954
- const sharedQueries = queries.filter((q) => q.isShared);
955
- const lines = [
956
- `# ${dashboard.name}`,
957
- "",
958
- "> Analytics dashboard overview",
959
- "",
960
- "## Key Metrics",
961
- ""
962
- ];
963
- const metricWidgets = dashboardWidgets.filter((w) => w.type === "METRIC");
964
- for (const widget of metricWidgets) {
965
- const w = widget;
966
- lines.push(`### ${w.name}`);
967
- lines.push(`**${formatNumber(w.value)}** ${formatChange(w.change)}`);
968
- lines.push("");
1440
+ const cacheKey = this.buildCacheKey(definition, params);
1441
+ const cachedResult = await this.cache.get(cacheKey);
1442
+ if (cachedResult) {
1443
+ return cachedResult;
969
1444
  }
970
- lines.push("## Visualizations");
971
- lines.push("");
972
- const chartWidgets = dashboardWidgets.filter((w) => w.type !== "METRIC");
973
- for (const widget of chartWidgets) {
974
- const w = widget;
975
- lines.push(`- **${w.name}** (${w.type.replace("_", " ")}) - ${w.dataPoints} data points`);
1445
+ let result;
1446
+ switch (definition.type) {
1447
+ case "AGGREGATION":
1448
+ if (!definition.aggregation) {
1449
+ throw new Error("Aggregation definition is missing");
1450
+ }
1451
+ result = await this.executeAggregation(definition.aggregation, params);
1452
+ break;
1453
+ case "METRIC":
1454
+ if (!definition.metricIds) {
1455
+ throw new Error("Metric IDs are missing");
1456
+ }
1457
+ result = await this.executeMetric(definition.metricIds, params);
1458
+ break;
1459
+ case "SQL":
1460
+ if (!definition.sql) {
1461
+ throw new Error("SQL query is missing");
1462
+ }
1463
+ result = await this.executeSql(definition.sql, params);
1464
+ break;
1465
+ default:
1466
+ result = {
1467
+ data: [],
1468
+ columns: [],
1469
+ rowCount: 0,
1470
+ executionTimeMs: Date.now() - startTime,
1471
+ cached: false,
1472
+ error: `Unknown query type: ${definition.type}`
1473
+ };
976
1474
  }
977
- lines.push("");
978
- lines.push("## Dashboard Stats");
979
- lines.push("");
980
- lines.push("| Metric | Value |");
981
- lines.push("|--------|-------|");
982
- lines.push(`| Total Dashboards | ${dashboards.length} |`);
983
- lines.push(`| Published | ${publishedDashboards.length} |`);
984
- lines.push(`| Total Views | ${totalViews.toLocaleString()} |`);
985
- lines.push(`| Shared Queries | ${sharedQueries.length} |`);
986
- return {
987
- mimeType: "text/markdown",
988
- body: lines.join(`
989
- `)
990
- };
1475
+ result.executionTimeMs = Date.now() - startTime;
1476
+ result.cached = false;
1477
+ await this.cache.set(cacheKey, result, 300);
1478
+ return result;
991
1479
  }
992
- };
993
- var dashboardListMarkdownRenderer = {
994
- target: "markdown",
995
- render: async (desc) => {
996
- if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
997
- throw new Error("dashboardListMarkdownRenderer: not DashboardList");
1480
+ validateQuery(definition) {
1481
+ const errors = [];
1482
+ if (!definition.type) {
1483
+ errors.push("Query type is required");
998
1484
  }
999
- const dashboards = mockDashboards;
1000
- const lines = [
1001
- "# Dashboards",
1002
- "",
1003
- "> Browse and manage analytics dashboards",
1004
- "",
1005
- "| Dashboard | Widgets | Views | Status | Last Viewed |",
1006
- "|-----------|---------|-------|--------|-------------|"
1007
- ];
1008
- for (const dashboard of dashboards) {
1009
- const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
1010
- const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "\u26AB";
1011
- lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
1485
+ switch (definition.type) {
1486
+ case "SQL":
1487
+ if (!definition.sql) {
1488
+ errors.push("SQL query is required for SQL type");
1489
+ }
1490
+ break;
1491
+ case "METRIC":
1492
+ if (!definition.metricIds || definition.metricIds.length === 0) {
1493
+ errors.push("Metric IDs are required for METRIC type");
1494
+ }
1495
+ break;
1496
+ case "AGGREGATION":
1497
+ if (!definition.aggregation) {
1498
+ errors.push("Aggregation definition is required for AGGREGATION type");
1499
+ } else {
1500
+ if (!definition.aggregation.source) {
1501
+ errors.push("Aggregation source is required");
1502
+ }
1503
+ if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
1504
+ errors.push("At least one measure is required");
1505
+ }
1506
+ }
1507
+ break;
1012
1508
  }
1013
- lines.push("");
1014
- lines.push("## Quick Actions");
1015
- lines.push("");
1016
- lines.push("- **Create Dashboard** - Start with a blank canvas");
1017
- lines.push("- **Import Template** - Use a pre-built template");
1018
- lines.push("- **Clone Dashboard** - Duplicate an existing dashboard");
1509
+ return { valid: errors.length === 0, errors };
1510
+ }
1511
+ buildCacheKey(definition, params) {
1512
+ return JSON.stringify({ definition, params });
1513
+ }
1514
+ async executeAggregation(aggregation, params) {
1515
+ const columns = [
1516
+ ...aggregation.dimensions.map((d) => ({
1517
+ name: d.name,
1518
+ type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
1519
+ label: d.name
1520
+ })),
1521
+ ...aggregation.measures.map((m) => ({
1522
+ name: m.name,
1523
+ type: "NUMBER",
1524
+ label: m.name,
1525
+ format: m.format
1526
+ }))
1527
+ ];
1528
+ const data = this.generateMockData(aggregation, params);
1019
1529
  return {
1020
- mimeType: "text/markdown",
1021
- body: lines.join(`
1022
- `)
1530
+ data,
1531
+ columns,
1532
+ rowCount: data.length,
1533
+ executionTimeMs: 0,
1534
+ cached: false
1023
1535
  };
1024
1536
  }
1025
- };
1026
- var queryBuilderMarkdownRenderer = {
1027
- target: "markdown",
1028
- render: async (desc) => {
1029
- if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
1030
- throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
1031
- }
1032
- const queries = mockQueries;
1033
- const lines = [
1034
- "# Query Builder",
1035
- "",
1036
- "> Create and manage data queries",
1037
- "",
1038
- "## Saved Queries",
1039
- "",
1040
- "| Query | Type | Shared | Executions |",
1041
- "|-------|------|--------|------------|"
1042
- ];
1043
- for (const query of queries) {
1044
- const sharedIcon = query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12";
1045
- lines.push(`| ${query.name} | ${query.type} | ${sharedIcon} | ${query.executionCount.toLocaleString()} |`);
1046
- }
1047
- lines.push("");
1048
- lines.push("## Query Types");
1049
- lines.push("");
1050
- lines.push("### METRIC");
1051
- lines.push("Query usage metrics from the metering system.");
1052
- lines.push("");
1053
- lines.push("### AGGREGATION");
1054
- lines.push("Build aggregations with measures and dimensions without writing SQL.");
1055
- lines.push("");
1056
- lines.push("### SQL");
1057
- lines.push("Write custom SQL queries for advanced analysis.");
1058
- lines.push("");
1059
- lines.push("## Features");
1060
- lines.push("");
1061
- lines.push("- Visual query builder");
1062
- lines.push("- Auto-complete for fields and functions");
1063
- lines.push("- Query validation and optimization");
1064
- lines.push("- Result caching");
1065
- lines.push("- Query sharing and collaboration");
1537
+ async executeMetric(metricIds, _params) {
1538
+ const data = metricIds.map((id) => ({
1539
+ metricId: id,
1540
+ value: Math.random() * 1000,
1541
+ change: (Math.random() - 0.5) * 20
1542
+ }));
1066
1543
  return {
1067
- mimeType: "text/markdown",
1068
- body: lines.join(`
1069
- `)
1544
+ data,
1545
+ columns: [
1546
+ { name: "metricId", type: "STRING" },
1547
+ { name: "value", type: "NUMBER" },
1548
+ { name: "change", type: "NUMBER" }
1549
+ ],
1550
+ rowCount: data.length,
1551
+ executionTimeMs: 0,
1552
+ cached: false
1553
+ };
1554
+ }
1555
+ async executeSql(_sql, _params) {
1556
+ return {
1557
+ data: [],
1558
+ columns: [],
1559
+ rowCount: 0,
1560
+ executionTimeMs: 0,
1561
+ cached: false,
1562
+ error: "SQL execution not implemented in demo"
1070
1563
  };
1071
1564
  }
1565
+ generateMockData(aggregation, params) {
1566
+ const data = [];
1567
+ const rowCount = 10;
1568
+ const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
1569
+ for (let i = 0;i < rowCount; i++) {
1570
+ const row = {};
1571
+ for (const dim of aggregation.dimensions) {
1572
+ if (dim.type === "TIME") {
1573
+ const date = new Date(params.dateRange?.start ?? new Date);
1574
+ date.setDate(date.getDate() + i);
1575
+ row[dim.name] = date.toISOString().split("T")[0];
1576
+ } else {
1577
+ row[dim.name] = `${dim.name}_${i % 5}`;
1578
+ }
1579
+ }
1580
+ for (const measure of aggregation.measures) {
1581
+ const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
1582
+ const noise = (Math.random() - 0.5) * 20;
1583
+ row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
1584
+ }
1585
+ data.push(row);
1586
+ }
1587
+ return data;
1588
+ }
1589
+ }
1590
+ function createQueryEngine(cache) {
1591
+ return new BasicQueryEngine(cache);
1592
+ }
1593
+
1594
+ // src/ui/AnalyticsDashboard.widgets.tsx
1595
+ import {
1596
+ ComparisonView,
1597
+ TimelineView,
1598
+ VisualizationCard,
1599
+ VisualizationGrid
1600
+ } from "@contractspec/lib.design-system";
1601
+ import { jsxDEV } from "react/jsx-dev-runtime";
1602
+ "use client";
1603
+ function AnalyticsWidgetBoard({
1604
+ dashboardName,
1605
+ widgets
1606
+ }) {
1607
+ if (!widgets.length) {
1608
+ return /* @__PURE__ */ jsxDEV("div", {
1609
+ className: "rounded-lg border border-dashed p-10 text-center text-muted-foreground",
1610
+ children: [
1611
+ 'No visualization widgets configured for "',
1612
+ dashboardName,
1613
+ '".'
1614
+ ]
1615
+ }, undefined, true, undefined, this);
1616
+ }
1617
+ return /* @__PURE__ */ jsxDEV("div", {
1618
+ children: [
1619
+ /* @__PURE__ */ jsxDEV("h3", {
1620
+ className: "mb-4 font-semibold text-lg",
1621
+ children: [
1622
+ 'Widgets in "',
1623
+ dashboardName,
1624
+ '"'
1625
+ ]
1626
+ }, undefined, true, undefined, this),
1627
+ /* @__PURE__ */ jsxDEV(VisualizationGrid, {
1628
+ children: widgets.map((widget2) => /* @__PURE__ */ jsxDEV("div", {
1629
+ className: gridSpanClass(widget2.gridWidth),
1630
+ children: renderVisualizationWidget(widget2)
1631
+ }, widget2.id, false, undefined, this))
1632
+ }, undefined, false, undefined, this)
1633
+ ]
1634
+ }, undefined, true, undefined, this);
1635
+ }
1636
+ function renderVisualizationWidget(widget2) {
1637
+ const footer = /* @__PURE__ */ jsxDEV("span", {
1638
+ className: "text-muted-foreground text-xs",
1639
+ children: [
1640
+ "Position: (",
1641
+ widget2.gridX,
1642
+ ", ",
1643
+ widget2.gridY,
1644
+ ") \u2022 ",
1645
+ widget2.gridWidth,
1646
+ "x",
1647
+ widget2.gridHeight
1648
+ ]
1649
+ }, undefined, true, undefined, this);
1650
+ if (widget2.layout === "comparison") {
1651
+ return /* @__PURE__ */ jsxDEV(ComparisonView, {
1652
+ description: widget2.description,
1653
+ items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
1654
+ title: widget2.name
1655
+ }, undefined, false, undefined, this);
1656
+ }
1657
+ if (widget2.layout === "timeline") {
1658
+ return /* @__PURE__ */ jsxDEV(TimelineView, {
1659
+ description: widget2.description,
1660
+ items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
1661
+ title: widget2.name
1662
+ }, undefined, false, undefined, this);
1663
+ }
1664
+ const binding2 = widget2.bindings[0];
1665
+ if (!binding2)
1666
+ return null;
1667
+ return /* @__PURE__ */ jsxDEV(VisualizationCard, {
1668
+ data: binding2.data,
1669
+ description: widget2.description ?? binding2.description,
1670
+ footer,
1671
+ height: binding2.height,
1672
+ spec: binding2.spec,
1673
+ title: widget2.name
1674
+ }, undefined, false, undefined, this);
1675
+ }
1676
+ function gridSpanClass(gridWidth) {
1677
+ if (gridWidth >= 12)
1678
+ return "md:col-span-2 xl:col-span-3";
1679
+ if (gridWidth >= 8)
1680
+ return "xl:col-span-2";
1681
+ if (gridWidth >= 6)
1682
+ return "md:col-span-2";
1683
+ return "";
1684
+ }
1685
+
1686
+ // src/ui/AnalyticsQueriesTable.tsx
1687
+ import { DataTable } from "@contractspec/lib.design-system";
1688
+ import { useContractTable } from "@contractspec/lib.presentation-runtime-react";
1689
+ import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
1690
+ import { HStack, VStack } from "@contractspec/lib.ui-kit-web/ui/stack";
1691
+ import { Text } from "@contractspec/lib.ui-kit-web/ui/text";
1692
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1693
+ "use client";
1694
+ var QUERY_TYPE_COLORS = {
1695
+ SQL: "default",
1696
+ METRIC: "secondary",
1697
+ AGGREGATION: "secondary",
1698
+ CUSTOM: "outline"
1072
1699
  };
1700
+ function formatJson(value) {
1701
+ return JSON.stringify(value, null, 2);
1702
+ }
1703
+ function AnalyticsQueriesTable({ queries }) {
1704
+ const controller = useContractTable({
1705
+ data: queries,
1706
+ columns: [
1707
+ {
1708
+ id: "query",
1709
+ header: "Query",
1710
+ label: "Query",
1711
+ accessor: (query) => query.name,
1712
+ cell: ({ item }) => /* @__PURE__ */ jsxDEV2(VStack, {
1713
+ gap: "xs",
1714
+ children: [
1715
+ /* @__PURE__ */ jsxDEV2(Text, {
1716
+ className: "font-medium text-sm",
1717
+ children: item.name
1718
+ }, undefined, false, undefined, this),
1719
+ /* @__PURE__ */ jsxDEV2(Text, {
1720
+ className: "text-muted-foreground text-xs",
1721
+ children: [
1722
+ "Updated ",
1723
+ item.updatedAt.toLocaleDateString()
1724
+ ]
1725
+ }, undefined, true, undefined, this)
1726
+ ]
1727
+ }, undefined, true, undefined, this),
1728
+ size: 240,
1729
+ minSize: 180,
1730
+ canSort: true,
1731
+ canPin: true,
1732
+ canResize: true
1733
+ },
1734
+ {
1735
+ id: "description",
1736
+ header: "Description",
1737
+ label: "Description",
1738
+ accessor: (query) => query.description ?? "",
1739
+ cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Text, {
1740
+ className: "line-clamp-2 text-muted-foreground text-sm",
1741
+ children: String(value || "No description")
1742
+ }, undefined, false, undefined, this),
1743
+ size: 300,
1744
+ minSize: 220,
1745
+ canSort: false,
1746
+ canHide: true,
1747
+ canResize: true
1748
+ },
1749
+ {
1750
+ id: "type",
1751
+ header: "Type",
1752
+ label: "Type",
1753
+ accessorKey: "type",
1754
+ cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Badge, {
1755
+ variant: QUERY_TYPE_COLORS[String(value)],
1756
+ children: String(value)
1757
+ }, undefined, false, undefined, this),
1758
+ size: 150,
1759
+ canSort: true,
1760
+ canHide: true,
1761
+ canResize: true
1762
+ },
1763
+ {
1764
+ id: "cacheTtlSeconds",
1765
+ header: "Cache TTL",
1766
+ label: "Cache TTL",
1767
+ accessorKey: "cacheTtlSeconds",
1768
+ cell: ({ value }) => `${String(value)}s`,
1769
+ align: "right",
1770
+ size: 140,
1771
+ canSort: true,
1772
+ canResize: true
1773
+ },
1774
+ {
1775
+ id: "isShared",
1776
+ header: "Shared",
1777
+ label: "Shared",
1778
+ accessorKey: "isShared",
1779
+ cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Badge, {
1780
+ variant: value ? "default" : "outline",
1781
+ children: value ? "Shared" : "Private"
1782
+ }, undefined, false, undefined, this),
1783
+ size: 140,
1784
+ canSort: true,
1785
+ canHide: true,
1786
+ canResize: true
1787
+ }
1788
+ ],
1789
+ initialState: {
1790
+ pagination: { pageIndex: 0, pageSize: 3 },
1791
+ columnVisibility: { description: false },
1792
+ columnPinning: { left: ["query"], right: [] }
1793
+ },
1794
+ renderExpandedContent: (query) => /* @__PURE__ */ jsxDEV2(VStack, {
1795
+ gap: "sm",
1796
+ className: "py-2",
1797
+ children: [
1798
+ /* @__PURE__ */ jsxDEV2(VStack, {
1799
+ gap: "xs",
1800
+ children: [
1801
+ /* @__PURE__ */ jsxDEV2(Text, {
1802
+ className: "font-medium text-sm",
1803
+ children: "Description"
1804
+ }, undefined, false, undefined, this),
1805
+ /* @__PURE__ */ jsxDEV2(Text, {
1806
+ className: "text-muted-foreground text-sm",
1807
+ children: query.description ?? "No description"
1808
+ }, undefined, false, undefined, this)
1809
+ ]
1810
+ }, undefined, true, undefined, this),
1811
+ query.sql ? /* @__PURE__ */ jsxDEV2(VStack, {
1812
+ gap: "xs",
1813
+ children: [
1814
+ /* @__PURE__ */ jsxDEV2(Text, {
1815
+ className: "font-medium text-sm",
1816
+ children: "SQL"
1817
+ }, undefined, false, undefined, this),
1818
+ /* @__PURE__ */ jsxDEV2("pre", {
1819
+ className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1820
+ children: query.sql
1821
+ }, undefined, false, undefined, this)
1822
+ ]
1823
+ }, undefined, true, undefined, this) : null,
1824
+ /* @__PURE__ */ jsxDEV2(VStack, {
1825
+ gap: "xs",
1826
+ children: [
1827
+ /* @__PURE__ */ jsxDEV2(Text, {
1828
+ className: "font-medium text-sm",
1829
+ children: "Definition"
1830
+ }, undefined, false, undefined, this),
1831
+ /* @__PURE__ */ jsxDEV2("pre", {
1832
+ className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1833
+ children: formatJson(query.definition)
1834
+ }, undefined, false, undefined, this)
1835
+ ]
1836
+ }, undefined, true, undefined, this)
1837
+ ]
1838
+ }, undefined, true, undefined, this),
1839
+ getCanExpand: () => true
1840
+ });
1841
+ return /* @__PURE__ */ jsxDEV2(DataTable, {
1842
+ controller,
1843
+ title: "Saved Queries",
1844
+ description: "Client-mode table using the shared ContractSpec controller and renderer.",
1845
+ toolbar: /* @__PURE__ */ jsxDEV2(HStack, {
1846
+ gap: "sm",
1847
+ className: "flex-wrap",
1848
+ children: [
1849
+ /* @__PURE__ */ jsxDEV2(Text, {
1850
+ className: "text-muted-foreground text-sm",
1851
+ children: [
1852
+ queries.length,
1853
+ " queries"
1854
+ ]
1855
+ }, undefined, true, undefined, this),
1856
+ /* @__PURE__ */ jsxDEV2(Text, {
1857
+ className: "text-muted-foreground text-sm",
1858
+ children: [
1859
+ queries.filter((query) => query.isShared).length,
1860
+ " shared"
1861
+ ]
1862
+ }, undefined, true, undefined, this)
1863
+ ]
1864
+ }, undefined, true, undefined, this),
1865
+ emptyState: /* @__PURE__ */ jsxDEV2("div", {
1866
+ className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
1867
+ children: "No queries saved"
1868
+ }, undefined, false, undefined, this)
1869
+ }, undefined, false, undefined, this);
1870
+ }
1871
+
1073
1872
  // src/ui/hooks/useAnalyticsData.ts
1074
- import { useCallback, useEffect, useState } from "react";
1075
1873
  import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1874
+ import { useCallback, useEffect, useState } from "react";
1076
1875
  "use client";
1077
1876
  function useAnalyticsData(projectId = "local-project") {
1078
1877
  const { handlers } = useTemplateRuntime();
@@ -1098,7 +1897,7 @@ function useAnalyticsData(projectId = "local-project") {
1098
1897
  if (first) {
1099
1898
  setSelectedDashboard(first);
1100
1899
  const dashboardWidgets = await analytics.getWidgets(first.id);
1101
- setWidgets(dashboardWidgets);
1900
+ setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(first.id));
1102
1901
  }
1103
1902
  }
1104
1903
  } catch (err) {
@@ -1113,7 +1912,7 @@ function useAnalyticsData(projectId = "local-project") {
1113
1912
  const selectDashboard = useCallback(async (dashboard) => {
1114
1913
  setSelectedDashboard(dashboard);
1115
1914
  const dashboardWidgets = await analytics.getWidgets(dashboard.id);
1116
- setWidgets(dashboardWidgets);
1915
+ setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(dashboard.id));
1117
1916
  }, [analytics]);
1118
1917
  const stats = {
1119
1918
  totalDashboards: dashboards.length,
@@ -1135,7 +1934,6 @@ function useAnalyticsData(projectId = "local-project") {
1135
1934
  }
1136
1935
 
1137
1936
  // src/ui/AnalyticsDashboard.tsx
1138
- import { useState as useState2 } from "react";
1139
1937
  import {
1140
1938
  Button,
1141
1939
  ErrorState,
@@ -1143,33 +1941,14 @@ import {
1143
1941
  StatCard,
1144
1942
  StatCardGroup
1145
1943
  } from "@contractspec/lib.design-system";
1146
- import { jsxDEV } from "react/jsx-dev-runtime";
1944
+ import { useMemo, useState as useState2 } from "react";
1945
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1147
1946
  "use client";
1148
1947
  var STATUS_COLORS = {
1149
1948
  PUBLISHED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1150
1949
  DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1151
1950
  ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
1152
1951
  };
1153
- var WIDGET_ICONS = {
1154
- LINE_CHART: "\uD83D\uDCC8",
1155
- BAR_CHART: "\uD83D\uDCCA",
1156
- PIE_CHART: "\uD83E\uDD67",
1157
- AREA_CHART: "\uD83D\uDCC9",
1158
- SCATTER_PLOT: "\u26AC",
1159
- METRIC: "\uD83D\uDD22",
1160
- TABLE: "\uD83D\uDCCB",
1161
- HEATMAP: "\uD83D\uDDFA\uFE0F",
1162
- FUNNEL: "\u23EC",
1163
- MAP: "\uD83C\uDF0D",
1164
- TEXT: "\uD83D\uDCDD",
1165
- EMBED: "\uD83D\uDD17"
1166
- };
1167
- var QUERY_TYPE_COLORS = {
1168
- SQL: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
1169
- METRIC: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
1170
- AGGREGATION: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
1171
- CUSTOM: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
1172
- };
1173
1952
  function AnalyticsDashboard() {
1174
1953
  const [activeTab, setActiveTab] = useState2("dashboards");
1175
1954
  const {
@@ -1187,33 +1966,34 @@ function AnalyticsDashboard() {
1187
1966
  { id: "dashboards", label: "Dashboards", icon: "\uD83D\uDCCA" },
1188
1967
  { id: "queries", label: "Queries", icon: "\uD83D\uDD0D" }
1189
1968
  ];
1969
+ const resolvedWidgets = useMemo(() => widgets.map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2)), [widgets]);
1190
1970
  if (loading) {
1191
- return /* @__PURE__ */ jsxDEV(LoaderBlock, {
1971
+ return /* @__PURE__ */ jsxDEV3(LoaderBlock, {
1192
1972
  label: "Loading Analytics..."
1193
1973
  }, undefined, false, undefined, this);
1194
1974
  }
1195
1975
  if (error) {
1196
- return /* @__PURE__ */ jsxDEV(ErrorState, {
1976
+ return /* @__PURE__ */ jsxDEV3(ErrorState, {
1197
1977
  title: "Failed to load Analytics",
1198
1978
  description: error.message,
1199
1979
  onRetry: refetch,
1200
1980
  retryLabel: "Retry"
1201
1981
  }, undefined, false, undefined, this);
1202
1982
  }
1203
- return /* @__PURE__ */ jsxDEV("div", {
1983
+ return /* @__PURE__ */ jsxDEV3("div", {
1204
1984
  className: "space-y-6",
1205
1985
  children: [
1206
- /* @__PURE__ */ jsxDEV("div", {
1986
+ /* @__PURE__ */ jsxDEV3("div", {
1207
1987
  className: "flex items-center justify-between",
1208
1988
  children: [
1209
- /* @__PURE__ */ jsxDEV("h2", {
1210
- className: "text-2xl font-bold",
1989
+ /* @__PURE__ */ jsxDEV3("h2", {
1990
+ className: "font-bold text-2xl",
1211
1991
  children: "Analytics Dashboard"
1212
1992
  }, undefined, false, undefined, this),
1213
- /* @__PURE__ */ jsxDEV(Button, {
1993
+ /* @__PURE__ */ jsxDEV3(Button, {
1214
1994
  onClick: () => alert("Create dashboard modal"),
1215
1995
  children: [
1216
- /* @__PURE__ */ jsxDEV("span", {
1996
+ /* @__PURE__ */ jsxDEV3("span", {
1217
1997
  className: "mr-2",
1218
1998
  children: "+"
1219
1999
  }, undefined, false, undefined, this),
@@ -1222,55 +2002,55 @@ function AnalyticsDashboard() {
1222
2002
  }, undefined, true, undefined, this)
1223
2003
  ]
1224
2004
  }, undefined, true, undefined, this),
1225
- /* @__PURE__ */ jsxDEV(StatCardGroup, {
2005
+ /* @__PURE__ */ jsxDEV3(StatCardGroup, {
1226
2006
  children: [
1227
- /* @__PURE__ */ jsxDEV(StatCard, {
2007
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1228
2008
  label: "Dashboards",
1229
2009
  value: stats.totalDashboards,
1230
2010
  hint: `${stats.publishedDashboards} published`
1231
2011
  }, undefined, false, undefined, this),
1232
- /* @__PURE__ */ jsxDEV(StatCard, {
2012
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1233
2013
  label: "Queries",
1234
2014
  value: stats.totalQueries,
1235
2015
  hint: `${stats.sharedQueries} shared`
1236
2016
  }, undefined, false, undefined, this),
1237
- /* @__PURE__ */ jsxDEV(StatCard, {
2017
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1238
2018
  label: "Widgets",
1239
2019
  value: widgets.length,
1240
2020
  hint: "on current dashboard"
1241
2021
  }, undefined, false, undefined, this)
1242
2022
  ]
1243
2023
  }, undefined, true, undefined, this),
1244
- /* @__PURE__ */ jsxDEV("nav", {
1245
- className: "bg-muted flex gap-1 rounded-lg p-1",
2024
+ /* @__PURE__ */ jsxDEV3("nav", {
2025
+ className: "flex gap-1 rounded-lg bg-muted p-1",
1246
2026
  role: "tablist",
1247
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV(Button, {
2027
+ children: tabs.map((tab) => /* @__PURE__ */ jsxDEV3(Button, {
1248
2028
  type: "button",
1249
2029
  role: "tab",
1250
2030
  "aria-selected": activeTab === tab.id,
1251
2031
  onClick: () => setActiveTab(tab.id),
1252
- className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
2032
+ className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
1253
2033
  children: [
1254
- /* @__PURE__ */ jsxDEV("span", {
2034
+ /* @__PURE__ */ jsxDEV3("span", {
1255
2035
  children: tab.icon
1256
2036
  }, undefined, false, undefined, this),
1257
2037
  tab.label
1258
2038
  ]
1259
2039
  }, tab.id, true, undefined, this))
1260
2040
  }, undefined, false, undefined, this),
1261
- /* @__PURE__ */ jsxDEV("div", {
2041
+ /* @__PURE__ */ jsxDEV3("div", {
1262
2042
  className: "min-h-[400px]",
1263
2043
  role: "tabpanel",
1264
2044
  children: [
1265
- activeTab === "dashboards" && /* @__PURE__ */ jsxDEV("div", {
2045
+ activeTab === "dashboards" && /* @__PURE__ */ jsxDEV3("div", {
1266
2046
  className: "space-y-6",
1267
2047
  children: [
1268
- /* @__PURE__ */ jsxDEV("div", {
2048
+ /* @__PURE__ */ jsxDEV3("div", {
1269
2049
  className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1270
2050
  children: [
1271
- dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV("div", {
2051
+ dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV3("div", {
1272
2052
  onClick: () => selectDashboard(dashboard),
1273
- className: `border-border bg-card cursor-pointer rounded-lg border p-4 transition-all ${selectedDashboard?.id === dashboard.id ? "ring-primary ring-2" : "hover:bg-muted/50"}`,
2053
+ className: `cursor-pointer rounded-lg border border-border bg-card p-4 transition-all ${selectedDashboard?.id === dashboard.id ? "ring-2 ring-primary" : "hover:bg-muted/50"}`,
1274
2054
  role: "button",
1275
2055
  tabIndex: 0,
1276
2056
  onKeyDown: (e) => {
@@ -1278,33 +2058,33 @@ function AnalyticsDashboard() {
1278
2058
  selectDashboard(dashboard);
1279
2059
  },
1280
2060
  children: [
1281
- /* @__PURE__ */ jsxDEV("div", {
2061
+ /* @__PURE__ */ jsxDEV3("div", {
1282
2062
  className: "mb-2 flex items-center justify-between",
1283
2063
  children: [
1284
- /* @__PURE__ */ jsxDEV("h3", {
2064
+ /* @__PURE__ */ jsxDEV3("h3", {
1285
2065
  className: "font-medium",
1286
2066
  children: dashboard.name
1287
2067
  }, undefined, false, undefined, this),
1288
- /* @__PURE__ */ jsxDEV("span", {
1289
- className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[dashboard.status] ?? ""}`,
2068
+ /* @__PURE__ */ jsxDEV3("span", {
2069
+ className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[dashboard.status] ?? ""}`,
1290
2070
  children: dashboard.status
1291
2071
  }, undefined, false, undefined, this)
1292
2072
  ]
1293
2073
  }, undefined, true, undefined, this),
1294
- /* @__PURE__ */ jsxDEV("p", {
1295
- className: "text-muted-foreground mb-3 text-sm",
2074
+ /* @__PURE__ */ jsxDEV3("p", {
2075
+ className: "mb-3 text-muted-foreground text-sm",
1296
2076
  children: dashboard.description
1297
2077
  }, undefined, false, undefined, this),
1298
- /* @__PURE__ */ jsxDEV("div", {
1299
- className: "text-muted-foreground flex items-center justify-between text-xs",
2078
+ /* @__PURE__ */ jsxDEV3("div", {
2079
+ className: "flex items-center justify-between text-muted-foreground text-xs",
1300
2080
  children: [
1301
- /* @__PURE__ */ jsxDEV("span", {
2081
+ /* @__PURE__ */ jsxDEV3("span", {
1302
2082
  children: [
1303
2083
  "/",
1304
2084
  dashboard.slug
1305
2085
  ]
1306
2086
  }, undefined, true, undefined, this),
1307
- dashboard.isPublic && /* @__PURE__ */ jsxDEV("span", {
2087
+ dashboard.isPublic && /* @__PURE__ */ jsxDEV3("span", {
1308
2088
  className: "text-green-600 dark:text-green-400",
1309
2089
  children: "\uD83C\uDF10 Public"
1310
2090
  }, undefined, false, undefined, this)
@@ -1312,149 +2092,20 @@ function AnalyticsDashboard() {
1312
2092
  }, undefined, true, undefined, this)
1313
2093
  ]
1314
2094
  }, dashboard.id, true, undefined, this)),
1315
- dashboards.length === 0 && /* @__PURE__ */ jsxDEV("div", {
1316
- className: "text-muted-foreground col-span-full flex h-64 items-center justify-center",
2095
+ dashboards.length === 0 && /* @__PURE__ */ jsxDEV3("div", {
2096
+ className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
1317
2097
  children: "No dashboards created yet"
1318
2098
  }, undefined, false, undefined, this)
1319
2099
  ]
1320
2100
  }, undefined, true, undefined, this),
1321
- selectedDashboard && widgets.length > 0 && /* @__PURE__ */ jsxDEV("div", {
1322
- children: [
1323
- /* @__PURE__ */ jsxDEV("h3", {
1324
- className: "mb-4 text-lg font-semibold",
1325
- children: [
1326
- 'Widgets in "',
1327
- selectedDashboard.name,
1328
- '"'
1329
- ]
1330
- }, undefined, true, undefined, this),
1331
- /* @__PURE__ */ jsxDEV("div", {
1332
- className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1333
- children: widgets.map((widget) => /* @__PURE__ */ jsxDEV("div", {
1334
- className: "border-border bg-card rounded-lg border p-4",
1335
- children: [
1336
- /* @__PURE__ */ jsxDEV("div", {
1337
- className: "mb-2 flex items-center gap-2",
1338
- children: [
1339
- /* @__PURE__ */ jsxDEV("span", {
1340
- className: "text-xl",
1341
- children: WIDGET_ICONS[widget.type] ?? "\uD83D\uDCCA"
1342
- }, undefined, false, undefined, this),
1343
- /* @__PURE__ */ jsxDEV("span", {
1344
- className: "font-medium",
1345
- children: widget.name
1346
- }, undefined, false, undefined, this)
1347
- ]
1348
- }, undefined, true, undefined, this),
1349
- /* @__PURE__ */ jsxDEV("div", {
1350
- className: "text-muted-foreground text-sm",
1351
- children: widget.type.replace(/_/g, " ")
1352
- }, undefined, false, undefined, this),
1353
- /* @__PURE__ */ jsxDEV("div", {
1354
- className: "text-muted-foreground mt-2 text-xs",
1355
- children: [
1356
- "Position: (",
1357
- widget.gridX,
1358
- ", ",
1359
- widget.gridY,
1360
- ") \u2022",
1361
- " ",
1362
- widget.gridWidth,
1363
- "x",
1364
- widget.gridHeight
1365
- ]
1366
- }, undefined, true, undefined, this)
1367
- ]
1368
- }, widget.id, true, undefined, this))
1369
- }, undefined, false, undefined, this)
1370
- ]
1371
- }, undefined, true, undefined, this)
2101
+ selectedDashboard ? /* @__PURE__ */ jsxDEV3(AnalyticsWidgetBoard, {
2102
+ dashboardName: selectedDashboard.name,
2103
+ widgets: resolvedWidgets
2104
+ }, undefined, false, undefined, this) : null
1372
2105
  ]
1373
2106
  }, undefined, true, undefined, this),
1374
- activeTab === "queries" && /* @__PURE__ */ jsxDEV("div", {
1375
- className: "border-border rounded-lg border",
1376
- children: /* @__PURE__ */ jsxDEV("table", {
1377
- className: "w-full",
1378
- children: [
1379
- /* @__PURE__ */ jsxDEV("thead", {
1380
- className: "border-border bg-muted/30 border-b",
1381
- children: /* @__PURE__ */ jsxDEV("tr", {
1382
- children: [
1383
- /* @__PURE__ */ jsxDEV("th", {
1384
- className: "px-4 py-3 text-left text-sm font-medium",
1385
- children: "Query"
1386
- }, undefined, false, undefined, this),
1387
- /* @__PURE__ */ jsxDEV("th", {
1388
- className: "px-4 py-3 text-left text-sm font-medium",
1389
- children: "Type"
1390
- }, undefined, false, undefined, this),
1391
- /* @__PURE__ */ jsxDEV("th", {
1392
- className: "px-4 py-3 text-left text-sm font-medium",
1393
- children: "Cache TTL"
1394
- }, undefined, false, undefined, this),
1395
- /* @__PURE__ */ jsxDEV("th", {
1396
- className: "px-4 py-3 text-left text-sm font-medium",
1397
- children: "Shared"
1398
- }, undefined, false, undefined, this)
1399
- ]
1400
- }, undefined, true, undefined, this)
1401
- }, undefined, false, undefined, this),
1402
- /* @__PURE__ */ jsxDEV("tbody", {
1403
- className: "divide-border divide-y",
1404
- children: [
1405
- queries.map((query) => /* @__PURE__ */ jsxDEV("tr", {
1406
- className: "hover:bg-muted/50",
1407
- children: [
1408
- /* @__PURE__ */ jsxDEV("td", {
1409
- className: "px-4 py-3",
1410
- children: [
1411
- /* @__PURE__ */ jsxDEV("div", {
1412
- className: "font-medium",
1413
- children: query.name
1414
- }, undefined, false, undefined, this),
1415
- /* @__PURE__ */ jsxDEV("div", {
1416
- className: "text-muted-foreground text-sm",
1417
- children: query.description
1418
- }, undefined, false, undefined, this)
1419
- ]
1420
- }, undefined, true, undefined, this),
1421
- /* @__PURE__ */ jsxDEV("td", {
1422
- className: "px-4 py-3",
1423
- children: /* @__PURE__ */ jsxDEV("span", {
1424
- className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${QUERY_TYPE_COLORS[query.type] ?? ""}`,
1425
- children: query.type
1426
- }, undefined, false, undefined, this)
1427
- }, undefined, false, undefined, this),
1428
- /* @__PURE__ */ jsxDEV("td", {
1429
- className: "text-muted-foreground px-4 py-3 text-sm",
1430
- children: [
1431
- query.cacheTtlSeconds,
1432
- "s"
1433
- ]
1434
- }, undefined, true, undefined, this),
1435
- /* @__PURE__ */ jsxDEV("td", {
1436
- className: "px-4 py-3",
1437
- children: query.isShared ? /* @__PURE__ */ jsxDEV("span", {
1438
- className: "text-green-600 dark:text-green-400",
1439
- children: "\u2713"
1440
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {
1441
- className: "text-muted-foreground",
1442
- children: "\u2014"
1443
- }, undefined, false, undefined, this)
1444
- }, undefined, false, undefined, this)
1445
- ]
1446
- }, query.id, true, undefined, this)),
1447
- queries.length === 0 && /* @__PURE__ */ jsxDEV("tr", {
1448
- children: /* @__PURE__ */ jsxDEV("td", {
1449
- colSpan: 4,
1450
- className: "text-muted-foreground px-4 py-8 text-center",
1451
- children: "No queries saved"
1452
- }, undefined, false, undefined, this)
1453
- }, undefined, false, undefined, this)
1454
- ]
1455
- }, undefined, true, undefined, this)
1456
- ]
1457
- }, undefined, true, undefined, this)
2107
+ activeTab === "queries" && /* @__PURE__ */ jsxDEV3(AnalyticsQueriesTable, {
2108
+ queries
1458
2109
  }, undefined, false, undefined, this)
1459
2110
  ]
1460
2111
  }, undefined, true, undefined, this)
@@ -1464,222 +2115,204 @@ function AnalyticsDashboard() {
1464
2115
 
1465
2116
  // src/ui/hooks/index.ts
1466
2117
  "use client";
1467
- // src/query-engine/index.ts
1468
- class InMemoryQueryCache {
1469
- cache = new Map;
1470
- async get(key) {
1471
- const entry = this.cache.get(key);
1472
- if (!entry)
1473
- return null;
1474
- if (entry.expiresAt < new Date) {
1475
- this.cache.delete(key);
1476
- return null;
1477
- }
1478
- return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
1479
- }
1480
- async set(key, result, ttlSeconds) {
1481
- const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1482
- this.cache.set(key, { result, expiresAt });
2118
+
2119
+ // src/ui/renderers/analytics.markdown.ts
2120
+ var mockDashboards = [
2121
+ {
2122
+ id: "dash-1",
2123
+ name: "Sales Overview",
2124
+ slug: "sales-overview",
2125
+ status: "PUBLISHED",
2126
+ widgetCount: 11,
2127
+ viewCount: 1250,
2128
+ lastViewedAt: "2026-03-18T12:00:00Z"
2129
+ },
2130
+ {
2131
+ id: "dash-2",
2132
+ name: "User Engagement",
2133
+ slug: "user-engagement",
2134
+ status: "PUBLISHED",
2135
+ widgetCount: 8,
2136
+ viewCount: 890,
2137
+ lastViewedAt: "2026-03-18T10:00:00Z"
1483
2138
  }
1484
- async invalidate(pattern) {
1485
- const regex = new RegExp(pattern);
1486
- for (const key of this.cache.keys()) {
1487
- if (regex.test(key)) {
1488
- this.cache.delete(key);
1489
- }
1490
- }
2139
+ ];
2140
+ var mockQueries = [
2141
+ {
2142
+ id: "q-1",
2143
+ name: "Monthly Revenue",
2144
+ type: "AGGREGATION",
2145
+ isShared: true,
2146
+ executionCount: 1500
2147
+ },
2148
+ {
2149
+ id: "q-2",
2150
+ name: "User Growth",
2151
+ type: "METRIC",
2152
+ isShared: true,
2153
+ executionCount: 890
2154
+ },
2155
+ {
2156
+ id: "q-3",
2157
+ name: "Product Sales",
2158
+ type: "SQL",
2159
+ isShared: false,
2160
+ executionCount: 340
2161
+ },
2162
+ {
2163
+ id: "q-4",
2164
+ name: "Conversion Funnel",
2165
+ type: "AGGREGATION",
2166
+ isShared: true,
2167
+ executionCount: 450
1491
2168
  }
2169
+ ];
2170
+ function dashboardWidgets(dashboardId) {
2171
+ return createExampleWidgets(dashboardId).map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2));
1492
2172
  }
1493
-
1494
- class BasicQueryEngine {
1495
- cache;
1496
- constructor(cache) {
1497
- this.cache = cache ?? new InMemoryQueryCache;
1498
- }
1499
- async execute(definition, params) {
1500
- const startTime = Date.now();
1501
- const validation = this.validateQuery(definition);
1502
- if (!validation.valid) {
2173
+ var analyticsDashboardMarkdownRenderer = {
2174
+ target: "markdown",
2175
+ render: async (desc) => {
2176
+ if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
2177
+ throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
2178
+ }
2179
+ const dashboard = mockDashboards[0];
2180
+ if (!dashboard) {
1503
2181
  return {
1504
- data: [],
1505
- columns: [],
1506
- rowCount: 0,
1507
- executionTimeMs: Date.now() - startTime,
1508
- cached: false,
1509
- error: validation.errors.join(", ")
2182
+ mimeType: "text/markdown",
2183
+ body: `# No Dashboards
2184
+
2185
+ No dashboards available.`
1510
2186
  };
1511
2187
  }
1512
- const cacheKey = this.buildCacheKey(definition, params);
1513
- const cachedResult = await this.cache.get(cacheKey);
1514
- if (cachedResult) {
1515
- return cachedResult;
1516
- }
1517
- let result;
1518
- switch (definition.type) {
1519
- case "AGGREGATION":
1520
- if (!definition.aggregation) {
1521
- throw new Error("Aggregation definition is missing");
1522
- }
1523
- result = await this.executeAggregation(definition.aggregation, params);
1524
- break;
1525
- case "METRIC":
1526
- if (!definition.metricIds) {
1527
- throw new Error("Metric IDs are missing");
1528
- }
1529
- result = await this.executeMetric(definition.metricIds, params);
1530
- break;
1531
- case "SQL":
1532
- if (!definition.sql) {
1533
- throw new Error("SQL query is missing");
1534
- }
1535
- result = await this.executeSql(definition.sql, params);
1536
- break;
1537
- default:
1538
- result = {
1539
- data: [],
1540
- columns: [],
1541
- rowCount: 0,
1542
- executionTimeMs: Date.now() - startTime,
1543
- cached: false,
1544
- error: `Unknown query type: ${definition.type}`
1545
- };
1546
- }
1547
- result.executionTimeMs = Date.now() - startTime;
1548
- result.cached = false;
1549
- await this.cache.set(cacheKey, result, 300);
1550
- return result;
1551
- }
1552
- validateQuery(definition) {
1553
- const errors = [];
1554
- if (!definition.type) {
1555
- errors.push("Query type is required");
2188
+ const widgets = dashboardWidgets(dashboard.id);
2189
+ const metricWidgets = widgets.filter((widget2) => widget2.bindings[0]?.spec.visualization.kind === "metric");
2190
+ const lines = [
2191
+ `# ${dashboard.name}`,
2192
+ "",
2193
+ "> Contract-backed analytics dashboard overview.",
2194
+ "",
2195
+ "## Key Metrics",
2196
+ ""
2197
+ ];
2198
+ for (const widget2 of metricWidgets) {
2199
+ const binding2 = widget2.bindings[0];
2200
+ if (!binding2)
2201
+ continue;
2202
+ lines.push(`- **${widget2.name}** via \`${binding2.spec.meta.key}\``);
1556
2203
  }
1557
- switch (definition.type) {
1558
- case "SQL":
1559
- if (!definition.sql) {
1560
- errors.push("SQL query is required for SQL type");
1561
- }
1562
- break;
1563
- case "METRIC":
1564
- if (!definition.metricIds || definition.metricIds.length === 0) {
1565
- errors.push("Metric IDs are required for METRIC type");
1566
- }
1567
- break;
1568
- case "AGGREGATION":
1569
- if (!definition.aggregation) {
1570
- errors.push("Aggregation definition is required for AGGREGATION type");
1571
- } else {
1572
- if (!definition.aggregation.source) {
1573
- errors.push("Aggregation source is required");
1574
- }
1575
- if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
1576
- errors.push("At least one measure is required");
1577
- }
1578
- }
1579
- break;
2204
+ lines.push("");
2205
+ lines.push("## Visual Blocks");
2206
+ lines.push("");
2207
+ for (const widget2 of widgets) {
2208
+ const kinds = widget2.bindings.map((binding2) => binding2.spec.visualization.kind).join(", ");
2209
+ lines.push(`- **${widget2.name}** (${widget2.layout}) \u2192 ${kinds}`);
1580
2210
  }
1581
- return { valid: errors.length === 0, errors };
1582
- }
1583
- buildCacheKey(definition, params) {
1584
- return JSON.stringify({ definition, params });
1585
- }
1586
- async executeAggregation(aggregation, params) {
1587
- const columns = [
1588
- ...aggregation.dimensions.map((d) => ({
1589
- name: d.name,
1590
- type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
1591
- label: d.name
1592
- })),
1593
- ...aggregation.measures.map((m) => ({
1594
- name: m.name,
1595
- type: "NUMBER",
1596
- label: m.name,
1597
- format: m.format
1598
- }))
1599
- ];
1600
- const data = this.generateMockData(aggregation, params);
2211
+ lines.push("");
2212
+ lines.push("## Dashboard Stats");
2213
+ lines.push("");
2214
+ lines.push("| Metric | Value |");
2215
+ lines.push("|--------|-------|");
2216
+ lines.push(`| Total Dashboards | ${mockDashboards.length} |`);
2217
+ lines.push(`| Published | ${mockDashboards.filter((item) => item.status === "PUBLISHED").length} |`);
2218
+ lines.push(`| Shared Queries | ${mockQueries.filter((query) => query.isShared).length} |`);
1601
2219
  return {
1602
- data,
1603
- columns,
1604
- rowCount: data.length,
1605
- executionTimeMs: 0,
1606
- cached: false
2220
+ mimeType: "text/markdown",
2221
+ body: lines.join(`
2222
+ `)
1607
2223
  };
1608
2224
  }
1609
- async executeMetric(metricIds, _params) {
1610
- const data = metricIds.map((id) => ({
1611
- metricId: id,
1612
- value: Math.random() * 1000,
1613
- change: (Math.random() - 0.5) * 20
1614
- }));
2225
+ };
2226
+ var dashboardListMarkdownRenderer = {
2227
+ target: "markdown",
2228
+ render: async (desc) => {
2229
+ if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
2230
+ throw new Error("dashboardListMarkdownRenderer: not DashboardList");
2231
+ }
2232
+ const lines = [
2233
+ "# Dashboards",
2234
+ "",
2235
+ "> Browse and manage analytics dashboards",
2236
+ "",
2237
+ "| Dashboard | Widgets | Views | Status | Last Viewed |",
2238
+ "|-----------|---------|-------|--------|-------------|"
2239
+ ];
2240
+ for (const dashboard of mockDashboards) {
2241
+ const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
2242
+ const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "\u26AB";
2243
+ lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
2244
+ }
1615
2245
  return {
1616
- data,
1617
- columns: [
1618
- { name: "metricId", type: "STRING" },
1619
- { name: "value", type: "NUMBER" },
1620
- { name: "change", type: "NUMBER" }
1621
- ],
1622
- rowCount: data.length,
1623
- executionTimeMs: 0,
1624
- cached: false
2246
+ mimeType: "text/markdown",
2247
+ body: lines.join(`
2248
+ `)
1625
2249
  };
1626
2250
  }
1627
- async executeSql(_sql, _params) {
2251
+ };
2252
+ var queryBuilderMarkdownRenderer = {
2253
+ target: "markdown",
2254
+ render: async (desc) => {
2255
+ if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
2256
+ throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
2257
+ }
2258
+ const lines = [
2259
+ "# Query Builder",
2260
+ "",
2261
+ "> Create and manage reusable data queries.",
2262
+ "",
2263
+ "| Query | Type | Shared | Executions |",
2264
+ "|-------|------|--------|------------|"
2265
+ ];
2266
+ for (const query of mockQueries) {
2267
+ lines.push(`| ${query.name} | ${query.type} | ${query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12"} | ${query.executionCount.toLocaleString()} |`);
2268
+ }
2269
+ lines.push("");
2270
+ lines.push("## Visualization Contracts");
2271
+ lines.push("");
2272
+ lines.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types.");
1628
2273
  return {
1629
- data: [],
1630
- columns: [],
1631
- rowCount: 0,
1632
- executionTimeMs: 0,
1633
- cached: false,
1634
- error: "SQL execution not implemented in demo"
2274
+ mimeType: "text/markdown",
2275
+ body: lines.join(`
2276
+ `)
1635
2277
  };
1636
2278
  }
1637
- generateMockData(aggregation, params) {
1638
- const data = [];
1639
- const rowCount = 10;
1640
- const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
1641
- for (let i = 0;i < rowCount; i++) {
1642
- const row = {};
1643
- for (const dim of aggregation.dimensions) {
1644
- if (dim.type === "TIME") {
1645
- const date = new Date(params.dateRange?.start ?? new Date);
1646
- date.setDate(date.getDate() + i);
1647
- row[dim.name] = date.toISOString().split("T")[0];
1648
- } else {
1649
- row[dim.name] = `${dim.name}_${i % 5}`;
1650
- }
1651
- }
1652
- for (const measure of aggregation.measures) {
1653
- const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
1654
- const noise = (Math.random() - 0.5) * 20;
1655
- row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
1656
- }
1657
- data.push(row);
1658
- }
1659
- return data;
1660
- }
1661
- }
1662
- function createQueryEngine(cache) {
1663
- return new BasicQueryEngine(cache);
1664
- }
2279
+ };
1665
2280
  export {
2281
+ visualizationRefKey,
1666
2282
  useAnalyticsData,
2283
+ resolveAnalyticsWidget,
2284
+ refOf,
1667
2285
  queryBuilderMarkdownRenderer,
1668
2286
  dashboardListMarkdownRenderer,
1669
2287
  createQueryEngine,
1670
2288
  createPosthogQueryEngine,
2289
+ createExampleWidgets,
1671
2290
  createAnalyticsHandlers,
1672
2291
  analyticsDashboardMarkdownRenderer,
2292
+ RevenueTrendVisualization,
2293
+ RevenueMetricVisualization,
2294
+ RetentionAreaVisualization,
2295
+ RegionalRevenueVisualization,
1673
2296
  QueryTypeEnum,
1674
2297
  QueryResultModel,
1675
2298
  QueryModel,
1676
2299
  PosthogQueryEngine,
2300
+ PipelineScatterVisualization,
1677
2301
  InMemoryQueryCache,
1678
2302
  ExecuteQueryInputModel,
1679
2303
  ExecuteQueryContract,
2304
+ EngagementHeatmapVisualization,
1680
2305
  CreateQueryInputModel,
1681
2306
  CreateQueryContract,
2307
+ ConversionFunnelVisualization,
2308
+ ChannelMixVisualization,
1682
2309
  BasicQueryEngine,
2310
+ AnalyticsVisualizationSpecs,
2311
+ AnalyticsVisualizationSpecMap,
2312
+ AnalyticsVisualizationSampleData,
2313
+ AnalyticsVisualizationRegistry,
2314
+ AnalyticsVisualizationRefs,
1683
2315
  AnalyticsDashboardFeature,
1684
- AnalyticsDashboard
2316
+ AnalyticsDashboard,
2317
+ AccountCoverageGeoVisualization
1685
2318
  };