derive-dashboards 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (410) hide show
  1. package/README.md +8 -5
  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/add.mjs +130 -0
  6. package/dist/cli/check.mjs +14 -1
  7. package/dist/cli/cli.mjs +14 -12
  8. package/dist/cli/config.mjs +12 -1
  9. package/dist/cli/doctor.mjs +147 -0
  10. package/dist/cli/import/dbt-schema.mjs +2 -2
  11. package/dist/cli/import/index.mjs +2 -2
  12. package/dist/cli/init.mjs +3 -2
  13. package/dist/cli/json.mjs +21 -0
  14. package/dist/cli/layers.mjs +33 -0
  15. package/dist/core/conformance/cases.d.mts +3 -0
  16. package/dist/core/conformance/cases.mjs +20 -4
  17. package/dist/core/conformance/check.mjs +6 -3
  18. package/dist/core/conformance/drill-cases.mjs +120 -0
  19. package/dist/core/document/layout.mjs +1 -1
  20. package/dist/core/document/view-layout.d.mts +14 -0
  21. package/dist/core/document/view-layout.mjs +157 -0
  22. package/dist/core/document/view.d.mts +26 -7
  23. package/dist/core/document/view.mjs +42 -11
  24. package/dist/core/engine/filter.mjs +2 -2
  25. package/dist/core/engine/index.d.mts +14 -2
  26. package/dist/core/engine/index.mjs +12 -1
  27. package/dist/core/engine/leaf.mjs +9 -4
  28. package/dist/core/engine/members.mjs +2 -2
  29. package/dist/core/engine/postgres.mjs +1 -1
  30. package/dist/core/engine/record-layout.d.mts +11 -0
  31. package/dist/core/engine/record-layout.mjs +7 -7
  32. package/dist/core/engine/records.d.mts +3 -2
  33. package/dist/core/engine/records.mjs +2 -1
  34. package/dist/core/engine/segmented.mjs +5 -2
  35. package/dist/core/engine/sql-records.mjs +2 -1
  36. package/dist/core/engine/statement.mjs +37 -3
  37. package/dist/core/engine/types.d.mts +3 -0
  38. package/dist/core/engine/version.d.mts +1 -1
  39. package/dist/core/engine/version.mjs +1 -1
  40. package/dist/core/error/codes.d.mts +33 -1
  41. package/dist/core/error/codes.mjs +30 -2
  42. package/dist/core/index.d.mts +13 -7
  43. package/dist/core/index.mjs +9 -5
  44. package/dist/core/model/catalog/check.mjs +1 -1
  45. package/dist/core/model/hints.d.mts +36 -0
  46. package/dist/core/model/member.d.mts +4 -2
  47. package/dist/core/model/member.mjs +19 -3
  48. package/dist/core/model/types.d.mts +21 -19
  49. package/dist/core/model/validate/drill.mjs +70 -0
  50. package/dist/core/model/validate/index.mjs +3 -0
  51. package/dist/core/model/validate/members.mjs +7 -4
  52. package/dist/core/model/validate/shape.mjs +150 -0
  53. package/dist/core/model/validate/source.mjs +5 -3
  54. package/dist/core/policy/bind-query.d.mts +12 -0
  55. package/dist/core/policy/bind-query.mjs +53 -0
  56. package/dist/core/query/alias.mjs +7 -1
  57. package/dist/core/query/drill/compose.d.mts +22 -0
  58. package/dist/core/query/drill/compose.mjs +85 -0
  59. package/dist/core/query/drill/fields.d.mts +21 -0
  60. package/dist/core/query/drill/fields.mjs +91 -0
  61. package/dist/core/query/drill/internal.d.mts +11 -0
  62. package/dist/core/query/drill/items.d.mts +29 -0
  63. package/dist/core/query/drill/items.mjs +98 -0
  64. package/dist/core/query/drill/line.d.mts +31 -0
  65. package/dist/core/query/drill/line.mjs +183 -0
  66. package/dist/core/query/drill/links.d.mts +33 -0
  67. package/dist/core/query/drill/links.mjs +31 -0
  68. package/dist/core/query/drill/operand.mjs +7 -0
  69. package/dist/core/query/drill/scopes.d.mts +22 -0
  70. package/dist/core/query/drill/scopes.mjs +58 -0
  71. package/dist/core/query/drill/selection.d.mts +37 -0
  72. package/dist/core/query/drill/selection.mjs +144 -0
  73. package/dist/core/query/drill/steps.d.mts +14 -0
  74. package/dist/core/query/drill/steps.mjs +35 -0
  75. package/dist/core/query/drill/synthetic-expr.mjs +85 -0
  76. package/dist/core/query/drill/synthetic.d.mts +22 -0
  77. package/dist/core/query/drill/synthetic.mjs +165 -0
  78. package/dist/core/query/drill/time.d.mts +11 -0
  79. package/dist/core/query/drill/time.mjs +71 -0
  80. package/dist/core/query/drill/types.d.mts +155 -0
  81. package/dist/core/query/drill/types.mjs +4 -0
  82. package/dist/core/query/drill/views.d.mts +62 -0
  83. package/dist/core/query/drill/views.mjs +257 -0
  84. package/dist/core/query/filter.d.mts +6 -0
  85. package/dist/core/query/picks.d.mts +8 -2
  86. package/dist/core/query/picks.mjs +11 -4
  87. package/dist/core/query/segments.d.mts +12 -2
  88. package/dist/core/query/segments.mjs +5 -2
  89. package/dist/core/result/columns.mjs +20 -4
  90. package/dist/core/result/types.d.mts +5 -1
  91. package/dist/core/schema/aliases.d.mts +7 -0
  92. package/dist/core/schema/aliases.mjs +77 -0
  93. package/dist/core/schema/answer-parts.mjs +117 -0
  94. package/dist/core/schema/answers.d.mts +2109 -128
  95. package/dist/core/schema/answers.mjs +11 -113
  96. package/dist/core/schema/commands.d.mts +2 -2
  97. package/dist/core/schema/document.d.mts +1 -1
  98. package/dist/core/schema/drill-answers.mjs +179 -0
  99. package/dist/core/schema/drill.d.mts +260 -0
  100. package/dist/core/schema/drill.mjs +107 -0
  101. package/dist/core/schema/index.d.mts +6 -3
  102. package/dist/core/schema/index.mjs +6 -3
  103. package/dist/core/schema/picks.d.mts +35 -0
  104. package/dist/core/schema/picks.mjs +23 -0
  105. package/dist/core/schema/query.d.mts +82 -1
  106. package/dist/core/schema/query.mjs +9 -5
  107. package/dist/core/schema/tools.mjs +1 -1
  108. package/dist/core/schema/view.d.mts +0 -35
  109. package/dist/core/schema/view.mjs +19 -24
  110. package/dist/core/store/schema.d.mts +5 -0
  111. package/dist/core/store/schema.mjs +10 -0
  112. package/dist/core/types/api.d.mts +21 -1
  113. package/dist/core/types/api.mjs +1 -1
  114. package/dist/core/types/drill-api.d.mts +210 -0
  115. package/dist/core/types/options.d.mts +21 -0
  116. package/dist/core/types/viewer.d.mts +5 -0
  117. package/dist/cursor-seal.d.mts +8 -0
  118. package/dist/cursor-seal.mjs +98 -0
  119. package/dist/dashboard-id.mjs +1 -1
  120. package/dist/dashboards.mjs +4 -0
  121. package/dist/drill-access.mjs +93 -0
  122. package/dist/drill-change.mjs +76 -0
  123. package/dist/drill-crumbs.mjs +113 -0
  124. package/dist/drill-distinct.mjs +130 -0
  125. package/dist/drill-explain.mjs +64 -0
  126. package/dist/drill-identity.mjs +35 -0
  127. package/dist/drill-item-id.mjs +35 -0
  128. package/dist/drill-items.mjs +132 -0
  129. package/dist/drill-open.mjs +169 -0
  130. package/dist/drill-seal.mjs +170 -0
  131. package/dist/drill-secret.mjs +14 -0
  132. package/dist/drill-share.mjs +53 -0
  133. package/dist/drill-summary.mjs +158 -0
  134. package/dist/drill-targets.mjs +53 -0
  135. package/dist/drill-totals.mjs +8 -0
  136. package/dist/drill-views.mjs +175 -0
  137. package/dist/drill.mjs +157 -0
  138. package/dist/editing.mjs +3 -3
  139. package/dist/endpoints/dashboards.mjs +28 -5
  140. package/dist/endpoints/drill.mjs +55 -0
  141. package/dist/endpoints/index.d.mts +245 -4
  142. package/dist/endpoints/index.mjs +5 -1
  143. package/dist/endpoints/meta.mjs +10 -1
  144. package/dist/endpoints/query.mjs +26 -4
  145. package/dist/execute.d.mts +19 -1
  146. package/dist/execute.mjs +34 -27
  147. package/dist/handler.mjs +5 -1
  148. package/dist/index.d.mts +3 -1
  149. package/dist/index.mjs +29 -2
  150. package/dist/llms.txt +22 -0
  151. package/dist/mcp/drill.mjs +61 -0
  152. package/dist/mcp/format.mjs +69 -11
  153. package/dist/mcp/index.d.mts +15 -4
  154. package/dist/mcp/index.mjs +13 -7
  155. package/dist/mcp/query.d.mts +7 -2
  156. package/dist/mcp/query.mjs +40 -6
  157. package/dist/node-postgres.d.mts +8 -4
  158. package/dist/node-postgres.mjs +29 -6
  159. package/dist/owner.mjs +3 -3
  160. package/dist/postgres-connection.d.mts +8 -2
  161. package/dist/postgres-connection.mjs +2 -1
  162. package/dist/postgres-store.mjs +1 -0
  163. package/dist/react/Canvas.mjs +28 -5
  164. package/dist/react/Cell.mjs +2 -1
  165. package/dist/react/Dashboard.d.mts +10 -5
  166. package/dist/react/Dashboard.mjs +62 -22
  167. package/dist/react/DashboardList.mjs +52 -24
  168. package/dist/react/DashboardListRow.mjs +49 -0
  169. package/dist/react/Discard.mjs +12 -4
  170. package/dist/react/Editing.mjs +19 -5
  171. package/dist/react/FilterBar.d.mts +7 -9
  172. package/dist/react/Grid.mjs +19 -24
  173. package/dist/react/Header.mjs +10 -1
  174. package/dist/react/History.mjs +5 -0
  175. package/dist/react/Parts.mjs +6 -2
  176. package/dist/react/ReadFailed.mjs +23 -0
  177. package/dist/react/ReviewPanel.mjs +13 -2
  178. package/dist/react/RowBody.d.mts +19 -0
  179. package/dist/react/RowBody.mjs +55 -0
  180. package/dist/react/Spaces.mjs +15 -1
  181. package/dist/react/Tile.d.mts +3 -1
  182. package/dist/react/Tile.mjs +84 -32
  183. package/dist/react/_virtual/_rolldown/runtime.mjs +12 -0
  184. package/dist/react/arrange-steps.mjs +16 -13
  185. package/dist/react/arrange.mjs +10 -3
  186. package/dist/react/builder/Calcs.mjs +35 -11
  187. package/dist/react/builder/FilterEditor.mjs +196 -0
  188. package/dist/react/builder/Filters.mjs +172 -116
  189. package/dist/react/builder/Formula.mjs +82 -0
  190. package/dist/react/builder/Groups.mjs +1 -0
  191. package/dist/react/builder/Preview.mjs +1 -1
  192. package/dist/react/builder/RangeEditor.mjs +184 -0
  193. package/dist/react/builder/Sections.mjs +41 -6
  194. package/dist/react/builder/Time.mjs +138 -60
  195. package/dist/react/builder/Values.mjs +85 -0
  196. package/dist/react/builder/WidgetBuilder.mjs +50 -49
  197. package/dist/react/builder/base.d.mts +5 -0
  198. package/dist/react/builder/base.mjs +33 -8
  199. package/dist/react/builder/calc.mjs +15 -1
  200. package/dist/react/builder/escape.d.mts +1 -0
  201. package/dist/react/builder/escape.mjs +62 -0
  202. package/dist/react/builder/filter-tree.d.mts +9 -0
  203. package/dist/react/builder/filter-tree.mjs +186 -0
  204. package/dist/react/builder/formula-parse.d.mts +18 -0
  205. package/dist/react/builder/formula-parse.mjs +136 -0
  206. package/dist/react/builder/labels.d.mts +1 -1
  207. package/dist/react/builder/state.d.mts +2 -1
  208. package/dist/react/builder/state.mjs +23 -37
  209. package/dist/react/builder/useBuilder.d.mts +12 -1
  210. package/dist/react/builder/useBuilder.mjs +6 -3
  211. package/dist/react/builder/words.d.mts +59 -0
  212. package/dist/react/builder/words.mjs +73 -0
  213. package/dist/react/client.d.mts +2 -0
  214. package/dist/react/client.mjs +1 -0
  215. package/dist/react/context.d.mts +28 -1
  216. package/dist/react/context.mjs +25 -4
  217. package/dist/react/drill/Bars.mjs +179 -0
  218. package/dist/react/drill/Controls.mjs +173 -0
  219. package/dist/react/drill/DashboardTile.d.mts +18 -0
  220. package/dist/react/drill/DashboardTile.mjs +107 -0
  221. package/dist/react/drill/DrillPanel.d.mts +31 -0
  222. package/dist/react/drill/DrillPanel.mjs +104 -0
  223. package/dist/react/drill/DrillTabs.mjs +52 -0
  224. package/dist/react/drill/Header.mjs +131 -0
  225. package/dist/react/drill/Items.d.mts +22 -0
  226. package/dist/react/drill/Items.mjs +164 -0
  227. package/dist/react/drill/ItemsFoot.mjs +60 -0
  228. package/dist/react/drill/Notes.mjs +58 -0
  229. package/dist/react/drill/PanelBody.mjs +74 -0
  230. package/dist/react/drill/PanelStates.mjs +37 -0
  231. package/dist/react/drill/board.d.mts +18 -0
  232. package/dist/react/drill/board.mjs +91 -0
  233. package/dist/react/drill/counts.mjs +14 -0
  234. package/dist/react/drill/host.mjs +26 -0
  235. package/dist/react/drill/item-parts.d.mts +5 -0
  236. package/dist/react/drill/item-parts.mjs +76 -0
  237. package/dist/react/drill/item-type.d.mts +26 -0
  238. package/dist/react/drill/item-type.mjs +7 -0
  239. package/dist/react/drill/lazy.d.mts +6 -0
  240. package/dist/react/drill/lazy.mjs +17 -0
  241. package/dist/react/drill/pages.mjs +48 -0
  242. package/dist/react/drill/panel-focus.mjs +51 -0
  243. package/dist/react/drill/props.d.mts +25 -0
  244. package/dist/react/drill/props.mjs +72 -0
  245. package/dist/react/drill/state.d.mts +18 -0
  246. package/dist/react/drill/state.mjs +68 -0
  247. package/dist/react/drill/useDrill.d.mts +46 -0
  248. package/dist/react/drill/useDrill.mjs +194 -0
  249. package/dist/react/drill/words.d.mts +101 -0
  250. package/dist/react/drill/words.mjs +79 -0
  251. package/dist/react/english.mjs +29 -6
  252. package/dist/react/filters/bar.d.mts +12 -0
  253. package/dist/react/filters/bar.mjs +135 -0
  254. package/dist/react/filters/calendar.mjs +193 -0
  255. package/dist/react/filters/chip.mjs +174 -0
  256. package/dist/react/filters/context.d.mts +22 -0
  257. package/dist/react/filters/context.mjs +78 -0
  258. package/dist/react/filters/dates.mjs +89 -0
  259. package/dist/react/filters/days.d.mts +36 -0
  260. package/dist/react/filters/days.mjs +87 -0
  261. package/dist/react/filters/field-step.mjs +81 -0
  262. package/dist/react/filters/hooks.d.mts +34 -0
  263. package/dist/react/filters/hooks.mjs +94 -0
  264. package/dist/react/filters/listbox.mjs +131 -0
  265. package/dist/react/filters/logic.d.mts +59 -0
  266. package/dist/react/filters/logic.mjs +109 -0
  267. package/dist/react/filters/menu-search.mjs +211 -0
  268. package/dist/react/filters/menu.mjs +85 -0
  269. package/dist/react/filters/number.mjs +127 -0
  270. package/dist/react/filters/numbers.d.mts +47 -0
  271. package/dist/react/filters/numbers.mjs +151 -0
  272. package/dist/react/filters/operator.mjs +104 -0
  273. package/dist/react/filters/phone.mjs +104 -0
  274. package/dist/react/filters/popover.d.mts +19 -0
  275. package/dist/react/filters/popover.mjs +153 -0
  276. package/dist/react/filters/rules.d.mts +8 -0
  277. package/dist/react/filters/rules.mjs +55 -0
  278. package/dist/react/filters/sheet.mjs +196 -0
  279. package/dist/react/filters/state.mjs +132 -0
  280. package/dist/react/filters/suggest.d.mts +47 -0
  281. package/dist/react/filters/suggest.mjs +97 -0
  282. package/dist/react/filters/values.mjs +166 -0
  283. package/dist/react/filters/words.d.mts +81 -0
  284. package/dist/react/filters/words.mjs +73 -0
  285. package/dist/react/format.d.mts +3 -3
  286. package/dist/react/format.mjs +45 -16
  287. package/dist/react/index.d.mts +34 -5
  288. package/dist/react/index.mjs +15 -4
  289. package/dist/react/messages.d.mts +47 -2
  290. package/dist/react/place.mjs +7 -3
  291. package/dist/react/renderers/index.d.mts +10 -2
  292. package/dist/react/renderers/index.mjs +116 -14
  293. package/dist/react/renderers/list.d.mts +22 -0
  294. package/dist/react/renderers/list.mjs +118 -0
  295. package/dist/react/review-words.mjs +1 -1
  296. package/dist/react/review.mjs +2 -2
  297. package/dist/react/scope.mjs +2 -7
  298. package/dist/react/series.d.mts +54 -0
  299. package/dist/react/series.mjs +191 -0
  300. package/dist/react/theme.css +2734 -1296
  301. package/dist/react/theme.css.d.ts +1 -0
  302. package/dist/react/tile-store.mjs +15 -3
  303. package/dist/react/useBoard.d.mts +7 -0
  304. package/dist/react/useBoard.mjs +4 -1
  305. package/dist/react/useDashboard.d.mts +4 -0
  306. package/dist/react/useDashboard.mjs +8 -1
  307. package/dist/react/useTiles.mjs +50 -15
  308. package/dist/react/view-grid.mjs +16 -0
  309. package/dist/react/view.d.mts +9 -0
  310. package/dist/react/view.mjs +22 -10
  311. package/dist/reading.d.mts +2 -0
  312. package/dist/reading.mjs +9 -1
  313. package/dist/recharts/axes.mjs +28 -0
  314. package/dist/recharts/axis.mjs +84 -0
  315. package/dist/recharts/bar.d.mts +7 -0
  316. package/dist/recharts/bar.mjs +140 -0
  317. package/dist/recharts/charts.d.mts +4 -6
  318. package/dist/recharts/charts.mjs +2 -114
  319. package/dist/recharts/index.d.mts +5 -3
  320. package/dist/recharts/index.mjs +6 -3
  321. package/dist/recharts/line.d.mts +2 -0
  322. package/dist/recharts/line.mjs +111 -0
  323. package/dist/recharts/marks.mjs +112 -0
  324. package/dist/recharts/parts.mjs +88 -0
  325. package/dist/recharts/series.d.mts +2 -22
  326. package/dist/recharts/series.mjs +1 -64
  327. package/dist/recharts/table.mjs +71 -0
  328. package/dist/records-read.mjs +44 -0
  329. package/dist/registry/filter-bar.json +26 -0
  330. package/dist/skills/derive-dashboards/SKILL.md +69 -0
  331. package/dist/store/apply.mjs +5 -5
  332. package/dist/store/commands.mjs +4 -4
  333. package/dist/store/discard.mjs +7 -7
  334. package/dist/store/drafts.mjs +5 -5
  335. package/dist/store/editor.mjs +1 -1
  336. package/dist/store/publish.mjs +12 -12
  337. package/dist/store/reader.mjs +41 -22
  338. package/dist/store/review.mjs +16 -16
  339. package/dist/store/rows.mjs +20 -20
  340. package/dist/store/undo.mjs +3 -3
  341. package/dist/store/unpublished.mjs +4 -4
  342. package/dist/store/versions.mjs +14 -14
  343. package/dist/testing/adapter-suite.mjs +4 -4
  344. package/dist/tiles.mjs +37 -3
  345. package/package.json +12 -10
  346. package/dist/react/FilterBar.mjs +0 -119
  347. package/dist/react/Records.d.mts +0 -12
  348. package/dist/react/Records.mjs +0 -97
  349. package/src/adapter/sql-adapter.ts +0 -95
  350. package/src/adapter/statement.ts +0 -185
  351. package/src/authorize.ts +0 -73
  352. package/src/body.ts +0 -169
  353. package/src/bounded.ts +0 -43
  354. package/src/cache.ts +0 -192
  355. package/src/checks.ts +0 -170
  356. package/src/custom-source.ts +0 -59
  357. package/src/dashboard-id.ts +0 -36
  358. package/src/dashboards.ts +0 -132
  359. package/src/editing.ts +0 -148
  360. package/src/endpoints/access.ts +0 -41
  361. package/src/endpoints/dashboards.ts +0 -92
  362. package/src/endpoints/drafts.ts +0 -138
  363. package/src/endpoints/index.ts +0 -21
  364. package/src/endpoints/meta.ts +0 -137
  365. package/src/endpoints/query.ts +0 -86
  366. package/src/endpoints/read.ts +0 -92
  367. package/src/endpoints/review.ts +0 -89
  368. package/src/endpoints/values.ts +0 -62
  369. package/src/endpoints/versions.ts +0 -104
  370. package/src/execute.ts +0 -207
  371. package/src/handler.ts +0 -232
  372. package/src/http.ts +0 -66
  373. package/src/index.ts +0 -163
  374. package/src/introspect.ts +0 -205
  375. package/src/mcp/api.ts +0 -59
  376. package/src/mcp/format.ts +0 -67
  377. package/src/mcp/index.ts +0 -151
  378. package/src/mcp/query.ts +0 -153
  379. package/src/mcp/resolve.ts +0 -114
  380. package/src/node-postgres.ts +0 -81
  381. package/src/owner.ts +0 -36
  382. package/src/postgres-connection.ts +0 -143
  383. package/src/postgres-store.ts +0 -82
  384. package/src/principal.ts +0 -39
  385. package/src/reading.ts +0 -56
  386. package/src/request-rows.ts +0 -23
  387. package/src/request.ts +0 -22
  388. package/src/storage.ts +0 -63
  389. package/src/store/apply.ts +0 -129
  390. package/src/store/commands.ts +0 -75
  391. package/src/store/conflicts.ts +0 -98
  392. package/src/store/create-tables.ts +0 -104
  393. package/src/store/discard.ts +0 -42
  394. package/src/store/drafts.ts +0 -133
  395. package/src/store/editor.ts +0 -28
  396. package/src/store/log.ts +0 -28
  397. package/src/store/publish.ts +0 -199
  398. package/src/store/publisher.ts +0 -21
  399. package/src/store/reader.ts +0 -139
  400. package/src/store/review.ts +0 -239
  401. package/src/store/rows.ts +0 -250
  402. package/src/store/tenant.ts +0 -28
  403. package/src/store/undo.ts +0 -56
  404. package/src/store/unpublished.ts +0 -33
  405. package/src/store/versions.ts +0 -106
  406. package/src/store/writer.ts +0 -19
  407. package/src/testing/adapter-suite.ts +0 -239
  408. package/src/testing/index.ts +0 -2
  409. package/src/tile-doc.ts +0 -46
  410. package/src/tiles.ts +0 -120
package/src/handler.ts DELETED
@@ -1,232 +0,0 @@
1
- import {
2
- BASE_ERROR_CODES,
3
- CONTRACT_VERSION,
4
- type DashEndpoint,
5
- type DashHook,
6
- type DashOptions,
7
- type HeadersLike,
8
- type HookContext,
9
- type Principal,
10
- type Viewer,
11
- } from "@derive-to/dashboards-core";
12
- import { EngineError } from "@derive-to/dashboards-core/engine";
13
- import { addRoute, createRouter, findRoute } from "rou3";
14
- import { coreEndpoints } from "./endpoints/index";
15
- import type { Runtime } from "./execute";
16
- import { errorResponse, HttpError, json, ndjson } from "./http";
17
- import { dashboardResource } from "./owner";
18
- import { checkTenant, principalOf } from "./principal";
19
-
20
- /** Engine refusals the caller can fix are 400s; a plan that fails its own check is a 500. */
21
- function engineStatus(error: EngineError): number {
22
- if (error.code === "PLAN_ASSERTION" || error.code === "NUMERIC_STORAGE") return 500;
23
- return error.code === "TENANT_MISSING" ? 403 : 400;
24
- }
25
-
26
- async function authorize(
27
- options: DashOptions,
28
- endpoint: DashEndpoint,
29
- ctx: { body: unknown; principal: Principal | null; request: Request },
30
- ) {
31
- const { access } = endpoint;
32
- if (access.kind === "public") return;
33
- if (ctx.principal?.channel !== "user") throw new HttpError(401, "UNAUTHORIZED", "Sign in first.");
34
- checkTenant(options, ctx.principal);
35
- if (access.kind === "signed_in") return;
36
- const named = access.resource(ctx.body);
37
- const resource =
38
- named.kind === "dashboard"
39
- ? await dashboardResource(options, ctx.request, ctx.principal, named.id)
40
- : named;
41
- const allowed = await options.access.can(ctx.principal.viewer, access.verb, resource);
42
- if (!allowed) throw new HttpError(403, "FORBIDDEN", BASE_ERROR_CODES.FORBIDDEN.message);
43
- }
44
-
45
- /**
46
- * A browser sends its page's origin with every POST. One that is neither this server's nor a
47
- * trusted one is refused, so another site cannot drive a signed-in viewer's session.
48
- */
49
- function checkOrigin(options: DashOptions, endpoint: DashEndpoint, request: Request): void {
50
- if (request.method === "GET" || endpoint.access.kind === "public") return;
51
- const origin = request.headers.get("origin");
52
- if (origin === null || origin === new URL(request.url).origin) return;
53
- if ((options.trustedOrigins ?? []).includes(origin)) return;
54
- throw new HttpError(403, "FORBIDDEN", `Requests from ${origin} are not trusted.`);
55
- }
56
-
57
- async function readBody(request: Request): Promise<unknown> {
58
- if (request.method === "GET") return Object.fromEntries(new URL(request.url).searchParams);
59
- try {
60
- return await request.json();
61
- } catch {
62
- throw new HttpError(400, "BODY_INVALID", "The body is not JSON. Send a JSON object.");
63
- }
64
- }
65
-
66
- type Hooks = { before: readonly DashHook[]; after: readonly DashHook[] };
67
-
68
- async function runHooks(hooks: readonly DashHook[], path: string, ctx: HookContext) {
69
- for (const hook of hooks.filter((h) => h.matcher(path))) {
70
- // Hooks run in plugin order, each after the one before.
71
- // oxlint-disable-next-line eslint/no-await-in-loop
72
- await hook.handler(ctx);
73
- }
74
- }
75
-
76
- /** One endpoint for one request: the viewer, access, the body, hooks, then the handler's answer. */
77
- async function run(
78
- rt: Runtime,
79
- hooks: Hooks,
80
- endpoint: DashEndpoint,
81
- call: { request: Request; viewer?: Viewer | undefined },
82
- ) {
83
- const { request } = call;
84
- const principal = await principalOf(rt.options, request, call.viewer);
85
- const raw = await readBody(request);
86
- await authorize(rt.options, endpoint, { body: raw, principal, request });
87
- const body = endpoint.parse(raw);
88
- const ctx = { body, principal, request };
89
- await runHooks(hooks.before, endpoint.path, { ...ctx, path: endpoint.path });
90
- const output = await endpoint.handler(ctx);
91
- const answered =
92
- endpoint.respond === "ndjson"
93
- ? { ...ctx, path: endpoint.path }
94
- : { ...ctx, path: endpoint.path, result: output };
95
- await runHooks(hooks.after, endpoint.path, answered);
96
- return output;
97
- }
98
-
99
- async function dispatch(
100
- rt: Runtime,
101
- hooks: Hooks,
102
- endpoint: DashEndpoint,
103
- request: Request,
104
- ): Promise<Response> {
105
- checkOrigin(rt.options, endpoint, request);
106
- const output = await run(rt, hooks, endpoint, { request });
107
- return endpoint.respond === "ndjson" ? ndjson(output) : json(200, output);
108
- }
109
-
110
- /**
111
- * Calls an endpoint from the host's own server, as better-auth's `auth.api` does: through the
112
- * same viewer, access check, body schema and hooks as over HTTP, and answers with the value
113
- * itself. Pass the incoming `request`: the call runs on its URL and headers, so a host that
114
- * reads the viewer or tenant from the cookie, a header or the host name gets the same answer as
115
- * over HTTP. `headers` alone works too, on a placeholder URL. Or name the `viewer` outright,
116
- * as an MCP server or a job does with no request to read one from: every check still runs as
117
- * that viewer. A refusal throws `HttpError` with its code. There is no browser, so no origin to
118
- * check.
119
- */
120
- export function serverCall(rt: Runtime, endpoint: DashEndpoint) {
121
- const hooks = hooksOf(rt);
122
- const base = rt.options.basePath ?? "/api/dashboards";
123
- return (
124
- input: { body?: unknown; headers?: HeadersLike; request?: Request; viewer?: Viewer } = {},
125
- ) => {
126
- const headers = new Headers(input.request?.headers);
127
- for (const [name, value] of new Headers(input.headers)) headers.set(name, value);
128
- headers.set("content-type", "application/json");
129
- const get = endpoint.method === "GET";
130
- const origin =
131
- input.request === undefined ? "http://server.call" : new URL(input.request.url).origin;
132
- const request = new Request(`${origin}${base}${endpoint.path}`, {
133
- method: endpoint.method,
134
- headers,
135
- ...(get ? {} : { body: JSON.stringify(input.body ?? {}) }),
136
- });
137
- return run(rt, hooks, endpoint, { request, viewer: input.viewer });
138
- };
139
- }
140
-
141
- /**
142
- * A refusal answers with its own code; what it keeps for the host alone goes to `onError`.
143
- * Anything else is the library's or the host's bug: it
144
- * goes to `onError` (the console by default) and answers 500 `INTERNAL`, never a stack.
145
- */
146
- function errorOf(rt: Runtime, error: unknown, request: Request): Response {
147
- if (error instanceof HttpError) {
148
- // oxlint-disable-next-line no-console -- the host's logger, or the console without one
149
- if (error.cause !== undefined) (rt.options.onError ?? console.error)(error.cause, request);
150
- return errorResponse(error);
151
- }
152
- if (error instanceof EngineError)
153
- return json(engineStatus(error), { error: { code: error.code, message: error.message } });
154
- // The default when the host gives no logger: an unexpected error must be seen somewhere.
155
- // oxlint-disable-next-line no-console
156
- (rt.options.onError ?? console.error)(error, request);
157
- return json(500, { error: { code: "INTERNAL", message: BASE_ERROR_CODES.INTERNAL.message } });
158
- }
159
-
160
- /** Each plugin's hooks, in plugin order. */
161
- function hooksOf(rt: Runtime): Hooks {
162
- const plugins = rt.options.plugins ?? [];
163
- return {
164
- before: plugins.flatMap((p) => p.hooks?.before ?? []),
165
- after: plugins.flatMap((p) => p.hooks?.after ?? []),
166
- };
167
- }
168
-
169
- /** Every endpoint, the core's and each plugin's; two at one method and path refuse to start. */
170
- function routes(rt: Runtime) {
171
- const base = rt.options.basePath ?? "/api/dashboards";
172
- const router = createRouter<DashEndpoint>();
173
- const plugins = rt.options.plugins ?? [];
174
- const endpoints: DashEndpoint[] = [
175
- ...Object.values(coreEndpoints(rt)),
176
- ...plugins.flatMap((p) => Object.values(p.endpoints ?? {})),
177
- ];
178
- for (const endpoint of endpoints) {
179
- const path = `${base}${endpoint.path}`;
180
- if (findRoute(router, endpoint.method, path) !== undefined)
181
- throw new Error(`Two endpoints answer ${endpoint.method} ${endpoint.path}.`);
182
- addRoute(router, endpoint.method, path, endpoint);
183
- }
184
- return { router, hooks: hooksOf(rt) };
185
- }
186
-
187
- /**
188
- * No endpoint answers this: say the method and path, and where the handler is mounted, since
189
- * the usual cause is mounting it somewhere other than `basePath`.
190
- */
191
- function notFound(
192
- rt: Runtime,
193
- router: Parameters<typeof findRoute<DashEndpoint>>[0],
194
- method: string,
195
- path: string,
196
- ): HttpError {
197
- const base = rt.options.basePath ?? "/api/dashboards";
198
- const other = ["GET", "POST"].find(
199
- (m) => m !== method && findRoute(router, m, path) !== undefined,
200
- );
201
- if (other !== undefined)
202
- return new HttpError(404, "NOT_FOUND", `${path} answers ${other}, not ${method}.`);
203
- const where = path.startsWith(base)
204
- ? `No endpoint answers ${method} ${path}.`
205
- : `${method} ${path} is outside basePath "${base}". Mount the handler there, or set basePath to where it is mounted.`;
206
- return new HttpError(404, "NOT_FOUND", where);
207
- }
208
-
209
- /** Every answer says which contract it keeps, so a client from another release can tell. */
210
- function stamped(response: Response): Response {
211
- response.headers.set("dd-contract", CONTRACT_VERSION);
212
- return response;
213
- }
214
-
215
- /**
216
- * The fetch handler: mount it at `basePath` (default `/api/dashboards`) in any framework
217
- * that speaks Request and Response.
218
- */
219
- export function createHandler(rt: Runtime): (request: Request) => Promise<Response> {
220
- const { router, hooks } = routes(rt);
221
- return async (request) => {
222
- const { pathname } = new URL(request.url);
223
- const match = findRoute(router, request.method, pathname);
224
- if (match === undefined)
225
- return stamped(errorResponse(notFound(rt, router, request.method, pathname)));
226
- try {
227
- return stamped(await dispatch(rt, hooks, match.data, request));
228
- } catch (error) {
229
- return stamped(errorOf(rt, error, request));
230
- }
231
- };
232
- }
package/src/http.ts DELETED
@@ -1,66 +0,0 @@
1
- import type { Issue, RuntimeErrorCode } from "@derive-to/dashboards-core";
2
-
3
- /** A refusal the handler turns into a JSON error response. */
4
- export class HttpError extends Error {
5
- readonly status: number;
6
- readonly code: RuntimeErrorCode;
7
- readonly issues: readonly Issue[] | undefined;
8
- /**
9
- * `issues`: what was wrong, item by item. `cause`: what only the host should see (a
10
- * database's own message, which can echo stored values); it goes to `onError`, never into
11
- * the answer.
12
- */
13
- constructor(
14
- status: number,
15
- code: HttpError["code"],
16
- message: string,
17
- more: { issues?: readonly Issue[]; cause?: unknown } = {},
18
- ) {
19
- const { issues, cause } = more;
20
- super(message, cause === undefined ? undefined : { cause });
21
- this.name = "HttpError";
22
- this.status = status;
23
- this.code = code;
24
- this.issues = issues;
25
- }
26
- }
27
-
28
- export function json(status: number, body: unknown): Response {
29
- return new Response(JSON.stringify(body), {
30
- status,
31
- headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
32
- });
33
- }
34
-
35
- export function errorResponse(error: HttpError): Response {
36
- const issues = error.issues === undefined ? {} : { issues: error.issues };
37
- return json(error.status, { error: { code: error.code, message: error.message, ...issues } });
38
- }
39
-
40
- function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
41
- return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
42
- }
43
-
44
- /**
45
- * Streams each value of `lines` as one line of JSON, written as soon as it is ready. The stream
46
- * stops reading when the client goes away.
47
- */
48
- export function ndjson(lines: unknown): Response {
49
- if (!isAsyncIterable(lines)) throw new Error("An ndjson endpoint must return an async iterable.");
50
- const iterator = lines[Symbol.asyncIterator]();
51
- const encoder = new TextEncoder();
52
- const body = new ReadableStream<Uint8Array>({
53
- async pull(controller) {
54
- const next = await iterator.next();
55
- if (next.done === true) controller.close();
56
- else controller.enqueue(encoder.encode(`${JSON.stringify(next.value)}\n`));
57
- },
58
- async cancel() {
59
- await iterator.return?.();
60
- },
61
- });
62
- return new Response(body, {
63
- status: 200,
64
- headers: { "content-type": "application/x-ndjson; charset=utf-8", "cache-control": "no-store" },
65
- });
66
- }
package/src/index.ts DELETED
@@ -1,163 +0,0 @@
1
- import {
2
- type Awaitable,
3
- BASE_ERROR_CODES,
4
- type CodeDashboard,
5
- type Dash,
6
- type DashEndpoint,
7
- type DashOptions,
8
- type DashPlugin,
9
- defineModel,
10
- type ServerCallInput,
11
- type SourceName,
12
- type UniqueIds,
13
- type ViewerFor,
14
- } from "@derive-to/dashboards-core";
15
- import { loadDocument } from "@derive-to/dashboards-core/schema";
16
- import { createCache } from "./cache";
17
- import { coreEndpoints } from "./endpoints/index";
18
- import { createHandler, serverCall } from "./handler";
19
- import { HttpError } from "./http";
20
- import { isSource } from "./reading";
21
-
22
- /**
23
- * Code-defined dashboards are checked when the handler is made, not when a viewer opens one: an
24
- * invalid document stops the server with every problem named, and a layout is repaired once.
25
- */
26
- function checkedDashboards(options: DashOptions): CodeDashboard[] {
27
- return (options.dashboards ?? []).map((d) => {
28
- const loaded = loadDocument(d.document);
29
- if (!loaded.ok) {
30
- const problems = loaded.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
31
- throw new Error(`The dashboard "${d.key}" is not a valid document: ${problems}`);
32
- }
33
- return { key: d.key, document: loaded.doc };
34
- });
35
- }
36
-
37
- /**
38
- * Every connection the model's sources read is given, and each one given as it is (not per
39
- * request) is a connection, or the server does not start.
40
- */
41
- function checkConnections(options: DashOptions): void {
42
- const missing = [...new Set(Object.values(options.model.sources).map((s) => s.in))].filter(
43
- (id) => !Object.hasOwn(options.connections, id),
44
- );
45
- if (missing.length > 0)
46
- throw new Error(
47
- `The model reads ${missing.map((m) => `"${m}"`).join(", ")}, which \`connections\` does not have. Add each as a key of \`connections\`.`,
48
- );
49
- const wrong = Object.entries(options.connections).find(
50
- ([, c]) => typeof c !== "function" && !isSource(c),
51
- );
52
- if (wrong !== undefined)
53
- throw new Error(
54
- `\`connections.${wrong[0]}\` is not a connection. Wrap your database client, postgresConnection({ run, transaction }), or your own data layer, customSource({ answer, records }).`,
55
- );
56
- }
57
-
58
- /**
59
- * Two plugins with one id would answer each other's paths, and a plugin named like one of the
60
- * library's calls would hide it under `api`: refuse to start.
61
- */
62
- function checkPluginIds(options: DashOptions, taken: readonly string[]): void {
63
- const ids = (options.plugins ?? []).map((p) => p.id);
64
- const twice = ids.find((id, i) => ids.indexOf(id) !== i);
65
- if (twice !== undefined) throw new Error(`Two plugins have the id "${twice}".`);
66
- const clash = ids.find((id) => taken.includes(id));
67
- if (clash !== undefined)
68
- throw new Error(`A plugin's id "${clash}" is a name the library uses under \`api\`.`);
69
- }
70
-
71
- /** Whether an endpoint's answer is a stream of lines (`ndjson`) rather than one value. */
72
- function isStream(output: unknown): output is AsyncIterable<unknown> {
73
- return (
74
- typeof output === "object" &&
75
- output !== null &&
76
- typeof Reflect.get(output, Symbol.asyncIterator) === "function"
77
- );
78
- }
79
-
80
- /** One endpoint by path; a streamed answer is read to its end and comes back as its lines. */
81
- async function callPath(
82
- byPath: ReadonlyMap<string, (input?: ServerCallInput) => Promise<unknown>>,
83
- path: string,
84
- input?: ServerCallInput,
85
- ): Promise<unknown> {
86
- const call = byPath.get(path);
87
- if (call === undefined)
88
- throw new HttpError(404, "NOT_FOUND", `There is no endpoint at ${path}. routes lists them.`);
89
- const output = await call(input);
90
- if (!isStream(output)) return output;
91
- const lines: unknown[] = [];
92
- for await (const line of output) lines.push(line);
93
- return lines;
94
- }
95
-
96
- /** What `deriveDashboards` returns: `api` calls every endpoint; `$Infer.Endpoints` types a client. */
97
- export type DashServer<O extends DashOptions> = Dash<O, ReturnType<typeof coreEndpoints>>;
98
-
99
- /**
100
- * Embedded dashboards for your product. Pass the model, how to read the viewer, who may see
101
- * what, and the connections the model reads; mount the returned handler. Everything it
102
- * returns is typed from the options: `$Infer.Member` and `$Infer.Query` from the model,
103
- * `$ERROR_CODES` from the plugins, and `api`: every endpoint, the library's by name and each
104
- * plugin's under its id, as a server-side call.
105
- */
106
- export function deriveDashboards<const O extends DashOptions>(
107
- options: O & {
108
- plugins?: UniqueIds<O["plugins"]>;
109
- /** Typed from the model: with tenant keys, the viewer must carry a value for each. */
110
- viewer: (request: Request) => Awaitable<ViewerFor<O["model"]> | null>;
111
- },
112
- ): DashServer<O> {
113
- defineModel(options.model);
114
- checkConnections(options);
115
- const checked = { ...options, dashboards: checkedDashboards(options) };
116
- const rt = { options: checked, cache: createCache(checked) };
117
- const library = coreEndpoints(rt);
118
- checkPluginIds(options, ["cache", ...Object.keys(library)]);
119
- const plugins: readonly DashPlugin[] = options.plugins ?? [];
120
- const invalidate = async (a: {
121
- tenant: Record<string, string>;
122
- sources?: readonly SourceName[];
123
- }) => {
124
- await rt.cache?.invalidate(a.tenant, a.sources);
125
- };
126
- const calls = (record: Record<string, DashEndpoint>) =>
127
- Object.fromEntries(Object.entries(record).map(([name, e]) => [name, serverCall(rt, e)]));
128
- const core = calls(library);
129
- const endpoints = Object.fromEntries(plugins.map((p) => [p.id, calls(p.endpoints ?? {})]));
130
- const all = [library, ...plugins.map((p) => p.endpoints ?? {})].flatMap((r) => Object.values(r));
131
- const byPath = new Map(all.map((e) => [e.path, serverCall(rt, e)]));
132
- const codes: Record<string, unknown> = { ...BASE_ERROR_CODES };
133
- for (const p of plugins) Object.assign(codes, p.$ERROR_CODES);
134
- // Built from the same plugin tuple the types read; `$Infer` carries types only.
135
- /* oxlint-disable typescript/no-unsafe-type-assertion */
136
- return {
137
- handler: createHandler(rt),
138
- api: { cache: { invalidate }, ...core, ...endpoints } as DashServer<O>["api"],
139
- $ERROR_CODES: codes as DashServer<O>["$ERROR_CODES"],
140
- call: (path, input) => callPath(byPath, path, input),
141
- routes: all.map((e) => ({ path: e.path, method: e.method })),
142
- $Infer: {} as DashServer<O>["$Infer"],
143
- options,
144
- };
145
- /* oxlint-enable typescript/no-unsafe-type-assertion */
146
- }
147
-
148
- export { type CustomSourceOptions, customSource } from "./custom-source";
149
- export { HttpError } from "./http";
150
- export { nodePostgres, type PgPool, type PgQueryable } from "./node-postgres";
151
- export {
152
- type PostgresConnectionOptions,
153
- postgresConnection,
154
- type RunSql,
155
- } from "./postgres-connection";
156
- export { type PostgresStoreOptions, postgresStore, type RunRows } from "./postgres-store";
157
- export { memoryStorage } from "./storage";
158
- export {
159
- createTables,
160
- type SchemaDiff,
161
- SchemaMismatchError,
162
- schemaDiff,
163
- } from "./store/create-tables";
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
- }