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
@@ -1,114 +0,0 @@
1
- // Agents name things the way people do: "Signups", "Plan", "Tasks". A question may name a
2
- // source, measure or field by its id, its short name or its label; each is turned into its id
3
- // here, and a name that matches nothing is refused with the names that would have worked.
4
- import type { MetaResponse } from "@derive-to/dashboards-core";
5
- import { HttpError } from "../http";
6
-
7
- type Source = MetaResponse["sources"][number];
8
- type Named = { id: string; label: string };
9
-
10
- const fold = (text: string) => text.trim().toLowerCase();
11
-
12
- /** The one entry `name` names, by id, by the part after the source, or by label. */
13
- function pick<T extends Named>(entries: readonly T[], name: string): T | undefined {
14
- const wanted = fold(name);
15
- return (
16
- entries.find((e) => e.id === name) ??
17
- entries.find((e) => fold(e.id.split(".").slice(1).join(".")) === wanted) ??
18
- entries.find((e) => fold(e.label) === wanted)
19
- );
20
- }
21
-
22
- const unknown = (what: string, name: string, choices: readonly Named[]) =>
23
- new HttpError(
24
- 400,
25
- "QUERY_INVALID",
26
- `There is no ${what} "${name}". Use one of: ${choices
27
- .slice(0, 40)
28
- .map((c) => `${c.label} (${c.id})`)
29
- .join(", ")}.`,
30
- );
31
-
32
- /** The source a question reads, by name or label. */
33
- export function sourceOf(meta: MetaResponse, name: string): Source {
34
- const found = pick(
35
- meta.sources.map((s) => ({ ...s, id: s.name })),
36
- name,
37
- );
38
- if (found === undefined)
39
- throw unknown(
40
- "source",
41
- name,
42
- meta.sources.map((s) => ({ id: s.name, label: s.label })),
43
- );
44
- return found;
45
- }
46
-
47
- /** A field's id: one of the source's own, by any of its names, or a joined one already by id. */
48
- function memberId(source: Source, name: string): string {
49
- if (name.split(".").length > 2) return name;
50
- const found = pick(source.dimensions, name);
51
- if (found === undefined) throw unknown("field", name, source.dimensions);
52
- return found.id;
53
- }
54
-
55
- function measureId(source: Source, name: string): string {
56
- const found = pick(source.measures, name);
57
- if (found === undefined) throw unknown("measure", name, source.measures);
58
- return found.id;
59
- }
60
-
61
- /** Every `member` in a filter tree, by id; the tree is otherwise as given. */
62
- function filterIds(source: Source, filter: unknown): unknown {
63
- if (Array.isArray(filter)) return filter.map((f) => filterIds(source, f));
64
- if (typeof filter !== "object" || filter === null) return filter;
65
- return Object.fromEntries(
66
- Object.entries(filter).map(([key, value]) =>
67
- key === "member" && typeof value === "string"
68
- ? [key, memberId(source, value)]
69
- : [key, filterIds(source, value)],
70
- ),
71
- );
72
- }
73
-
74
- type Loose = {
75
- source: string;
76
- measures: readonly { measure: string }[];
77
- dimensions?: readonly { member: string }[];
78
- time?: { dimension: string };
79
- filters?: unknown;
80
- };
81
-
82
- /** The question with every source, measure and field named by its id. */
83
- export function resolveQuery<Q extends Loose>(meta: MetaResponse, query: Q): Q {
84
- const source = sourceOf(meta, query.source);
85
- return {
86
- ...query,
87
- source: source.name,
88
- measures: query.measures.map((m) => ({ ...m, measure: measureId(source, m.measure) })),
89
- ...(query.dimensions === undefined
90
- ? {}
91
- : {
92
- dimensions: query.dimensions.map((d) => ({ ...d, member: memberId(source, d.member) })),
93
- }),
94
- ...(query.time === undefined
95
- ? {}
96
- : { time: { ...query.time, dimension: memberId(source, query.time.dimension) } }),
97
- ...(query.filters === undefined ? {} : { filters: filterIds(source, query.filters) }),
98
- };
99
- }
100
-
101
- /** A dashboard named by id or title, from those the viewer can open. */
102
- export function dashboardOf(
103
- listed: readonly { id: string; title: string }[],
104
- name: string,
105
- ): { id: string; title: string } {
106
- const found =
107
- listed.find((d) => d.id === name) ?? listed.find((d) => fold(d.title) === fold(name));
108
- if (found !== undefined) return found;
109
- throw new HttpError(
110
- 404,
111
- "NOT_FOUND",
112
- `There is no dashboard "${name}". Open one of: ${listed.map((d) => `${d.title} (${d.id})`).join(", ")}.`,
113
- );
114
- }
@@ -1,81 +0,0 @@
1
- import type { IntrospectingConnection } from "@derive-to/dashboards-core";
2
- import { postgresConnection, type RunSql } from "./postgres-connection";
3
- import { postgresStore, type RunRows } from "./postgres-store";
4
-
5
- /** What `nodePostgres` uses of a node-postgres client: its `query` with a config object. */
6
- export type PgQueryable = {
7
- query(config: { text: string; values?: unknown[]; rowMode?: "array" }): Promise<{
8
- rows: unknown[];
9
- }>;
10
- };
11
-
12
- /** What `nodePostgres` uses of a node-postgres `Pool`: `query`, and `connect` for a transaction. */
13
- export type PgPool = PgQueryable & {
14
- connect(): Promise<PgQueryable & { release(destroy?: boolean | Error): void }>;
15
- };
16
-
17
- /** Rows as arrays in select order, for queries; as objects by column, for the store. */
18
- const arrays =
19
- (client: PgQueryable): RunSql =>
20
- async (text, params) =>
21
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- rowMode "array" returns arrays
22
- (await client.query({ text, values: [...params], rowMode: "array" })).rows as unknown[][];
23
- const objects =
24
- (client: PgQueryable): RunRows =>
25
- async (text, params) =>
26
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- without rowMode, rows are objects
27
- (await client.query({ text, values: [...params] })).rows as Record<string, unknown>[];
28
-
29
- /**
30
- * One client of the pool for `fn`, inside a transaction `begin` starts: committed when `fn`
31
- * resolves, rolled back when it throws, and the client always given back (dropped from the pool
32
- * when even the rollback failed).
33
- */
34
- async function inTransaction<T>(
35
- pool: PgPool,
36
- begin: string,
37
- fn: (client: PgQueryable) => Promise<T>,
38
- ): Promise<T> {
39
- const client = await pool.connect();
40
- let broken = false;
41
- try {
42
- await client.query({ text: begin });
43
- const value = await fn(client);
44
- await client.query({ text: "COMMIT" });
45
- return value;
46
- } catch (error) {
47
- await client.query({ text: "ROLLBACK" }).catch(() => {
48
- broken = true;
49
- });
50
- throw error;
51
- } finally {
52
- client.release(broken);
53
- }
54
- }
55
-
56
- /**
57
- * The query connection and the store for a node-postgres `Pool`, set up the safe way: each
58
- * request's queries read one snapshot on one pooled client, begun in one round trip with the
59
- * request's statement timeout (so a slow query stops in the database), and every store write
60
- * is one transaction. Works the same behind PgBouncer in transaction mode.
61
- *
62
- * const { connection, store } = nodePostgres(pool);
63
- * deriveDashboards({ ..., connections: { main: connection }, database: store });
64
- */
65
- export function nodePostgres(
66
- pool: PgPool,
67
- options: { id?: string } = {},
68
- ): { connection: IntrospectingConnection; store: ReturnType<typeof postgresStore> } {
69
- return {
70
- connection: postgresConnection({
71
- ...(options.id === undefined ? {} : { id: options.id }),
72
- run: arrays(pool),
73
- sendsBegin: true,
74
- transaction: (fn, begin) => inTransaction(pool, begin, (client) => fn(arrays(client))),
75
- }),
76
- store: postgresStore({
77
- run: objects(pool),
78
- transaction: (fn) => inTransaction(pool, "BEGIN", (client) => fn(objects(client))),
79
- }),
80
- };
81
- }
package/src/owner.ts DELETED
@@ -1,36 +0,0 @@
1
- import {
2
- type DashOptions,
3
- type Principal,
4
- principalTenant,
5
- type Resource,
6
- type Row,
7
- } from "@derive-to/dashboards-core";
8
- import { parseDashboardId } from "./dashboard-id";
9
- import { adapterFor } from "./dashboards";
10
- import { requestDashboardRow } from "./request-rows";
11
-
12
- /** Who made a stored dashboard, as `can` receives it. */
13
- const ownerOf = (row: Row): { id: string; kind: "user" | "agent" } => ({
14
- id: String(row["owner_id"]),
15
- kind: row["owner_kind"] === "agent" ? "agent" : "user",
16
- });
17
-
18
- /**
19
- * A dashboard as `can` sees it: its id, and who made it when it is stored, so a host's rule
20
- * such as "people edit what they made" needs no table of its own. A built-in has no owner,
21
- * customized or not.
22
- */
23
- export async function dashboardResource(
24
- options: DashOptions,
25
- request: Request,
26
- principal: Principal,
27
- id: string,
28
- ): Promise<Resource> {
29
- const adapter = adapterFor(options, request);
30
- if (adapter === undefined || id === "") return { kind: "dashboard", id };
31
- const tenant = principalTenant(principal);
32
- const row = await requestDashboardRow(request, adapter, tenant, parseDashboardId(id));
33
- // A built-in's stored copy belongs to nobody: it was made by whoever first pressed Edit.
34
- if (row === null || row["default_of"] !== null) return { kind: "dashboard", id };
35
- return { kind: "dashboard", id, owner: ownerOf(row) };
36
- }
@@ -1,143 +0,0 @@
1
- import type { IntrospectingConnection, ReadSession, RunOptions } from "@derive-to/dashboards-core";
2
- import { postgres } from "@derive-to/dashboards-core/engine";
3
- import { bounded, pastDeadline } from "./bounded";
4
- import { HttpError } from "./http";
5
- import { describePostgres, introspectPostgres } from "./introspect";
6
-
7
- /** Runs one statement with its parameters and returns its rows as arrays, in select order. */
8
- export type RunSql = (
9
- text: string,
10
- params: readonly unknown[],
11
- ) => Promise<readonly (readonly unknown[])[]>;
12
-
13
- export type PostgresConnectionOptions = {
14
- /** Defaults to "main". */
15
- id?: string;
16
- /**
17
- * Runs a statement on any connection. Without `transaction`, a statement past the request's
18
- * deadline is answered with QUERY_TIMEOUT on time, but keeps running in the database until
19
- * it ends: only `transaction` sets a statement timeout that stops it there.
20
- */
21
- run: RunSql;
22
- /**
23
- * Runs `fn` inside one transaction on one connection. With it, every statement of a request
24
- * reads one snapshot; without it, each statement reads its own. `begin` starts that
25
- * transaction in one round trip: BEGIN with a read-only REPEATABLE READ snapshot, then the
26
- * request's statement timeout, two statements without parameters.
27
- */
28
- transaction?: <T>(fn: (run: RunSql) => Promise<T>, begin: string) => Promise<T>;
29
- /**
30
- * True when `transaction` sends the `begin` it is given in place of its own BEGIN
31
- * (node-postgres: `await client.query(begin)`). Otherwise it begins its own way (PGlite's
32
- * `db.transaction`) and the snapshot and the timeout are set after, one round trip each.
33
- */
34
- sendsBegin?: boolean;
35
- };
36
-
37
- const SNAPSHOT = "ISOLATION LEVEL REPEATABLE READ, READ ONLY";
38
-
39
- /** The statements that make a transaction a request's: its snapshot, then its timeout. */
40
- function settings(deadline: number) {
41
- const timeout = `SET LOCAL statement_timeout = ${Math.max(1, Math.ceil(deadline - Date.now()))}`;
42
- return {
43
- begin: `BEGIN ${SNAPSHOT}; ${timeout}`,
44
- snapshot: `SET TRANSACTION ${SNAPSHOT}`,
45
- timeout,
46
- };
47
- }
48
-
49
- /** Postgres cancelled the statement: its statement_timeout passed. */
50
- const QUERY_CANCELED = "57014";
51
-
52
- function timedOut(error: unknown): boolean {
53
- return (
54
- typeof error === "object" && error !== null && "code" in error && error.code === QUERY_CANCELED
55
- );
56
- }
57
-
58
- /**
59
- * Postgres could not read a given value as its column's type: invalid text for a number or a
60
- * uuid (22P02), or for a time (22007). The engine's own arithmetic raises neither.
61
- */
62
- const BAD_VALUE = new Set(["22P02", "22007"]);
63
-
64
- const badValue = (error: unknown): boolean =>
65
- typeof error === "object" &&
66
- error !== null &&
67
- "code" in error &&
68
- typeof error.code === "string" &&
69
- BAD_VALUE.has(error.code);
70
-
71
- /** The engine reads columns by position; rows as objects mean `rowMode: "array"` was left out. */
72
- function arrayRows<R>(rows: readonly R[]): readonly R[] {
73
- if (rows.length > 0 && !Array.isArray(rows[0]))
74
- throw new Error(
75
- 'postgresConnection\'s run must return rows as arrays, in select order (node-postgres: rowMode: "array").',
76
- );
77
- return rows;
78
- }
79
-
80
- /**
81
- * Each statement checks the request is still wanted and inside its deadline before it runs,
82
- * and is answered no later than the deadline, whether or not the database stops it.
83
- */
84
- function sessionOf(run: RunSql, options: RunOptions, concurrent: boolean): ReadSession {
85
- return {
86
- ...(concurrent ? { concurrent: true } : {}),
87
- run: async (sql) => {
88
- options.signal.throwIfAborted();
89
- if (Date.now() >= options.deadline) throw pastDeadline();
90
- try {
91
- return { rows: arrayRows(await bounded(run(sql.text, sql.params), options)) };
92
- } catch (error) {
93
- if (timedOut(error)) throw pastDeadline();
94
- // Fails closed with a reason, never as a server error: most often the viewer's tenant
95
- // value does not fit the tenant column's type (an id "acme" on an integer column).
96
- // Postgres's own message can echo stored values, so it goes to the host only.
97
- if (badValue(error))
98
- throw new HttpError(
99
- 400,
100
- "QUERY_INVALID",
101
- "A value does not fit its column's type in the database. Check the viewer's tenant values against the tenant columns, and the query's filter values.",
102
- { cause: error },
103
- );
104
- throw error;
105
- }
106
- },
107
- };
108
- }
109
-
110
- /**
111
- * A Postgres connection for the engine, from two small functions the host writes for its
112
- * driver: one that runs a statement (rows as arrays, in select order), and one that runs a
113
- * function inside a transaction on one client, sending `begin` as its BEGIN (`sendsBegin`).
114
- * With node-postgres, `nodePostgres(pool)` writes both, and the store's, the safe way.
115
- */
116
- export function postgresConnection(options: PostgresConnectionOptions): IntrospectingConnection {
117
- return {
118
- id: options.id ?? "main",
119
- dialect: postgres,
120
- introspect: () => introspectPostgres(options.run),
121
- describe: (query, columns) => describePostgres(options.run, query, columns),
122
-
123
- async session(runOptions, fn) {
124
- const { transaction } = options;
125
- if (transaction === undefined) {
126
- // No transaction: every statement is its own, so a tile's independent ones go out at once.
127
- return {
128
- value: await fn(sessionOf(options.run, runOptions, true)),
129
- consistency: "statement",
130
- };
131
- }
132
- const { begin, snapshot, timeout } = settings(runOptions.deadline);
133
- const value = await transaction(async (run) => {
134
- if (options.sendsBegin !== true) {
135
- await run(snapshot, []);
136
- await run(timeout, []);
137
- }
138
- return fn(sessionOf(run, runOptions, false));
139
- }, begin);
140
- return { value, consistency: "snapshot" };
141
- },
142
- };
143
- }
@@ -1,82 +0,0 @@
1
- import type { DashAdapter, Row } from "@derive-to/dashboards-core";
2
- import { type SqlRunner, sqlAdapter } from "./adapter/sql-adapter";
3
- import type { Statement } from "./adapter/statement";
4
-
5
- /** Runs one statement with its parameters and returns its rows as objects keyed by column. */
6
- export type RunRows = (text: string, params: readonly unknown[]) => Promise<readonly Row[]>;
7
-
8
- export type PostgresStoreOptions = {
9
- /** Runs a statement on any connection. */
10
- run: RunRows;
11
- /**
12
- * Runs `fn` inside one transaction on one connection, committing when it resolves and
13
- * rolling back when it throws. Every write of the store is one transaction.
14
- */
15
- transaction: <T>(fn: (run: RunRows) => Promise<T>) => Promise<T>;
16
- };
17
-
18
- /** A statement's text with Postgres's numbered placeholders. */
19
- const textOf = (s: Statement) => s.strings.reduce((all, part, i) => `${all}$${i}${part}`);
20
-
21
- /** The store reads rows by column name; rows as arrays mean the driver was set up for queries. */
22
- function objectRows(rows: readonly Row[]): Row[] {
23
- if (rows.length > 0 && Array.isArray(rows[0]))
24
- throw new Error(
25
- 'postgresStore\'s run must return rows as objects by column name, not arrays: give it a run without rowMode: "array".',
26
- );
27
- return [...rows];
28
- }
29
-
30
- function runner(options: PostgresStoreOptions, run: RunRows, depth: number): SqlRunner {
31
- const self: SqlRunner = {
32
- dialect: "postgres",
33
- run: async (statement) => objectRows(await run(textOf(statement), statement.values)),
34
- async execute(ddl) {
35
- await run(ddl, []);
36
- },
37
- // Outside a transaction, a new one; inside one, a savepoint, so a step can fail alone.
38
- transaction: async (fn) => {
39
- if (depth === 0) return options.transaction((tx) => fn(runner(options, tx, 1)));
40
- const savepoint = `dd_step_${depth}`;
41
- await run(`SAVEPOINT ${savepoint}`, []);
42
- try {
43
- const value = await fn(runner(options, run, depth + 1));
44
- await run(`RELEASE SAVEPOINT ${savepoint}`, []);
45
- return value;
46
- } catch (error) {
47
- await run(`ROLLBACK TO SAVEPOINT ${savepoint}`, []);
48
- throw error;
49
- }
50
- },
51
- };
52
- return self;
53
- }
54
-
55
- /**
56
- * Where dashboards are stored, in the host's own Postgres database, through whatever driver it
57
- * already uses: give it a function that runs a statement and returns rows as objects, and one
58
- * that runs a transaction. With node-postgres:
59
- *
60
- * postgresStore({
61
- * run: async (text, params) => (await pool.query(text, [...params])).rows,
62
- * transaction: async (fn) => {
63
- * const client = await pool.connect();
64
- * try {
65
- * await client.query("BEGIN");
66
- * const value = await fn(async (text, params) => (await client.query(text, [...params])).rows);
67
- * await client.query("COMMIT");
68
- * return value;
69
- * } catch (error) {
70
- * await client.query("ROLLBACK");
71
- * throw error;
72
- * } finally {
73
- * client.release();
74
- * }
75
- * },
76
- * })
77
- *
78
- * Its `dd_` tables come from `generate` in your own schema, or from `createTables`.
79
- */
80
- export function postgresStore(options: PostgresStoreOptions): DashAdapter {
81
- return sqlAdapter("postgres", runner(options, options.run, 0));
82
- }
package/src/principal.ts DELETED
@@ -1,39 +0,0 @@
1
- import type { DashOptions, Principal, Viewer } from "@derive-to/dashboards-core";
2
- import { HttpError } from "./http";
3
-
4
- /**
5
- * The signed-in viewer, its tenant narrowed to the model's keys: what the store and the cache
6
- * scope by is exactly what queries are scoped by, and `{}` in an app of one tenant.
7
- */
8
- export async function principalOf(
9
- options: DashOptions,
10
- request: Request,
11
- given?: Viewer,
12
- ): Promise<Principal | null> {
13
- const viewer = given ?? (await options.viewer(request));
14
- if (viewer === null) return null;
15
- const values = viewer.tenant ?? {};
16
- const tenant = Object.fromEntries(
17
- (options.model.tenant?.keys ?? []).flatMap((k) => {
18
- const value = values[k] ?? "";
19
- return value === "" ? [] : [[k, value] as const];
20
- }),
21
- );
22
- return { channel: "user", viewer: { ...viewer, tenant } };
23
- }
24
-
25
- /** With tenant keys, a viewer without a value for each reads and writes nothing, stored or not. */
26
- export function checkTenant(
27
- options: DashOptions,
28
- principal: Principal & { channel: "user" },
29
- ): void {
30
- const missing = (options.model.tenant?.keys ?? []).find(
31
- (k) => (principal.viewer.tenant?.[k] ?? "") === "",
32
- );
33
- if (missing !== undefined)
34
- throw new HttpError(
35
- 403,
36
- "TENANT_MISSING",
37
- `The viewer has no value for the tenant key "${missing}": viewer() must return it in the viewer's tenant.`,
38
- );
39
- }
package/src/reading.ts DELETED
@@ -1,56 +0,0 @@
1
- import type { CustomSource, DashOptions, QueryConnection } from "@derive-to/dashboards-core";
2
- import { customReader, type Reader, sqlReader } from "@derive-to/dashboards-core/engine";
3
- import { boundedSource, isCustomSource } from "./custom-source";
4
-
5
- /** Whether a value is a connection the engine can read through. */
6
- function isConnection(handle: unknown): handle is QueryConnection {
7
- return (
8
- typeof handle === "object" && handle !== null && "session" in handle && "dialect" in handle
9
- );
10
- }
11
-
12
- /** Whether a value is anything `connections` may hold: a database or a host's data layer. */
13
- export const isSource = (handle: unknown): handle is QueryConnection | CustomSource =>
14
- isConnection(handle) || isCustomSource(handle);
15
-
16
- /** What one read needs from its request: the options, the request, the source and the cap. */
17
- export type ReadAt = { options: DashOptions; request: Request; source: string; maxRows: number };
18
-
19
- /** The connection a source reads from; per request where the host gives a function. */
20
- function connectionOf(at: ReadAt): QueryConnection | CustomSource {
21
- const connection = at.options.model.sources[at.source]?.in ?? "";
22
- const entry = at.options.connections[connection];
23
- const handle: unknown = typeof entry === "function" ? entry(at.request) : entry;
24
- if (!isSource(handle))
25
- throw new Error(
26
- `\`connections.${connection}\` gave no connection for this request. It must return postgresConnection({ run, transaction }) or customSource({ answer }).`,
27
- );
28
- return handle;
29
- }
30
-
31
- export type Reading<T> = {
32
- value: T;
33
- consistency: "snapshot" | "statement";
34
- /** Whether the host's own data layer answered, not the library's SQL. */
35
- custom: boolean;
36
- };
37
-
38
- /**
39
- * Runs `fn` with a reader for the source's connection, under the request's deadline and abort:
40
- * in one read-only session of a database, or through the host's custom source, each of its
41
- * calls bounded by the same deadline.
42
- */
43
- export async function withReader<T>(
44
- at: ReadAt,
45
- fn: (reader: Reader) => Promise<T>,
46
- ): Promise<Reading<T>> {
47
- const source = connectionOf(at);
48
- const deadline = Date.now() + (at.options.query?.deadlineMs ?? 15_000);
49
- const run = { signal: at.request.signal, deadline, maxRows: at.maxRows };
50
- if (isCustomSource(source)) {
51
- const value = await fn(customReader(boundedSource(source), run));
52
- return { value, consistency: "statement", custom: true };
53
- }
54
- const { value, consistency } = await source.session(run, (s) => fn(sqlReader(s, source.dialect)));
55
- return { value, consistency, custom: false };
56
- }
@@ -1,23 +0,0 @@
1
- import { canonical, type DashAdapter, type Row, type Tenant } from "@derive-to/dashboards-core";
2
- import { dashboardRow } from "./store/rows";
3
-
4
- /**
5
- * The dashboard rows one request's checks read (who made it, for `can`; which stored row an id
6
- * names), read once per request. A request's writes read their rows again in their own
7
- * transaction, so nothing here decides a write.
8
- */
9
- const read = new WeakMap<Request, Map<string, Promise<Row | null>>>();
10
-
11
- export function requestDashboardRow(
12
- request: Request,
13
- adapter: DashAdapter,
14
- tenant: Tenant,
15
- by: { id: string } | { key: string },
16
- ): Promise<Row | null> {
17
- const rows = read.get(request) ?? new Map<string, Promise<Row | null>>();
18
- read.set(request, rows);
19
- const key = canonical({ tenant, by });
20
- const found = rows.get(key) ?? dashboardRow(adapter, tenant, by);
21
- rows.set(key, found);
22
- return found;
23
- }
package/src/request.ts DELETED
@@ -1,22 +0,0 @@
1
- import type { Calendar, DashOptions, Doc, Principal, Viewer } from "@derive-to/dashboards-core";
2
- import { HttpError } from "./http";
3
-
4
- /** The signed-in viewer a request runs as; anything else is a 401. */
5
- export function userOf(principal: Principal | null): Principal & { viewer: Viewer } {
6
- if (principal?.channel !== "user") throw new HttpError(401, "UNAUTHORIZED", "Sign in first.");
7
- return principal;
8
- }
9
-
10
- /** The request's one `now`: the host's clock, which tests and samples pin. */
11
- export function nowOf(options: DashOptions): Date {
12
- return options.now?.() ?? new Date();
13
- }
14
-
15
- /** The request's calendar: the dashboard's zone, then the host's, then UTC. */
16
- export function calendarOf(options: DashOptions, doc?: Doc): Calendar {
17
- return {
18
- timezone: doc?.scope.timezone ?? options.time?.timezone ?? "UTC",
19
- weekStart: options.time?.weekStart ?? 1,
20
- fiscalYearStartMonth: options.time?.fiscalYearStartMonth ?? 1,
21
- };
22
- }
package/src/storage.ts DELETED
@@ -1,63 +0,0 @@
1
- import type { SecondaryStorage } from "@derive-to/dashboards-core";
2
-
3
- const MEMORY_ENTRIES = 1000;
4
-
5
- /** The process's own storage when the host gives none: a bounded map, oldest entry out first. */
6
- export function memoryStorage(limit = MEMORY_ENTRIES): SecondaryStorage {
7
- return memoryMap<string>(limit);
8
- }
9
-
10
- /** Values kept in this process, the oldest dropped past `limit`, each until its ttl (seconds). */
11
- function memoryMap<T>(limit: number) {
12
- const entries = new Map<string, { value: T; expires: number }>();
13
- return {
14
- get(key: string): T | null {
15
- const entry = entries.get(key);
16
- if (entry === undefined || entry.expires <= Date.now()) {
17
- entries.delete(key);
18
- return null;
19
- }
20
- return entry.value;
21
- },
22
- set(key: string, value: T, ttl?: number): void {
23
- entries.delete(key);
24
- entries.set(key, { value, expires: ttl === undefined ? Infinity : Date.now() + ttl * 1000 });
25
- const oldest = entries.keys().next();
26
- if (entries.size > limit && oldest.done !== true) entries.delete(oldest.value);
27
- },
28
- delete(key: string): void {
29
- entries.delete(key);
30
- },
31
- };
32
- }
33
-
34
- /** Where answers are kept: as JSON in the host's storage, or as they are in this process's memory. */
35
- export type Entries<T> = {
36
- get(key: string): Promise<T | null>;
37
- set(key: string, entry: T, ttl: number): Promise<void>;
38
- };
39
-
40
- export function entriesIn<T>(storage: SecondaryStorage | undefined): Entries<T> {
41
- if (storage === undefined) {
42
- // In memory there is nothing to parse: an answer read back is the object stored.
43
- const map = memoryMap<T>(MEMORY_ENTRIES);
44
- return {
45
- get: (key) => Promise.resolve(map.get(key)),
46
- set: (key, entry, ttl) => {
47
- map.set(key, entry, ttl);
48
- return Promise.resolve();
49
- },
50
- };
51
- }
52
- return {
53
- async get(key) {
54
- const stored = await storage.get(key);
55
- // The storage holds only what this class wrote.
56
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion
57
- return stored === null ? null : (JSON.parse(stored) as T);
58
- },
59
- set: async (key, entry, ttl) => {
60
- await storage.set(key, JSON.stringify(entry), ttl);
61
- },
62
- };
63
- }