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/authorize.ts DELETED
@@ -1,73 +0,0 @@
1
- import {
2
- type DashOptions,
3
- type Principal,
4
- parseMemberId,
5
- queryClosure,
6
- type Viewer,
7
- type WireQuery,
8
- } from "@derive-to/dashboards-core";
9
- import { HttpError } from "./http";
10
-
11
- /** Whether the model marks a closure member (`source.name`) sensitive. */
12
- function isSensitive(options: DashOptions, id: string): boolean {
13
- const ref = parseMemberId(id);
14
- if (ref === undefined) return false;
15
- const source = options.model.sources[ref.source];
16
- return (source?.dimensions[ref.name] ?? source?.measures[ref.name])?.sensitive === true;
17
- }
18
-
19
- /** A member the model marks sensitive is refused unless the host's `sensitive` says yes. */
20
- function sensitiveAllowed(options: DashOptions, viewer: Viewer | undefined, id: string): boolean {
21
- if (!isSensitive(options, id)) return true;
22
- return viewer !== undefined && options.access.sensitive?.(viewer, id) === true;
23
- }
24
-
25
- /**
26
- * The closure of a query, refused with every problem when it is not valid. The message is the
27
- * first problem itself, so a person or an agent reads the fix without opening the issues.
28
- */
29
- function closureOf(options: DashOptions, query: WireQuery) {
30
- const closure = queryClosure(options.model, query);
31
- const [first, ...rest] = closure.issues;
32
- if (first !== undefined) {
33
- const more = rest.length === 0 ? "" : ` (and ${rest.length} more)`;
34
- throw new HttpError(400, "QUERY_INVALID", `${first.message}${more}`, {
35
- issues: closure.issues,
36
- });
37
- }
38
- return closure;
39
- }
40
-
41
- /**
42
- * Every form of query, by reference or free: no sensitive member unless the host allows it for
43
- * this viewer. A principal with no viewer (a public link) never reads one.
44
- */
45
- export function checkSensitive(options: DashOptions, principal: Principal, query: WireQuery): void {
46
- const viewer = principal.channel === "user" ? principal.viewer : undefined;
47
- const refused = closureOf(options, query).members.find(
48
- (id) => !sensitiveAllowed(options, viewer, id),
49
- );
50
- if (refused !== undefined) throw new HttpError(403, "FORBIDDEN", `"${refused}" is sensitive.`);
51
- }
52
-
53
- /**
54
- * A free query (the widget builder's preview, an agent's question) is a different grant from viewing a dashboard: the
55
- * viewer needs `view` on every source and every member it reads.
56
- */
57
- export async function authorizeFree(
58
- options: DashOptions,
59
- viewer: Viewer,
60
- query: WireQuery,
61
- ): Promise<void> {
62
- const closure = closureOf(options, query);
63
- const checks = [
64
- ...closure.sources.map((id) => ({ kind: "source" as const, id })),
65
- ...closure.members.map((id) => ({ kind: "member" as const, id })),
66
- ];
67
- const answers = await Promise.all(
68
- checks.map((r) => Promise.resolve(options.access.can(viewer, "view", r))),
69
- );
70
- const refused = checks.find((_r, i) => answers[i] !== true);
71
- if (refused !== undefined)
72
- throw new HttpError(403, "FORBIDDEN", `You cannot read the ${refused.kind} "${refused.id}".`);
73
- }
package/src/body.ts DELETED
@@ -1,169 +0,0 @@
1
- import type { Command } from "@derive-to/dashboards-core";
2
- import {
3
- commandSchema,
4
- type JsonSchema,
5
- jsonSchema,
6
- picksSchema,
7
- wireQuerySchema,
8
- } from "@derive-to/dashboards-core/schema";
9
- import { z } from "zod";
10
- import { HttpError } from "./http";
11
-
12
- /** The request bodies every endpoint checks before anything reads them. Unknown keys are refused. */
13
-
14
- const id = z.string().min(1).max(200);
15
- const picks = picksSchema;
16
-
17
- /** One edit command, typed as the contract's `Command`, which the schema satisfies. */
18
- const commands: z.ZodType<Command> = commandSchema;
19
-
20
- /** A page of rows: after which row it starts (the `next` of the page before) and how many. */
21
- const page = {
22
- after: z.string().min(1).max(4000).exactOptional(),
23
- limit: z.int().min(1).max(1000).exactOptional(),
24
- };
25
-
26
- /** A tile by reference: the dashboard, the widget, which of its queries, and the viewer's picks. */
27
- const tileRef = {
28
- dashboardId: id,
29
- widgetId: id,
30
- query: z.string().max(100).exactOptional(),
31
- picks: picks.exactOptional(),
32
- /** The version the client is showing; a different current version is a 409. */
33
- version: z.int().min(0).exactOptional(),
34
- /** Run against the viewer's own open draft instead: needs `edit`. */
35
- draft: z.literal(true).exactOptional(),
36
- /** Run against what publishing the viewer's draft would make now: needs `edit`. */
37
- merged: z.literal(true).exactOptional(),
38
- /** Run against an earlier published version, to preview it: needs `edit`. */
39
- at: z.int().min(1).exactOptional(),
40
- };
41
-
42
- export const bodies = {
43
- dashboard: z.strictObject({ dashboardId: id }),
44
- tile: z.strictObject(tileRef),
45
- tiles: z.strictObject({
46
- dashboardId: id,
47
- version: z.int().min(0).exactOptional(),
48
- tiles: z
49
- .array(z.strictObject({ widgetId: id, query: z.string().max(100).exactOptional() }))
50
- .min(1)
51
- .max(50),
52
- picks: picks.exactOptional(),
53
- draft: z.literal(true).exactOptional(),
54
- merged: z.literal(true).exactOptional(),
55
- at: z.int().min(1).exactOptional(),
56
- }),
57
- records: z.strictObject({ ...tileRef, ...page }),
58
- controlValues: z.strictObject({
59
- dashboardId: id,
60
- controlId: id,
61
- search: z.string().max(200).exactOptional(),
62
- limit: page.limit,
63
- draft: z.literal(true).exactOptional(),
64
- }),
65
- memberValues: z.strictObject({
66
- member: id,
67
- search: z.string().max(200).exactOptional(),
68
- limit: page.limit,
69
- }),
70
- query: z.strictObject({ query: wireQuerySchema }),
71
- queryBatch: z.strictObject({ queries: z.array(wireQuerySchema).min(1).max(50) }),
72
- queryRecords: z.strictObject({ query: wireQuerySchema, ...page }),
73
- list: z.strictObject({}),
74
- newDashboard: z.strictObject({
75
- title: z.string().min(1).max(500),
76
- /** The client's id for this create, so a retry makes one dashboard. */
77
- requestId: z.string().min(1).max(200).exactOptional(),
78
- /** Start from a published version of another dashboard, as a copy. */
79
- from: z.strictObject({ dashboardId: id, version: z.int().min(1) }).exactOptional(),
80
- }),
81
- applyDraft: z.strictObject({
82
- dashboardId: id,
83
- expectedRevision: z.int().min(0),
84
- commands: z.array(commands).min(1).max(100).readonly(),
85
- }),
86
- publishDraft: z.strictObject({
87
- dashboardId: id,
88
- expectedRevision: z.int().min(0),
89
- requestId: id,
90
- /** The version the review was on top of: another one published since refuses it. */
91
- head: z.int().min(0),
92
- }),
93
- undo: z.strictObject({ dashboardId: id, expectedRevision: z.int().min(0) }),
94
- rebase: z.strictObject({
95
- dashboardId: id,
96
- expectedRevision: z.int().min(0),
97
- head: z.int().min(0),
98
- drop: z.array(id).max(100).readonly().exactOptional(),
99
- restore: z.array(id).max(100).readonly().exactOptional(),
100
- }),
101
- version: z.strictObject({ dashboardId: id, version: z.int().min(1) }),
102
- versions: z.strictObject({ dashboardId: id, before: z.int().min(1).exactOptional() }),
103
- restore: z.strictObject({
104
- dashboardId: id,
105
- version: z.number().int().min(1),
106
- requestId: z.string().min(1).max(200),
107
- }),
108
- discardDraft: z.strictObject({ dashboardId: id, expectedRevision: z.int().min(0) }),
109
- };
110
-
111
- /** Every endpoint that takes a body, by path, and the body it takes; a test holds it complete. */
112
- const BODIES_BY_PATH = {
113
- "/dashboards/get": bodies.dashboard,
114
- "/dashboards/tile": bodies.tile,
115
- "/dashboards/tiles": bodies.tiles,
116
- "/dashboards/records": bodies.records,
117
- "/dashboards/control-values": bodies.controlValues,
118
- "/dashboards/new": bodies.newDashboard,
119
- "/dashboards/draft/start": bodies.dashboard,
120
- "/dashboards/draft/apply": bodies.applyDraft,
121
- "/dashboards/draft/undo": bodies.undo,
122
- "/dashboards/draft/preview": bodies.dashboard,
123
- "/dashboards/draft/rebase": bodies.rebase,
124
- "/dashboards/draft/publish": bodies.publishDraft,
125
- "/dashboards/draft/discard": bodies.discardDraft,
126
- "/dashboards/versions": bodies.versions,
127
- "/dashboards/version": bodies.version,
128
- "/dashboards/restore": bodies.restore,
129
- "/query/run": bodies.query,
130
- "/query/validate": bodies.query,
131
- "/query/batch": bodies.queryBatch,
132
- "/query/records": bodies.queryRecords,
133
- "/meta/values": bodies.memberValues,
134
- } as const;
135
-
136
- /** Each endpoint's body as JSON Schema, from the same schemas the endpoints check with. */
137
- export function bodySchemas(): Record<string, JsonSchema> {
138
- return Object.fromEntries(
139
- Object.entries(BODIES_BY_PATH).map(([path, schema]): [string, JsonSchema] => [
140
- path,
141
- jsonSchema(schema),
142
- ]),
143
- );
144
- }
145
-
146
- /** Each problem with a body, as one line a person can act on: where it is, and what is wrong. */
147
- function described(error: z.ZodError): string {
148
- return error.issues
149
- .map((issue) => {
150
- const where = issue.path.map(String).join(".");
151
- const message = /[.!?]$/u.test(issue.message) ? issue.message : `${issue.message}.`;
152
- return where === "" ? message : `${where}: ${message}`;
153
- })
154
- .join(" ");
155
- }
156
-
157
- /**
158
- * Checks a body against its schema; a body it does not accept is a 400 that says where and why.
159
- * A free query's body is refused as `QUERY_INVALID`, any other as `BODY_INVALID`.
160
- */
161
- export function parseWith<T>(
162
- schema: z.ZodType<T>,
163
- input: unknown,
164
- code: "BODY_INVALID" | "QUERY_INVALID" = "BODY_INVALID",
165
- ): T {
166
- const parsed = schema.safeParse(input);
167
- if (!parsed.success) throw new HttpError(400, code, described(parsed.error));
168
- return parsed.data;
169
- }
package/src/bounded.ts DELETED
@@ -1,43 +0,0 @@
1
- import type { RunOptions } from "@derive-to/dashboards-core";
2
- import { HttpError } from "./http";
3
-
4
- export const pastDeadline = () =>
5
- new HttpError(504, "QUERY_TIMEOUT", "The query ran past its deadline.");
6
-
7
- /** Work's result, or QUERY_TIMEOUT at the deadline and the abort's reason on abort. */
8
- export async function bounded<T>(
9
- work: Promise<T>,
10
- options: Pick<RunOptions, "signal" | "deadline">,
11
- ): Promise<T> {
12
- let timer: ReturnType<typeof setTimeout> | undefined;
13
- let onAbort: (() => void) | undefined;
14
- const stop = new Promise<never>((_, reject) => {
15
- timer = setTimeout(
16
- () => {
17
- reject(pastDeadline());
18
- },
19
- Math.max(0, options.deadline - Date.now()),
20
- );
21
- onAbort = () => {
22
- const reason: unknown = options.signal.reason;
23
- reject(reason instanceof Error ? reason : new Error("The request was aborted."));
24
- };
25
- options.signal.addEventListener("abort", onAbort, { once: true });
26
- });
27
- try {
28
- return await Promise.race([work, stop]);
29
- } finally {
30
- clearTimeout(timer);
31
- if (onAbort !== undefined) options.signal.removeEventListener("abort", onAbort);
32
- }
33
- }
34
-
35
- /** Starts `work` only when the request is still wanted and inside its deadline, and bounds it. */
36
- export function boundedCall<T>(
37
- options: Pick<RunOptions, "signal" | "deadline">,
38
- work: () => Promise<T>,
39
- ): Promise<T> {
40
- options.signal.throwIfAborted();
41
- if (Date.now() >= options.deadline) throw pastDeadline();
42
- return bounded(work(), options);
43
- }
package/src/cache.ts DELETED
@@ -1,192 +0,0 @@
1
- import {
2
- bindPolicy,
3
- canonical,
4
- type DashOptions,
5
- type Model,
6
- namedPolicy,
7
- type Principal,
8
- policyBinding,
9
- principalTenant,
10
- queryClosure,
11
- type SecondaryStorage,
12
- type SourceName,
13
- viaJoins,
14
- type WireQuery,
15
- } from "@derive-to/dashboards-core";
16
- import { ENGINE_VERSION } from "@derive-to/dashboards-core/engine";
17
- import type { Answered } from "./execute";
18
- import { type Entries, entriesIn, memoryStorage } from "./storage";
19
-
20
- export async function sha256(text: string): Promise<string> {
21
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
22
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
23
- }
24
-
25
- /** The parents a source's rows are visible through, all the way up. */
26
- function viaParents(model: Model, source: SourceName, seen: Set<SourceName>): void {
27
- const def = model.sources[source];
28
- if (seen.has(source) || def === undefined) return;
29
- seen.add(source);
30
- for (const join of viaJoins(def)) {
31
- const to = def.joins?.[join]?.to;
32
- if (to !== undefined) viaParents(model, to, seen);
33
- }
34
- }
35
-
36
- /** Every source an answer can depend on: what the query reads, what its lock and required filters are on, and their via parents. */
37
- export function manifest(model: Model, query: WireQuery, on: readonly SourceName[]): SourceName[] {
38
- const seen = new Set<SourceName>();
39
- for (const source of [...queryClosure(model, query).sources, ...on])
40
- viaParents(model, source, seen);
41
- return [...seen].toSorted();
42
- }
43
-
44
- /**
45
- * The bound row policy of each source the answer reads (its manifest: the query's sources, the
46
- * lock's, and every parent they are visible through): two viewers share an entry when those
47
- * bind alike, whatever the policies of sources it does not read.
48
- */
49
- function boundPolicies(
50
- model: Model,
51
- principal: Principal,
52
- sources: readonly SourceName[],
53
- ): Record<string, unknown> {
54
- return Object.fromEntries(
55
- sources.flatMap((name): [string, unknown][] => {
56
- const def = model.sources[name];
57
- if (def === undefined) return [];
58
- const policy = policyBinding(def);
59
- if (typeof policy === "object" && "via" in policy) return [[name, "via"]];
60
- const rules = typeof policy === "string" ? namedPolicy(model, policy) : policy;
61
- return [[name, bindPolicy(rules, principal)]];
62
- }),
63
- );
64
- }
65
-
66
- type Entry = { at: number; value: Answered };
67
-
68
- /** What decides an answer, besides the rows: everything that goes into its cache key. */
69
- type CacheKey = {
70
- principal: Principal;
71
- query: WireQuery;
72
- lock: unknown;
73
- required: unknown;
74
- calendar: unknown;
75
- maxRows: number;
76
- /** `now` floored to the quantum; only a relative range reads it. */
77
- now: number;
78
- /** The sources whose epochs the entry depends on. */
79
- sources: readonly SourceName[];
80
- };
81
-
82
- const epochKey = (tenant: Record<string, string>, source: string) =>
83
- `dd:epoch:${canonical(tenant)}:${source}`;
84
-
85
- export type Cache = {
86
- answer(key: CacheKey, compute: () => Promise<Answered>): Promise<Answered>;
87
- /** Drops a tenant's cached answers that read any of `sources` (every source when absent). */
88
- invalidate(tenant: Record<string, string>, sources?: readonly SourceName[]): Promise<void>;
89
- };
90
-
91
- const marked = (value: Answered, cache: "hit" | "stale" | "miss"): Answered => ({
92
- ...value,
93
- receipt: { ...value.receipt, cache, answeredBy: cache === "miss" ? "base" : "cache" },
94
- });
95
-
96
- /**
97
- * Answers keyed by everything that decides them. Each source's epoch is in the key, so a write
98
- * invalidates by bumping the epochs of the sources it changed; old entries are never read again
99
- * and expire on their own.
100
- */
101
- class ResultCache implements Cache {
102
- readonly #options: DashOptions;
103
- readonly #ttl: number;
104
- readonly #stale: number;
105
- readonly #storage: SecondaryStorage;
106
- readonly #entries: Entries<Entry>;
107
- readonly #inFlight = new Map<string, Promise<Answered>>();
108
- readonly #modelHash: Promise<string>;
109
-
110
- constructor(options: DashOptions, cache: NonNullable<DashOptions["cache"]>) {
111
- this.#options = options;
112
- this.#ttl = cache.ttl ?? 60;
113
- this.#stale = cache.staleTtl ?? 0;
114
- this.#storage = options.secondaryStorage ?? memoryStorage();
115
- this.#entries = entriesIn<Entry>(options.secondaryStorage);
116
- this.#modelHash = sha256(canonical(options.model));
117
- }
118
-
119
- async #keyOf(k: CacheKey): Promise<string> {
120
- const tenant = principalTenant(k.principal);
121
- const epochs = await Promise.all(
122
- k.sources.map(async (s) => (await this.#storage.get(epochKey(tenant, s))) ?? "0"),
123
- );
124
- const relative = k.query.time !== undefined && "last" in k.query.time.range;
125
- const parts = {
126
- v: ENGINE_VERSION,
127
- model: await this.#modelHash,
128
- tenant,
129
- policy: boundPolicies(this.#options.model, k.principal, k.sources),
130
- query: k.query,
131
- lock: k.lock,
132
- required: k.required,
133
- calendar: k.calendar,
134
- maxRows: k.maxRows,
135
- ...(relative ? { now: k.now } : {}),
136
- epochs: Object.fromEntries(k.sources.map((s, i) => [s, epochs[i]])),
137
- };
138
- return `dd:result:${await sha256(canonical(parts))}`;
139
- }
140
-
141
- /** Computes once per key at a time, stores the answer, and hands every waiter the same one. */
142
- #refresh(key: string, compute: () => Promise<Answered>): Promise<Answered> {
143
- const running = this.#inFlight.get(key);
144
- if (running !== undefined) return running;
145
- const task = (async () => {
146
- try {
147
- const value = await compute();
148
- await this.#entries.set(key, { at: Date.now(), value }, this.#ttl + this.#stale);
149
- return value;
150
- } finally {
151
- this.#inFlight.delete(key);
152
- }
153
- })();
154
- this.#inFlight.set(key, task);
155
- return task;
156
- }
157
-
158
- /** A stale answer's refresh runs where the host runs background work, and never fails a request. */
159
- #background(task: Promise<unknown>): void {
160
- const quiet = task.catch(() => null);
161
- this.#options.advanced?.backgroundTasks?.handler(quiet);
162
- }
163
-
164
- async answer(k: CacheKey, compute: () => Promise<Answered>): Promise<Answered> {
165
- const key = await this.#keyOf(k);
166
- const entry = await this.#entries.get(key);
167
- if (entry !== null) {
168
- const age = (Date.now() - entry.at) / 1000;
169
- if (age < this.#ttl) return marked(entry.value, "hit");
170
- if (age < this.#ttl + this.#stale) {
171
- this.#background(this.#refresh(key, compute));
172
- return marked(entry.value, "stale");
173
- }
174
- }
175
- return marked(await this.#refresh(key, compute), "miss");
176
- }
177
-
178
- async invalidate(tenant: Record<string, string>, sources?: readonly SourceName[]): Promise<void> {
179
- const names = sources ?? Object.keys(this.#options.model.sources);
180
- await Promise.all(
181
- names.map(async (s) => {
182
- const current = Number((await this.#storage.get(epochKey(tenant, s))) ?? "0");
183
- await this.#storage.set(epochKey(tenant, s), String(current + 1));
184
- }),
185
- );
186
- }
187
- }
188
-
189
- /** The result cache, or undefined when the host did not ask for one. */
190
- export function createCache(options: DashOptions): Cache | undefined {
191
- return options.cache === undefined ? undefined : new ResultCache(options, options.cache);
192
- }
package/src/checks.ts DELETED
@@ -1,170 +0,0 @@
1
- import {
2
- type Command,
3
- type Control,
4
- type Doc,
5
- lockChanged,
6
- type Principal,
7
- parseMemberId,
8
- QueryReferenceError,
9
- type Resource,
10
- resolveDimension,
11
- toWire,
12
- type Viewer,
13
- type Widget,
14
- } from "@derive-to/dashboards-core";
15
- import { authorizeFree } from "./authorize";
16
- import { editorOf, storedId, storeFor } from "./editing";
17
- import type { Runtime } from "./execute";
18
- import { HttpError } from "./http";
19
- import { dashboardResource } from "./owner";
20
-
21
- /** The checks an edit passes: every query readable by the editor, a lock changed only with `manage`. */
22
-
23
- type User = Principal & { viewer: Viewer };
24
-
25
- /** A stored query as the engine reads it; one that names a missing formula part is refused. */
26
- function wireOf(query: Parameters<typeof toWire>[0]) {
27
- try {
28
- return toWire(query).wire;
29
- } catch (error) {
30
- if (error instanceof QueryReferenceError)
31
- throw new HttpError(400, "QUERY_REFERENCE", error.message);
32
- throw error;
33
- }
34
- }
35
-
36
- /**
37
- * Every query a batch adds or changes, each named query of a new widget included, must resolve against the model and be one the
38
- * editor may read: nobody builds a widget over data they cannot see. A lock needs `manage`.
39
- */
40
- export async function checkCommands(
41
- rt: Runtime,
42
- viewer: Viewer,
43
- dashboard: Resource,
44
- commands: readonly Command[],
45
- ) {
46
- const queries = commands.flatMap((c) =>
47
- c.type === "widget.setQuery"
48
- ? [c.query]
49
- : c.type === "widget.add"
50
- ? Object.values(c.widget.queries)
51
- : [],
52
- );
53
- // oxlint-disable-next-line no-await-in-loop -- one check per query, in order
54
- for (const query of queries) await authorizeFree(rt.options, viewer, wireOf(query));
55
- await checkFilters(
56
- rt,
57
- viewer,
58
- commands.flatMap((c) => (c.type === "control.add" ? [c.control] : [])),
59
- );
60
- if (commands.some((c) => c.type === "lock.set" || c.type === "lock.remove")) {
61
- const can = await rt.options.access.can(viewer, "manage", dashboard);
62
- if (!can) throw new HttpError(403, "FORBIDDEN", "Changing a dashboard's lock needs manage.");
63
- }
64
- }
65
-
66
- /**
67
- * Every filter a batch adds narrows a field the model has and the editor may read: a filter on
68
- * a field that does not exist would never apply, and one on a hidden field would show its values.
69
- */
70
- async function checkFilters(rt: Runtime, viewer: Viewer, controls: readonly Control[]) {
71
- const members = controls.flatMap((c) => (c.kind === "filter" ? [c.member] : []));
72
- for (const member of members) {
73
- const ref = parseMemberId(member);
74
- const known =
75
- ref !== undefined && resolveDimension(rt.options.model, ref.source, member) !== undefined;
76
- if (!known)
77
- throw new HttpError(
78
- 400,
79
- "QUERY_REFERENCE",
80
- `A filter names "${member}", which is not a field of the model.`,
81
- );
82
- // oxlint-disable-next-line no-await-in-loop -- one check per filter, in order
83
- const can = await rt.options.access.can(viewer, "view", { kind: "member", id: member });
84
- if (!can) throw new HttpError(403, "FORBIDDEN", `A filter on "${member}" needs view on it.`);
85
- }
86
- }
87
-
88
- /** Widgets brought back whole (a put-back on review): every query in them must be one the editor may read. */
89
- export async function checkWidgets(
90
- rt: Runtime,
91
- viewer: Viewer,
92
- dashboard: Resource,
93
- widgets: readonly Widget[],
94
- ) {
95
- const commands = widgets.map(
96
- (widget, i): Command => ({
97
- commandId: String(i),
98
- type: "widget.add",
99
- tab: "",
100
- id: String(i),
101
- widget,
102
- at: { x: 0, y: 0, w: 1, h: 1 },
103
- }),
104
- );
105
- await checkCommands(rt, viewer, dashboard, commands);
106
- }
107
-
108
- /**
109
- * A whole document an editor brings back, as a restore does: every query in it must be one they
110
- * may read, and if its lock differs from the current one, they need `manage`, exactly as if
111
- * they had made those changes by hand.
112
- */
113
- export async function checkDocument(
114
- rt: Runtime,
115
- viewer: Viewer,
116
- dashboard: Resource,
117
- docs: { restored: Doc; current: Doc | undefined },
118
- ) {
119
- const { restored: doc, current } = docs;
120
- const queries = Object.values(doc.widgets).flatMap((w) => Object.values(w.queries));
121
- // oxlint-disable-next-line no-await-in-loop -- one check per query, in order
122
- for (const query of queries) await authorizeFree(rt.options, viewer, wireOf(query));
123
- await checkFilters(rt, viewer, doc.controls);
124
- if (current !== undefined && lockChanged(current, doc)) {
125
- const can = await rt.options.access.can(viewer, "manage", dashboard);
126
- if (!can)
127
- throw new HttpError(
128
- 403,
129
- "FORBIDDEN",
130
- "That version has a different lock; restoring it needs manage.",
131
- );
132
- }
133
- }
134
-
135
- /**
136
- * An earlier published version of a dashboard: the one rule for reading one, whether to
137
- * preview it, run its tiles or copy it. It needs `edit`, and `manage` when its lock differs
138
- * from the current one, so it never shows more than the person could see by restoring it.
139
- */
140
- export async function versionDoc(
141
- rt: Runtime,
142
- request: Request,
143
- user: User,
144
- ref: { dashboardId: string; version: number },
145
- ) {
146
- const resource = await dashboardResource(rt.options, request, user, ref.dashboardId);
147
- if (!(await rt.options.access.can(user.viewer, "edit", resource)))
148
- throw new HttpError(403, "FORBIDDEN", "Reading an earlier version needs edit.");
149
- const id = await storedId(rt, request, user, ref.dashboardId);
150
- const store = storeFor(rt, request);
151
- const { tenant } = editorOf(user);
152
- const old = id === null ? null : await store.getVersion({ tenant, id, version: ref.version });
153
- if (id === null)
154
- throw new HttpError(404, "NOT_FOUND", `"${ref.dashboardId}" has no published versions.`);
155
- if (old === null)
156
- throw new HttpError(
157
- 404,
158
- "NOT_FOUND",
159
- `There is no version ${String(ref.version)} of "${ref.dashboardId}".`,
160
- );
161
- const current = await store.get({ tenant, ref: { id } });
162
- const lockDiffers = current !== null && lockChanged(current.doc, old.doc);
163
- if (lockDiffers && !(await rt.options.access.can(user.viewer, "manage", resource)))
164
- throw new HttpError(
165
- 403,
166
- "FORBIDDEN",
167
- "That version has a different lock; seeing it needs manage.",
168
- );
169
- return old;
170
- }