derive-dashboards 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/README.md +4 -3
  2. package/dist/adapter/sql-adapter.mjs +4 -4
  3. package/dist/body.mjs +11 -1
  4. package/dist/cache.d.mts +1 -1
  5. package/dist/cli/check.mjs +14 -1
  6. package/dist/cli/import/dbt-schema.mjs +2 -2
  7. package/dist/cli/import/index.mjs +2 -2
  8. package/dist/core/conformance/cases.d.mts +3 -0
  9. package/dist/core/conformance/cases.mjs +20 -4
  10. package/dist/core/conformance/check.mjs +6 -3
  11. package/dist/core/conformance/drill-cases.mjs +120 -0
  12. package/dist/core/document/view.d.mts +26 -7
  13. package/dist/core/document/view.mjs +42 -11
  14. package/dist/core/engine/index.d.mts +14 -2
  15. package/dist/core/engine/index.mjs +12 -1
  16. package/dist/core/engine/members.mjs +1 -1
  17. package/dist/core/engine/postgres.mjs +1 -1
  18. package/dist/core/engine/record-layout.d.mts +11 -0
  19. package/dist/core/engine/record-layout.mjs +7 -7
  20. package/dist/core/engine/records.d.mts +3 -2
  21. package/dist/core/engine/records.mjs +2 -1
  22. package/dist/core/engine/segmented.mjs +5 -2
  23. package/dist/core/engine/sql-records.mjs +2 -1
  24. package/dist/core/engine/statement.mjs +37 -3
  25. package/dist/core/engine/types.d.mts +3 -0
  26. package/dist/core/engine/version.d.mts +1 -1
  27. package/dist/core/engine/version.mjs +1 -1
  28. package/dist/core/error/codes.d.mts +31 -0
  29. package/dist/core/error/codes.mjs +28 -1
  30. package/dist/core/index.d.mts +9 -5
  31. package/dist/core/index.mjs +5 -3
  32. package/dist/core/model/catalog/check.mjs +1 -1
  33. package/dist/core/model/hints.d.mts +36 -0
  34. package/dist/core/model/member.d.mts +4 -2
  35. package/dist/core/model/member.mjs +16 -3
  36. package/dist/core/model/types.d.mts +8 -6
  37. package/dist/core/model/validate/drill.mjs +70 -0
  38. package/dist/core/model/validate/index.mjs +3 -0
  39. package/dist/core/model/validate/shape.mjs +150 -0
  40. package/dist/core/model/validate/source.mjs +5 -3
  41. package/dist/core/query/alias.mjs +7 -1
  42. package/dist/core/query/drill/compose.d.mts +22 -0
  43. package/dist/core/query/drill/compose.mjs +85 -0
  44. package/dist/core/query/drill/fields.d.mts +21 -0
  45. package/dist/core/query/drill/fields.mjs +91 -0
  46. package/dist/core/query/drill/internal.d.mts +11 -0
  47. package/dist/core/query/drill/items.d.mts +29 -0
  48. package/dist/core/query/drill/items.mjs +98 -0
  49. package/dist/core/query/drill/line.d.mts +31 -0
  50. package/dist/core/query/drill/line.mjs +183 -0
  51. package/dist/core/query/drill/links.d.mts +33 -0
  52. package/dist/core/query/drill/links.mjs +31 -0
  53. package/dist/core/query/drill/operand.mjs +7 -0
  54. package/dist/core/query/drill/scopes.d.mts +22 -0
  55. package/dist/core/query/drill/scopes.mjs +58 -0
  56. package/dist/core/query/drill/selection.d.mts +37 -0
  57. package/dist/core/query/drill/selection.mjs +144 -0
  58. package/dist/core/query/drill/steps.d.mts +14 -0
  59. package/dist/core/query/drill/steps.mjs +35 -0
  60. package/dist/core/query/drill/synthetic-expr.mjs +85 -0
  61. package/dist/core/query/drill/synthetic.d.mts +22 -0
  62. package/dist/core/query/drill/synthetic.mjs +165 -0
  63. package/dist/core/query/drill/time.d.mts +11 -0
  64. package/dist/core/query/drill/time.mjs +71 -0
  65. package/dist/core/query/drill/types.d.mts +155 -0
  66. package/dist/core/query/drill/types.mjs +4 -0
  67. package/dist/core/query/drill/views.d.mts +62 -0
  68. package/dist/core/query/drill/views.mjs +257 -0
  69. package/dist/core/query/segments.d.mts +12 -2
  70. package/dist/core/query/segments.mjs +3 -1
  71. package/dist/core/result/columns.mjs +17 -4
  72. package/dist/core/result/types.d.mts +5 -1
  73. package/dist/core/schema/answer-parts.mjs +117 -0
  74. package/dist/core/schema/answers.d.mts +2108 -128
  75. package/dist/core/schema/answers.mjs +10 -113
  76. package/dist/core/schema/commands.d.mts +2 -2
  77. package/dist/core/schema/document.d.mts +1 -1
  78. package/dist/core/schema/drill-answers.mjs +179 -0
  79. package/dist/core/schema/drill.d.mts +260 -0
  80. package/dist/core/schema/drill.mjs +107 -0
  81. package/dist/core/schema/index.d.mts +4 -2
  82. package/dist/core/schema/index.mjs +4 -2
  83. package/dist/core/schema/picks.d.mts +35 -0
  84. package/dist/core/schema/picks.mjs +23 -0
  85. package/dist/core/schema/query.d.mts +1 -1
  86. package/dist/core/schema/tools.mjs +1 -1
  87. package/dist/core/schema/view.d.mts +0 -35
  88. package/dist/core/schema/view.mjs +19 -24
  89. package/dist/core/store/schema.d.mts +5 -0
  90. package/dist/core/store/schema.mjs +10 -0
  91. package/dist/core/types/api.d.mts +15 -1
  92. package/dist/core/types/api.mjs +1 -1
  93. package/dist/core/types/drill-api.d.mts +210 -0
  94. package/dist/core/types/options.d.mts +21 -0
  95. package/dist/core/types/viewer.d.mts +5 -0
  96. package/dist/cursor-seal.d.mts +8 -0
  97. package/dist/cursor-seal.mjs +98 -0
  98. package/dist/dashboard-id.mjs +1 -1
  99. package/dist/drill-access.mjs +93 -0
  100. package/dist/drill-change.mjs +76 -0
  101. package/dist/drill-crumbs.mjs +113 -0
  102. package/dist/drill-distinct.mjs +130 -0
  103. package/dist/drill-explain.mjs +64 -0
  104. package/dist/drill-identity.mjs +35 -0
  105. package/dist/drill-item-id.mjs +35 -0
  106. package/dist/drill-items.mjs +132 -0
  107. package/dist/drill-open.mjs +169 -0
  108. package/dist/drill-seal.mjs +170 -0
  109. package/dist/drill-secret.mjs +14 -0
  110. package/dist/drill-share.mjs +53 -0
  111. package/dist/drill-summary.mjs +158 -0
  112. package/dist/drill-targets.mjs +53 -0
  113. package/dist/drill-totals.mjs +8 -0
  114. package/dist/drill-views.mjs +175 -0
  115. package/dist/drill.mjs +157 -0
  116. package/dist/editing.mjs +2 -2
  117. package/dist/endpoints/dashboards.mjs +11 -3
  118. package/dist/endpoints/drill.mjs +55 -0
  119. package/dist/endpoints/index.d.mts +233 -2
  120. package/dist/endpoints/index.mjs +5 -1
  121. package/dist/endpoints/query.mjs +26 -4
  122. package/dist/execute.d.mts +19 -1
  123. package/dist/execute.mjs +15 -17
  124. package/dist/index.d.mts +3 -1
  125. package/dist/index.mjs +29 -2
  126. package/dist/mcp/drill.mjs +61 -0
  127. package/dist/mcp/format.mjs +27 -3
  128. package/dist/mcp/index.d.mts +15 -4
  129. package/dist/mcp/index.mjs +13 -7
  130. package/dist/mcp/query.d.mts +7 -2
  131. package/dist/mcp/query.mjs +7 -3
  132. package/dist/node-postgres.d.mts +8 -4
  133. package/dist/node-postgres.mjs +29 -6
  134. package/dist/owner.mjs +3 -3
  135. package/dist/postgres-connection.d.mts +8 -2
  136. package/dist/postgres-connection.mjs +2 -1
  137. package/dist/react/Dashboard.d.mts +10 -5
  138. package/dist/react/Dashboard.mjs +51 -23
  139. package/dist/react/DashboardList.mjs +30 -2
  140. package/dist/react/Discard.mjs +7 -2
  141. package/dist/react/Grid.mjs +12 -5
  142. package/dist/react/Header.mjs +9 -0
  143. package/dist/react/Parts.mjs +6 -2
  144. package/dist/react/ReviewPanel.mjs +13 -2
  145. package/dist/react/RowBody.d.mts +19 -0
  146. package/dist/react/RowBody.mjs +55 -0
  147. package/dist/react/Tile.d.mts +1 -1
  148. package/dist/react/Tile.mjs +54 -30
  149. package/dist/react/builder/state.d.mts +1 -1
  150. package/dist/react/client.d.mts +2 -0
  151. package/dist/react/client.mjs +1 -0
  152. package/dist/react/context.d.mts +15 -1
  153. package/dist/react/context.mjs +19 -4
  154. package/dist/react/drill/Bars.mjs +179 -0
  155. package/dist/react/drill/Controls.mjs +173 -0
  156. package/dist/react/drill/DashboardTile.d.mts +18 -0
  157. package/dist/react/drill/DashboardTile.mjs +107 -0
  158. package/dist/react/drill/DrillPanel.d.mts +31 -0
  159. package/dist/react/drill/DrillPanel.mjs +104 -0
  160. package/dist/react/drill/DrillTabs.mjs +52 -0
  161. package/dist/react/drill/Header.mjs +131 -0
  162. package/dist/react/drill/Items.d.mts +22 -0
  163. package/dist/react/drill/Items.mjs +164 -0
  164. package/dist/react/drill/ItemsFoot.mjs +60 -0
  165. package/dist/react/drill/Notes.mjs +58 -0
  166. package/dist/react/drill/PanelBody.mjs +74 -0
  167. package/dist/react/drill/PanelStates.mjs +37 -0
  168. package/dist/react/drill/board.d.mts +18 -0
  169. package/dist/react/drill/board.mjs +91 -0
  170. package/dist/react/drill/counts.mjs +14 -0
  171. package/dist/react/drill/host.mjs +26 -0
  172. package/dist/react/drill/item-parts.d.mts +5 -0
  173. package/dist/react/drill/item-parts.mjs +76 -0
  174. package/dist/react/drill/item-type.d.mts +26 -0
  175. package/dist/react/drill/item-type.mjs +7 -0
  176. package/dist/react/drill/lazy.d.mts +6 -0
  177. package/dist/react/drill/lazy.mjs +17 -0
  178. package/dist/react/drill/pages.mjs +48 -0
  179. package/dist/react/drill/panel-focus.mjs +51 -0
  180. package/dist/react/drill/props.d.mts +25 -0
  181. package/dist/react/drill/props.mjs +72 -0
  182. package/dist/react/drill/state.d.mts +18 -0
  183. package/dist/react/drill/state.mjs +68 -0
  184. package/dist/react/drill/useDrill.d.mts +46 -0
  185. package/dist/react/drill/useDrill.mjs +194 -0
  186. package/dist/react/drill/words.d.mts +98 -0
  187. package/dist/react/drill/words.mjs +77 -0
  188. package/dist/react/english.mjs +9 -1
  189. package/dist/react/format.d.mts +3 -3
  190. package/dist/react/format.mjs +34 -12
  191. package/dist/react/index.d.mts +27 -4
  192. package/dist/react/index.mjs +10 -3
  193. package/dist/react/messages.d.mts +14 -1
  194. package/dist/react/renderers/index.d.mts +10 -2
  195. package/dist/react/renderers/index.mjs +54 -14
  196. package/dist/react/renderers/list.d.mts +22 -0
  197. package/dist/react/renderers/list.mjs +118 -0
  198. package/dist/react/review-words.mjs +1 -1
  199. package/dist/react/review.mjs +2 -2
  200. package/dist/react/scope.mjs +2 -7
  201. package/dist/react/series.d.mts +37 -0
  202. package/dist/react/series.mjs +95 -0
  203. package/dist/react/theme.css +1823 -1296
  204. package/dist/react/theme.css.d.ts +1 -0
  205. package/dist/react/tile-store.mjs +15 -3
  206. package/dist/react/useBoard.d.mts +5 -0
  207. package/dist/react/useBoard.mjs +4 -1
  208. package/dist/react/useDashboard.d.mts +1 -0
  209. package/dist/react/useDashboard.mjs +2 -1
  210. package/dist/react/useTiles.mjs +50 -15
  211. package/dist/react/view.d.mts +9 -0
  212. package/dist/react/view.mjs +22 -10
  213. package/dist/reading.d.mts +2 -0
  214. package/dist/reading.mjs +9 -1
  215. package/dist/recharts/charts.d.mts +0 -1
  216. package/dist/recharts/charts.mjs +128 -34
  217. package/dist/recharts/index.d.mts +2 -2
  218. package/dist/recharts/index.mjs +2 -2
  219. package/dist/recharts/marks.mjs +83 -0
  220. package/dist/recharts/series.d.mts +2 -22
  221. package/dist/recharts/series.mjs +1 -64
  222. package/dist/records-read.mjs +44 -0
  223. package/dist/store/apply.mjs +5 -5
  224. package/dist/store/commands.mjs +4 -4
  225. package/dist/store/discard.mjs +7 -7
  226. package/dist/store/drafts.mjs +5 -5
  227. package/dist/store/editor.mjs +1 -1
  228. package/dist/store/publish.mjs +12 -12
  229. package/dist/store/reader.mjs +41 -22
  230. package/dist/store/review.mjs +16 -16
  231. package/dist/store/rows.mjs +20 -20
  232. package/dist/store/undo.mjs +3 -3
  233. package/dist/store/unpublished.mjs +4 -4
  234. package/dist/store/versions.mjs +14 -14
  235. package/dist/testing/adapter-suite.mjs +4 -4
  236. package/dist/tiles.mjs +37 -3
  237. package/package.json +8 -10
  238. package/dist/react/Records.d.mts +0 -12
  239. package/dist/react/Records.mjs +0 -97
  240. package/src/adapter/sql-adapter.ts +0 -95
  241. package/src/adapter/statement.ts +0 -185
  242. package/src/authorize.ts +0 -73
  243. package/src/body.ts +0 -169
  244. package/src/bounded.ts +0 -43
  245. package/src/cache.ts +0 -192
  246. package/src/checks.ts +0 -170
  247. package/src/custom-source.ts +0 -59
  248. package/src/dashboard-id.ts +0 -36
  249. package/src/dashboards.ts +0 -132
  250. package/src/editing.ts +0 -148
  251. package/src/endpoints/access.ts +0 -41
  252. package/src/endpoints/dashboards.ts +0 -92
  253. package/src/endpoints/drafts.ts +0 -138
  254. package/src/endpoints/index.ts +0 -21
  255. package/src/endpoints/meta.ts +0 -137
  256. package/src/endpoints/query.ts +0 -86
  257. package/src/endpoints/read.ts +0 -92
  258. package/src/endpoints/review.ts +0 -89
  259. package/src/endpoints/values.ts +0 -62
  260. package/src/endpoints/versions.ts +0 -104
  261. package/src/execute.ts +0 -207
  262. package/src/handler.ts +0 -232
  263. package/src/http.ts +0 -66
  264. package/src/index.ts +0 -163
  265. package/src/introspect.ts +0 -205
  266. package/src/mcp/api.ts +0 -59
  267. package/src/mcp/format.ts +0 -67
  268. package/src/mcp/index.ts +0 -151
  269. package/src/mcp/query.ts +0 -153
  270. package/src/mcp/resolve.ts +0 -114
  271. package/src/node-postgres.ts +0 -81
  272. package/src/owner.ts +0 -36
  273. package/src/postgres-connection.ts +0 -143
  274. package/src/postgres-store.ts +0 -82
  275. package/src/principal.ts +0 -39
  276. package/src/reading.ts +0 -56
  277. package/src/request-rows.ts +0 -23
  278. package/src/request.ts +0 -22
  279. package/src/storage.ts +0 -63
  280. package/src/store/apply.ts +0 -129
  281. package/src/store/commands.ts +0 -75
  282. package/src/store/conflicts.ts +0 -98
  283. package/src/store/create-tables.ts +0 -104
  284. package/src/store/discard.ts +0 -42
  285. package/src/store/drafts.ts +0 -133
  286. package/src/store/editor.ts +0 -28
  287. package/src/store/log.ts +0 -28
  288. package/src/store/publish.ts +0 -199
  289. package/src/store/publisher.ts +0 -21
  290. package/src/store/reader.ts +0 -139
  291. package/src/store/review.ts +0 -239
  292. package/src/store/rows.ts +0 -250
  293. package/src/store/tenant.ts +0 -28
  294. package/src/store/undo.ts +0 -56
  295. package/src/store/unpublished.ts +0 -33
  296. package/src/store/versions.ts +0 -106
  297. package/src/store/writer.ts +0 -19
  298. package/src/testing/adapter-suite.ts +0 -239
  299. package/src/testing/index.ts +0 -2
  300. package/src/tile-doc.ts +0 -46
  301. package/src/tiles.ts +0 -120
package/src/introspect.ts DELETED
@@ -1,205 +0,0 @@
1
- import type { ColumnType, DbSchema } from "@derive-to/dashboards-core";
2
- import type { RunSql } from "./postgres-connection";
3
-
4
- /** The schemas Postgres keeps for itself; nothing in them is the host's. */
5
- const SYSTEM =
6
- "n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg_toast%'";
7
- const SEP = String.fromCodePoint(31);
8
-
9
- const TABLES = `
10
- SELECT n.nspname, c.relname, c.relkind, c.reltuples
11
- FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
12
- WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f') AND ${SYSTEM}
13
- ORDER BY n.nspname, c.relname`;
14
-
15
- const COLUMNS = `
16
- SELECT n.nspname, c.relname, a.attname, t.typname, NOT a.attnotnull,
17
- CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 THEN ((a.atttypmod - 4) >> 16) & 65535 END,
18
- CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 THEN (a.atttypmod - 4) & 65535 END
19
- FROM pg_attribute a
20
- JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace
21
- JOIN pg_type t ON t.oid = a.atttypid
22
- WHERE a.attnum > 0 AND NOT a.attisdropped AND c.relkind IN ('r', 'p', 'v', 'm', 'f') AND ${SYSTEM}
23
- ORDER BY n.nspname, c.relname, a.attnum`;
24
-
25
- const KEYS = `
26
- SELECT n.nspname, c.relname, i.indisprimary, pg_get_expr(i.indpred, i.indrelid),
27
- (SELECT string_agg(a.attname, chr(31) ORDER BY k.ord) FROM unnest(i.indkey) WITH ORDINALITY k(num, ord)
28
- JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.num)
29
- FROM pg_index i JOIN pg_class c ON c.oid = i.indrelid JOIN pg_namespace n ON n.oid = c.relnamespace
30
- WHERE i.indisunique AND ${SYSTEM}`;
31
-
32
- const FOREIGN_KEYS = `
33
- SELECT n.nspname, c.relname, r.relname,
34
- (SELECT string_agg(a.attname, chr(31) ORDER BY k.ord) FROM unnest(f.conkey) WITH ORDINALITY k(num, ord)
35
- JOIN pg_attribute a ON a.attrelid = f.conrelid AND a.attnum = k.num),
36
- (SELECT string_agg(a.attname, chr(31) ORDER BY k.ord) FROM unnest(f.confkey) WITH ORDINALITY k(num, ord)
37
- JOIN pg_attribute a ON a.attrelid = f.confrelid AND a.attnum = k.num)
38
- FROM pg_constraint f JOIN pg_class c ON c.oid = f.conrelid JOIN pg_class r ON r.oid = f.confrelid
39
- JOIN pg_namespace n ON n.oid = c.relnamespace
40
- WHERE f.contype = 'f' AND ${SYSTEM}`;
41
-
42
- const CHECKS = `
43
- SELECT n.nspname, c.relname, pg_get_constraintdef(k.oid)
44
- FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
45
- WHERE k.contype = 'c' AND ${SYSTEM}`;
46
-
47
- const TYPES: Record<string, ColumnType> = {
48
- text: "text",
49
- varchar: "text",
50
- bpchar: "text",
51
- citext: "text",
52
- name: "text",
53
- uuid: "text",
54
- int2: "integer",
55
- int4: "integer",
56
- int8: "bigint",
57
- numeric: "numeric",
58
- float4: "float",
59
- float8: "float",
60
- bool: "boolean",
61
- timestamptz: "timestamptz",
62
- timestamp: "timestamp",
63
- date: "date",
64
- json: "json",
65
- jsonb: "json",
66
- bytea: "bytes",
67
- };
68
-
69
- const KINDS = { r: "table", p: "table", v: "view", m: "materialized_view", f: "foreign" } as const;
70
-
71
- const str = (v: unknown): string => {
72
- if (typeof v === "string") return v;
73
- return typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
74
- };
75
- const list = (v: unknown) => (v === null || v === undefined ? [] : str(v).split(SEP));
76
- const key = (schema: unknown, table: unknown) => `${str(schema)}.${str(table)}`;
77
-
78
- /** Groups rows by their table, so each table's parts are read in one pass. */
79
- function byTable(rows: readonly (readonly unknown[])[]) {
80
- const groups = new Map<string, (readonly unknown[])[]>();
81
- for (const row of rows)
82
- groups.set(key(row[0], row[1]), [...(groups.get(key(row[0], row[1])) ?? []), row]);
83
- return (schema: unknown, table: unknown) => groups.get(key(schema, table)) ?? [];
84
- }
85
-
86
- function column(row: readonly unknown[]): DbSchema["tables"][number]["columns"][number] {
87
- const typname = str(row[3]);
88
- return {
89
- name: str(row[2]),
90
- type: TYPES[typname] ?? "other",
91
- nullable: row[4] === true,
92
- ...(typname === "citext" ? { collation: "citext" } : {}),
93
- ...(row[5] === null || row[5] === undefined ? {} : { precision: Number(row[5]) }),
94
- ...(row[6] === null || row[6] === undefined ? {} : { scale: Number(row[6]) }),
95
- };
96
- }
97
-
98
- /**
99
- * What a Postgres database says about its own tables: columns with types, nullability, numeric
100
- * precision and scale, unique keys (partial ones with their predicate), foreign keys and checks.
101
- * `init` proposes a model from it and `check` proves the model against it.
102
- */
103
- type Rows = readonly (readonly unknown[])[];
104
- type Lookup = (schema: unknown, table: unknown) => Rows;
105
-
106
- const kindOf = (relkind: unknown): DbSchema["tables"][number]["kind"] => {
107
- const found = Object.entries(KINDS).find(([k]) => k === str(relkind));
108
- return found === undefined ? "table" : found[1];
109
- };
110
-
111
- const keyOf = (r: readonly unknown[]) => ({
112
- primary: r[2] === true,
113
- columns: list(r[4]),
114
- ...(r[3] === null || r[3] === undefined ? {} : { where: str(r[3]) }),
115
- });
116
-
117
- const foreignKeyOf = (r: readonly unknown[]) => ({
118
- columns: list(r[3]),
119
- references: { table: str(r[2]), columns: list(r[4]) },
120
- });
121
-
122
- function tableOf(
123
- t: readonly unknown[],
124
- parts: { col: Lookup; uk: Lookup; fk: Lookup; ck: Lookup },
125
- ) {
126
- const estimate = Number(t[3]);
127
- return {
128
- schema: str(t[0]),
129
- name: str(t[1]),
130
- kind: kindOf(t[2]),
131
- columns: parts.col(t[0], t[1]).map((r) => column(r)),
132
- keys: parts.uk(t[0], t[1]).map((r) => keyOf(r)),
133
- foreignKeys: parts.fk(t[0], t[1]).map((r) => foreignKeyOf(r)),
134
- checks: parts.ck(t[0], t[1]).map((r) => str(r[2])),
135
- ...(estimate >= 0 ? { rowEstimate: estimate } : {}),
136
- };
137
- }
138
-
139
- /**
140
- * What a Postgres database says about its own tables: columns with types, nullability, numeric
141
- * precision and scale, unique keys (partial ones with their predicate), foreign keys and checks.
142
- * `init` proposes a model from it and `check` proves the model against it.
143
- */
144
- export async function introspectPostgres(run: RunSql): Promise<DbSchema> {
145
- const [tables, columns, keys, foreign, checks] = await Promise.all(
146
- [TABLES, COLUMNS, KEYS, FOREIGN_KEYS, CHECKS].map((q) => run(q, [])),
147
- );
148
- const parts = {
149
- col: byTable(columns ?? []),
150
- uk: byTable(keys ?? []),
151
- fk: byTable(foreign ?? []),
152
- ck: byTable(checks ?? []),
153
- };
154
- return { tables: (tables ?? []).map((t) => tableOf(t, parts)) };
155
- }
156
-
157
- /** `pg_typeof`'s names for the types `TYPES` reads by their catalog names. */
158
- const TYPE_NAMES: Record<string, ColumnType> = {
159
- text: "text",
160
- "character varying": "text",
161
- character: "text",
162
- citext: "text",
163
- name: "text",
164
- uuid: "text",
165
- smallint: "integer",
166
- integer: "integer",
167
- bigint: "bigint",
168
- numeric: "numeric",
169
- real: "float",
170
- "double precision": "float",
171
- boolean: "boolean",
172
- "timestamp with time zone": "timestamptz",
173
- "timestamp without time zone": "timestamp",
174
- date: "date",
175
- json: "json",
176
- jsonb: "json",
177
- bytea: "bytes",
178
- };
179
-
180
- const quoted = (name: string) => `"${name.replaceAll('"', '""')}"`;
181
-
182
- /**
183
- * The types of `columns` in the result of a source's own query, without reading a row: the
184
- * query cut to no rows is joined on to one row, so each column is a null of its own type for
185
- * `pg_typeof` to name. A column the query does not give fails with Postgres's own message.
186
- */
187
- export async function describePostgres(
188
- run: RunSql,
189
- query: string,
190
- columns: readonly string[],
191
- ): Promise<DbSchema["tables"][number]["columns"]> {
192
- const body = query.trim().replace(/;$/u, "");
193
- const types = columns.map((c) => `pg_typeof(q.${quoted(c)})::text`).join(", ");
194
- const text = `SELECT ${types} FROM (SELECT 1) AS one LEFT JOIN (SELECT * FROM (${body}) AS s LIMIT 0) AS q ON true`;
195
- const [row] = await run(text, []);
196
- return columns.map((name, i) => {
197
- const pgType = str(row?.[i]);
198
- return {
199
- name,
200
- type: TYPE_NAMES[pgType] ?? "other",
201
- nullable: true,
202
- ...(pgType === "citext" ? { collation: "citext" } : {}),
203
- };
204
- });
205
- }
package/src/mcp/api.ts DELETED
@@ -1,59 +0,0 @@
1
- // dashboards_api: every endpoint by path, as the signed-in person. Edits, publishing, history,
2
- // and each plugin's endpoints, with nothing to keep in step: the paths come from the server,
3
- // and GET /meta/schemas gives each body's JSON Schema when the agent needs it.
4
- import type { Viewer } from "@derive-to/dashboards-core";
5
- import { z } from "zod";
6
- import { ok, type ToolResult } from "./format";
7
- import type { Callable } from "./query";
8
-
9
- /** The longest answer handed back as text; the whole answer is always in the structured content. */
10
- const MOST_TEXT = 20_000;
11
-
12
- export type ApiServer = Callable & { routes: readonly { path: string; method: "GET" | "POST" }[] };
13
-
14
- /** The tool's input: one of the server's paths, and the body it takes. */
15
- export function apiInput(routes: ApiServer["routes"]) {
16
- const paths = routes.map((r) => r.path);
17
- const [first, ...rest] = paths;
18
- if (first === undefined) throw new Error("The dashboards server has no endpoints.");
19
- return z.object({
20
- path: z.enum([first, ...rest]).describe("The endpoint to call."),
21
- body: z
22
- .record(z.string(), z.unknown())
23
- .optional()
24
- .describe(
25
- "The endpoint's body (none for a GET). GET /meta/schemas lists every body's JSON Schema.",
26
- ),
27
- });
28
- }
29
-
30
- /** What the tool says it does: how editing goes, then every path with its method. */
31
- export function apiDescription(routes: ApiServer["routes"]): string {
32
- return [
33
- "Calls any dashboards endpoint as the signed-in person, with their access. For questions and reading dashboards, prefer dashboards_query.",
34
- "Editing: POST /dashboards/new or /dashboards/draft/start opens your own draft; /dashboards/draft/apply applies commands (each answer gives the revision the next names); /dashboards/draft/preview shows what would go live; /dashboards/draft/publish puts it live. Nothing is live until publish.",
35
- "Paths:",
36
- ...routes.map((r) => `${r.method} ${r.path}`),
37
- ].join("\n");
38
- }
39
-
40
- /** Calls one endpoint as the viewer; the answer comes back as JSON text and structured content. */
41
- export async function runApi(
42
- dashboards: ApiServer,
43
- viewer: Viewer,
44
- input: { path: string; body?: Record<string, unknown> | undefined },
45
- ): Promise<ToolResult> {
46
- const route = dashboards.routes.find((r) => r.path === input.path);
47
- const body = route?.method === "GET" ? undefined : (input.body ?? {});
48
- const answer = await dashboards.call(input.path, {
49
- ...(body === undefined ? {} : { body }),
50
- viewer,
51
- });
52
- const text = JSON.stringify(answer ?? null, null, 1);
53
- return ok(
54
- text.length > MOST_TEXT
55
- ? `${text.slice(0, MOST_TEXT)}\n... cut; the whole answer is in the structured content.`
56
- : text,
57
- answer,
58
- );
59
- }
package/src/mcp/format.ts DELETED
@@ -1,67 +0,0 @@
1
- // How tool answers read to a model: a short table it can quote, a sentence when there is
2
- // nothing to show, and every refusal as the code, the reason and what to do instead.
3
- import type { QueryAnswer } from "@derive-to/dashboards-core";
4
- import { HttpError } from "../http";
5
-
6
- /** What a tool call answers: text for the model, and the whole answer as structured content. */
7
- export type ToolResult = {
8
- content: { type: "text"; text: string }[];
9
- structuredContent?: Record<string, unknown>;
10
- isError?: true;
11
- };
12
-
13
- /** The most rows a table shows the model; the rest are counted, and all are in the structured answer. */
14
- const SHOWN = 30;
15
-
16
- /** A cell as text: exact numbers as their digits, no value as a blank. */
17
- function cellText(cell: unknown): string {
18
- if (cell === null || cell === undefined) return "";
19
- if (typeof cell === "object" && "v" in cell) return String(cell.v);
20
- if (typeof cell === "string") return cell.replaceAll("|", "\\|");
21
- if (typeof cell === "number" || typeof cell === "boolean") return String(cell);
22
- return JSON.stringify(cell);
23
- }
24
-
25
- /** Rows under their column labels, as a Markdown table, cut at SHOWN rows with a count. */
26
- export function table(labels: readonly string[], rows: readonly (readonly unknown[])[]): string {
27
- if (rows.length === 0) return "No rows.";
28
- const lines = [
29
- `| ${labels.join(" | ")} |`,
30
- `| ${labels.map(() => "---").join(" | ")} |`,
31
- ...rows.slice(0, SHOWN).map((row) => `| ${row.map((c) => cellText(c)).join(" | ")} |`),
32
- ];
33
- if (rows.length > SHOWN)
34
- lines.push(`\n${rows.length - SHOWN} more rows are in the structured answer.`);
35
- return lines.join("\n");
36
- }
37
-
38
- /** A query's answer: its table, the comparison period's beside it, and whether it was cut. */
39
- export function answerText(answer: QueryAnswer): string {
40
- if (answer.unreadable === true)
41
- return "This viewer may not read the rows this question asks about.";
42
- const labels = answer.columns.map((c) => c.label);
43
- const parts = [table(labels, answer.rows)];
44
- if (answer.compare !== undefined) {
45
- const { from, to } = answer.compare.range;
46
- parts.push(`Compared with ${from} to ${to}:`, table(labels, answer.compare.rows));
47
- }
48
- if (answer.status === "truncated") parts.push("The answer was cut at its row limit.");
49
- return parts.join("\n\n");
50
- }
51
-
52
- export const ok = (text: string, data?: unknown): ToolResult => ({
53
- content: [{ type: "text", text }],
54
- ...(data === undefined ? {} : { structuredContent: { result: data } }),
55
- });
56
-
57
- /** A refusal the model can act on: the code, the reason, each problem with the input, and a hint. */
58
- export function refused(error: unknown, hint?: string): ToolResult {
59
- if (!(error instanceof HttpError)) throw error;
60
- const issues = (error.issues ?? []).map((i) => `- ${i.path.join(".") || "input"}: ${i.message}`);
61
- const text = [
62
- `${error.code}: ${error.message}`,
63
- ...issues,
64
- ...(hint === undefined ? [] : [hint]),
65
- ];
66
- return { content: [{ type: "text", text: text.join("\n") }], isError: true };
67
- }
package/src/mcp/index.ts DELETED
@@ -1,151 +0,0 @@
1
- // Dashboards in an MCP server, or any agent framework: two tools. dashboards_query reads
2
- // (questions, the rows behind them, dashboards read out) and is marked read only, so clients
3
- // can run it without asking; dashboards_api reaches every endpoint, edits included, which go to
4
- // the agent's own draft until it publishes. Both run as the viewer the host names, so an agent
5
- // can do what its person can and nothing more.
6
- import type { Viewer } from "@derive-to/dashboards-core";
7
- import { z } from "zod";
8
- import { HttpError } from "../http";
9
- import { type ApiServer, apiDescription, apiInput, runApi } from "./api";
10
- import { refused, type ToolResult } from "./format";
11
- import { queryInput, runQuery } from "./query";
12
-
13
- export type { ToolResult } from "./format";
14
-
15
- /** MCP's tool annotations: what a client may assume about a tool before it runs it. */
16
- export type ToolAnnotations = {
17
- readOnlyHint?: boolean;
18
- destructiveHint?: boolean;
19
- idempotentHint?: boolean;
20
- openWorldHint?: boolean;
21
- };
22
-
23
- /** One tool as plain data, for MCP or any agent framework. */
24
- export type DashboardTool = {
25
- name: string;
26
- title: string;
27
- description: string;
28
- inputSchema: z.ZodObject;
29
- annotations: ToolAnnotations;
30
- /**
31
- * Runs the tool as `viewer`, checking its input against `inputSchema` first. A refusal comes
32
- * back as an error result saying why and what to do.
33
- */
34
- run: (input: unknown, viewer: Viewer) => Promise<ToolResult>;
35
- };
36
-
37
- export type DashboardToolsOptions = {
38
- /** Put before each tool's name; `dashboards_` by default. */
39
- prefix?: string;
40
- /** False leaves out dashboards_api, so an agent can read but never change anything. */
41
- api?: boolean;
42
- /** The link to a dashboard in your app, given with every dashboard the agent opens. */
43
- linkFor?: (dashboardId: string) => string;
44
- };
45
-
46
- /** An agent acts for its person: marked so, its edits are its own draft and history says an agent made them. */
47
- const asAgent = (viewer: Viewer): Viewer =>
48
- viewer.agent === undefined ? { ...viewer, agent: { for: viewer.id } } : viewer;
49
-
50
- const HINT =
51
- "Fix the input and call again; dashboards_query with op describe lists what can be asked.";
52
-
53
- /**
54
- * A tool's run: the input checked against its schema (an agent framework may not check it),
55
- * then run as the agent acting for the viewer. A refusal becomes a result the model can act on;
56
- * anything else is a bug and throws.
57
- */
58
- function guarded<S extends z.ZodObject>(
59
- schema: S,
60
- run: (input: z.infer<S>, viewer: Viewer) => Promise<ToolResult>,
61
- ): DashboardTool["run"] {
62
- return async (raw, viewer) => {
63
- const parsed = schema.safeParse(raw);
64
- if (!parsed.success)
65
- return refused(new HttpError(400, "BODY_INVALID", z.prettifyError(parsed.error)), HINT);
66
- try {
67
- return await run(parsed.data, asAgent(viewer));
68
- } catch (error) {
69
- return refused(error, HINT);
70
- }
71
- };
72
- }
73
-
74
- /** The two tools, as plain data: `name`, `description`, `inputSchema` (Zod), `annotations`, `run(input, viewer)`. */
75
- export function dashboardTools(
76
- dashboards: ApiServer,
77
- options: DashboardToolsOptions = {},
78
- ): DashboardTool[] {
79
- const prefix = options.prefix ?? "dashboards_";
80
- const query: DashboardTool = {
81
- name: `${prefix}query`,
82
- title: "Ask about the data",
83
- description:
84
- "Answers questions from the data, as the signed-in person: describe what can be asked, ask a question (measures by groups over a time range, top N, compared with the period before), list the rows behind it, list dashboards, or open one with every tile answered. Start with op describe when unsure what exists.",
85
- inputSchema: queryInput,
86
- annotations: { readOnlyHint: true, openWorldHint: false },
87
- run: guarded(queryInput, (input, viewer) =>
88
- runQuery({ dashboards, viewer, linkFor: options.linkFor }, input),
89
- ),
90
- };
91
- if (options.api === false) return [query];
92
- const api = apiInput(dashboards.routes);
93
- const apiTool: DashboardTool = {
94
- name: `${prefix}api`,
95
- title: "Dashboards API",
96
- description: apiDescription(dashboards.routes),
97
- inputSchema: api,
98
- annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
99
- run: guarded(api, (input, viewer) => runApi(dashboards, viewer, input)),
100
- };
101
- return [query, apiTool];
102
- }
103
-
104
- /** What a tool call carries besides its input, as the MCP SDK passes it: the caller's auth. */
105
- export type McpCallExtra = {
106
- authInfo?: { token: string; clientId: string; scopes: string[]; extra?: Record<string, unknown> };
107
- sessionId?: string;
108
- };
109
-
110
- /** What `addDashboardTools` needs of an MCP server: `McpServer` from `@modelcontextprotocol/sdk` has it. */
111
- export type McpServerLike = {
112
- registerTool(
113
- name: string,
114
- config: {
115
- title?: string;
116
- description?: string;
117
- inputSchema?: z.ZodObject;
118
- annotations?: ToolAnnotations;
119
- },
120
- callback: (input: Record<string, unknown>, extra: McpCallExtra) => Promise<ToolResult>,
121
- ): unknown;
122
- };
123
-
124
- /**
125
- * Adds the two tools to an MCP server you already run. `viewer` reads the person from the
126
- * call (`extra.authInfo` from your MCP auth); none refuses the call.
127
- */
128
- export function addDashboardTools(
129
- server: McpServerLike,
130
- dashboards: ApiServer,
131
- options: DashboardToolsOptions & {
132
- viewer: (extra: McpCallExtra) => Viewer | null | Promise<Viewer | null>;
133
- },
134
- ): void {
135
- for (const tool of dashboardTools(dashboards, options)) {
136
- const { name, title, description, inputSchema, annotations } = tool;
137
- const callback = async (
138
- input: Record<string, unknown>,
139
- extra: McpCallExtra,
140
- ): Promise<ToolResult> => {
141
- const viewer = await options.viewer(extra);
142
- if (viewer === null)
143
- return {
144
- content: [{ type: "text", text: "UNAUTHORIZED: sign in to use dashboards." }],
145
- isError: true,
146
- };
147
- return tool.run(input, viewer);
148
- };
149
- server.registerTool(name, { title, description, inputSchema, annotations }, callback);
150
- }
151
- }
package/src/mcp/query.ts DELETED
@@ -1,153 +0,0 @@
1
- // dashboards_query: the read-only tool. Five ops cover what an agent asks of dashboards: what
2
- // can be asked, a question, the rows behind it, which dashboards there are, and one read out.
3
- import type { DashOptions, TileLine, Viewer } from "@derive-to/dashboards-core";
4
- import { picksSchema, wireQuerySchema } from "@derive-to/dashboards-core/schema";
5
- import { z } from "zod";
6
- import { HttpError } from "../http";
7
- import type { DashServer } from "../index";
8
- import { answerText, ok, type ToolResult, table } from "./format";
9
- import { dashboardOf, resolveQuery, sourceOf } from "./resolve";
10
-
11
- /** What the tools need of `deriveDashboards(...)`: its calls, by name and by path. */
12
- export type Callable = Pick<DashServer<DashOptions>, "api" | "call" | "routes">;
13
-
14
- export type QueryContext = {
15
- dashboards: Callable;
16
- viewer: Viewer;
17
- /** The link to a dashboard in the host's app, added to what `open` answers. */
18
- linkFor?: ((dashboardId: string) => string) | undefined;
19
- };
20
-
21
- /** A question, with `kind` optional since there is only one kind. */
22
- const question = wireQuerySchema.extend({ kind: z.literal("aggregate").optional() });
23
-
24
- export const queryInput = z.object({
25
- op: z
26
- .enum(["describe", "ask", "rows", "list", "open"])
27
- .describe(
28
- "describe: what can be asked (sources, measures, fields). ask: answer a question. rows: the records behind a question. list: the dashboards. open: one dashboard, every tile answered.",
29
- ),
30
- query: question
31
- .optional()
32
- .describe(
33
- "For ask and rows. Sources, measures and fields may be named by id or label. Ids: measures m0, m1...; dimensions d0, d1...",
34
- ),
35
- source: z.string().optional().describe("For describe: one source only."),
36
- dashboard: z.string().optional().describe("For open: the dashboard's title or id."),
37
- filters: picksSchema
38
- .optional()
39
- .describe("For open: values for the dashboard's filters, by control id."),
40
- limit: z
41
- .number()
42
- .int()
43
- .min(1)
44
- .max(200)
45
- .optional()
46
- .describe("For rows: how many (50 by default)."),
47
- });
48
- export type QueryInput = z.infer<typeof queryInput>;
49
-
50
- const meta = (c: QueryContext) => c.dashboards.api.meta({ viewer: c.viewer });
51
- const listed = (c: QueryContext) => c.dashboards.api.listDashboards({ viewer: c.viewer });
52
-
53
- async function describe(c: QueryContext, only?: string): Promise<ToolResult> {
54
- const all = await meta(c);
55
- const sources = only === undefined ? all.sources : [sourceOf(all, only)];
56
- const text = sources.map((s) =>
57
- [
58
- `## ${s.label} (${s.name})`,
59
- `Measures: ${s.measures.map((m) => `${m.label} (${m.id}${m.aggregate === undefined ? "" : `, ${m.aggregate}`})`).join("; ")}`,
60
- `Fields: ${s.dimensions.map((d) => `${d.label} (${d.id}, ${d.type})`).join("; ")}`,
61
- ...(s.joins.length === 0
62
- ? []
63
- : [`Joins: ${s.joins.map((j) => `${j.label} (${j.name} to ${j.source})`).join("; ")}`]),
64
- ].join("\n"),
65
- );
66
- return ok(text.join("\n\n") || "Nothing this viewer may read.", { sources });
67
- }
68
-
69
- /** The question, every name turned into its id. */
70
- async function resolved(c: QueryContext, input: QueryInput) {
71
- if (input.query === undefined)
72
- throw new HttpError(
73
- 400,
74
- "QUERY_INVALID",
75
- `${input.op} needs a query: a source and at least one measure.`,
76
- );
77
- return resolveQuery(await meta(c), { ...input.query, kind: "aggregate" as const });
78
- }
79
-
80
- async function ask(c: QueryContext, input: QueryInput): Promise<ToolResult> {
81
- const query = await resolved(c, input);
82
- const answer = await c.dashboards.api.queryRun({ body: { query }, viewer: c.viewer });
83
- return ok(answerText(answer), answer);
84
- }
85
-
86
- async function rows(c: QueryContext, input: QueryInput): Promise<ToolResult> {
87
- const query = await resolved(c, input);
88
- const body = { query, limit: input.limit ?? 50 };
89
- const page = await c.dashboards.api.queryRecords({ body, viewer: c.viewer });
90
- const labels = page.columns.map((col) => col.label);
91
- return ok(table(labels, page.rows), page);
92
- }
93
-
94
- async function list(c: QueryContext): Promise<ToolResult> {
95
- const all = await listed(c);
96
- const rowsOf = all.dashboards.map((d) => [
97
- d.title,
98
- d.id,
99
- "unpublished" in d ? "draft" : `v${d.version}`,
100
- ]);
101
- return ok(table(["Dashboard", "Id", "Version"], rowsOf), all);
102
- }
103
-
104
- /** Every line a streamed answer gives, read to its end. */
105
- async function collect<T>(stream: AsyncIterable<T>): Promise<T[]> {
106
- const lines: T[] = [];
107
- for await (const line of stream) lines.push(line);
108
- return lines;
109
- }
110
-
111
- /** One tile's part of the read-out: its title, then its answer or why it has none. */
112
- function tileText(title: string, line: TileLine | undefined): string {
113
- if (line === undefined || "done" in line) return `### ${title}\nNo answer.`;
114
- if (!line.ok) return `### ${title}\n${line.error.code}: ${line.error.message}`;
115
- return `### ${title}\n${answerText(line.result)}`;
116
- }
117
-
118
- /** One dashboard read out: each tile's title and answer, in layout order, and its link. */
119
- async function open(c: QueryContext, input: QueryInput): Promise<ToolResult> {
120
- const { id } = dashboardOf((await listed(c)).dashboards, input.dashboard ?? "");
121
- const got = await c.dashboards.api.getDashboard({ body: { dashboardId: id }, viewer: c.viewer });
122
- const widgets = got.document.tabs
123
- .flatMap((t) => t.layout.map((item) => item.widget))
124
- .slice(0, 50);
125
- const body = {
126
- dashboardId: id,
127
- version: got.version,
128
- tiles: widgets.map((widgetId) => ({ widgetId })),
129
- ...(input.filters === undefined ? {} : { picks: input.filters }),
130
- };
131
- const lines =
132
- widgets.length === 0
133
- ? []
134
- : await collect(await c.dashboards.api.tiles({ body, viewer: c.viewer }));
135
- const tiles = widgets.map((widgetId, i) =>
136
- tileText(
137
- got.document.widgets[widgetId]?.title ?? widgetId,
138
- lines.find((l) => "i" in l && l.i === i),
139
- ),
140
- );
141
- const link = c.linkFor?.(id);
142
- const head = `# ${got.document.meta.title}${link === undefined ? "" : `\n${link}`}`;
143
- return ok([head, ...tiles].join("\n\n"), { dashboard: got, tiles: lines });
144
- }
145
-
146
- /** Runs one op of dashboards_query as the viewer. */
147
- export function runQuery(c: QueryContext, input: QueryInput): Promise<ToolResult> {
148
- if (input.op === "describe") return describe(c, input.source);
149
- if (input.op === "ask") return ask(c, input);
150
- if (input.op === "rows") return rows(c, input);
151
- if (input.op === "list") return list(c);
152
- return open(c, input);
153
- }