@malloy-publisher/sdk 0.2.7 → 0.3.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 (221) hide show
  1. package/README.md +180 -204
  2. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +134 -0
  3. package/dist/DocumentStorageProvider-tGvodI8f.es.js +24268 -0
  4. package/dist/RenderedResult-CPi6uQWq.cjs.js +115 -0
  5. package/dist/RenderedResult-mDE-4u8S.es.js +542 -0
  6. package/dist/{ServerProvider-xXW1HJOJ.cjs.js → ServerProvider-CH71GsoL.cjs.js} +1 -1
  7. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-X2Ma0HRs.es.js} +324 -359
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9561 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/api.d.ts +13 -1
  13. package/dist/client/index.cjs.js +1 -1
  14. package/dist/client/index.es.js +1 -1
  15. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  16. package/dist/components/Dashboard/Dashboard.d.ts +23 -16
  17. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  18. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  19. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  20. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  21. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  22. package/dist/components/Dashboard/index.d.ts +2 -0
  23. package/dist/components/Dashboard/promoteMeasureRow.d.ts +40 -0
  24. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  25. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  26. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  27. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  28. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  29. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  30. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  31. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  32. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  33. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  34. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  35. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  36. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  37. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  38. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  39. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  40. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  41. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  42. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  43. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  44. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  45. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  46. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  47. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  48. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  49. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  50. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  51. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  52. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  53. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  54. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  55. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +25 -0
  56. package/dist/components/DocumentStorage/index.d.ts +3 -0
  57. package/dist/components/FloatingIconButton.d.ts +16 -0
  58. package/dist/components/Model/index.d.ts +0 -1
  59. package/dist/components/Prose.d.ts +46 -0
  60. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  61. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  62. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  63. package/dist/components/RenderedResult/index.d.ts +2 -0
  64. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  65. package/dist/components/drill/index.d.ts +2 -1
  66. package/dist/components/drill/resolveDrill.d.ts +22 -0
  67. package/dist/components/drill/useDrill.d.ts +11 -2
  68. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  69. package/dist/components/given/filterValue.d.ts +63 -0
  70. package/dist/components/given/index.d.ts +1 -0
  71. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  72. package/dist/components/index.d.ts +3 -3
  73. package/dist/components/styles.d.ts +3 -7
  74. package/dist/core-8NVBCLZh.cjs.js +148 -0
  75. package/dist/{core-BY7vB5gN.es.js → core-B8oMW4sm.es.js} +3540 -2335
  76. package/dist/hooks/index.d.ts +3 -1
  77. package/dist/hooks/useDocumentControls.d.ts +70 -0
  78. package/dist/hooks/useQueryResult.d.ts +40 -0
  79. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  80. package/dist/index.cjs.js +34 -1
  81. package/dist/index.es.js +21487 -79
  82. package/dist/sdk.css +1 -1
  83. package/dist/styles.css +0 -1
  84. package/dist/utils/malloyLiteral.d.ts +11 -0
  85. package/package.json +25 -14
  86. package/src/builder-entry.ts +55 -0
  87. package/src/components/ApiErrorDisplay.tsx +1 -1
  88. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  89. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  90. package/src/components/Dashboard/Dashboard.tsx +184 -229
  91. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  92. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  93. package/src/components/Dashboard/DashboardTile.tsx +67 -101
  94. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  95. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  96. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  97. package/src/components/Dashboard/TileCard.tsx +120 -0
  98. package/src/components/Dashboard/index.ts +2 -0
  99. package/src/components/Dashboard/promoteMeasureRow.spec.ts +207 -0
  100. package/src/components/Dashboard/promoteMeasureRow.ts +160 -0
  101. package/src/components/Dashboard/telemetry.ts +44 -0
  102. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  103. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  104. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  105. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  106. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  107. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  108. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  109. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  110. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  111. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  112. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  113. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  114. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  115. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  116. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  117. package/src/components/DashboardBuilder/catalog.ts +225 -0
  118. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  119. package/src/components/DashboardBuilder/controls.ts +398 -0
  120. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  121. package/src/components/DashboardBuilder/diff.ts +93 -0
  122. package/src/components/DashboardBuilder/document.ts +209 -0
  123. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  124. package/src/components/DashboardBuilder/layout.ts +143 -0
  125. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  126. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  127. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  128. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  129. package/src/components/DashboardBuilder/preview.ts +172 -0
  130. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  131. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  132. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  133. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  134. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  135. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  136. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  137. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  138. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  139. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  140. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  141. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  142. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  143. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  144. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  145. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  146. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  147. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  148. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  149. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  150. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +58 -0
  151. package/src/components/DocumentStorage/index.ts +16 -0
  152. package/src/components/Environment/About.tsx +4 -36
  153. package/src/components/FloatingIconButton.tsx +41 -0
  154. package/src/components/Model/Model.tsx +6 -23
  155. package/src/components/Model/ModelCell.tsx +34 -72
  156. package/src/components/Model/index.ts +0 -1
  157. package/src/components/Notebook/Notebook.tsx +27 -156
  158. package/src/components/Notebook/NotebookCell.tsx +37 -191
  159. package/src/components/Prose.spec.tsx +85 -0
  160. package/src/components/Prose.tsx +179 -0
  161. package/src/components/QueryResult/QueryResult.tsx +15 -43
  162. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  163. package/src/components/RenderedResult/ResultContainer.tsx +25 -36
  164. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  165. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  166. package/src/components/RenderedResult/index.ts +16 -0
  167. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  168. package/src/components/RenderedResult/resultSizing.ts +308 -0
  169. package/src/components/ResultsDialog.tsx +2 -1
  170. package/src/components/drill/index.ts +6 -0
  171. package/src/components/drill/resolveDrill.ts +22 -1
  172. package/src/components/drill/useDrill.spec.tsx +94 -0
  173. package/src/components/drill/useDrill.tsx +52 -12
  174. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  175. package/src/components/drill/useDrillSelf.ts +110 -0
  176. package/src/components/given/GivenInput.spec.tsx +196 -2
  177. package/src/components/given/GivenInput.tsx +300 -25
  178. package/src/components/given/GivensPanel.tsx +1 -1
  179. package/src/components/given/filterValue.spec.ts +112 -0
  180. package/src/components/given/filterValue.ts +188 -0
  181. package/src/components/given/index.ts +4 -0
  182. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  183. package/src/components/given/useGivenUrlParams.ts +87 -0
  184. package/src/components/index.ts +11 -3
  185. package/src/components/styles.ts +0 -37
  186. package/src/hooks/index.ts +13 -1
  187. package/src/hooks/useDocumentControls.ts +170 -0
  188. package/src/hooks/useGivensState.spec.ts +158 -0
  189. package/src/hooks/useGivensState.ts +114 -23
  190. package/src/hooks/useQueryResult.ts +82 -0
  191. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  192. package/src/hooks/useSuggestOptions.ts +94 -51
  193. package/src/utils/malloyLiteral.spec.ts +43 -0
  194. package/src/utils/malloyLiteral.ts +76 -0
  195. package/vite.config.ts +5 -1
  196. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  197. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  198. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  199. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  200. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  201. package/dist/components/Workbook/Workbook.d.ts +0 -7
  202. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  203. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  204. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  205. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  206. package/dist/components/Workbook/index.d.ts +0 -7
  207. package/dist/core-CWKmWEg2.cjs.js +0 -148
  208. package/dist/index-B0WyZAUA.es.js +0 -66412
  209. package/dist/index-kxVD1RjY.cjs.js +0 -356
  210. package/dist/markdown-editor.css +0 -341
  211. package/src/components/AnalyzePackageButton.tsx +0 -319
  212. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  213. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  214. package/src/components/Workbook/ModelPicker.tsx +0 -134
  215. package/src/components/Workbook/MutableCell.tsx +0 -458
  216. package/src/components/Workbook/Workbook.tsx +0 -501
  217. package/src/components/Workbook/WorkbookList.tsx +0 -110
  218. package/src/components/Workbook/WorkbookManager.ts +0 -214
  219. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  220. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  221. package/src/components/Workbook/index.ts +0 -10
@@ -0,0 +1,1098 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type {
5
+ DashboardDocument,
6
+ DashboardDrill,
7
+ DashboardSource,
8
+ DashboardTile,
9
+ } from "./document";
10
+ import type { LocalGiven } from "./document";
11
+ import {
12
+ artifactLine,
13
+ declarationLine,
14
+ declarationsUnder,
15
+ givenDeclarations,
16
+ } from "./malloyText";
17
+ import {
18
+ BINDING_CLAUSE,
19
+ blockAbove,
20
+ readDashboardDocument,
21
+ readFailed,
22
+ } from "./readDocument";
23
+
24
+ /**
25
+ * Write a change back into a `dashboards/*.malloy` file by PATCHING it.
26
+ *
27
+ * The builder does not regenerate the file. It rewrites the bytes it owns and
28
+ * leaves every other byte exactly where it was, which is what lets it edit a
29
+ * dashboard somebody else wrote: comments, formatting, declaration order and
30
+ * unmodelled Malloy all survive an edit because nothing rewrites them.
31
+ *
32
+ * The safety property is a SEMANTIC round-trip, not a byte one. After splicing,
33
+ * the result is read back and compared against the document that was asked for;
34
+ * a mismatch refuses the write. Byte-identity with a regenerated file would be
35
+ * a weaker thing to know, and would make every commented file read-only.
36
+ *
37
+ * A refused write NEVER discards the edit. The caller keeps its document and is
38
+ * told the writer produced something it could not read back — that is a defect
39
+ * in this module, not a mistake by the person editing.
40
+ *
41
+ * SCOPE, deliberately: a tile's presentation, its filter bindings, the order of
42
+ * tiles, and the dashboard's OWN givens — added, removed or retagged. Never an
43
+ * import, and never a model file: a filter the builder adds is a declaration in
44
+ * this file, which is the convention {@link LocalGiven} describes. And tiles
45
+ * ADDED or REMOVED: a new `view:` inside the extension of the source it reads
46
+ * (or a new extension, when the file imports that source by name), a removed
47
+ * one deleted with its `#` tags. Those moves are the one place the file cannot
48
+ * say who owns the comment beside a declaration, so the builder shows the diff
49
+ * before a structural save and the `//` comments are left where they were.
50
+ *
51
+ * A given is different from a tile in exactly the way that matters there: the
52
+ * `#` tags above its declaration are its control contract and have no other
53
+ * owner, so removing the declaration can take them with it, and a `//` comment
54
+ * in the same block is left where it is.
55
+ */
56
+
57
+ export interface SpliceFailure {
58
+ ok: false;
59
+ reason: string;
60
+ }
61
+
62
+ export type SpliceResult = { ok: true; source: string } | SpliceFailure;
63
+
64
+ /** Narrow to the failure arm; see {@link readFailed} for why a guard. */
65
+ export const spliceFailed = (result: SpliceResult): result is SpliceFailure =>
66
+ result.ok === false;
67
+
68
+ /**
69
+ * A stable serialisation for comparing documents.
70
+ *
71
+ * `JSON.stringify` is key-ORDER sensitive, and the two documents being compared
72
+ * are built differently: the reader emits properties in its own canonical order,
73
+ * while a caller that assigns `tile.label = …` appends that key at the end. The
74
+ * gate would then refuse a correct edit and report a writer defect that is
75
+ * really a serialisation artefact. Sorting keys compares the documents rather
76
+ * than the way they happen to be spelled.
77
+ */
78
+ function canonical(value: unknown): string {
79
+ const walk = (node: unknown): unknown => {
80
+ if (Array.isArray(node)) return node.map(walk);
81
+ if (node && typeof node === "object") {
82
+ const out: Record<string, unknown> = {};
83
+ for (const key of Object.keys(node as object).sort())
84
+ out[key] = walk((node as Record<string, unknown>)[key]);
85
+ return out;
86
+ }
87
+ return node;
88
+ };
89
+ return JSON.stringify(walk(value));
90
+ }
91
+
92
+ /** A byte-range replacement. Applied last-first so earlier offsets stay valid. */
93
+ interface Edit {
94
+ start: number;
95
+ end: number;
96
+ text: string;
97
+ }
98
+
99
+ /** Start offset of each line, so a line number can become a byte range. */
100
+ function lineStarts(source: string): number[] {
101
+ const starts = [0];
102
+ for (let i = 0; i < source.length; i++)
103
+ if (source[i] === "\n") starts.push(i + 1);
104
+ return starts;
105
+ }
106
+
107
+ function applyEdits(source: string, edits: Edit[]): string {
108
+ let out = source;
109
+ for (const edit of [...edits].sort((a, b) => b.start - a.start))
110
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
111
+ return out;
112
+ }
113
+
114
+ /** The `#` tags a tile's presentation implies, in the order they are written. */
115
+ function tagsFor(tile: DashboardTile): string[] {
116
+ const tags: string[] = [];
117
+ if (tile.colspan !== undefined) tags.push(`# colspan=${tile.colspan}`);
118
+ if (tile.break) tags.push("# break");
119
+ if (tile.borderless) tags.push("# borderless");
120
+ if (tile.label !== undefined) tags.push(`# label=${quoted(tile.label)}`);
121
+ if (tile.subtitle !== undefined)
122
+ tags.push(`# subtitle=${quoted(tile.subtitle)}`);
123
+ return tags;
124
+ }
125
+
126
+ /** Which property a tag line carries, so an existing line can be replaced. */
127
+ function tagKey(text: string): string | undefined {
128
+ const m = /^#\s*([a-z_]+)/.exec(text);
129
+ return m?.[1];
130
+ }
131
+
132
+ /**
133
+ * The tag keys the document MODELS, and therefore the only tag lines the
134
+ * writer may rewrite or remove. Every other `#` line on a tile — `# big_value`,
135
+ * `# bar_chart`, `# currency`, a host's own tag — is the renderer's, not ours,
136
+ * and survives an edit like any other unmodelled Malloy.
137
+ *
138
+ * Without this rule, unticking one filter on the storefront overview's KPI
139
+ * strip deleted its `# big_value` and the strip came back as a one-row table;
140
+ * the round-trip gate cannot catch that, because the projection never held
141
+ * the tag it lost.
142
+ */
143
+ const MODELLED_TAG_KEYS: ReadonlySet<string> = new Set([
144
+ "colspan",
145
+ "break",
146
+ "borderless",
147
+ "label",
148
+ "subtitle",
149
+ ]);
150
+
151
+ /**
152
+ * The same rule for a given: the keys {@link givenTagLine} writes are the only
153
+ * ones the writer may rewrite or remove. A routed annotation such as
154
+ * `#(secure)` has no key at all, so it is never ours, and a relabel that took
155
+ * it with the control contract would strip an access marker the projection
156
+ * cannot see it lost.
157
+ */
158
+ const MODELLED_GIVEN_TAG_KEYS: ReadonlySet<string> = new Set([
159
+ "label",
160
+ "description",
161
+ "control",
162
+ "suggest",
163
+ "range_min",
164
+ "range_max",
165
+ ]);
166
+
167
+ const isSameDocumentExceptTiles = (
168
+ a: DashboardDocument,
169
+ b: DashboardDocument,
170
+ ) => canonical(a.imports) === canonical(b.imports);
171
+
172
+ /**
173
+ * A given's tag line, composed from its control contract. One line, in the
174
+ * order `givens.malloy` writes them, so a file the builder wrote reads like one
175
+ * a person wrote.
176
+ */
177
+ function givenTagLine(given: LocalGiven): string | undefined {
178
+ const parts: string[] = [];
179
+ if (given.label !== undefined) parts.push(`label=${quoted(given.label)}`);
180
+ if (given.description !== undefined)
181
+ parts.push(`description=${quoted(given.description)}`);
182
+ if (given.control !== undefined) parts.push(`control=${given.control}`);
183
+ if (given.suggest) {
184
+ const by =
185
+ given.suggest.source !== undefined
186
+ ? `source=${given.suggest.source}`
187
+ : given.suggest.query !== undefined
188
+ ? `query=${given.suggest.query}`
189
+ : undefined;
190
+ parts.push(
191
+ `suggest { ${by ? `${by} ` : ""}dimension=${given.suggest.dimension} }`,
192
+ );
193
+ }
194
+ if (given.rangeMin !== undefined) parts.push(`range_min=${given.rangeMin}`);
195
+ if (given.rangeMax !== undefined) parts.push(`range_max=${given.rangeMax}`);
196
+ return parts.length > 0 ? `# ${parts.join(" ")}` : undefined;
197
+ }
198
+
199
+ /** `given: NAME :: type is default`, the one-line spelling the builder writes. */
200
+ const givenDeclaration = (given: LocalGiven) =>
201
+ `given: ${given.name} :: ${given.type} is ${given.default}`;
202
+
203
+ /**
204
+ * The last line of the declaration starting at `line`: the line itself for a
205
+ * one-line `view: x is y + { … }`, or the matching closing brace for a body
206
+ * (`view: x is {`, `source: s is b extend {`). Braces inside strings are not
207
+ * a concern Malloy dashboards have raised, so the count is plain.
208
+ */
209
+ function declarationEnd(lines: string[], line: number): number {
210
+ let depth = 0;
211
+ let opened = false;
212
+ for (let i = line; i < lines.length; i++) {
213
+ for (const ch of lines[i]) {
214
+ if (ch === "{") {
215
+ depth++;
216
+ opened = true;
217
+ } else if (ch === "}") depth--;
218
+ }
219
+ if (opened && depth <= 0) return i;
220
+ if (!opened && i === line) return i;
221
+ }
222
+ return lines.length - 1;
223
+ }
224
+
225
+ /** `# drill { to=… given=… }`, one line, as the reader spells it back. */
226
+ function drillTagLine(drill: DashboardDrill): string {
227
+ const to =
228
+ drill.to.length === 1
229
+ ? drill.to[0]
230
+ : `[${drill.to.map((d) => `"${d}"`).join(", ")}]`;
231
+ return `# drill { to=${to}${drill.given ? ` given=${drill.given}` : ""} }`;
232
+ }
233
+
234
+ const drillKey = (d: DashboardDrill) => `${d.source}.${d.name}`;
235
+
236
+ /** A tag string value, with the characters the tag parser unescapes escaped. */
237
+ const quoted = (text: string) =>
238
+ `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
239
+
240
+ /**
241
+ * One tile's identity, ignoring presentation and position — but not its
242
+ * declaration: a tile redeclared from another view is a different tile to
243
+ * the file, removed and added, which `document.tileKey` does not say.
244
+ */
245
+ const tileKey = (t: DashboardTile) =>
246
+ canonical([t.name, t.source, t.declaration]);
247
+
248
+ /** The tile list as identities, IN ORDER. Differs under a reorder. */
249
+ const tileIdentity = (document: DashboardDocument) =>
250
+ canonical(document.tiles.map(tileKey));
251
+
252
+ interface TileMembership {
253
+ currentKeys: Set<string>;
254
+ nextKeys: Set<string>;
255
+ removedTiles: DashboardTile[];
256
+ addedTiles: DashboardTile[];
257
+ newSources: DashboardSource[];
258
+ currentSources: Map<string, DashboardSource>;
259
+ reordered: boolean;
260
+ }
261
+
262
+ /** Everything a planner reads, and the edits it adds to. */
263
+ interface SpliceContext extends TileMembership {
264
+ sourceText: string;
265
+ lines: string[];
266
+ starts: number[];
267
+ wholeLine: (line: number) => { start: number; end: number };
268
+ indentOf: (line: number) => string;
269
+ current: DashboardDocument;
270
+ next: DashboardDocument;
271
+ edits: Edit[];
272
+ }
273
+
274
+ /**
275
+ * Which tiles and sources come and go between the two documents, and whether
276
+ * the change is one the builder may write at all.
277
+ */
278
+ function checkShape(
279
+ current: DashboardDocument,
280
+ next: DashboardDocument,
281
+ ): SpliceFailure | TileMembership {
282
+ // Tiles ADDED and REMOVED, by identity. A removed tile's declaration goes,
283
+ // with its `#` tags; a `//` comment above it stays, because the file cannot
284
+ // say whether it belonged to the tile, the row or the page, and a comment
285
+ // left behind is a smaller wrong than one destroyed — and the builder shows
286
+ // this diff before it saves. An added tile is a `view:` in the extension of
287
+ // the source it reads, or a new extension when the file has none yet.
288
+ //
289
+ // REORDERING is neither: a tile's position is the `tiles=[…]` array on the
290
+ // `## artifact` tag, and moving a tile there moves no declaration.
291
+ const currentKeys = new Set(current.tiles.map(tileKey));
292
+ const nextKeys = new Set(next.tiles.map(tileKey));
293
+ const removedTiles = current.tiles.filter((t) => !nextKeys.has(tileKey(t)));
294
+ const addedTiles = next.tiles.filter((t) => !currentKeys.has(tileKey(t)));
295
+ const membershipChanged = removedTiles.length > 0 || addedTiles.length > 0;
296
+ const reordered =
297
+ membershipChanged || tileIdentity(current) !== tileIdentity(next);
298
+ for (const tile of addedTiles) {
299
+ if (tile.declaration.kind !== "reference") {
300
+ return {
301
+ ok: false,
302
+ reason:
303
+ `A new tile names a view of a source; \`${tile.name}\` is ` +
304
+ `${tile.declaration.kind === "inline" ? "an inline query" : "not declared here"}, ` +
305
+ `which the builder cannot write.`,
306
+ };
307
+ }
308
+ }
309
+ // Sources may only be ADDED, and only for a tile being added on them — the
310
+ // builder never renames or removes an extension, and never edits imports,
311
+ // so a new extension's base has to be a source the file already imports by
312
+ // name (or already extends).
313
+ const currentSources = new Map(current.sources.map((s) => [s.name, s]));
314
+ const importedByName = new Set(
315
+ current.imports.flatMap((i) => (i.kind === "names" ? i.names : [])),
316
+ );
317
+ for (const source of current.sources) importedByName.add(source.base);
318
+ const newSources = next.sources.filter((s) => !currentSources.has(s.name));
319
+ for (const source of current.sources) {
320
+ const still = next.sources.find((s) => s.name === source.name);
321
+ if (!still || still.base !== source.base) {
322
+ return {
323
+ ok: false,
324
+ reason: `The source \`${source.name}\` cannot be changed or removed here.`,
325
+ };
326
+ }
327
+ }
328
+ for (const source of newSources) {
329
+ if (!addedTiles.some((t) => t.source === source.name)) {
330
+ return {
331
+ ok: false,
332
+ reason: `A new source \`${source.name}\` needs a tile on it.`,
333
+ };
334
+ }
335
+ if (!importedByName.has(source.base)) {
336
+ return {
337
+ ok: false,
338
+ reason:
339
+ `\`${source.base}\` is not imported by name in this file, so a ` +
340
+ `tile cannot be put on it. The builder does not add imports: ` +
341
+ `import { ${source.base} } from the model first.`,
342
+ };
343
+ }
344
+ }
345
+ if (!isSameDocumentExceptTiles(current, next)) {
346
+ return {
347
+ ok: false,
348
+ reason: "The dashboard's imports cannot be changed here.",
349
+ };
350
+ }
351
+ return {
352
+ currentKeys,
353
+ nextKeys,
354
+ removedTiles,
355
+ addedTiles,
356
+ newSources,
357
+ currentSources,
358
+ reordered,
359
+ };
360
+ }
361
+
362
+ function planOrder(ctx: SpliceContext): SpliceFailure | undefined {
363
+ const { lines, wholeLine, next, reordered, currentKeys, nextKeys, edits } =
364
+ ctx;
365
+ // A reorder is one rewritten array on the `## artifact` line. Each entry is
366
+ // re-emitted AS IT WAS WRITTEN rather than rebuilt from `source` and `name`,
367
+ // so a file that spells a tile `overview->kpis` keeps its spelling and the
368
+ // diff is the reordering and nothing else.
369
+ if (reordered) {
370
+ const artifactAt = artifactLine(lines);
371
+ if (artifactAt < 0) {
372
+ return {
373
+ ok: false,
374
+ reason: "Could not find the `## artifact` tag to reorder.",
375
+ };
376
+ }
377
+ const written = [...lines[artifactAt].matchAll(/"([^"]+)"/g)].map(
378
+ (m) => m[1],
379
+ );
380
+ const byKey = new Map<string, string>();
381
+ for (const entry of written) {
382
+ const parts = entry.split("->").map((part) => part.trim());
383
+ if (parts.length === 2) byKey.set(`${parts[0]}->${parts[1]}`, entry);
384
+ }
385
+ // An existing tile keeps its spelling; a new one is written canonically.
386
+ const nextEntries = next.tiles.map(
387
+ (tile) =>
388
+ byKey.get(`${tile.source}->${tile.name}`) ??
389
+ (nextKeys.has(tileKey(tile)) && !currentKeys.has(tileKey(tile))
390
+ ? `${tile.source} -> ${tile.name}`
391
+ : undefined),
392
+ );
393
+ if (nextEntries.some((entry) => entry === undefined)) {
394
+ return {
395
+ ok: false,
396
+ reason:
397
+ "A tile in the new order is not one the `## artifact` tag names.",
398
+ };
399
+ }
400
+ const list = `tiles=[${nextEntries.map((e) => `"${e}"`).join(", ")}]`;
401
+ // The `## artifact` tag must stay on ONE line or the package fails to
402
+ // compile, so the array is replaced in place rather than reformatted.
403
+ const rewritten = lines[artifactAt].replace(
404
+ /tiles\s*=\s*\[[\s\S]*?\]/,
405
+ list,
406
+ );
407
+ if (rewritten !== lines[artifactAt])
408
+ edits.push({ ...wholeLine(artifactAt), text: `${rewritten}\n` });
409
+ }
410
+ return undefined;
411
+ }
412
+
413
+ function planSettings(ctx: SpliceContext): SpliceFailure | undefined {
414
+ const { lines, wholeLine, current, next, edits } = ctx;
415
+ // THE PAGE'S OWN SETTINGS. Title, autorun and starting values are
416
+ // properties on the one-line `## artifact { … }` tag; the grid width is the
417
+ // `dashboard { columns=N }` beside it; the description is the run of `##"`
418
+ // lines above. Each is patched in place on its own line, so the tag stays
419
+ // on one line — the package fails to compile otherwise — and a property
420
+ // the file spells its own way keeps that spelling when it did not change.
421
+ if (
422
+ current.title !== next.title ||
423
+ current.autorun !== next.autorun ||
424
+ current.columns !== next.columns ||
425
+ canonical(current.startingGivens) !== canonical(next.startingGivens)
426
+ ) {
427
+ const artifactAt = artifactLine(lines);
428
+ if (artifactAt < 0) {
429
+ return {
430
+ ok: false,
431
+ reason:
432
+ "Could not find the `## artifact` tag to change the page's settings.",
433
+ };
434
+ }
435
+ // Whatever the reorder wrote to this line is the text to patch further.
436
+ const already = edits.find(
437
+ (edit) =>
438
+ edit.start === wholeLine(artifactAt).start &&
439
+ edit.end === wholeLine(artifactAt).end,
440
+ );
441
+ let line = already ? already.text.replace(/\n$/, "") : lines[artifactAt];
442
+ // The artifact tag's braces: everything up to the matching `}`.
443
+ const open = line.indexOf("artifact");
444
+ const braceOpen = line.indexOf("{", open);
445
+ let depth = 0;
446
+ let braceClose = -1;
447
+ for (let i = braceOpen; i < line.length; i++) {
448
+ if (line[i] === "{") depth++;
449
+ else if (line[i] === "}" && --depth === 0) {
450
+ braceClose = i;
451
+ break;
452
+ }
453
+ }
454
+ if (braceOpen < 0 || braceClose < 0) {
455
+ return {
456
+ ok: false,
457
+ reason: "Could not read the `## artifact { … }` tag.",
458
+ };
459
+ }
460
+ let inner = line.slice(braceOpen + 1, braceClose);
461
+ const setProperty = (key: string, value: string | undefined) => {
462
+ const re = new RegExp(
463
+ `\\s*\\b${key}=(?:"(?:[^"\\\\]|\\\\.)*"|[^\\s}]+)`,
464
+ );
465
+ if (value === undefined) inner = inner.replace(re, "");
466
+ else if (re.test(inner)) inner = inner.replace(re, ` ${key}=${value}`);
467
+ else inner = `${inner.replace(/\s+$/, "")} ${key}=${value} `;
468
+ };
469
+ if (current.title !== next.title)
470
+ setProperty("title", next.title ? quoted(next.title) : undefined);
471
+ if (current.autorun !== next.autorun)
472
+ setProperty(
473
+ "autorun",
474
+ next.autorun === undefined ? undefined : String(next.autorun),
475
+ );
476
+ if (
477
+ canonical(current.startingGivens) !== canonical(next.startingGivens)
478
+ ) {
479
+ inner = inner.replace(/\s*\bgivens\s*\{[^}]*\}/, "");
480
+ const entries = Object.entries(next.startingGivens ?? {});
481
+ // Quoted: a tag value is a string, and the reader hands back the
482
+ // string's text — `CATEGORY="Jeans"` reads as `Jeans`, which is
483
+ // what the document holds and what is written back here.
484
+ if (entries.length > 0)
485
+ inner = `${inner.replace(/\s+$/, "")} givens { ${entries
486
+ .map(([k, v]) => `${k}=${quoted(v)}`)
487
+ .join(" ")} }`;
488
+ }
489
+ inner = inner.replace(/\s{2,}/g, " ");
490
+ line = `${line.slice(0, braceOpen + 1)}${inner.startsWith(" ") ? inner : ` ${inner}`}${inner.endsWith(" ") ? "" : " "}${line.slice(braceClose)}`;
491
+ if (current.columns !== next.columns) {
492
+ line = line.replace(/\s*dashboard\s*\{[^}]*\}/, "");
493
+ if (next.columns !== undefined)
494
+ line = `${line.trimEnd()} dashboard { columns=${next.columns} }`;
495
+ }
496
+ if (already) already.text = `${line}\n`;
497
+ else edits.push({ ...wholeLine(artifactAt), text: `${line}\n` });
498
+ }
499
+ if (current.description !== next.description) {
500
+ // The run of `##"` lines, wherever it is; a new one goes above the tag.
501
+ const docLines = lines
502
+ .map((l, i) => (l.trim().startsWith('##"') ? i : -1))
503
+ .filter((i) => i >= 0);
504
+ const text = (next.description ?? "")
505
+ .split("\n")
506
+ .map((para) => (para.trim() === "" ? '##"' : `##" ${para.trim()}`))
507
+ .join("\n");
508
+ if (docLines.length > 0) {
509
+ const first = docLines[0];
510
+ const last = docLines[docLines.length - 1];
511
+ edits.push({
512
+ start: wholeLine(first).start,
513
+ end: wholeLine(last).end,
514
+ text: next.description === undefined ? "" : `${text}\n`,
515
+ });
516
+ } else if (next.description !== undefined) {
517
+ const artifactAt = artifactLine(lines);
518
+ const at = wholeLine(artifactAt).start;
519
+ edits.push({ start: at, end: at, text: `${text}\n` });
520
+ }
521
+ }
522
+ return undefined;
523
+ }
524
+
525
+ function planGivens(ctx: SpliceContext): SpliceFailure | undefined {
526
+ const { lines, wholeLine, indentOf, current, next, edits } = ctx;
527
+ // THE DASHBOARD'S OWN GIVENS. Added, removed, or retagged — by name, since
528
+ // a given's name is its identity in every `where:` that reads it.
529
+ const givensBefore = new Map(
530
+ (current.localGivens ?? []).map((g) => [g.name, g]),
531
+ );
532
+ const givensAfter = new Map(
533
+ (next.localGivens ?? []).map((g) => [g.name, g]),
534
+ );
535
+ const declared = givenDeclarations(lines);
536
+ const removedLines = new Set<number>();
537
+
538
+ for (const [name, was] of givensBefore) {
539
+ const want = givensAfter.get(name);
540
+ if (want !== undefined && canonical(want) === canonical(was)) continue;
541
+ const at = declared.get(name);
542
+ if (at === undefined) {
543
+ return {
544
+ ok: false,
545
+ reason: `Could not find where the given \`${name}\` is declared.`,
546
+ };
547
+ }
548
+ // Only the keys this document models are the writer's to rewrite. A
549
+ // removed declaration is the exception and takes every tag with it: a
550
+ // `#` line left behind does not lapse, it attaches to whatever is
551
+ // declared next, so an orphaned `#(secure)` would silently move.
552
+ const { tags } = blockAbove(lines, at.line);
553
+ const owned =
554
+ want === undefined
555
+ ? tags
556
+ : tags.filter((tag) => {
557
+ const key = tagKey(tag.text);
558
+ return key !== undefined && MODELLED_GIVEN_TAG_KEYS.has(key);
559
+ });
560
+ for (const tag of owned) {
561
+ edits.push({ ...wholeLine(tag.line), text: "" });
562
+ removedLines.add(tag.line);
563
+ }
564
+ if (want === undefined) {
565
+ edits.push({ ...wholeLine(at.line), text: "" });
566
+ removedLines.add(at.line);
567
+ // A declaration set off by blank lines takes one of them with it, or
568
+ // the two separators meet and the file gains an empty line per edit.
569
+ const first = Math.min(at.line, ...tags.map((tag) => tag.line));
570
+ const above = at.blockHeader ?? first;
571
+ const belowIsBlank = (lines[at.line + 1] ?? "x").trim() === "";
572
+ const aboveIsBlank = above === 0 || lines[above - 1].trim() === "";
573
+ const lastInBlock =
574
+ at.blockHeader === undefined ||
575
+ ![...declared.values()].some(
576
+ (other) =>
577
+ other.blockHeader === at.blockHeader &&
578
+ other.line > at.line &&
579
+ givensAfter.has(
580
+ [...declared.entries()].find(
581
+ ([, v]) => v === other,
582
+ )?.[0] ?? "",
583
+ ),
584
+ );
585
+ if (
586
+ belowIsBlank &&
587
+ aboveIsBlank &&
588
+ lastInBlock &&
589
+ !removedLines.has(at.line + 1)
590
+ ) {
591
+ edits.push({ ...wholeLine(at.line + 1), text: "" });
592
+ removedLines.add(at.line + 1);
593
+ }
594
+ continue;
595
+ }
596
+ // Retagged, or redeclared: the tag line is rewritten above the
597
+ // declaration, and the declaration itself only if its type or default
598
+ // changed — a block-form declaration keeps its own spelling.
599
+ const indent = indentOf(at.line);
600
+ const tagLine = givenTagLine(want);
601
+ const declarationChanged =
602
+ want.type !== was.type || want.default !== was.default;
603
+ const declaration = declarationChanged
604
+ ? at.blockHeader === undefined
605
+ ? givenDeclaration(want)
606
+ : `${want.name} :: ${want.type} is ${want.default}`
607
+ : lines[at.line].trim();
608
+ edits.push({
609
+ ...wholeLine(at.line),
610
+ text:
611
+ (tagLine ? `${indent}${tagLine}\n` : "") +
612
+ `${indent}${declaration}\n`,
613
+ });
614
+ }
615
+
616
+ // A block whose every declaration went has to lose its `given:` header too,
617
+ // or the file stops compiling on an empty block.
618
+ for (const [name, at] of declared) {
619
+ if (at.blockHeader === undefined || givensAfter.has(name)) continue;
620
+ const siblingsLeft = [...declared.values()].some(
621
+ (other) =>
622
+ other.blockHeader === at.blockHeader &&
623
+ !removedLines.has(other.line),
624
+ );
625
+ if (!siblingsLeft && !removedLines.has(at.blockHeader)) {
626
+ edits.push({ ...wholeLine(at.blockHeader), text: "" });
627
+ removedLines.add(at.blockHeader);
628
+ }
629
+ }
630
+
631
+ const added = [...givensAfter.values()].filter(
632
+ (g) => !givensBefore.has(g.name),
633
+ );
634
+ if (added.length > 0) {
635
+ // A new given goes with the others: after the last one declared, or —
636
+ // for a file declaring its first — after the imports, where a reader
637
+ // expects the page's own declarations to begin.
638
+ const lastGiven = Math.max(
639
+ -1,
640
+ ...[...declared.values()].map((at) => at.line),
641
+ );
642
+ const lastImport = (() => {
643
+ let found = -1;
644
+ for (let i = 0; i < lines.length; i++) {
645
+ const text = lines[i].trim();
646
+ if (text.startsWith("import ")) found = i;
647
+ // A multi-line `import { … } from "…"` ends on its `from` line.
648
+ else if (found >= 0 && /^}\s*from\s/.test(text)) found = i;
649
+ }
650
+ return found;
651
+ })();
652
+ const anchor = lastGiven >= 0 ? lastGiven : lastImport;
653
+ const block = added
654
+ .map((given) => {
655
+ const tagLine = givenTagLine(given);
656
+ return (
657
+ (tagLine ? `${tagLine}\n` : "") + `${givenDeclaration(given)}\n`
658
+ );
659
+ })
660
+ .join("\n");
661
+ const at = anchor >= 0 ? wholeLine(anchor).end : wholeLine(0).end;
662
+ edits.push({ start: at, end: at, text: `\n${block}` });
663
+
664
+ // A file declaring a given needs the experiment switched on, at the top,
665
+ // where every file in this repository that declares one puts it.
666
+ const hasSwitch = lines.some((l) =>
667
+ l.trim().startsWith("##! experimental.givens"),
668
+ );
669
+ if (!hasSwitch)
670
+ edits.push({ start: 0, end: 0, text: "##! experimental.givens\n" });
671
+ }
672
+ return undefined;
673
+ }
674
+
675
+ function planDrills(ctx: SpliceContext): SpliceFailure | undefined {
676
+ const { lines, wholeLine, indentOf, current, next, edits } = ctx;
677
+ // DRILLS. A drill is one `# drill` tag on a dimension THIS FILE declares —
678
+ // added above the declaration, rewritten, or taken off. The dimension itself
679
+ // is never written: a dimension no view reads is a dead drill, and the
680
+ // builder does not edit views, so the author declares the dimension and the
681
+ // builder makes it clickable.
682
+ const drillsBefore = new Map(
683
+ (current.drills ?? []).map((d) => [drillKey(d), d]),
684
+ );
685
+ const drillsAfter = new Map(
686
+ (next.drills ?? []).map((d) => [drillKey(d), d]),
687
+ );
688
+ for (const key of new Set([...drillsBefore.keys(), ...drillsAfter.keys()])) {
689
+ const was = drillsBefore.get(key);
690
+ const want = drillsAfter.get(key);
691
+ if (was && want && canonical(was) === canonical(want)) continue;
692
+ const drill = (want ?? was) as DashboardDrill;
693
+ if (want && want.to.length === 0) {
694
+ return {
695
+ ok: false,
696
+ reason: `The drill on \`${key}\` names no destination.`,
697
+ };
698
+ }
699
+ const at = declarationsUnder(lines, drill.source, "dimension").get(
700
+ drill.name,
701
+ );
702
+ if (at === undefined) {
703
+ return {
704
+ ok: false,
705
+ reason:
706
+ `\`${drill.name}\` is not a dimension \`${drill.source}\` declares ` +
707
+ `in this file, so a drill cannot be put on it here.`,
708
+ };
709
+ }
710
+ const { tags } = blockAbove(lines, at.line);
711
+ const existing = tags.find((tag) => /^#\s*drill\b/.test(tag.text));
712
+ const indent = indentOf(at.line);
713
+ if (want === undefined) {
714
+ if (existing) edits.push({ ...wholeLine(existing.line), text: "" });
715
+ } else if (existing) {
716
+ edits.push({
717
+ ...wholeLine(existing.line),
718
+ text: `${indent}${drillTagLine(want)}\n`,
719
+ });
720
+ } else {
721
+ // Directly above the declaration, under any other tags it has.
722
+ const start = wholeLine(at.line).start;
723
+ edits.push({
724
+ start,
725
+ end: start,
726
+ text: `${indent}${drillTagLine(want)}\n`,
727
+ });
728
+ }
729
+ }
730
+ return undefined;
731
+ }
732
+
733
+ function planRemovedTiles(ctx: SpliceContext): SpliceFailure | undefined {
734
+ const { lines, wholeLine, removedTiles, edits } = ctx;
735
+ // REMOVED TILES: the declaration and its `#` tags. An inline view's body
736
+ // runs to its closing brace; a reference is one line. An inherited tile has
737
+ // nothing here to remove — its entry left the artifact list above.
738
+ for (const tile of removedTiles) {
739
+ if (tile.declaration.kind === "inherited") continue;
740
+ const declLine = declarationLine(lines, "view", tile.name);
741
+ if (declLine < 0) {
742
+ return {
743
+ ok: false,
744
+ reason: `Could not find where \`${tile.name}\` is declared.`,
745
+ };
746
+ }
747
+ const endLine = declarationEnd(lines, declLine);
748
+ const { tags } = blockAbove(lines, declLine);
749
+ const first = Math.min(declLine, ...tags.map((t) => t.line));
750
+ for (const tag of tags) edits.push({ ...wholeLine(tag.line), text: "" });
751
+ edits.push({
752
+ start: wholeLine(declLine).start,
753
+ end: wholeLine(endLine).end,
754
+ text: "",
755
+ });
756
+ // The blank line after it goes too when what came before was a blank
757
+ // line or the extension's opening brace — otherwise two separators meet,
758
+ // or the body starts with an empty line. It STAYS after a `//` comment
759
+ // that is being left behind: closing the gap would hand that comment to
760
+ // the next tile, which is the ownership guess this whole rule avoids.
761
+ const before = first === 0 ? "" : lines[first - 1].trim();
762
+ if (
763
+ (lines[endLine + 1] ?? "x").trim() === "" &&
764
+ (first === 0 || before === "" || before.endsWith("{"))
765
+ )
766
+ edits.push({ ...wholeLine(endLine + 1), text: "" });
767
+ }
768
+ return undefined;
769
+ }
770
+
771
+ function planAddedTiles(ctx: SpliceContext): SpliceFailure | undefined {
772
+ const {
773
+ sourceText,
774
+ lines,
775
+ wholeLine,
776
+ current,
777
+ addedTiles,
778
+ newSources,
779
+ currentSources,
780
+ edits,
781
+ } = ctx;
782
+ // ADDED TILES: a `view:` with its tags, inside the extension of the source
783
+ // the tile reads — before that extension's closing brace — or in a new
784
+ // extension after the last one, when the file has none for that source.
785
+ const byExtension = new Map<string, DashboardTile[]>();
786
+ for (const tile of addedTiles) {
787
+ const list = byExtension.get(tile.source) ?? [];
788
+ list.push(tile);
789
+ byExtension.set(tile.source, list);
790
+ }
791
+ const declarationOf = (tile: DashboardTile, indent: string) => {
792
+ const from =
793
+ tile.declaration.kind === "reference"
794
+ ? tile.declaration.from
795
+ : tile.name;
796
+ const bindings = (tile.filters ?? [])
797
+ .map((f) => `where: ${f.field} ${f.op ?? "~"} $${f.given}`)
798
+ .join(", ");
799
+ return [
800
+ ...tagsFor(tile).map((tag) => `${indent}${tag}`),
801
+ `${indent}view: ${tile.name} is ${from}${bindings ? ` + { ${bindings} }` : ""}`,
802
+ ].join("\n");
803
+ };
804
+ let lastExtensionEnd = -1;
805
+ for (const source of current.sources) {
806
+ const open = declarationLine(lines, "source", source.name);
807
+ if (open >= 0)
808
+ lastExtensionEnd = Math.max(
809
+ lastExtensionEnd,
810
+ declarationEnd(lines, open),
811
+ );
812
+ }
813
+ for (const [sourceName, tiles] of byExtension) {
814
+ if (currentSources.has(sourceName)) {
815
+ const open = declarationLine(lines, "source", sourceName);
816
+ if (open < 0) {
817
+ return {
818
+ ok: false,
819
+ reason: `Could not find where the source \`${sourceName}\` is declared.`,
820
+ };
821
+ }
822
+ const close = declarationEnd(lines, open);
823
+ // The indent the extension already uses for its views, else two spaces.
824
+ let indent = " ";
825
+ for (let i = open + 1; i < close; i++) {
826
+ const m = /^(\s+)view:/.exec(lines[i]);
827
+ if (m) {
828
+ indent = m[1];
829
+ break;
830
+ }
831
+ }
832
+ // Before the closing brace, set off by a blank line from what precedes.
833
+ const at = wholeLine(close).start;
834
+ const precededByBlank = (lines[close - 1] ?? "").trim() === "";
835
+ edits.push({
836
+ start: at,
837
+ end: at,
838
+ text:
839
+ (precededByBlank ? "" : "\n") +
840
+ tiles.map((tile) => declarationOf(tile, indent)).join("\n\n") +
841
+ "\n",
842
+ });
843
+ } else {
844
+ const source = newSources.find((s) => s.name === sourceName);
845
+ if (!source) {
846
+ return {
847
+ ok: false,
848
+ reason: `The tile's source \`${sourceName}\` is not declared.`,
849
+ };
850
+ }
851
+ const block =
852
+ `\nsource: ${source.name} is ${source.base} extend {\n` +
853
+ tiles.map((tile) => declarationOf(tile, " ")).join("\n\n") +
854
+ "\n}\n";
855
+ // After the last extension; failing that, after the last given or
856
+ // import, where the page's own declarations begin.
857
+ let anchor = lastExtensionEnd;
858
+ if (anchor < 0) {
859
+ for (let i = 0; i < lines.length; i++) {
860
+ const text = lines[i].trim();
861
+ if (
862
+ /^(import\s|given:|}\s*from\s)/.test(text) ||
863
+ /^[A-Z_]+\s*::/.test(text)
864
+ )
865
+ anchor = i;
866
+ }
867
+ }
868
+ const at = anchor >= 0 ? wholeLine(anchor).end : sourceText.length;
869
+ // A file that ends without a newline needs one before the block.
870
+ const separator =
871
+ at === sourceText.length && !sourceText.endsWith("\n") ? "\n" : "";
872
+ edits.push({ start: at, end: at, text: separator + block });
873
+ lastExtensionEnd = anchor;
874
+ }
875
+ }
876
+ return undefined;
877
+ }
878
+
879
+ function planTilePresentation(ctx: SpliceContext): SpliceFailure | undefined {
880
+ const { lines, starts, wholeLine, indentOf, current, next, edits } = ctx;
881
+ // Presentation edits are matched by IDENTITY, not by position: after a
882
+ // reorder `next.tiles[i]` and `current.tiles[i]` are different tiles, and
883
+ // comparing them pairwise would report every moved tile as changed and
884
+ // rewrite tags that nobody touched.
885
+ const currentByKey = new Map(current.tiles.map((t) => [tileKey(t), t]));
886
+
887
+ for (const tile of next.tiles) {
888
+ const was = currentByKey.get(tileKey(tile));
889
+ // Written whole above, tags and all.
890
+ if (was === undefined) continue;
891
+ if (canonical(was) === canonical(tile)) continue;
892
+
893
+ // An inherited tile is declared in the model, not here, so there is
894
+ // nothing in this file to patch. Saying so beats writing a tag that would
895
+ // land on the wrong object.
896
+ if (tile.declaration.kind === "inherited") {
897
+ return {
898
+ ok: false,
899
+ reason:
900
+ `\`${tile.source} -> ${tile.name}\` is declared on its source, ` +
901
+ `not in this dashboard, so its presentation cannot be changed here.`,
902
+ };
903
+ }
904
+
905
+ const declLine = lines.findIndex((l) =>
906
+ new RegExp(`view:\\s*${tile.name}\\s+is\\b`).test(l),
907
+ );
908
+ if (declLine < 0) {
909
+ return {
910
+ ok: false,
911
+ reason: `Could not find where \`${tile.name}\` is declared.`,
912
+ };
913
+ }
914
+
915
+ const { tags } = blockAbove(lines, declLine);
916
+ const indent = indentOf(declLine);
917
+ const wanted = tagsFor(tile);
918
+ const wantedByKey = new Map(
919
+ wanted.map((text) => [tagKey(text) ?? text, text]),
920
+ );
921
+ const seen = new Set<string>();
922
+
923
+ // Existing tag lines are patched or removed IN PLACE, so anything else in
924
+ // the block — a comment explaining the tile — keeps its position.
925
+ for (const tag of tags) {
926
+ const key = tagKey(tag.text);
927
+ // Not a property this document models: not ours to touch.
928
+ if (key === undefined || !MODELLED_TAG_KEYS.has(key)) continue;
929
+ const want = wantedByKey.get(key);
930
+ if (want === undefined) {
931
+ // Removed: take the whole line, including its newline.
932
+ edits.push({ ...wholeLine(tag.line), text: "" });
933
+ continue;
934
+ }
935
+ seen.add(key);
936
+ if (want !== tag.text)
937
+ edits.push({ ...wholeLine(tag.line), text: `${indent}${want}\n` });
938
+ }
939
+
940
+ // New tags go immediately above the declaration, which is where a reader
941
+ // looks for them and where `blockAbove` will find them again.
942
+ const added = wanted.filter((text) => !seen.has(tagKey(text) ?? text));
943
+ if (added.length > 0) {
944
+ const at = starts[declLine];
945
+ edits.push({
946
+ start: at,
947
+ end: at,
948
+ text: added.map((text) => `${indent}${text}\n`).join(""),
949
+ });
950
+ }
951
+
952
+ // The filter bindings live in the declaration itself, as a refinement.
953
+ // Only the BINDING clauses are ours to rewrite: a `limit:`, an `order_by:`
954
+ // or a `where:` on a literal that someone put in the same refinement is
955
+ // unmodelled Malloy and stays, ahead of the bindings, exactly as written.
956
+ const existing =
957
+ /\+\s*\{([\s\S]*)\}\s*$/.exec(lines[declLine])?.[1] ?? "";
958
+ const kept = existing
959
+ .replace(BINDING_CLAUSE, "")
960
+ .replace(/\s*,\s*,\s*/g, ", ")
961
+ .replace(/^[\s,;]+|[\s,;]+$/g, "");
962
+ const bindings = (tile.filters ?? []).map(
963
+ (f) => `where: ${f.field} ${f.op ?? "~"} $${f.given}`,
964
+ );
965
+ const clauses = [...(kept ? [kept] : []), ...bindings];
966
+ const withoutRefinement = lines[declLine].replace(
967
+ /\s*\+\s*\{[\s\S]*\}\s*$/,
968
+ "",
969
+ );
970
+ const rewritten =
971
+ clauses.length === 0
972
+ ? withoutRefinement
973
+ : `${withoutRefinement} + { ${clauses.join(", ")} }`;
974
+ if (rewritten !== lines[declLine])
975
+ edits.push({ ...wholeLine(declLine), text: `${rewritten}\n` });
976
+ }
977
+ return undefined;
978
+ }
979
+
980
+ export async function spliceDashboardDocument(
981
+ sourceText: string,
982
+ next: DashboardDocument,
983
+ ): Promise<SpliceResult> {
984
+ const before = await readDashboardDocument(sourceText);
985
+ if (readFailed(before)) {
986
+ return {
987
+ ok: false,
988
+ reason: `Cannot edit a file that will not open: ${before.reason}`,
989
+ };
990
+ }
991
+ const current = before.document;
992
+ const shape = checkShape(current, next);
993
+ if ("reason" in shape) return shape;
994
+
995
+ const lines = sourceText.split("\n");
996
+ const starts = lineStarts(sourceText);
997
+ const wholeLine = (line: number): { start: number; end: number } => ({
998
+ start: starts[line],
999
+ end: line + 1 < starts.length ? starts[line + 1] : sourceText.length,
1000
+ });
1001
+ const indentOf = (line: number) => /^\s*/.exec(lines[line])?.[0] ?? "";
1002
+
1003
+ const edits: Edit[] = [];
1004
+ const ctx: SpliceContext = {
1005
+ ...shape,
1006
+ sourceText,
1007
+ lines,
1008
+ starts,
1009
+ wholeLine,
1010
+ indentOf,
1011
+ current,
1012
+ next,
1013
+ edits,
1014
+ };
1015
+
1016
+ // Each concern plans its own edits against the file as it stands; the
1017
+ // order matters only where one patches a line another rewrote, which the
1018
+ // settings planner handles by patching the reorder's text.
1019
+ for (const plan of [
1020
+ planOrder,
1021
+ planSettings,
1022
+ planGivens,
1023
+ planDrills,
1024
+ planRemovedTiles,
1025
+ planAddedTiles,
1026
+ planTilePresentation,
1027
+ ]) {
1028
+ const failure = plan(ctx);
1029
+ if (failure) return failure;
1030
+ }
1031
+
1032
+ // Drills are compared as a set: their order is the file's, and a caller
1033
+ // appending one to the array has no way to know where its dimension sits.
1034
+ //
1035
+ // An optional collection the reader omits and a caller materialises as `[]`
1036
+ // are the same document, so they compare equal. Without that, a host that
1037
+ // normalises its shape asks for no change, gets no edits, and would be told
1038
+ // its save did not produce what it asked for.
1039
+ const comparable = (document: DashboardDocument): DashboardDocument => {
1040
+ const { drills, localGivens, ...rest } = document;
1041
+ const tiles = document.tiles.map((tile) => {
1042
+ if (tile.filters?.length) return tile;
1043
+ const { filters: _filters, ...tileRest } = tile;
1044
+ return tileRest as DashboardTile;
1045
+ });
1046
+ return {
1047
+ ...rest,
1048
+ tiles,
1049
+ ...(drills?.length
1050
+ ? {
1051
+ drills: [...drills].sort((a, b) =>
1052
+ drillKey(a).localeCompare(drillKey(b)),
1053
+ ),
1054
+ }
1055
+ : {}),
1056
+ ...(localGivens?.length ? { localGivens } : {}),
1057
+ } as DashboardDocument;
1058
+ };
1059
+
1060
+ // No edit means no planner found anything to place. That is only correct if
1061
+ // the document asked for is the one already on disk -- otherwise the ask
1062
+ // fell through every planner and returning `ok` would report a write that
1063
+ // never happened.
1064
+ if (edits.length === 0) {
1065
+ if (canonical(comparable(current)) !== canonical(comparable(next))) {
1066
+ return {
1067
+ ok: false,
1068
+ reason:
1069
+ "The edit did not produce the dashboard that was asked for, so it " +
1070
+ "was not written. Your changes are still here.",
1071
+ };
1072
+ }
1073
+ return { ok: true, source: sourceText };
1074
+ }
1075
+
1076
+ const spliced = applyEdits(sourceText, edits);
1077
+
1078
+ // The gate. Read back what was actually written and compare it against what
1079
+ // was asked for. Comments survived because they were never rewritten;
1080
+ // correctness is established here rather than assumed.
1081
+ const after = await readDashboardDocument(spliced);
1082
+ if (readFailed(after)) {
1083
+ return {
1084
+ ok: false,
1085
+ reason: `The edit produced a file that cannot be read back: ${after.reason}`,
1086
+ };
1087
+ }
1088
+ if (canonical(comparable(after.document)) !== canonical(comparable(next))) {
1089
+ return {
1090
+ ok: false,
1091
+ reason:
1092
+ "The edit did not produce the dashboard that was asked for, so it " +
1093
+ "was not written. Your changes are still here.",
1094
+ };
1095
+ }
1096
+
1097
+ return { ok: true, source: spliced };
1098
+ }