@tetrascience-npm/ts-lib-viz 0.0.0-stage → 0.1.5

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 (278) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2171 -2
  3. package/dist/src/builder/PlotPanel.d.ts +42 -0
  4. package/dist/src/builder/PlotPanel.js +433 -0
  5. package/dist/src/builder/Popover.d.ts +37 -0
  6. package/dist/src/builder/Popover.js +32 -0
  7. package/dist/src/builder/Stepper.d.ts +21 -0
  8. package/dist/src/builder/Stepper.js +41 -0
  9. package/dist/src/builder/index.d.ts +10 -0
  10. package/dist/src/builder/index.js +10 -0
  11. package/dist/src/core/adapters.d.ts +86 -0
  12. package/dist/src/core/adapters.js +219 -0
  13. package/dist/src/core/aggregate.d.ts +74 -0
  14. package/dist/src/core/aggregate.js +102 -0
  15. package/dist/src/core/annotations.d.ts +34 -0
  16. package/dist/src/core/annotations.js +71 -0
  17. package/dist/src/core/band-order.d.ts +86 -0
  18. package/dist/src/core/band-order.js +132 -0
  19. package/dist/src/core/binning.d.ts +123 -0
  20. package/dist/src/core/binning.js +193 -0
  21. package/dist/src/core/bounds.d.ts +40 -0
  22. package/dist/src/core/bounds.js +107 -0
  23. package/dist/src/core/brush.d.ts +73 -0
  24. package/dist/src/core/brush.js +102 -0
  25. package/dist/src/core/build.d.ts +322 -0
  26. package/dist/src/core/build.js +496 -0
  27. package/dist/src/core/camera.d.ts +152 -0
  28. package/dist/src/core/camera.js +303 -0
  29. package/dist/src/core/capabilities.d.ts +24 -0
  30. package/dist/src/core/capabilities.js +307 -0
  31. package/dist/src/core/chord.d.ts +49 -0
  32. package/dist/src/core/chord.js +57 -0
  33. package/dist/src/core/circular.d.ts +83 -0
  34. package/dist/src/core/circular.js +63 -0
  35. package/dist/src/core/cluster.d.ts +136 -0
  36. package/dist/src/core/cluster.js +607 -0
  37. package/dist/src/core/critique.d.ts +92 -0
  38. package/dist/src/core/critique.js +905 -0
  39. package/dist/src/core/density.d.ts +38 -0
  40. package/dist/src/core/density.js +82 -0
  41. package/dist/src/core/figure-set.d.ts +34 -0
  42. package/dist/src/core/figure-set.js +55 -0
  43. package/dist/src/core/finding-codes.d.ts +10 -0
  44. package/dist/src/core/finding-codes.js +1 -0
  45. package/dist/src/core/fit-types.d.ts +46 -0
  46. package/dist/src/core/fit-types.js +7 -0
  47. package/dist/src/core/fitter.d.ts +62 -0
  48. package/dist/src/core/fitter.js +102 -0
  49. package/dist/src/core/frame-geometry.d.ts +407 -0
  50. package/dist/src/core/frame-geometry.js +612 -0
  51. package/dist/src/core/frame.d.ts +329 -0
  52. package/dist/src/core/frame.js +1432 -0
  53. package/dist/src/core/geom-table.d.ts +503 -0
  54. package/dist/src/core/geom-table.js +484 -0
  55. package/dist/src/core/geom-types.d.ts +182 -0
  56. package/dist/src/core/geom-types.js +17 -0
  57. package/dist/src/core/grammar.d.ts +359 -0
  58. package/dist/src/core/grammar.js +397 -0
  59. package/dist/src/core/heat-reductions.d.ts +36 -0
  60. package/dist/src/core/heat-reductions.js +133 -0
  61. package/dist/src/core/hexbin.d.ts +84 -0
  62. package/dist/src/core/hexbin.js +168 -0
  63. package/dist/src/core/hierarchy.d.ts +59 -0
  64. package/dist/src/core/hierarchy.js +248 -0
  65. package/dist/src/core/hit.d.ts +75 -0
  66. package/dist/src/core/hit.js +37 -0
  67. package/dist/src/core/index.d.ts +33 -0
  68. package/dist/src/core/index.js +18 -0
  69. package/dist/src/core/internal.d.ts +58 -0
  70. package/dist/src/core/internal.js +58 -0
  71. package/dist/src/core/labels.d.ts +37 -0
  72. package/dist/src/core/labels.js +54 -0
  73. package/dist/src/core/layers.d.ts +594 -0
  74. package/dist/src/core/layers.js +2892 -0
  75. package/dist/src/core/load.d.ts +17 -0
  76. package/dist/src/core/load.js +356 -0
  77. package/dist/src/core/marginal.d.ts +65 -0
  78. package/dist/src/core/marginal.js +116 -0
  79. package/dist/src/core/mesh.d.ts +69 -0
  80. package/dist/src/core/mesh.js +237 -0
  81. package/dist/src/core/omission.d.ts +41 -0
  82. package/dist/src/core/omission.js +62 -0
  83. package/dist/src/core/palette-sets.d.ts +623 -0
  84. package/dist/src/core/palette-sets.js +1058 -0
  85. package/dist/src/core/palette.d.ts +871 -0
  86. package/dist/src/core/palette.js +511 -0
  87. package/dist/src/core/plot-data.d.ts +71 -0
  88. package/dist/src/core/plot-data.js +82 -0
  89. package/dist/src/core/predicate.d.ts +50 -0
  90. package/dist/src/core/predicate.js +20 -0
  91. package/dist/src/core/profile.d.ts +111 -0
  92. package/dist/src/core/profile.js +221 -0
  93. package/dist/src/core/readout.d.ts +108 -0
  94. package/dist/src/core/readout.js +215 -0
  95. package/dist/src/core/region.d.ts +56 -0
  96. package/dist/src/core/region.js +101 -0
  97. package/dist/src/core/rings.d.ts +96 -0
  98. package/dist/src/core/rings.js +171 -0
  99. package/dist/src/core/rules.d.ts +45 -0
  100. package/dist/src/core/rules.js +69 -0
  101. package/dist/src/core/sankey.d.ts +49 -0
  102. package/dist/src/core/sankey.js +96 -0
  103. package/dist/src/core/select.d.ts +52 -0
  104. package/dist/src/core/select.js +216 -0
  105. package/dist/src/core/side-track.d.ts +98 -0
  106. package/dist/src/core/side-track.js +197 -0
  107. package/dist/src/core/sizing.d.ts +54 -0
  108. package/dist/src/core/sizing.js +37 -0
  109. package/dist/src/core/spec-edit.d.ts +68 -0
  110. package/dist/src/core/spec-edit.js +105 -0
  111. package/dist/src/core/spec.d.ts +1111 -0
  112. package/dist/src/core/spec.js +39 -0
  113. package/dist/src/core/stats.d.ts +161 -0
  114. package/dist/src/core/stats.js +318 -0
  115. package/dist/src/core/tick-format.d.ts +21 -0
  116. package/dist/src/core/tick-format.js +87 -0
  117. package/dist/src/core/tokens.d.ts +47 -0
  118. package/dist/src/core/tokens.js +138 -0
  119. package/dist/src/core/transform.d.ts +21 -0
  120. package/dist/src/core/transform.js +19 -0
  121. package/dist/src/core/voxels.d.ts +53 -0
  122. package/dist/src/core/voxels.js +129 -0
  123. package/dist/src/core/zoom.d.ts +76 -0
  124. package/dist/src/core/zoom.js +103 -0
  125. package/dist/src/graph/GraphSurface.d.ts +127 -0
  126. package/dist/src/graph/GraphSurface.js +423 -0
  127. package/dist/src/graph/data.d.ts +103 -0
  128. package/dist/src/graph/data.js +140 -0
  129. package/dist/src/graph/index.d.ts +7 -0
  130. package/dist/src/graph/index.js +7 -0
  131. package/dist/src/mcp/data.d.ts +28 -0
  132. package/dist/src/mcp/data.js +131 -0
  133. package/dist/src/mcp/index.d.ts +7 -0
  134. package/dist/src/mcp/index.js +7 -0
  135. package/dist/src/mcp/paths.d.ts +12 -0
  136. package/dist/src/mcp/paths.js +30 -0
  137. package/dist/src/mcp/render.d.ts +67 -0
  138. package/dist/src/mcp/render.js +189 -0
  139. package/dist/src/mcp/server.d.ts +7 -0
  140. package/dist/src/mcp/server.js +25 -0
  141. package/dist/src/mcp/tools.d.ts +82 -0
  142. package/dist/src/mcp/tools.js +412 -0
  143. package/dist/src/react/BrushLayer.d.ts +20 -0
  144. package/dist/src/react/BrushLayer.js +98 -0
  145. package/dist/src/react/ColorLegend.d.ts +45 -0
  146. package/dist/src/react/ColorLegend.js +64 -0
  147. package/dist/src/react/Figure.d.ts +19 -0
  148. package/dist/src/react/Figure.js +6 -0
  149. package/dist/src/react/Frame.d.ts +87 -0
  150. package/dist/src/react/Frame.js +192 -0
  151. package/dist/src/react/MarkLegend.d.ts +32 -0
  152. package/dist/src/react/MarkLegend.js +24 -0
  153. package/dist/src/react/SeriesLegend.d.ts +38 -0
  154. package/dist/src/react/SeriesLegend.js +27 -0
  155. package/dist/src/react/SizeLegend.d.ts +24 -0
  156. package/dist/src/react/SizeLegend.js +25 -0
  157. package/dist/src/react/Toolbar.d.ts +109 -0
  158. package/dist/src/react/Toolbar.js +483 -0
  159. package/dist/src/react/Tooltip.d.ts +37 -0
  160. package/dist/src/react/Tooltip.js +59 -0
  161. package/dist/src/react/Viz.d.ts +112 -0
  162. package/dist/src/react/Viz.js +1311 -0
  163. package/dist/src/react/export.d.ts +32 -0
  164. package/dist/src/react/export.js +181 -0
  165. package/dist/src/react/geoms/Area.d.ts +38 -0
  166. package/dist/src/react/geoms/Area.js +48 -0
  167. package/dist/src/react/geoms/Bars.d.ts +130 -0
  168. package/dist/src/react/geoms/Bars.js +164 -0
  169. package/dist/src/react/geoms/Box.d.ts +50 -0
  170. package/dist/src/react/geoms/Box.js +32 -0
  171. package/dist/src/react/geoms/Chord.d.ts +60 -0
  172. package/dist/src/react/geoms/Chord.js +78 -0
  173. package/dist/src/react/geoms/Contour.d.ts +44 -0
  174. package/dist/src/react/geoms/Contour.js +78 -0
  175. package/dist/src/react/geoms/DensityCurve.d.ts +30 -0
  176. package/dist/src/react/geoms/DensityCurve.js +38 -0
  177. package/dist/src/react/geoms/FitCurve.d.ts +26 -0
  178. package/dist/src/react/geoms/FitCurve.js +52 -0
  179. package/dist/src/react/geoms/Freqpoly.d.ts +30 -0
  180. package/dist/src/react/geoms/Freqpoly.js +45 -0
  181. package/dist/src/react/geoms/Gauge.d.ts +42 -0
  182. package/dist/src/react/geoms/Gauge.js +90 -0
  183. package/dist/src/react/geoms/Heatmap.d.ts +79 -0
  184. package/dist/src/react/geoms/Heatmap.js +51 -0
  185. package/dist/src/react/geoms/Hexbin.d.ts +74 -0
  186. package/dist/src/react/geoms/Hexbin.js +89 -0
  187. package/dist/src/react/geoms/Icicle.d.ts +38 -0
  188. package/dist/src/react/geoms/Icicle.js +9 -0
  189. package/dist/src/react/geoms/Ideogram.d.ts +58 -0
  190. package/dist/src/react/geoms/Ideogram.js +77 -0
  191. package/dist/src/react/geoms/Interval.d.ts +30 -0
  192. package/dist/src/react/geoms/Interval.js +39 -0
  193. package/dist/src/react/geoms/Line.d.ts +39 -0
  194. package/dist/src/react/geoms/Line.js +52 -0
  195. package/dist/src/react/geoms/Parallel.d.ts +38 -0
  196. package/dist/src/react/geoms/Parallel.js +131 -0
  197. package/dist/src/react/geoms/Pie.d.ts +62 -0
  198. package/dist/src/react/geoms/Pie.js +59 -0
  199. package/dist/src/react/geoms/Points.d.ts +84 -0
  200. package/dist/src/react/geoms/Points.js +207 -0
  201. package/dist/src/react/geoms/Points3d.d.ts +49 -0
  202. package/dist/src/react/geoms/Points3d.js +58 -0
  203. package/dist/src/react/geoms/Radar.d.ts +39 -0
  204. package/dist/src/react/geoms/Radar.js +59 -0
  205. package/dist/src/react/geoms/Range.d.ts +31 -0
  206. package/dist/src/react/geoms/Range.js +20 -0
  207. package/dist/src/react/geoms/RingStack.d.ts +39 -0
  208. package/dist/src/react/geoms/RingStack.js +65 -0
  209. package/dist/src/react/geoms/Rule.d.ts +29 -0
  210. package/dist/src/react/geoms/Rule.js +51 -0
  211. package/dist/src/react/geoms/Sankey.d.ts +24 -0
  212. package/dist/src/react/geoms/Sankey.js +51 -0
  213. package/dist/src/react/geoms/Segment.d.ts +36 -0
  214. package/dist/src/react/geoms/Segment.js +39 -0
  215. package/dist/src/react/geoms/Sunburst.d.ts +46 -0
  216. package/dist/src/react/geoms/Sunburst.js +64 -0
  217. package/dist/src/react/geoms/Surface.d.ts +32 -0
  218. package/dist/src/react/geoms/Surface.js +49 -0
  219. package/dist/src/react/geoms/Text.d.ts +35 -0
  220. package/dist/src/react/geoms/Text.js +40 -0
  221. package/dist/src/react/geoms/Treemap.d.ts +39 -0
  222. package/dist/src/react/geoms/Treemap.js +16 -0
  223. package/dist/src/react/geoms/Violin.d.ts +56 -0
  224. package/dist/src/react/geoms/Violin.js +60 -0
  225. package/dist/src/react/geoms/Volume.d.ts +37 -0
  226. package/dist/src/react/geoms/Volume.js +40 -0
  227. package/dist/src/react/geoms/Waterfall.d.ts +43 -0
  228. package/dist/src/react/geoms/Waterfall.js +18 -0
  229. package/dist/src/react/geoms/cube-stage.d.ts +39 -0
  230. package/dist/src/react/geoms/cube-stage.js +85 -0
  231. package/dist/src/react/geoms/hierarchy-cells.d.ts +42 -0
  232. package/dist/src/react/geoms/hierarchy-cells.js +59 -0
  233. package/dist/src/react/geoms/sector-axis.d.ts +66 -0
  234. package/dist/src/react/geoms/sector-axis.js +99 -0
  235. package/dist/src/react/gl/GlMesh.d.ts +22 -0
  236. package/dist/src/react/gl/GlMesh.js +78 -0
  237. package/dist/src/react/gl/GlPoints.d.ts +45 -0
  238. package/dist/src/react/gl/GlPoints.js +117 -0
  239. package/dist/src/react/gl/GlVolume.d.ts +28 -0
  240. package/dist/src/react/gl/GlVolume.js +112 -0
  241. package/dist/src/react/gl/GlWalls.d.ts +24 -0
  242. package/dist/src/react/gl/GlWalls.js +55 -0
  243. package/dist/src/react/gl/context.d.ts +71 -0
  244. package/dist/src/react/gl/context.js +98 -0
  245. package/dist/src/react/gl/encode.d.ts +120 -0
  246. package/dist/src/react/gl/encode.js +215 -0
  247. package/dist/src/react/gl/index.d.ts +10 -0
  248. package/dist/src/react/gl/index.js +8 -0
  249. package/dist/src/react/gl/refresh.d.ts +7 -0
  250. package/dist/src/react/gl/refresh.js +19 -0
  251. package/dist/src/react/gl/renderer.d.ts +377 -0
  252. package/dist/src/react/gl/renderer.js +1081 -0
  253. package/dist/src/react/gl/shaders.d.ts +92 -0
  254. package/dist/src/react/gl/shaders.js +405 -0
  255. package/dist/src/react/gl/surface.d.ts +31 -0
  256. package/dist/src/react/gl/surface.js +73 -0
  257. package/dist/src/react/index.d.ts +12 -0
  258. package/dist/src/react/index.js +11 -0
  259. package/dist/src/react/orbit.d.ts +38 -0
  260. package/dist/src/react/orbit.js +81 -0
  261. package/dist/src/react/sides/DendrogramPanel.d.ts +32 -0
  262. package/dist/src/react/sides/DendrogramPanel.js +39 -0
  263. package/dist/src/react/sides/DensityPanel.d.ts +31 -0
  264. package/dist/src/react/sides/DensityPanel.js +37 -0
  265. package/dist/src/react/sides/HistogramPanel.d.ts +30 -0
  266. package/dist/src/react/sides/HistogramPanel.js +18 -0
  267. package/dist/src/react/sides/RugPanel.d.ts +28 -0
  268. package/dist/src/react/sides/RugPanel.js +21 -0
  269. package/dist/src/react/sides/TrackPanel.d.ts +37 -0
  270. package/dist/src/react/sides/TrackPanel.js +27 -0
  271. package/dist/src/react/theme.d.ts +48 -0
  272. package/dist/src/react/theme.js +148 -0
  273. package/dist/src/react/useFits.d.ts +26 -0
  274. package/dist/src/react/useFits.js +62 -0
  275. package/dist/src/react/useZoom.d.ts +50 -0
  276. package/dist/src/react/useZoom.js +141 -0
  277. package/package.json +164 -5
  278. package/theme/default.css +62 -0
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Rows a tool call plots, and what the columns mean.
3
+ *
4
+ * Rows can be imported from JSON or CSV.
5
+ */
6
+ import { type FieldOverride, type PlotData } from "../core/internal.js";
7
+ /** Where a tool call's rows come from. */
8
+ export type Source = {
9
+ kind: "inline";
10
+ rows: Record<string, unknown>[];
11
+ } | {
12
+ kind: "file";
13
+ path: string;
14
+ };
15
+ /** Reads the rows behind a source, as they arrived. */
16
+ export declare function readSource(source: Source): Promise<Record<string, unknown>[]>;
17
+ /**
18
+ * Resolves a source to plot data and its column metadata.
19
+ *
20
+ * The core adapter reads time columns, as it does for `Viz`, so a drawing call and a page chart
21
+ * the same rows one way. Other host based tables can come from its own imports in the
22
+ * `./tools.js` handlers without requiring a query engine.
23
+ */
24
+ export declare function loadSource(source: Source, stated?: Record<string, FieldOverride>): Promise<{
25
+ rows: Record<string, unknown>[];
26
+ fieldOverrides: Record<string, FieldOverride>;
27
+ data: PlotData;
28
+ }>;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Rows a tool call plots, and what the columns mean.
3
+ *
4
+ * Rows can be imported from JSON or CSV.
5
+ */
6
+ import { readFile } from "node:fs/promises";
7
+ import { fromRows, ISO, TIME_NAME } from "../core/internal.js";
8
+ import { confine } from "./paths.js";
9
+ /**
10
+ * Splits CSV text into records of fields, honoring double quotes.
11
+ *
12
+ * A quoted field keeps its delimiters and newlines, as in a sample name or an instrument's notes column.
13
+ */
14
+ function records(text, delimiter) {
15
+ const out = [];
16
+ let record = [];
17
+ let field = "";
18
+ let quoted = false;
19
+ for (let at = 0; at < text.length; at += 1) {
20
+ const char = text[at];
21
+ if (quoted) {
22
+ if (char !== '"')
23
+ field += char;
24
+ else if (text[at + 1] === '"') {
25
+ field += '"';
26
+ at += 1;
27
+ }
28
+ else
29
+ quoted = false;
30
+ }
31
+ else if (char === '"')
32
+ quoted = true;
33
+ else if (char === delimiter) {
34
+ record.push(field);
35
+ field = "";
36
+ }
37
+ else if (char === "\n") {
38
+ out.push([...record, field]);
39
+ record = [];
40
+ field = "";
41
+ }
42
+ else
43
+ field += char;
44
+ }
45
+ out.push([...record, field]);
46
+ /* A blank line reads as one empty field. */
47
+ return out.filter((fields) => fields.length > 1 || fields[0].trim() !== "");
48
+ }
49
+ /** Whether a trimmed cell reads as a number. A leading zero marks an identifier. */
50
+ const numeric = (text) => text !== "-" && !/^-?0\d/.test(text) && Number.isFinite(Number(text));
51
+ /** A cell an instrument export writes for a missing reading. */
52
+ const MISSING = /^(-|nan|n\/?a|n\.?d\.?|null)$/i;
53
+ /**
54
+ * Rows off CSV text, typed by column.
55
+ *
56
+ * A column is numeric where it holds a number and every other filled cell reads as one or as a missing
57
+ * reading, which becomes null. Any other column is text.
58
+ */
59
+ function parseCsv(text, delimiter) {
60
+ const [header, ...cells] = records(text, delimiter).map((fields) => fields.map((value) => value.trim()));
61
+ if (!header)
62
+ return [];
63
+ const numbers = header.map((_, index) => cells.some((row) => row[index] && numeric(row[index])) &&
64
+ cells.every((row) => !row[index] || MISSING.test(row[index]) || numeric(row[index])));
65
+ return cells.map((values) => {
66
+ const row = {};
67
+ header.forEach((name, index) => {
68
+ const value = values[index] ?? "";
69
+ if (!numbers[index])
70
+ row[name] = value === "" ? null : value;
71
+ else
72
+ row[name] = value === "" || MISSING.test(value) ? null : Number(value);
73
+ });
74
+ return row;
75
+ });
76
+ }
77
+ /** Whether a cell holds no reading, as null or a missing-reading token. */
78
+ const gap = (value) => value == null || (typeof value === "string" && MISSING.test(value));
79
+ /**
80
+ * Rows with each missing-reading token in a time-named column as null.
81
+ *
82
+ * A time column of ISO text or epoch numbers then reads on a calendar scale past its gaps.
83
+ */
84
+ function gapped(rows) {
85
+ const names = new Set(rows.flatMap((row) => Object.keys(row)));
86
+ let out = rows;
87
+ for (const name of names) {
88
+ const filled = rows.map((row) => row[name]).filter((value) => !gap(value));
89
+ const timed = TIME_NAME.test(name) &&
90
+ filled.length > 0 &&
91
+ filled.every((value) => typeof value === "number" || (typeof value === "string" && ISO.test(value)));
92
+ if (timed)
93
+ out = out.map((row) => (row[name] != null && gap(row[name]) ? { ...row, [name]: null } : row));
94
+ }
95
+ return out;
96
+ }
97
+ /** Whether a value is an array of rows, each an object keyed by column. */
98
+ const allRows = (value) => Array.isArray(value) && value.every((row) => row !== null && typeof row === "object" && !Array.isArray(row));
99
+ /** Reads the rows behind a source, as they arrived. */
100
+ export async function readSource(source) {
101
+ if (source.kind === "inline") {
102
+ if (allRows(source.rows))
103
+ return source.rows;
104
+ throw new Error("inline rows take an array of objects, one per row");
105
+ }
106
+ const path = await confine(source.path, [".json", ".csv", ".tsv"]);
107
+ const text = await readFile(path, "utf8");
108
+ if (/\.(csv|tsv)$/i.test(path))
109
+ return parseCsv(text, /\.tsv$/i.test(path) ? "\t" : ",");
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(text);
113
+ }
114
+ catch {
115
+ throw new Error(`${source.path} is not valid JSON`);
116
+ }
117
+ if (allRows(parsed))
118
+ return parsed;
119
+ throw new Error(`${source.path} holds no array of rows at its root`);
120
+ }
121
+ /**
122
+ * Resolves a source to plot data and its column metadata.
123
+ *
124
+ * The core adapter reads time columns, as it does for `Viz`, so a drawing call and a page chart
125
+ * the same rows one way. Other host based tables can come from its own imports in the
126
+ * `./tools.js` handlers without requiring a query engine.
127
+ */
128
+ export async function loadSource(source, stated = {}) {
129
+ const rows = gapped(await readSource(source));
130
+ return { rows, fieldOverrides: stated, data: fromRows(rows, { fieldOverrides: stated }) };
131
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The `/mcp` surface: the tool catalog, its handlers, and headless drawing.
3
+ *
4
+ * Node only. This is not exposed to `/core`, `/react`, `/builder` or `/graph`.
5
+ */
6
+ export { callTool, TOOLS, type CallResult, type Edits } from "./tools.js";
7
+ export { MultiPanelFigure, renderPng, renderSvg, type RenderOptions } from "./render.js";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The `/mcp` surface: the tool catalog, its handlers, and headless drawing.
3
+ *
4
+ * Node only. This is not exposed to `/core`, `/react`, `/builder` or `/graph`.
5
+ */
6
+ export { callTool, TOOLS } from "./tools.js";
7
+ export { MultiPanelFigure, renderPng, renderSvg } from "./render.js";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Paths a tool call names, held to the directory `VIZ_MCP_ROOT` names.
3
+ *
4
+ * Node only. The barrel leaves this module out.
5
+ */
6
+ /**
7
+ * A client's path, resolved inside `VIZ_MCP_ROOT` with its links followed.
8
+ *
9
+ * Throws with the root unset or at the filesystem root, on an extension outside `extensions`, and on a
10
+ * path landing outside the root.
11
+ */
12
+ export declare function confine(path: string, extensions: readonly string[]): Promise<string>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Paths a tool call names, held to the directory `VIZ_MCP_ROOT` names.
3
+ *
4
+ * Node only. The barrel leaves this module out.
5
+ */
6
+ import { realpath } from "node:fs/promises";
7
+ import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
8
+ /**
9
+ * A client's path, resolved inside `VIZ_MCP_ROOT` with its links followed.
10
+ *
11
+ * Throws with the root unset or at the filesystem root, on an extension outside `extensions`, and on a
12
+ * path landing outside the root.
13
+ */
14
+ export async function confine(path, extensions) {
15
+ if (!extensions.includes(extname(path).toLowerCase())) {
16
+ throw new Error(`${basename(path)}: this call takes a ${extensions.join(", ")} file`);
17
+ }
18
+ const setting = process.env.VIZ_MCP_ROOT;
19
+ const root = setting ? await realpath(setting) : "";
20
+ if (root === "" || root === parse(root).root) {
21
+ throw new Error(`${path}: file paths need VIZ_MCP_ROOT set to a directory below the filesystem root`);
22
+ }
23
+ const target = resolve(root, path);
24
+ const real = await realpath(target).catch(async () => join(await realpath(dirname(target)), basename(target)));
25
+ const within = relative(root, real);
26
+ if (within === "" || isAbsolute(within) || within.split(sep)[0] === "..") {
27
+ throw new Error(`${path} is outside VIZ_MCP_ROOT ${root}`);
28
+ }
29
+ return real;
30
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * A spec drawn without a browser.
3
+ *
4
+ * Renders through `react-dom/server`. Label sizing comes off character count.
5
+ *
6
+ * Above `GL_ABOVE` points the figure draws binned. The GL path requires a browser.
7
+ */
8
+ import { type ChartSpec, type FieldOverride, type FigureSet, type Palettes, type VizData } from "../core/internal.js";
9
+ /**
10
+ * Which values the tokens resolve to.
11
+ *
12
+ * `tokens` leaves references for a page that declares the theme.
13
+ *
14
+ * `renderPng` refuses `tokens`. resvg resolves no custom property.
15
+ */
16
+ export type Theme = "light" | "dark" | "tokens";
17
+ /** Panel size a tool call draws at, where the spec states none. */
18
+ export declare const DEFAULT_SIZE: {
19
+ width: number;
20
+ height: number;
21
+ };
22
+ /** The size one panel draws at. A stated height wins over the aspect, and the aspect over the default. */
23
+ export declare function panelSize(spec: ChartSpec): {
24
+ width: number;
25
+ height: number;
26
+ };
27
+ /**
28
+ * The two color maps a theme draws with.
29
+ *
30
+ * A headless draw reads no ground. `tokens` takes the dark span, per the ADR
31
+ * "A tokens-theme file takes the dark ramp".
32
+ */
33
+ export declare const palettesForTheme: (theme: Theme) => Palettes;
34
+ /** Raised for a faceted figure. Headless drawing covers one panel, and a facet grid is HTML. */
35
+ export declare class MultiPanelFigure extends Error {
36
+ readonly by: string;
37
+ constructor(by: string);
38
+ }
39
+ /** What a headless draw reads: the spec, its rows, and the file's theme, ground and scale. */
40
+ export interface RenderOptions {
41
+ spec: ChartSpec;
42
+ /** Rows, columns, or an arrow table. */
43
+ data: VizData;
44
+ /** Units and labels the table cannot carry, keyed by column. */
45
+ fieldOverrides?: Record<string, FieldOverride>;
46
+ /** Color pinning and story order across a figure set. */
47
+ set?: FigureSet;
48
+ /** The two color maps. The theme's own where none is given. */
49
+ palettes?: Palettes;
50
+ theme?: Theme;
51
+ /** Whether the file paints its own paper. On unless the theme is `tokens`, where the page shows through. */
52
+ ground?: boolean;
53
+ /** Pixel scale for the raster copy. Two draws a retina-density file. */
54
+ scale?: number;
55
+ }
56
+ /** What the drawn file left out. */
57
+ export interface Drawn {
58
+ svg: string;
59
+ /** A shape, size, opacity, dash or track guide, which stays with the page. */
60
+ legendDropped: boolean;
61
+ }
62
+ /** Draws a spec to a standalone SVG string. */
63
+ export declare const renderSvg: (options: RenderOptions) => string;
64
+ /** Draws a spec to a PNG. The rasterizer, a native addon, loads on the first call. */
65
+ export declare function renderPng(options: RenderOptions): Drawn & {
66
+ png: Uint8Array;
67
+ };
@@ -0,0 +1,189 @@
1
+ /**
2
+ * A spec drawn without a browser.
3
+ *
4
+ * Renders through `react-dom/server`. Label sizing comes off character count.
5
+ *
6
+ * Above `GL_ABOVE` points the figure draws binned. The GL path requires a browser.
7
+ */
8
+ import { createRequire } from "node:module";
9
+ import { createElement } from "react";
10
+ import { renderToStaticMarkup } from "react-dom/server";
11
+ import { axisLabel, buildPanels, DARK_THEME, KINDS, layerScale, LIGHT_THEME, paint, palettesFor, toPlotData, } from "../core/internal.js";
12
+ import { resolveTokens } from "../react/export.js";
13
+ import { Viz } from "../react/Viz.js";
14
+ const require = createRequire(import.meta.url);
15
+ /** Panel size a tool call draws at, where the spec states none. */
16
+ export const DEFAULT_SIZE = { width: 720, height: 440 };
17
+ /** The size one panel draws at. A stated height wins over the aspect, and the aspect over the default. */
18
+ export function panelSize(spec) {
19
+ const width = spec.width ?? DEFAULT_SIZE.width;
20
+ const height = spec.height ?? (spec.aspect ? Math.max(1, Math.round(width * spec.aspect)) : DEFAULT_SIZE.height);
21
+ return { width, height };
22
+ }
23
+ const FONT_STACK = "ui-sans-serif, system-ui, -apple-system, Segoe UI, Helvetica, Arial, sans-serif";
24
+ /** Every token as a reference to itself. The page declares the values. */
25
+ const PASS_THROUGH = Object.fromEntries(Object.keys(LIGHT_THEME).map((token) => [token, `var(${token})`]));
26
+ const snapshotFor = (theme) => theme === "dark" ? DARK_THEME : theme === "tokens" ? PASS_THROUGH : LIGHT_THEME;
27
+ /**
28
+ * The two color maps a theme draws with.
29
+ *
30
+ * A headless draw reads no ground. `tokens` takes the dark span, per the ADR
31
+ * "A tokens-theme file takes the dark ramp".
32
+ */
33
+ export const palettesForTheme = (theme) => palettesFor({ dark: theme !== "light" });
34
+ /**
35
+ * A font for the file. It opens away from the page's stylesheet.
36
+ *
37
+ * Token declarations stay out. `resolveTokens` substitutes literals for resvg to paint.
38
+ */
39
+ const styleBlock = () => `<style>text{font-family:${FONT_STACK}}</style>`;
40
+ const paperRect = (snapshot) => `<rect x="0" y="0" width="100%" height="100%" fill="${snapshot["--viz-paper"]}"/>`;
41
+ /** Raised for a faceted figure. Headless drawing covers one panel, and a facet grid is HTML. */
42
+ export class MultiPanelFigure extends Error {
43
+ by;
44
+ constructor(by) {
45
+ super(`headless drawing covers one panel, and this figure facets on ${by}. Clear facet to draw it.`);
46
+ this.by = by;
47
+ this.name = "MultiPanelFigure";
48
+ }
49
+ }
50
+ /** Takes the frame's SVG element out of the markup, by its panel marker. Legend swatches stay out. */
51
+ function panelElement(markup) {
52
+ const open = markup.indexOf("<svg data-viz-panel");
53
+ if (open < 0)
54
+ return null;
55
+ const tag = /<svg\b|<\/svg>/g;
56
+ tag.lastIndex = open;
57
+ let depth = 0;
58
+ for (let hit = tag.exec(markup); hit; hit = tag.exec(markup)) {
59
+ depth += hit[0] === "</svg>" ? -1 : 1;
60
+ if (depth === 0)
61
+ return markup.slice(open, hit.index + "</svg>".length);
62
+ }
63
+ return null;
64
+ }
65
+ /** Pixel sizes the color key lays out with. */
66
+ const KEY = { type: 11, line: 18, swatch: 4, char: 6.2, pad: 12, bar: 160 };
67
+ const escaped = (text) => text.replace(/[&<>"]/g, (character) => `&#${character.charCodeAt(0)};`);
68
+ const keyText = (x, y, text, token) => `<text x="${x}" y="${y}" font-size="${KEY.type}" fill="var(${token})">${escaped(text)}</text>`;
69
+ /** A scale's end as the bar writes it, to three significant figures. */
70
+ const keyNumber = (value) => String(Number(value.toPrecision(3)));
71
+ /**
72
+ * The series legend's swatches and one bar a color scale, laid out under the plot.
73
+ *
74
+ * Read off the frame `Viz` draws from. Other guides stay with the page.
75
+ */
76
+ function keyFor({ spec, data, fieldOverrides, set, palettes }, width) {
77
+ if (spec.legend?.position === "none")
78
+ return { markup: "", height: 0, dropped: false };
79
+ const panels = paint(buildPanels(spec, toPlotData(data, { fieldOverrides }), {
80
+ palettes,
81
+ partition: { groups: [] },
82
+ pinned: set?.assignments,
83
+ }), spec.layers, palettes, spec.scales);
84
+ const built = panels.status === "ready" ? panels.panels[0]?.frame : undefined;
85
+ if (!built)
86
+ return { markup: "", height: 0, dropped: false };
87
+ const guided = built.traces.filter((trace) => trace.showLegend !== false);
88
+ const parts = [];
89
+ let y = 0;
90
+ if (built.legend.length > 1) {
91
+ const named = guided.find((trace) => trace.colorLevels?.length || (trace.grouped ? undefined : trace.splitField));
92
+ const layer = spec.layers.find((each) => each.id === (named ?? guided[0])?.layerId);
93
+ const title = (layer ? layerScale(spec, layer)?.title : undefined) ??
94
+ axisLabel(named?.colorField ?? (named?.grouped ? undefined : named?.splitField));
95
+ if (title) {
96
+ parts.push(keyText(KEY.pad, y + KEY.type, title, "--viz-ink-muted"));
97
+ y += KEY.line;
98
+ }
99
+ let x = KEY.pad;
100
+ for (const row of built.legend) {
101
+ const run = KEY.swatch * 2 + 6 + row.label.length * KEY.char;
102
+ if (x > KEY.pad && x + run > width - KEY.pad) {
103
+ x = KEY.pad;
104
+ y += KEY.line;
105
+ }
106
+ parts.push(`<circle cx="${x + KEY.swatch}" cy="${y + KEY.type - KEY.swatch}" r="${KEY.swatch}" fill="${escaped(row.color)}"/>`);
107
+ parts.push(keyText(x + KEY.swatch * 2 + 6, y + KEY.type, row.label, "--viz-ink"));
108
+ x += run + KEY.pad;
109
+ }
110
+ y += KEY.line;
111
+ }
112
+ const scaled = guided.filter((trace) => trace.colorDomain);
113
+ const bars = [...new Map(scaled.map((trace) => [trace.colorField?.id ?? trace.layerId, trace])).values()];
114
+ bars.forEach((trace, at) => {
115
+ const [lo, hi] = trace.colorDomain;
116
+ const layer = spec.layers.find((each) => each.id === trace.layerId);
117
+ const title = (layer ? layerScale(spec, layer)?.title : undefined) ?? axisLabel(trace.colorField) ?? trace.name;
118
+ const stops = Array.from({ length: 16 }, (_, step) => {
119
+ const t = step / 15;
120
+ return `<stop offset="${t}" stop-color="${trace.ramp(lo + (hi - lo) * t)}"/>`;
121
+ });
122
+ parts.push(keyText(KEY.pad, y + KEY.type, title, "--viz-ink-muted"), `<linearGradient id="viz-key-${at}">${stops.join("")}</linearGradient>`, `<rect x="${KEY.pad}" y="${y + KEY.line - 2}" width="${KEY.bar}" height="8" rx="2" fill="url(#viz-key-${at})"/>`, keyText(KEY.pad, y + KEY.line * 2 + 4, keyNumber(lo), "--viz-ink-muted"), `<text x="${KEY.pad + KEY.bar}" y="${y + KEY.line * 2 + 4}" font-size="${KEY.type}" text-anchor="end" fill="var(--viz-ink-muted)">${keyNumber(hi)}</text>`);
123
+ y += KEY.line * 2 + 10;
124
+ });
125
+ const dropped = guided.some((trace) => trace.shapeChannel?.levels?.length ||
126
+ trace.alphaChannel?.levels?.length ||
127
+ trace.linetypeChannel ||
128
+ trace.sizeField) || Boolean(spec.sides?.some((side) => side.content.kind === "track"));
129
+ return parts.length ? { markup: parts.join(""), height: y + KEY.pad, dropped } : { markup: "", height: 0, dropped };
130
+ }
131
+ /** Completes the chart's own element as a standalone, scalable file, its color key under the plot. */
132
+ function standalone(markup, snapshot, ground, key) {
133
+ const element = panelElement(markup);
134
+ if (!element)
135
+ throw new Error("render: no svg in the markup Viz produced");
136
+ const size = /width="([\d.]+)" height="([\d.]+)"/.exec(element);
137
+ if (!size)
138
+ throw new Error("render: the svg root states no width and height");
139
+ const height = Number(size[2]) + key.height;
140
+ const svg = element
141
+ .replace(size[0], `width="${size[1]}" height="${height}"`)
142
+ .replace("<svg", `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size[1]} ${height}"`);
143
+ const head = svg.indexOf(">") + 1;
144
+ const tail = svg.lastIndexOf("</svg>");
145
+ const placed = key.height ? `<g transform="translate(0 ${size[2]})">${key.markup}</g>` : "";
146
+ const file = svg.slice(0, head) +
147
+ styleBlock() +
148
+ (ground ? paperRect(snapshot) : "") +
149
+ svg.slice(head, tail) +
150
+ placed +
151
+ svg.slice(tail);
152
+ return resolveTokens(file, snapshot);
153
+ }
154
+ /** Draws a spec to a standalone SVG string, beside what the file left out. */
155
+ function drawSvg({ spec, theme = "light", ground = theme !== "tokens", scale: _scale, ...props }) {
156
+ if (spec.facet)
157
+ throw new MultiPanelFigure(spec.facet.by);
158
+ /* A caller writes this spec as JSON, and a kind from a newer version reaches here unchecked. */
159
+ const unknown = spec.layers.find((layer) => !KINDS.includes(layer.kind));
160
+ if (unknown)
161
+ throw new Error(`ts-lib-viz: ${unknown.kind} is no kind this version draws. KINDS lists them.`);
162
+ /* A caller writes this spec as JSON and no type checks it. A panel with no extent lays out at `NaN`. */
163
+ const unsized = spec.sides?.find((side) => !Number.isFinite(side.size));
164
+ if (unsized) {
165
+ throw new Error(`a side panel takes its extent as \`size\` in pixels, and the ${unsized.position} panel states none.`);
166
+ }
167
+ const size = panelSize(spec);
168
+ const viz = { ...props, palettes: props.palettes ?? palettesForTheme(theme), spec: { ...spec, ...size } };
169
+ const markup = renderToStaticMarkup(createElement(Viz, viz));
170
+ const key = keyFor(viz, size.width);
171
+ return { svg: standalone(markup, snapshotFor(theme), ground, key), legendDropped: key.dropped };
172
+ }
173
+ /** Draws a spec to a standalone SVG string. */
174
+ export const renderSvg = (options) => drawSvg(options).svg;
175
+ /** Draws a spec to a PNG. The rasterizer, a native addon, loads on the first call. */
176
+ export function renderPng(options) {
177
+ if (options.theme === "tokens") {
178
+ throw new Error('renderPng: the tokens theme resolves in a browser. Ask for format "svg", or a light or dark png.');
179
+ }
180
+ const drawn = drawSvg(options);
181
+ const scale = options.scale ?? 2;
182
+ const width = panelSize(options.spec).width * scale;
183
+ const { Resvg } = require("@resvg/resvg-js");
184
+ const raster = new Resvg(drawn.svg, {
185
+ fitTo: { mode: "width", value: Math.round(width) },
186
+ font: { loadSystemFonts: true, defaultFontFamily: "Helvetica" },
187
+ });
188
+ return { ...drawn, png: raster.render().asPng() };
189
+ }
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The stdio server a desktop client launches.
4
+ *
5
+ * This file contains only transport and dispatch.
6
+ */
7
+ export {};
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The stdio server a desktop client launches.
4
+ *
5
+ * This file contains only transport and dispatch.
6
+ */
7
+ import { createRequire } from "node:module";
8
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
9
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
11
+ import { callTool, TOOLS } from "./tools.js";
12
+ /** The package version, read from the manifest through the package's own export of it. */
13
+ const { version } = createRequire(import.meta.url)("@tetrascience-npm/ts-lib-viz/package.json");
14
+ const server = new Server({ name: "ts-lib-viz", version }, { capabilities: { tools: {} } });
15
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [...TOOLS] }));
16
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
17
+ try {
18
+ return await callTool(request.params.name, request.params.arguments ?? {});
19
+ }
20
+ catch (error) {
21
+ const message = error instanceof Error ? error.message : String(error);
22
+ return { content: [{ type: "text", text: message }], isError: true };
23
+ }
24
+ });
25
+ await server.connect(new StdioServerTransport());
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Tools and handlers.
3
+ *
4
+ * Public for use by another source table. Calls are stateless. Any follow up turns edit the same produced source.
5
+ */
6
+ import { type Aes, type Aesthetic, type ChartScales, type ChartSpec, type LegendOptions, type PlotKind } from "../core/internal.js";
7
+ /** Chart-level fields an edit may set. Layers have their own operations. */
8
+ type PatchFields = Pick<ChartSpec, "headline" | "subtitle" | "caption" | "facet" | "coord" | "scales" | "tooltip" | "annotations" | "legend" | "overrides" | "sides" | "width" | "height" | "aspect" | "ratio" | "sizing">;
9
+ /** Each field optional, and a null clears it. */
10
+ type Nullable<T> = {
11
+ [Field in keyof T]?: T[Field] | null;
12
+ };
13
+ /** The patch an edit merges. An object field takes any of its own fields, and scales takes them per aesthetic. */
14
+ type Patch = Omit<Nullable<PatchFields>, "facet" | "legend" | "scales"> & {
15
+ facet?: Nullable<NonNullable<ChartSpec["facet"]>> | null;
16
+ legend?: Nullable<LegendOptions> | null;
17
+ scales?: {
18
+ [Scale in keyof ChartScales]?: Nullable<NonNullable<ChartScales[Scale]>> | null;
19
+ } | null;
20
+ };
21
+ /** One layer an edit adds: its kind, its own aes, and flat options the kind reads. */
22
+ type LayerRequest = {
23
+ kind: PlotKind;
24
+ aes?: Aes;
25
+ [option: string]: unknown;
26
+ };
27
+ export interface Edits {
28
+ /** Merged onto the chart. An object merges field by field, and a `null` clears the field it sits on. */
29
+ patch?: Patch;
30
+ addLayer?: readonly LayerRequest[];
31
+ /** Layer ids to drop. */
32
+ removeLayer?: readonly string[];
33
+ /** Aesthetic bindings, against the first layer where none is named. */
34
+ bind?: readonly {
35
+ layer?: string;
36
+ aes: Aesthetic;
37
+ field: string | readonly string[] | null;
38
+ }[];
39
+ }
40
+ /**
41
+ * Applies one edit set to a chart, returning a new document.
42
+ *
43
+ * Layer ids, removal and binding go through the spec editors. An id no layer holds, or a removal of
44
+ * the last layer, throws where the editor hands the spec back.
45
+ */
46
+ export declare function applyEdits(spec: ChartSpec, edits: Edits): ChartSpec;
47
+ /** Builds a one-layer chart from a kind and its bindings. */
48
+ export declare function buildSpec(input: {
49
+ kind: PlotKind;
50
+ aes: Aes;
51
+ headline?: string;
52
+ id?: string;
53
+ layer?: Record<string, unknown>;
54
+ edits?: Edits;
55
+ }): ChartSpec;
56
+ export interface CallResult {
57
+ content: ({
58
+ type: "image";
59
+ data: string;
60
+ mimeType: string;
61
+ } | {
62
+ type: "text";
63
+ text: string;
64
+ })[];
65
+ isError?: boolean;
66
+ [extra: string]: unknown;
67
+ }
68
+ /** One catalog entry: the tool's name, what it does, and the JSON Schema its arguments meet. Read-only throughout. */
69
+ export interface Tool {
70
+ readonly name: string;
71
+ readonly description: string;
72
+ readonly inputSchema: {
73
+ readonly type: "object";
74
+ readonly properties: Readonly<Record<string, object>>;
75
+ readonly required: readonly string[];
76
+ };
77
+ }
78
+ export declare const TOOLS: readonly Tool[];
79
+ type Args = Record<string, unknown>;
80
+ /** Runs one tool call by name. */
81
+ export declare function callTool(name: string, args: Args): Promise<CallResult>;
82
+ export {};