@malloy-publisher/sdk 0.9.0 → 0.9.2

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 (292) hide show
  1. package/dist/{Dashboard-H1kJlDFo.es.js → DashboardTile-BFcxdv7R.es.js} +15918 -17760
  2. package/dist/DashboardTile-sg8LjUk8.cjs.js +137 -0
  3. package/dist/RenderedResult-B48wAjM8.cjs.js +141 -0
  4. package/dist/{RenderedResult-BRgIgxWh.es.js → RenderedResult-CBLHr32C.es.js} +193 -183
  5. package/dist/{ServerProvider-Boxrv6Ym.es.js → ServerProvider-DCV8BUWD.es.js} +529 -521
  6. package/dist/ServerProvider-HRqT3w1C.cjs.js +1 -0
  7. package/dist/builder/index.cjs.js +146 -58
  8. package/dist/builder/index.es.js +9076 -6479
  9. package/dist/builder-entry.d.ts +4 -0
  10. package/dist/client/api.d.ts +82 -48
  11. package/dist/client/configuration.d.ts +1 -1
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.d.ts +1 -1
  14. package/dist/client/index.es.js +84 -82
  15. package/dist/components/Dashboard/Dashboard.d.ts +8 -15
  16. package/dist/components/Dashboard/DashboardGrid.d.ts +23 -6
  17. package/dist/components/Dashboard/DashboardTile.d.ts +10 -1
  18. package/dist/components/Dashboard/DashboardView.d.ts +36 -0
  19. package/dist/components/Dashboard/TileCard.d.ts +15 -4
  20. package/dist/components/Dashboard/TileFilterTag.d.ts +12 -0
  21. package/dist/components/Dashboard/index.d.ts +3 -0
  22. package/dist/components/Dashboard/telemetry.d.ts +15 -3
  23. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +8 -1
  24. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +16 -5
  25. package/dist/components/DashboardBuilder/ChartPicker.d.ts +29 -0
  26. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +48 -21
  27. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +17 -4
  28. package/dist/components/DashboardBuilder/DiffDialog.d.ts +2 -10
  29. package/dist/components/DashboardBuilder/FilterDialog.d.ts +2 -2
  30. package/dist/components/DashboardBuilder/FilterStrip.d.ts +3 -1
  31. package/dist/components/DashboardBuilder/InlineMarkdown.d.ts +18 -0
  32. package/dist/components/DashboardBuilder/InlineText.d.ts +19 -0
  33. package/dist/components/DashboardBuilder/NotebookEditor.d.ts +15 -0
  34. package/dist/components/DashboardBuilder/SaveNotice.d.ts +27 -0
  35. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +19 -7
  36. package/dist/components/DashboardBuilder/SourceViewPicker.d.ts +9 -0
  37. package/dist/components/DashboardBuilder/TextTileBody.d.ts +7 -0
  38. package/dist/components/DashboardBuilder/TileFrame.d.ts +14 -12
  39. package/dist/components/DashboardBuilder/TileMenu.d.ts +11 -3
  40. package/dist/components/DashboardBuilder/annotationText.d.ts +4 -0
  41. package/dist/components/DashboardBuilder/catalog.d.ts +4 -0
  42. package/dist/components/DashboardBuilder/changedTile.d.ts +7 -0
  43. package/dist/components/DashboardBuilder/chartLine.d.ts +33 -0
  44. package/dist/components/DashboardBuilder/controls.d.ts +2 -2
  45. package/dist/components/DashboardBuilder/document.d.ts +42 -26
  46. package/dist/components/DashboardBuilder/documentSession.d.ts +100 -0
  47. package/dist/components/DashboardBuilder/legacyNotebook.d.ts +73 -0
  48. package/dist/components/DashboardBuilder/loadMalloy.d.ts +15 -0
  49. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -5
  50. package/dist/components/DashboardBuilder/malloyTree.d.ts +119 -0
  51. package/dist/components/DashboardBuilder/newDashboard.d.ts +3 -1
  52. package/dist/components/DashboardBuilder/openDraft.d.ts +10 -0
  53. package/dist/components/DashboardBuilder/preview.d.ts +24 -4
  54. package/dist/components/DashboardBuilder/readDocument.d.ts +4 -1
  55. package/dist/components/DashboardBuilder/readForEditor.d.ts +16 -0
  56. package/dist/components/DashboardBuilder/sortable.d.ts +14 -0
  57. package/dist/components/DashboardBuilder/spliceDocument.d.ts +13 -13
  58. package/dist/components/DashboardBuilder/spliceResult.d.ts +11 -0
  59. package/dist/components/DashboardBuilder/tagParse.d.ts +24 -0
  60. package/dist/components/DashboardBuilder/telemetry.d.ts +43 -0
  61. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +3 -1
  62. package/dist/components/DashboardBuilder/testing/inline.d.ts +4 -0
  63. package/dist/components/DashboardBuilder/useBuilderSession.d.ts +89 -0
  64. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +9 -6
  65. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +17 -55
  66. package/dist/components/DashboardBuilder/useDocumentEditor.d.ts +105 -0
  67. package/dist/components/DashboardBuilder/useExitGuard.d.ts +19 -0
  68. package/dist/components/DashboardBuilder/useFilterForm.d.ts +3 -3
  69. package/dist/components/DocumentCreate/canRetry.d.ts +6 -0
  70. package/dist/components/DocumentCreate/createDocument.d.ts +58 -0
  71. package/dist/components/DocumentCreate/documentPath.d.ts +10 -0
  72. package/dist/components/DocumentCreate/events.d.ts +10 -0
  73. package/dist/components/DocumentCreate/exportedSources.d.ts +7 -0
  74. package/dist/components/DocumentCreate/guards.d.ts +12 -0
  75. package/dist/components/DocumentCreate/index.d.ts +6 -0
  76. package/dist/components/DocumentCreate/newNotebook.d.ts +9 -0
  77. package/dist/components/DocumentCreate/useDocumentChoices.d.ts +32 -0
  78. package/dist/components/DocumentStorage/DocumentStorage.d.ts +2 -1
  79. package/dist/components/NarrowEditGate.d.ts +8 -0
  80. package/dist/components/Notebook/Notebook.d.ts +1 -1
  81. package/dist/components/Package/NewDocumentDialog.d.ts +33 -0
  82. package/dist/components/Package/Package.d.ts +1 -0
  83. package/dist/components/Package/documentLocation.d.ts +28 -0
  84. package/dist/components/Package/index.d.ts +4 -0
  85. package/dist/components/Package/useDocumentLocation.d.ts +12 -0
  86. package/dist/components/PackageSection.d.ts +2 -2
  87. package/dist/components/RenderedResult/RenderedResult.d.ts +2 -0
  88. package/dist/components/RenderedResult/ResultContainer.d.ts +8 -1
  89. package/dist/components/RenderedResult/ResultPanel.d.ts +3 -1
  90. package/dist/components/RenderedResult/resultSizing.d.ts +9 -1
  91. package/dist/components/ServerProvider.d.ts +2 -1
  92. package/dist/components/UnsavedChangesDialog.d.ts +9 -0
  93. package/dist/components/given/GivensPanel.d.ts +2 -2
  94. package/dist/components/index.d.ts +2 -0
  95. package/dist/hooks/index.d.ts +1 -0
  96. package/dist/hooks/useNarrowScreen.d.ts +4 -0
  97. package/dist/hooks/useQueryResult.d.ts +2 -0
  98. package/dist/hooks/useSettled.d.ts +14 -0
  99. package/dist/index.cjs.js +23 -24
  100. package/dist/index.es.js +9714 -7072
  101. package/dist/text/index.cjs.js +1 -0
  102. package/dist/text/index.d.ts +2 -0
  103. package/dist/text/index.es.js +6 -0
  104. package/dist/text-entry-BJwltZiy.cjs.js +7 -0
  105. package/dist/text-entry-CbbBcZl8.es.js +196 -0
  106. package/dist/text-entry.d.ts +2 -0
  107. package/dist/utils/clock.d.ts +2 -0
  108. package/package.json +10 -1
  109. package/src/builder-entry.ts +35 -0
  110. package/src/components/Dashboard/Dashboard.tsx +27 -278
  111. package/src/components/Dashboard/DashboardGrid.tsx +68 -7
  112. package/src/components/Dashboard/DashboardTile.spec.tsx +24 -0
  113. package/src/components/Dashboard/DashboardTile.tsx +31 -4
  114. package/src/components/Dashboard/DashboardView.spec.tsx +212 -0
  115. package/src/components/Dashboard/DashboardView.tsx +352 -0
  116. package/src/components/Dashboard/RowsDialog.tsx +1 -1
  117. package/src/components/Dashboard/TileCard.tsx +44 -10
  118. package/src/components/Dashboard/TileFilterTag.spec.tsx +73 -0
  119. package/src/components/Dashboard/TileFilterTag.tsx +78 -0
  120. package/src/components/Dashboard/defaultTileSpan.spec.ts +32 -0
  121. package/src/components/Dashboard/index.ts +3 -0
  122. package/src/components/Dashboard/telemetry.ts +16 -5
  123. package/src/components/DashboardBuilder/AddTileDialog.spec.tsx +88 -0
  124. package/src/components/DashboardBuilder/AddTileDialog.tsx +137 -111
  125. package/src/components/DashboardBuilder/BuilderToolbar.tsx +85 -27
  126. package/src/components/DashboardBuilder/ChartPicker.render.spec.tsx +25 -0
  127. package/src/components/DashboardBuilder/ChartPicker.spec.ts +77 -0
  128. package/src/components/DashboardBuilder/ChartPicker.tsx +153 -0
  129. package/src/components/DashboardBuilder/DashboardBuilder.charts.spec.tsx +205 -0
  130. package/src/components/DashboardBuilder/DashboardBuilder.exit.spec.tsx +192 -0
  131. package/src/components/DashboardBuilder/DashboardBuilder.inline.spec.tsx +329 -0
  132. package/src/components/DashboardBuilder/DashboardBuilder.notebook.spec.tsx +363 -0
  133. package/src/components/DashboardBuilder/DashboardBuilder.notice.spec.tsx +194 -0
  134. package/src/components/DashboardBuilder/DashboardBuilder.openDraft.spec.tsx +157 -0
  135. package/src/components/DashboardBuilder/DashboardBuilder.sources.spec.tsx +124 -0
  136. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +103 -78
  137. package/src/components/DashboardBuilder/DashboardBuilder.textTiles.spec.tsx +177 -0
  138. package/src/components/DashboardBuilder/DashboardBuilder.tsx +610 -315
  139. package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +58 -8
  140. package/src/components/DashboardBuilder/DashboardEditor.emptyStart.spec.tsx +191 -0
  141. package/src/components/DashboardBuilder/DashboardEditor.filterTag.spec.tsx +162 -0
  142. package/src/components/DashboardBuilder/DashboardEditor.notebook.spec.tsx +316 -0
  143. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +56 -10
  144. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +5 -22
  145. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +96 -14
  146. package/src/components/DashboardBuilder/DashboardEditor.tsx +482 -332
  147. package/src/components/DashboardBuilder/DiffDialog.spec.tsx +25 -0
  148. package/src/components/DashboardBuilder/DiffDialog.tsx +5 -24
  149. package/src/components/DashboardBuilder/DrillDialog.tsx +1 -1
  150. package/src/components/DashboardBuilder/FilterDialog.tsx +10 -3
  151. package/src/components/DashboardBuilder/FilterStrip.tsx +26 -4
  152. package/src/components/DashboardBuilder/InlineMarkdown.tsx +184 -0
  153. package/src/components/DashboardBuilder/InlineText.tsx +106 -0
  154. package/src/components/DashboardBuilder/NotebookEditor.tsx +44 -0
  155. package/src/components/DashboardBuilder/SaveNotice.tsx +113 -0
  156. package/src/components/DashboardBuilder/SettingsPopover.spec.tsx +87 -0
  157. package/src/components/DashboardBuilder/SettingsPopover.tsx +225 -67
  158. package/src/components/DashboardBuilder/SourceViewPicker.tsx +122 -0
  159. package/src/components/DashboardBuilder/TextTileBody.tsx +28 -0
  160. package/src/components/DashboardBuilder/TileFrame.tsx +89 -115
  161. package/src/components/DashboardBuilder/TileMenu.tsx +168 -90
  162. package/src/components/DashboardBuilder/annotationText.spec.ts +33 -0
  163. package/src/components/DashboardBuilder/annotationText.ts +17 -0
  164. package/src/components/DashboardBuilder/artifactBlock.spec.ts +248 -0
  165. package/src/components/DashboardBuilder/artifactTagParity.spec.ts +41 -0
  166. package/src/components/DashboardBuilder/catalog.aggregate.spec.ts +49 -0
  167. package/src/components/DashboardBuilder/catalog.spec.ts +2 -0
  168. package/src/components/DashboardBuilder/catalog.ts +61 -21
  169. package/src/components/DashboardBuilder/changedTile.spec.ts +46 -0
  170. package/src/components/DashboardBuilder/changedTile.ts +28 -0
  171. package/src/components/DashboardBuilder/chartLine.spec.ts +180 -0
  172. package/src/components/DashboardBuilder/chartLine.ts +121 -0
  173. package/src/components/DashboardBuilder/controls.spec.ts +21 -10
  174. package/src/components/DashboardBuilder/controls.ts +22 -8
  175. package/src/components/DashboardBuilder/document.ts +53 -5
  176. package/src/components/DashboardBuilder/documentSession.spec.ts +209 -0
  177. package/src/components/DashboardBuilder/documentSession.ts +257 -0
  178. package/src/components/DashboardBuilder/emptyStart.spec.ts +131 -0
  179. package/src/components/DashboardBuilder/invariants.spec.ts +6 -2
  180. package/src/components/DashboardBuilder/legacyNotebook.chart.spec.ts +77 -0
  181. package/src/components/DashboardBuilder/legacyNotebook.convert.spec.ts +630 -0
  182. package/src/components/DashboardBuilder/legacyNotebook.read.spec.ts +338 -0
  183. package/src/components/DashboardBuilder/legacyNotebook.ts +1117 -0
  184. package/src/components/DashboardBuilder/loadMalloy.spec.ts +80 -0
  185. package/src/components/DashboardBuilder/loadMalloy.ts +39 -0
  186. package/src/components/DashboardBuilder/malloyText.spec.ts +48 -0
  187. package/src/components/DashboardBuilder/malloyText.ts +181 -27
  188. package/src/components/DashboardBuilder/malloyTree.ts +155 -7
  189. package/src/components/DashboardBuilder/newDashboard.spec.ts +46 -2
  190. package/src/components/DashboardBuilder/newDashboard.ts +30 -3
  191. package/src/components/DashboardBuilder/openDraft.ts +52 -0
  192. package/src/components/DashboardBuilder/preview.shapes.spec.ts +75 -0
  193. package/src/components/DashboardBuilder/preview.spec.ts +159 -12
  194. package/src/components/DashboardBuilder/preview.ts +83 -9
  195. package/src/components/DashboardBuilder/readDocument.spec.ts +139 -27
  196. package/src/components/DashboardBuilder/readDocument.ts +130 -44
  197. package/src/components/DashboardBuilder/readForEditor.spec.ts +80 -0
  198. package/src/components/DashboardBuilder/readForEditor.ts +47 -0
  199. package/src/components/DashboardBuilder/scannerShapes.spec.ts +14 -13
  200. package/src/components/DashboardBuilder/sortable.spec.ts +65 -0
  201. package/src/components/DashboardBuilder/sortable.tsx +2 -12
  202. package/src/components/DashboardBuilder/spliceDocument.chart.spec.ts +340 -0
  203. package/src/components/DashboardBuilder/spliceDocument.imports.spec.ts +167 -0
  204. package/src/components/DashboardBuilder/spliceDocument.spec.ts +229 -94
  205. package/src/components/DashboardBuilder/spliceDocument.ts +762 -130
  206. package/src/components/DashboardBuilder/spliceResult.ts +15 -0
  207. package/src/components/DashboardBuilder/statementExtent.spec.ts +33 -30
  208. package/src/components/DashboardBuilder/tagParse.spec.ts +149 -0
  209. package/src/components/DashboardBuilder/tagParse.ts +103 -0
  210. package/src/components/DashboardBuilder/telemetry.ts +47 -0
  211. package/src/components/DashboardBuilder/testing/artifactTagParity.json +197 -0
  212. package/src/components/DashboardBuilder/testing/fixtures.ts +16 -1
  213. package/src/components/DashboardBuilder/testing/inline.ts +25 -0
  214. package/src/components/DashboardBuilder/textTiles.spec.ts +718 -0
  215. package/src/components/DashboardBuilder/useBuilderSession.spec.ts +335 -0
  216. package/src/components/DashboardBuilder/useBuilderSession.ts +292 -0
  217. package/src/components/DashboardBuilder/useBuilderShortcuts.overlay.spec.tsx +65 -0
  218. package/src/components/DashboardBuilder/useBuilderShortcuts.spec.tsx +60 -0
  219. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +36 -10
  220. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +16 -13
  221. package/src/components/DashboardBuilder/useDashboardEditor.ts +54 -181
  222. package/src/components/DashboardBuilder/useDocumentEditor.spec.ts +565 -0
  223. package/src/components/DashboardBuilder/useDocumentEditor.ts +399 -0
  224. package/src/components/DashboardBuilder/useExitGuard.spec.ts +159 -0
  225. package/src/components/DashboardBuilder/useExitGuard.ts +89 -0
  226. package/src/components/DashboardBuilder/useFilterForm.existing.spec.tsx +41 -0
  227. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +24 -2
  228. package/src/components/DashboardBuilder/useFilterForm.ts +41 -13
  229. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +28 -5
  230. package/src/components/DashboardBuilder/useTileReorder.ts +5 -7
  231. package/src/components/DocumentCreate/canRetry.spec.ts +32 -0
  232. package/src/components/DocumentCreate/canRetry.ts +19 -0
  233. package/src/components/DocumentCreate/createDocument.spec.ts +310 -0
  234. package/src/components/DocumentCreate/createDocument.ts +159 -0
  235. package/src/components/DocumentCreate/documentPath.ts +40 -0
  236. package/src/components/DocumentCreate/events.ts +15 -0
  237. package/src/components/DocumentCreate/exportedSources.ts +25 -0
  238. package/src/components/DocumentCreate/guards.ts +45 -0
  239. package/src/components/DocumentCreate/index.ts +27 -0
  240. package/src/components/DocumentCreate/newNotebook.spec.ts +156 -0
  241. package/src/components/DocumentCreate/newNotebook.ts +44 -0
  242. package/src/components/DocumentCreate/useDocumentChoices.spec.tsx +138 -0
  243. package/src/components/DocumentCreate/useDocumentChoices.ts +113 -0
  244. package/src/components/DocumentStorage/DocumentStorage.ts +2 -1
  245. package/src/components/Model/ModelExplorer.spec.tsx +2 -2
  246. package/src/components/Model/SourcesExplorer.tsx +2 -4
  247. package/src/components/NarrowEditGate.spec.tsx +73 -0
  248. package/src/components/NarrowEditGate.tsx +29 -0
  249. package/src/components/Notebook/Notebook.layout.spec.tsx +94 -0
  250. package/src/components/Notebook/Notebook.tsx +66 -27
  251. package/src/components/Package/NewDocumentDialog.spec.tsx +749 -0
  252. package/src/components/Package/NewDocumentDialog.tsx +401 -0
  253. package/src/components/Package/Package.artifacts.spec.tsx +190 -0
  254. package/src/components/Package/Package.create.spec.tsx +380 -0
  255. package/src/components/Package/Package.notebooks.spec.tsx +18 -0
  256. package/src/components/Package/Package.tsx +366 -171
  257. package/src/components/Package/documentLocation.spec.ts +81 -0
  258. package/src/components/Package/documentLocation.ts +55 -0
  259. package/src/components/Package/index.ts +13 -0
  260. package/src/components/Package/useDocumentLocation.ts +59 -0
  261. package/src/components/PackageSection.tsx +2 -2
  262. package/src/components/RenderedResult/RenderedResult.tsx +18 -1
  263. package/src/components/RenderedResult/ResultContainer.tsx +44 -11
  264. package/src/components/RenderedResult/ResultPanel.tsx +4 -0
  265. package/src/components/RenderedResult/resultSizing.spec.ts +68 -0
  266. package/src/components/RenderedResult/resultSizing.ts +14 -3
  267. package/src/components/ServerProvider.tsx +2 -1
  268. package/src/components/UnsavedChangesDialog.spec.tsx +70 -0
  269. package/src/components/UnsavedChangesDialog.tsx +49 -0
  270. package/src/components/given/GivensPanel.spec.tsx +6 -6
  271. package/src/components/given/GivensPanel.tsx +3 -3
  272. package/src/components/index.ts +2 -0
  273. package/src/hooks/index.ts +3 -0
  274. package/src/hooks/useNarrowScreen.ts +21 -0
  275. package/src/hooks/useQueryResult.ts +16 -0
  276. package/src/hooks/useSettled.spec.ts +41 -0
  277. package/src/hooks/useSettled.ts +27 -0
  278. package/src/mainEntry.spec.ts +145 -0
  279. package/src/text-entry.ts +12 -0
  280. package/src/textEntry.spec.ts +118 -0
  281. package/src/utils/clock.spec.ts +12 -0
  282. package/src/utils/clock.ts +6 -0
  283. package/vite.config.ts +4 -0
  284. package/dist/Dashboard-ChyylkTD.cjs.js +0 -136
  285. package/dist/RenderedResult-AJPMUkAD.cjs.js +0 -135
  286. package/dist/ServerProvider-CXrOKD6g.cjs.js +0 -1
  287. package/dist/components/DashboardBuilder/useTileResize.d.ts +0 -29
  288. package/dist/components/Package/NewDashboardDialog.d.ts +0 -18
  289. package/src/components/DashboardBuilder/useTileResize.spec.tsx +0 -121
  290. package/src/components/DashboardBuilder/useTileResize.ts +0 -110
  291. package/src/components/Package/NewDashboardDialog.spec.tsx +0 -129
  292. package/src/components/Package/NewDashboardDialog.tsx +0 -265
@@ -0,0 +1,1117 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * Where everything in a `.malloy` notebook IS, as exact offsets into its text.
6
+ *
7
+ * The browser-side twin of the server's `readNotebookCells`, which cannot ship
8
+ * here: it statically imports `@malloydata/malloy` and carries only line
9
+ * numbers. This one reads the same parse the same way and adds what a writer
10
+ * needs, a span per cell, so everything between the spans can be kept byte for
11
+ * byte. Like the server it is all-or-nothing: anything it cannot place refuses
12
+ * the whole notebook rather than yielding a partial read to edit.
13
+ *
14
+ * {@link convertLegacyNotebook} builds on that read to rewrite such a notebook
15
+ * as the layout notebook the dashboard builder edits.
16
+ */
17
+
18
+ import {
19
+ commentIndex,
20
+ isRule,
21
+ Reader,
22
+ readTileList,
23
+ translate,
24
+ type Ctx,
25
+ type Span,
26
+ type TokenStream,
27
+ } from "./malloyTree";
28
+ import { mentionsChartTag, parseChartLine } from "./chartLine";
29
+ import { annotationTextProblem } from "./annotationText";
30
+ import {
31
+ ARTIFACT_NOT_FIRST,
32
+ artifactLeads,
33
+ artifactTag,
34
+ isBareName,
35
+ setsArtifactProperty,
36
+ } from "./malloyText";
37
+ import { parseTagLines } from "./tagParse";
38
+ import { loadMalloy, loadMalloyTag } from "./loadMalloy";
39
+
40
+ export type { Span };
41
+
42
+ /** A `# <chart>` line the chart rule recognizes, whole line including its newline. */
43
+ export interface ChartLineSpan {
44
+ span: Span;
45
+ /** The line less its newline. */
46
+ text: string;
47
+ }
48
+
49
+ /** The chart tag lines of a query cell. */
50
+ export interface QueryChart {
51
+ lines: ChartLineSpan[];
52
+ /** A `#` line that names a chart tag but is not one the rule recognizes, kept byte for byte. */
53
+ unmodelled?: string;
54
+ /** Where a new chart line goes: the start of the line holding the statement's code. */
55
+ insertAt: number;
56
+ }
57
+
58
+ export interface NotebookSourceCell {
59
+ kind: "markdown" | "query" | "definition";
60
+ /** The movable chunk: from the first line of its tag/prose/caption/comment block to the end of the statement's last line (incl. newline). */
61
+ span: Span;
62
+ /** markdown cells: the prose; query cells: the attached header prose, if any. */
63
+ markdown?: string;
64
+ /** Statement cells: the attached `(markdown)`/`(text)` notes and `"` captions, each a whole note token run. */
65
+ prose?: Span[];
66
+ /** Query cells only. */
67
+ chart?: QueryChart;
68
+ /** Stable id for React keys and history; its index in the read. */
69
+ id: string;
70
+ }
71
+
72
+ /**
73
+ * A notebook's layout. `header` starts at 0; the cells follow in file order
74
+ * without overlapping it or each other, and every byte between two spans (or
75
+ * after the last) is a gap the writer keeps as it found it.
76
+ */
77
+ export interface NotebookSource {
78
+ text: string;
79
+ header: Span;
80
+ cells: NotebookSourceCell[];
81
+ }
82
+
83
+ export type NotebookSourceResult =
84
+ | { ok: true; source: NotebookSource }
85
+ | { ok: false; refused: string; line?: number };
86
+
87
+ export const notebookSourceRefused = (
88
+ r: NotebookSourceResult,
89
+ ): r is Extract<NotebookSourceResult, { ok: false }> => r.ok === false;
90
+
91
+ interface Token {
92
+ type: number;
93
+ channel: number;
94
+ startIndex: number;
95
+ stopIndex: number;
96
+ line: number;
97
+ }
98
+
99
+ type Node = Ctx & { symbol?: Token };
100
+
101
+ type Malloy = typeof import("@malloydata/malloy");
102
+
103
+ // By accessor, never by class name: the host bundler minifies the peer dependency.
104
+ const callAccessor = (node: Node, name: string): unknown => {
105
+ const accessor = node[name];
106
+ return typeof accessor === "function" ? accessor.call(node) : undefined;
107
+ };
108
+
109
+ /** `malloyStatement` accessors, in step with the server reader's `STATEMENT_ACCESSORS`. */
110
+ const STATEMENT_ACCESSORS: readonly [string, "run" | "notes" | "definition"][] =
111
+ [
112
+ ["runStatement", "run"],
113
+ ["docAnnotations", "notes"],
114
+ ["importStatement", "definition"],
115
+ ["defineSourceStatement", "definition"],
116
+ ["defineQuery", "definition"],
117
+ ["defineGivenStatement", "definition"],
118
+ ["defineUserTypeStatement", "definition"],
119
+ ["exportStatement", "definition"],
120
+ ];
121
+
122
+ const TEXT_BLOCK_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
123
+ const PARSE_URL = "file:///publisher-notebook-builder/notebook.malloy";
124
+
125
+ const normalizeNewlines = (text: string) => text.replace(/\r\n?/g, "\n");
126
+
127
+ interface Note {
128
+ text: string;
129
+ route: string | undefined;
130
+ /** Set only on a prose note: `(markdown)`, `"` or `(text)`. */
131
+ body?: string;
132
+ block: boolean;
133
+ startLine: number;
134
+ endLine: number;
135
+ }
136
+
137
+ type Item =
138
+ | {
139
+ kind: "statement";
140
+ run: boolean;
141
+ markdown?: string;
142
+ prose: Span[];
143
+ chart: QueryChart;
144
+ startLine: number;
145
+ endLine: number;
146
+ }
147
+ | { kind: "note"; note: Note };
148
+
149
+ /** A notebook's layout, or why it cannot be edited; a refusal's `line` is 1-based, while lines inside are 0-based. */
150
+ export async function readNotebookSource(
151
+ text: string,
152
+ ): Promise<NotebookSourceResult> {
153
+ const refuse = (line: number, why: string): NotebookSourceResult => ({
154
+ ok: false,
155
+ refused: `Line ${line + 1}: ${why}`,
156
+ line: line + 1,
157
+ });
158
+ // Lines here end only at LF, so a lone CR would hide a line boundary from every span.
159
+ const loneCr = /\r(?!\n)/.exec(text);
160
+ if (loneCr)
161
+ return refuse(
162
+ text.slice(0, loneCr.index).split("\n").length - 1,
163
+ "a carriage return that is not part of a CRLF line ending, so the cells cannot be located. Fix: save the file with LF or CRLF line endings.",
164
+ );
165
+
166
+ let translation: Awaited<ReturnType<typeof translate>>;
167
+ let malloy: Malloy;
168
+ try {
169
+ translation = await translate(text, PARSE_URL);
170
+ // The same dynamic import as `translate`, for Malloy's own note routing.
171
+ malloy = await loadMalloy();
172
+ } catch (error) {
173
+ return refuse(0, `Malloy could not read this notebook: ${error}`);
174
+ }
175
+ const syntax = translation.problems.find((p) => p.code === "syntax-error");
176
+ if (syntax)
177
+ return refuse(
178
+ syntax.at?.range?.start?.line ?? 0,
179
+ `Malloy could not parse this notebook (${syntax.message ?? "unknown"}), so it cannot be edited here. Fix: correct the syntax on that line.`,
180
+ );
181
+
182
+ const root = translation.parse?.root as Node | undefined;
183
+ const stream = translation.parse?.tokenStream as TokenStream | undefined;
184
+ const vocabulary = stream?.tokenSource?.vocabulary;
185
+ const tokens =
186
+ typeof stream?.getTokens === "function"
187
+ ? (stream.getTokens() as Token[])
188
+ : undefined;
189
+ if (
190
+ !root ||
191
+ typeof root.getChild !== "function" ||
192
+ !stream ||
193
+ !tokens ||
194
+ typeof vocabulary?.getSymbolicName !== "function" ||
195
+ (tokens.length === 0 && text.trim() !== "")
196
+ )
197
+ return {
198
+ ok: false,
199
+ refused:
200
+ "This build of Malloy does not expose a parse tree and token stream the notebook builder can read, so editing is off.",
201
+ };
202
+ const symbolOf = (token: Token) => vocabulary.getSymbolicName(token.type);
203
+
204
+ const routeOf = (note: string): string | undefined =>
205
+ malloy.routeOf({ value: note.trimStart() } as Parameters<
206
+ Malloy["routeOf"]
207
+ >[0]);
208
+ const payloadOf = (note: string): string =>
209
+ malloy.payloadOf({ value: note } as Parameters<Malloy["payloadOf"]>[0]);
210
+ const isProseRoute = (route: string | undefined) =>
211
+ route === "markdown" || route === '"' || route === "text";
212
+ const lineBody = (note: string) =>
213
+ normalizeNewlines(payloadOf(note)).replace(/\n$/, "");
214
+ // Text on a block's opener line is prose too, except a lone bare word on a `(markdown)`/`(text)` opener, which names it.
215
+ const blockBody = (opener: string, bodyLines: string[]) => {
216
+ const rest = payloadOf(opener).trim();
217
+ const onOpener =
218
+ routeOf(opener) !== '"' && TEXT_BLOCK_NAME.test(rest) ? "" : rest;
219
+ return normalizeNewlines(
220
+ [onOpener && `${onOpener}\n`, ...bodyLines].join(""),
221
+ ).replace(/\n$/, "");
222
+ };
223
+
224
+ const r = new Reader(text);
225
+ const comments = commentIndex(r, stream);
226
+ const tokenText = (token: Token) =>
227
+ text.slice(r.utf16(token.startIndex), r.utf16(token.stopIndex + 1));
228
+ const spanOf = (node: Node) => {
229
+ const startCp = node.start?.startIndex;
230
+ const stopCp = node.stop?.stopIndex;
231
+ const span = r.span(node);
232
+ if (startCp === undefined || stopCp === undefined || !span)
233
+ return undefined;
234
+ // A note's token carries its newline; its last line is the one before it.
235
+ let last = span.end;
236
+ while (
237
+ last > span.start &&
238
+ (text[last - 1] === "\n" || text[last - 1] === "\r")
239
+ )
240
+ last--;
241
+ return {
242
+ startCp,
243
+ stopCp,
244
+ ...span,
245
+ startLine: r.line(span.start),
246
+ endLine: r.line(Math.max(span.start, last - 1)),
247
+ };
248
+ };
249
+ const firstTokenAt = (cp: number): number => {
250
+ let lo = 0;
251
+ let hi = tokens.length;
252
+ while (lo < hi) {
253
+ const mid = (lo + hi) >> 1;
254
+ if (tokens[mid].startIndex < cp) lo = mid + 1;
255
+ else hi = mid;
256
+ }
257
+ return lo;
258
+ };
259
+ // A statement's own `#(markdown)` prose, read from the notes it opens with; blocks and runs join with a blank line.
260
+ const attachedProse = (
261
+ startCp: number,
262
+ stopCp: number,
263
+ ): { markdown: string | undefined; prose: Span[]; chart: QueryChart } => {
264
+ const segments: string[] = [];
265
+ const prose: Span[] = [];
266
+ const chart: QueryChart = { lines: [], insertAt: r.utf16(startCp) };
267
+ let lineEnd = -2;
268
+ for (let i = firstTokenAt(startCp); i < tokens.length; i++) {
269
+ const token = tokens[i];
270
+ if (token.startIndex > stopCp) break;
271
+ if (token.channel !== 0) continue;
272
+ const name = symbolOf(token);
273
+ if (name !== "ANNOTATION" && name !== "BLOCK_ANNOTATION_BEGIN") {
274
+ chart.insertAt = r.lineStarts[r.line(r.utf16(token.startIndex))];
275
+ break;
276
+ }
277
+ const note = normalizeNewlines(tokenText(token));
278
+ const bodyTexts: string[] = [];
279
+ if (name === "BLOCK_ANNOTATION_BEGIN") {
280
+ while (symbolOf(tokens[i + 1] ?? token) === "BLOCK_ANNOTATION_TEXT")
281
+ bodyTexts.push(tokenText(tokens[++i]));
282
+ if (symbolOf(tokens[i + 1] ?? token) === "BLOCK_ANNOTATION_END")
283
+ i++;
284
+ }
285
+ // The lexer's own extent, since a `|#` at another column than the opener's is still body.
286
+ if (isProseRoute(routeOf(note))) {
287
+ const start = r.utf16(token.startIndex);
288
+ const lineStart = r.lineStarts[r.line(start)];
289
+ // Indentation left behind joins the next line, and a block opened there then never closes at its column.
290
+ const indentOnly = /^[ \t]*$/.test(text.slice(lineStart, start));
291
+ prose.push({
292
+ start: indentOnly ? lineStart : start,
293
+ end: r.utf16(tokens[i].stopIndex + 1),
294
+ });
295
+ }
296
+ if (name === "ANNOTATION") {
297
+ const line = note.replace(/\n$/, "");
298
+ if (parseChartLine(line)) {
299
+ const start = r.utf16(token.startIndex);
300
+ const lineStart = r.lineStarts[r.line(start)];
301
+ chart.lines.push({
302
+ span: {
303
+ start: /^[ \t]*$/.test(text.slice(lineStart, start))
304
+ ? lineStart
305
+ : start,
306
+ end: r.utf16(token.stopIndex + 1),
307
+ },
308
+ text: line,
309
+ });
310
+ } else if (mentionsChartTag(line) && chart.unmodelled === undefined)
311
+ chart.unmodelled = line.trim();
312
+ }
313
+ if (routeOf(note) !== "markdown") {
314
+ lineEnd = -2;
315
+ } else if (name === "BLOCK_ANNOTATION_BEGIN") {
316
+ segments.push(blockBody(note, bodyTexts));
317
+ lineEnd = -2;
318
+ } else {
319
+ const body = lineBody(note);
320
+ if (token.line === lineEnd + 1)
321
+ segments[segments.length - 1] += `\n${body}`;
322
+ else segments.push(body);
323
+ lineEnd = token.line;
324
+ }
325
+ }
326
+ return {
327
+ markdown: segments.length > 0 ? segments.join("\n\n") : undefined,
328
+ prose,
329
+ chart,
330
+ };
331
+ };
332
+
333
+ const covered: [number, number][] = [];
334
+ const items: Item[] = [];
335
+ const cannotHold = (
336
+ line: number,
337
+ what: string,
338
+ fix = "remove it, or rewrite it as an import, source:, query:, given:, type: or export statement, a run:, or a `##(markdown)` / `##|(markdown)` prose note.",
339
+ ) =>
340
+ refuse(
341
+ line,
342
+ `${what}, which no notebook cell can hold, so the notebook cannot be edited here. Fix: ${fix}`,
343
+ );
344
+
345
+ for (let i = 0; i < (root.childCount ?? 0); i++) {
346
+ const child = root.getChild(i) as Node;
347
+ if (!isRule(child)) {
348
+ const token = child?.symbol;
349
+ const name = token ? symbolOf(token) : undefined;
350
+ if (token && name === "EOF") continue;
351
+ if (token && name === "SEMI") {
352
+ covered.push([token.startIndex, token.stopIndex]);
353
+ continue;
354
+ }
355
+ return cannotHold(
356
+ (token?.line ?? 1) - 1,
357
+ "a token outside any statement",
358
+ );
359
+ }
360
+ const span = spanOf(child);
361
+ if (!span) return cannotHold(0, "a statement with no readable range");
362
+ const match = STATEMENT_ACCESSORS.find(
363
+ ([accessor]) => callAccessor(child, accessor) !== undefined,
364
+ );
365
+ if (!match && callAccessor(child, "ignoredObjectAnnotations"))
366
+ return cannotHold(
367
+ span.startLine,
368
+ "a # tag that annotates no statement",
369
+ "move the tag directly above its run:, or write trailing prose as a `##(markdown)` note.",
370
+ );
371
+ if (!match) {
372
+ const firstLine = text.slice(span.start, span.end).split("\n")[0];
373
+ return cannotHold(
374
+ span.startLine,
375
+ `\`${firstLine.trim()}\` is a statement the notebook reader does not recognize`,
376
+ );
377
+ }
378
+ covered.push([span.startCp, span.stopCp]);
379
+ const [accessor, kind] = match;
380
+ if (kind !== "notes") {
381
+ const { markdown, prose, chart } = attachedProse(
382
+ span.startCp,
383
+ span.stopCp,
384
+ );
385
+ items.push({
386
+ kind: "statement",
387
+ run: kind === "run",
388
+ ...(markdown !== undefined && { markdown }),
389
+ prose,
390
+ chart,
391
+ startLine: span.startLine,
392
+ endLine: span.endLine,
393
+ });
394
+ continue;
395
+ }
396
+ const group = callAccessor(child, accessor) as Node;
397
+ for (const noteNode of (callAccessor(group, "docAnnotation") ??
398
+ []) as Node[]) {
399
+ const noteSpan = spanOf(noteNode);
400
+ if (!noteSpan)
401
+ return cannotHold(span.startLine, "a note with no readable range");
402
+ const block =
403
+ callAccessor(noteNode, "docBlockAnnotation") !== undefined;
404
+ const own = tokens.filter(
405
+ (t) =>
406
+ t.startIndex >= noteSpan.startCp &&
407
+ t.stopIndex <= noteSpan.stopCp,
408
+ );
409
+ const bodyTokens = own.filter(
410
+ (t) => symbolOf(t) === "BLOCK_ANNOTATION_TEXT",
411
+ );
412
+ // A block's note text ends with its body, as the server reads it: with the closer, MOTLY drops the tag.
413
+ const lastBody = bodyTokens[bodyTokens.length - 1] ?? own[0];
414
+ const noteText = normalizeNewlines(
415
+ block && lastBody
416
+ ? text
417
+ .slice(noteSpan.start, r.utf16(lastBody.stopIndex + 1))
418
+ .replace(/\r?\n$/, "")
419
+ : text.slice(noteSpan.start, noteSpan.end),
420
+ );
421
+ const route = routeOf(noteText);
422
+ const body = !isProseRoute(route)
423
+ ? undefined
424
+ : block
425
+ ? blockBody(noteText.split("\n", 1)[0], bodyTokens.map(tokenText))
426
+ : lineBody(noteText);
427
+ items.push({
428
+ kind: "note",
429
+ note: {
430
+ text: noteText,
431
+ route,
432
+ ...(body !== undefined && { body }),
433
+ block,
434
+ startLine: noteSpan.startLine,
435
+ endLine: noteSpan.endLine,
436
+ },
437
+ });
438
+ }
439
+ }
440
+
441
+ // The lexer folds the rest of a closer's line into the closer, and the writer, rebuilding from `markdown`, would drop it.
442
+ for (const token of tokens) {
443
+ if (symbolOf(token) !== "BLOCK_ANNOTATION_END") continue;
444
+ const trailing = tokenText(token)
445
+ .trimStart()
446
+ .replace(/^\|#{1,2}/, "")
447
+ .trim();
448
+ if (trailing)
449
+ return refuse(
450
+ token.line - 1,
451
+ `the text after a block's closer (\`${trailing}\`) is not part of any cell, so the notebook cannot be edited here. Fix: put it on its own line, or inside the block.`,
452
+ );
453
+ }
454
+
455
+ // Both lists are in file order, so one forward sweep checks every token.
456
+ let range = 0;
457
+ for (const token of tokens) {
458
+ if (token.channel !== 0 || symbolOf(token) === "EOF") continue;
459
+ while (range < covered.length && covered[range][1] < token.startIndex)
460
+ range++;
461
+ const [from, to] = covered[range] ?? [Infinity, -Infinity];
462
+ if (token.startIndex < from || token.stopIndex > to)
463
+ return cannotHold(token.line - 1, "a token outside any statement");
464
+ }
465
+
466
+ const artifactAt = items.findIndex(
467
+ (item) => item.kind === "note" && setsArtifactProperty(item.note.text),
468
+ );
469
+ if (artifactAt < 0)
470
+ return refuse(
471
+ 0,
472
+ "this file has no ## artifact note, so it is not a notebook the builder can edit. Fix: add `## artifact { kind=notebook }` after the ##! line.",
473
+ );
474
+ const above = items.findIndex(
475
+ (item, index) => index < artifactAt && item.kind === "statement",
476
+ );
477
+ if (above >= 0)
478
+ return refuse(
479
+ (items[above] as { startLine: number }).startLine,
480
+ 'a statement sits above the `## artifact` tag, where only `##!` flags, comments and `"` notes may. Fix: move it below the artifact tag.',
481
+ );
482
+
483
+ // Cells span whole lines, so two items on one line cannot be moved apart.
484
+ for (let i = 1; i < items.length; i++) {
485
+ const prev = items[i - 1];
486
+ const item = items[i];
487
+ const prevEnd = prev.kind === "note" ? prev.note.endLine : prev.endLine;
488
+ const start = item.kind === "note" ? item.note.startLine : item.startLine;
489
+ if (start <= prevEnd)
490
+ return cannotHold(
491
+ start,
492
+ "a line holding two statements or notes",
493
+ "put each statement and note on its own line.",
494
+ );
495
+ }
496
+
497
+ const lineEnd = (line: number) => r.lineStarts[line + 1] ?? text.length;
498
+ interface Building {
499
+ cell: Omit<NotebookSourceCell, "span">;
500
+ startLine: number;
501
+ endLine: number;
502
+ }
503
+ const building: Building[] = [];
504
+ let headerEnd = -1;
505
+ let inHeader = true;
506
+ // The markdown cell a contiguous `##(markdown)` line run is building, which the next adjacent line joins.
507
+ let lineRun: Building | undefined;
508
+ items.forEach((item, index) => {
509
+ if (item.kind === "statement") {
510
+ inHeader = false;
511
+ lineRun = undefined;
512
+ building.push({
513
+ cell: {
514
+ kind: item.run ? "query" : "definition",
515
+ ...(item.markdown !== undefined && { markdown: item.markdown }),
516
+ ...(item.prose.length > 0 && { prose: item.prose }),
517
+ ...(item.run && { chart: item.chart }),
518
+ id: "",
519
+ },
520
+ startLine: item.startLine,
521
+ endLine: item.endLine,
522
+ });
523
+ return;
524
+ }
525
+ const { note } = item;
526
+ const floating = index > artifactAt && note.body !== undefined;
527
+ if (!floating) {
528
+ // A non-prose note is header until the first cell, and gap content after it.
529
+ if (inHeader) headerEnd = note.endLine;
530
+ lineRun = undefined;
531
+ return;
532
+ }
533
+ inHeader = false;
534
+ if (!note.block && lineRun && lineRun.endLine + 1 === note.startLine) {
535
+ lineRun.cell.markdown += `\n${note.body}`;
536
+ lineRun.endLine = note.endLine;
537
+ return;
538
+ }
539
+ const cell: Building = {
540
+ cell: { kind: "markdown", markdown: note.body, id: "" },
541
+ startLine: note.startLine,
542
+ endLine: note.endLine,
543
+ };
544
+ building.push(cell);
545
+ lineRun = note.block ? undefined : cell;
546
+ });
547
+
548
+ const header: Span = { start: 0, end: lineEnd(headerEnd) };
549
+ let boundary = headerEnd;
550
+ const cells: NotebookSourceCell[] = building.map(
551
+ ({ cell, startLine, endLine }, index) => {
552
+ // A comment directly above a cell, with no blank line between, travels with it.
553
+ let first = startLine;
554
+ while (first - 1 > boundary && comments.lines.has(first - 1)) first--;
555
+ boundary = endLine;
556
+ return {
557
+ ...cell,
558
+ span: { start: r.lineStarts[first], end: lineEnd(endLine) },
559
+ id: String(index),
560
+ };
561
+ },
562
+ );
563
+
564
+ // A comment cut by a span boundary would be split by a move.
565
+ for (const span of [header, ...cells.map((c) => c.span)]) {
566
+ const cut = comments.all.find(
567
+ (c) =>
568
+ (c.start < span.start && c.end > span.start) ||
569
+ (c.start < span.end && c.end > span.end),
570
+ );
571
+ if (cut)
572
+ return cannotHold(
573
+ r.line(cut.start),
574
+ "a comment that straddles a cell",
575
+ "start the comment on its own line.",
576
+ );
577
+ }
578
+ return { ok: true, source: { text, header, cells } };
579
+ }
580
+
581
+ /* ------------------------------------------------------------------ */
582
+ /* Converting the cell format to the layout format */
583
+ /* ------------------------------------------------------------------ */
584
+
585
+ export type LegacyConversion =
586
+ | { ok: true; text: string; tiles: number }
587
+ | { ok: false; refused: string; line?: number };
588
+
589
+ export const conversionRefused = (
590
+ r: LegacyConversion,
591
+ ): r is Extract<LegacyConversion, { ok: false }> => r.ok === false;
592
+
593
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
594
+ const QUERY_DEFINITION = /^query\s*:\s*([A-Za-z_][A-Za-z0-9_]*)\s+is\s+/;
595
+
596
+ /** A tag string value, with the characters the tag parser unescapes escaped. */
597
+ const tagString = (text: string) =>
598
+ `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
599
+
600
+ /** `text` with comments and string contents blanked to spaces, newlines kept, so a scan for syntax lands only on code. */
601
+ function blankNonCode(text: string): string {
602
+ let out = "";
603
+ let i = 0;
604
+ while (i < text.length) {
605
+ const two = text.slice(i, i + 2);
606
+ if (two === "//" || two === "--") {
607
+ const end = text.indexOf("\n", i);
608
+ const stop = end < 0 ? text.length : end;
609
+ out += " ".repeat(stop - i);
610
+ i = stop;
611
+ } else if (two === "/*") {
612
+ const end = text.indexOf("*/", i + 2);
613
+ const stop = end < 0 ? text.length : end + 2;
614
+ out += text.slice(i, stop).replace(/[^\n]/g, " ");
615
+ i = stop;
616
+ } else if (text[i] === "'" || text[i] === '"' || text[i] === "`") {
617
+ const quote = text[i];
618
+ let j = i + 1;
619
+ while (j < text.length && text[j] !== quote)
620
+ j += text[j] === "\\" ? 2 : 1;
621
+ const stop = Math.min(j, text.length);
622
+ out += quote + text.slice(i + 1, stop).replace(/[^\n]/g, " ");
623
+ if (stop < text.length) out += quote;
624
+ i = stop + 1;
625
+ } else {
626
+ out += text[i];
627
+ i++;
628
+ }
629
+ }
630
+ return out;
631
+ }
632
+
633
+ /** Every `->` outside brackets in already-blanked code. */
634
+ function topLevelArrows(blank: string): number[] {
635
+ const at: number[] = [];
636
+ let depth = 0;
637
+ for (let i = 0; i < blank.length; i++) {
638
+ const c = blank[i];
639
+ if (c === "{" || c === "(" || c === "[") depth++;
640
+ else if (c === "}" || c === ")" || c === "]") depth--;
641
+ else if (depth === 0 && c === "-" && blank[i + 1] === ">") at.push(i);
642
+ }
643
+ return at;
644
+ }
645
+
646
+ /** Removals applied last-first to `text`, which starts at `base` in the file the spans address. */
647
+ function withoutSpans(text: string, base: number, spans: Span[]): string {
648
+ let out = text;
649
+ for (const span of [...spans].sort((a, b) => b.start - a.start))
650
+ out = out.slice(0, span.start - base) + out.slice(span.end - base);
651
+ return out;
652
+ }
653
+
654
+ /** The `##|(markdown) name` block for a text tile; a body line that would close it early gets one space of indent. */
655
+ function textBlock(name: string, markdown: string): string {
656
+ const body = markdown
657
+ .split("\n")
658
+ .map((line) => (line.startsWith("|##") ? ` ${line}` : line))
659
+ .join("\n");
660
+ return `##|(markdown) ${name}\n${body === "" ? "" : `${body}\n`}|##\n`;
661
+ }
662
+
663
+ /** An extension-body line: tags and comments lose their old indent, other lines (inside a block comment) keep theirs. */
664
+ function indented(line: string): string {
665
+ if (line.trim() === "") return "";
666
+ return /^\s*(#|\/\/|--|\/\*)/.test(line)
667
+ ? ` ${line.trimStart()}`
668
+ : ` ${line}`;
669
+ }
670
+
671
+ interface LegacyStatement {
672
+ cell: NotebookSourceCell;
673
+ /** Text of the lines above the statement, less the prose that becomes text tiles. */
674
+ above: string;
675
+ /** From the statement's keyword to the end of the cell. */
676
+ statement: string;
677
+ /** The cell's whole text with only attached markdown removed: a definition is kept as it was. */
678
+ kept: string;
679
+ /** `"` notes above a `run:`. */
680
+ caption?: string;
681
+ line: number;
682
+ }
683
+
684
+ /** A view name from a tile's label or caption: snake_case words, or undefined when nothing usable is left. */
685
+ function viewNameFor(label: string | undefined): string | undefined {
686
+ const words = (label ?? "")
687
+ .toLowerCase()
688
+ .replace(/[^a-z0-9]+/g, "_")
689
+ .replace(/^_+|_+$/g, "");
690
+ // Long labels are cut at a word, not in the middle of one.
691
+ const cut = words.length > 40 ? words.lastIndexOf("_", 40) : words.length;
692
+ const slug = words.slice(0, cut > 0 ? cut : 40);
693
+ return /^[a-z]/.test(slug) && isBareName(slug) ? slug : undefined;
694
+ }
695
+
696
+ /**
697
+ * Rewrite a cell-format notebook (`run:` cells and prose cells) as a layout
698
+ * notebook: the same file with a `tiles=[…]` list, each prose cell a
699
+ * `##|(markdown)` block, and each `run:` a view in a `<source>_tiles`
700
+ * extension. Text outside the cells is carried over as written.
701
+ *
702
+ * PURE: text in, text out. The caller keeps the original to hand back on Undo.
703
+ */
704
+ export async function convertLegacyNotebook(
705
+ text: string,
706
+ ): Promise<LegacyConversion> {
707
+ const read = await readNotebookSource(text);
708
+ if (notebookSourceRefused(read))
709
+ return { ok: false, refused: read.refused, line: read.line };
710
+ const { header, cells } = read.source;
711
+ const refuse = (line: number, why: string): LegacyConversion => ({
712
+ ok: false,
713
+ refused: `Line ${line + 1}: ${why}`,
714
+ line: line + 1,
715
+ });
716
+
717
+ const headerLines = text.slice(header.start, header.end).split("\n");
718
+ const artifact = artifactTag(headerLines);
719
+ if (artifact && !artifactLeads(artifact.text))
720
+ return refuse(artifact.from, ARTIFACT_NOT_FIRST);
721
+ if (!artifact || readTileList(artifact.text))
722
+ return refuse(
723
+ Math.max(artifact?.from ?? 0, 0),
724
+ "this notebook already lists its tiles, so there is nothing to convert.",
725
+ );
726
+
727
+ const translation = await translate(
728
+ text,
729
+ "file:///publisher-notebook-builder/convert.malloy",
730
+ );
731
+ const stream = translation.parse?.tokenStream as TokenStream | undefined;
732
+ const vocabulary = stream?.tokenSource?.vocabulary;
733
+ const tokens = (stream?.getTokens?.() ?? []) as Token[];
734
+ if (typeof vocabulary?.getSymbolicName !== "function")
735
+ return refuse(0, "Malloy's token stream is not available.");
736
+ const malloy = await loadMalloy();
737
+ const { parseAnnotation } = await loadMalloyTag();
738
+ const symbolOf = (token: Token) => vocabulary.getSymbolicName(token.type);
739
+ const r = new Reader(text);
740
+ const comments = commentIndex(r, stream as TokenStream);
741
+ const tokenText = (token: Token) =>
742
+ text.slice(r.utf16(token.startIndex), r.utf16(token.stopIndex + 1));
743
+ const routeOf = (note: string) =>
744
+ malloy.routeOf({ value: note.trimStart() } as Parameters<
745
+ typeof malloy.routeOf
746
+ >[0]);
747
+ const payloadOf = (note: string) =>
748
+ malloy.payloadOf({ value: note } as Parameters<
749
+ typeof malloy.payloadOf
750
+ >[0]);
751
+ const lf = (value: string) => value.replace(/\r\n?/g, "\n");
752
+
753
+ // Names the new text and views must not take.
754
+ const taken = new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g));
755
+ const unique = (base: string) => {
756
+ let name = base;
757
+ for (let n = 2; taken.has(name); n++) name = `${base}_${n}`;
758
+ taken.add(name);
759
+ return name;
760
+ };
761
+
762
+ const analyse = (cell: NotebookSourceCell): LegacyStatement | undefined => {
763
+ const inside = tokens.filter(
764
+ (t) =>
765
+ t.channel === 0 &&
766
+ r.utf16(t.startIndex) >= cell.span.start &&
767
+ r.utf16(t.stopIndex + 1) <= cell.span.end,
768
+ );
769
+ const markdownRemovals: Span[] = [];
770
+ const captionRemovals: Span[] = [];
771
+ const captions: string[] = [];
772
+ let statement: Token | undefined;
773
+ for (let i = 0; i < inside.length; i++) {
774
+ const name = symbolOf(inside[i]);
775
+ if (name !== "ANNOTATION" && name !== "BLOCK_ANNOTATION_BEGIN") {
776
+ statement = inside[i];
777
+ break;
778
+ }
779
+ let last = i;
780
+ const bodies: string[] = [];
781
+ if (name === "BLOCK_ANNOTATION_BEGIN") {
782
+ while (
783
+ symbolOf(inside[last + 1] ?? inside[i]) ===
784
+ "BLOCK_ANNOTATION_TEXT"
785
+ )
786
+ bodies.push(tokenText(inside[++last]));
787
+ if (
788
+ symbolOf(inside[last + 1] ?? inside[i]) ===
789
+ "BLOCK_ANNOTATION_END"
790
+ )
791
+ last++;
792
+ }
793
+ const note = lf(tokenText(inside[i]));
794
+ const route = routeOf(note);
795
+ const from = r.utf16(inside[i].startIndex);
796
+ const lineStart = r.lineStarts[r.line(from)];
797
+ const span = {
798
+ start: /^[ \t]*$/.test(text.slice(lineStart, from))
799
+ ? lineStart
800
+ : from,
801
+ end: r.utf16(inside[last].stopIndex + 1),
802
+ };
803
+ if (route === "markdown") markdownRemovals.push(span);
804
+ else if (route === '"') {
805
+ captionRemovals.push(span);
806
+ captions.push(
807
+ name === "ANNOTATION"
808
+ ? lf(payloadOf(note)).replace(/\n$/, "").trim()
809
+ : [lf(payloadOf(note.split("\n", 1)[0])), ...bodies.map(lf)]
810
+ .map((l) => l.trim())
811
+ .filter(Boolean)
812
+ .join(" "),
813
+ );
814
+ }
815
+ i = last;
816
+ }
817
+ if (!statement) return undefined;
818
+ const statementAt = r.utf16(statement.startIndex);
819
+ const cellText = text.slice(cell.span.start, cell.span.end);
820
+ return {
821
+ cell,
822
+ above: withoutSpans(
823
+ text.slice(cell.span.start, statementAt),
824
+ cell.span.start,
825
+ (cell.kind === "query"
826
+ ? [...markdownRemovals, ...captionRemovals]
827
+ : markdownRemovals
828
+ ).filter((s) => s.end <= statementAt),
829
+ ),
830
+ statement: text.slice(statementAt, cell.span.end).trimEnd(),
831
+ kept: withoutSpans(cellText, cell.span.start, markdownRemovals),
832
+ ...(cell.kind === "query" &&
833
+ captions.length > 0 && { caption: captions.join(" ") }),
834
+ line: r.line(statementAt),
835
+ };
836
+ };
837
+
838
+ // Pass one: what each cell is, and the named queries a `run:` can name.
839
+ const named = new Map<string, { expression: string; cell: number }>();
840
+ const analysed = new Map<number, LegacyStatement>();
841
+ for (const [index, cell] of cells.entries()) {
842
+ if (cell.kind === "markdown") continue;
843
+ const found = analyse(cell);
844
+ if (!found)
845
+ return refuse(
846
+ r.line(cell.span.start),
847
+ "a cell with no statement the converter can place.",
848
+ );
849
+ analysed.set(index, found);
850
+ const query = QUERY_DEFINITION.exec(found.statement);
851
+ if (cell.kind === "definition" && query)
852
+ named.set(query[1], {
853
+ expression: found.statement.slice(query[0].length).trim(),
854
+ cell: index,
855
+ });
856
+ }
857
+
858
+ interface Resolved {
859
+ source: string;
860
+ body: string;
861
+ used: string[];
862
+ }
863
+ const resolve = (
864
+ statement: LegacyStatement,
865
+ ): Resolved | LegacyConversion => {
866
+ const keyword = /^run\s*:\s*/.exec(statement.statement);
867
+ if (!keyword)
868
+ return refuse(statement.line, "a run that is not `run: <query>`.");
869
+ let expression = statement.statement.slice(keyword[0].length).trim();
870
+ const used: string[] = [];
871
+ for (let hops = 0; hops < 10; hops++) {
872
+ const blank = blankNonCode(expression);
873
+ const lead = /^[A-Za-z_][A-Za-z0-9_]*/.exec(blank)?.[0];
874
+ const definition = lead ? named.get(lead) : undefined;
875
+ if (!lead || !definition) break;
876
+ const rest = expression.slice(lead.length).trim();
877
+ const restBlank = blank.slice(lead.length).trim();
878
+ if (
879
+ restBlank !== "" &&
880
+ !restBlank.startsWith("->") &&
881
+ !restBlank.startsWith("+")
882
+ )
883
+ break;
884
+ if (restBlank.startsWith("+")) {
885
+ const arrows = topLevelArrows(blankNonCode(definition.expression));
886
+ if (arrows.length !== 1)
887
+ return refuse(
888
+ statement.line,
889
+ `\`${lead} + { … }\` refines a query with more than one stage, which cannot become one view.`,
890
+ );
891
+ }
892
+ used.push(lead);
893
+ // A trailing `//` or `--` comment on the definition would swallow a refinement on its line.
894
+ const joiner = /(\/\/|--)[^\n]*$/.test(definition.expression)
895
+ ? "\n"
896
+ : " ";
897
+ expression = `${definition.expression}${rest === "" ? "" : `${joiner}${rest}`}`;
898
+ }
899
+ const blank = blankNonCode(expression);
900
+ // The hop limit stopped on a query name; `q -> …` would otherwise convert as a source called `q`.
901
+ if (named.has(/^[A-Za-z_][A-Za-z0-9_]*/.exec(blank)?.[0] ?? ""))
902
+ return refuse(
903
+ statement.line,
904
+ "this run names a query defined through more than 10 other queries, which the converter does not follow.",
905
+ );
906
+ const arrows = topLevelArrows(blank);
907
+ if (arrows.length === 0)
908
+ return refuse(
909
+ statement.line,
910
+ "this run is not `source -> view`, so it cannot become a tile. Fix: write it as `run: <source> -> <view>`.",
911
+ );
912
+ const head = expression.slice(0, arrows[0]).trim();
913
+ if (/\bextend\b/.test(blank.slice(0, arrows[0])))
914
+ return refuse(
915
+ statement.line,
916
+ "this run extends its source inline before `->`, so it cannot become a tile. Fix: declare the extension with a `source:` statement and run that.",
917
+ );
918
+ if (!IDENTIFIER.test(head) && !/^`[^`]+`$/.test(head))
919
+ return refuse(
920
+ statement.line,
921
+ "the source of this run is not a name, so it cannot become a tile. Fix: name it with a `source:` statement and run that.",
922
+ );
923
+ const body = expression.slice(arrows[0] + 2).trim();
924
+ if (body === "")
925
+ return refuse(statement.line, "this run has nothing after `->`.");
926
+ return { source: head, body, used };
927
+ };
928
+
929
+ // Pass two, in order: tiles, the views they run, and the cells left in place.
930
+ interface Extension {
931
+ name: string;
932
+ base: string;
933
+ views: string[];
934
+ }
935
+ const extensions = new Map<string, Extension>();
936
+ const entries: string[] = [];
937
+ const dropped = new Set<number>();
938
+ const placed = new Map<number, string>();
939
+ let textCount = 0;
940
+ let tileCount = 0;
941
+
942
+ const consumers = new Map<string, number>();
943
+ for (const statement of analysed.values()) {
944
+ if (statement.cell.kind !== "query") continue;
945
+ const resolved = resolve(statement);
946
+ if ("ok" in resolved) return resolved;
947
+ for (const name of resolved.used)
948
+ consumers.set(name, (consumers.get(name) ?? 0) + 1);
949
+ }
950
+ // A named query used by exactly one run, and by nothing else, is that run's view.
951
+ const consumable = (name: string) =>
952
+ consumers.get(name) === 1 &&
953
+ (text.match(new RegExp(`\\b${name}\\b`, "g")) ?? []).length === 2;
954
+ const carried = new Map<string, string[]>();
955
+
956
+ for (const [index, cell] of cells.entries()) {
957
+ if (cell.kind === "markdown") {
958
+ const name = unique(`text_${++textCount}`);
959
+ entries.push(`${name} { kind=text }`);
960
+ const aside = comments.all
961
+ .filter((c) => c.start >= cell.span.start && c.end <= cell.span.end)
962
+ .map((c) => `${text.slice(c.start, c.end)}\n`)
963
+ .join("");
964
+ placed.set(index, aside + textBlock(name, cell.markdown ?? ""));
965
+ continue;
966
+ }
967
+ const statement = analysed.get(index) as LegacyStatement;
968
+ let lead = "";
969
+ if (cell.markdown !== undefined) {
970
+ const name = unique(`text_${++textCount}`);
971
+ entries.push(`${name} { kind=text }`);
972
+ lead = `${textBlock(name, cell.markdown)}\n`;
973
+ }
974
+ if (cell.kind === "definition") {
975
+ const query = QUERY_DEFINITION.exec(statement.statement)?.[1];
976
+ if (query && consumable(query)) {
977
+ dropped.add(index);
978
+ carried.set(
979
+ query,
980
+ statement.above.split("\n").filter((l) => l.trim() !== ""),
981
+ );
982
+ if (lead) placed.set(index, lead.replace(/\n$/, ""));
983
+ continue;
984
+ }
985
+ placed.set(index, `${lead}${statement.kept}`);
986
+ continue;
987
+ }
988
+
989
+ const resolved = resolve(statement) as Resolved;
990
+ // The generated name is a bare identifier; the quoted base stays verbatim on the `extend`.
991
+ const base = resolved.source
992
+ .replace(/`/g, "")
993
+ .replace(/[^A-Za-z0-9_]+/g, "_")
994
+ .replace(/^(?=[0-9])/, "_");
995
+ let extension = extensions.get(resolved.source);
996
+ if (!extension) {
997
+ extension = {
998
+ name: unique(`${base}_tiles`),
999
+ base: resolved.source,
1000
+ views: [],
1001
+ };
1002
+ extensions.set(resolved.source, extension);
1003
+ }
1004
+
1005
+ const above = [
1006
+ ...resolved.used.flatMap((name) => carried.get(name) ?? []),
1007
+ ...statement.above.split("\n"),
1008
+ ].filter((l) => l.trim() !== "");
1009
+ const tagLines = above.filter((l) => /^\s*#(?!["(|])/.test(l));
1010
+ const tag =
1011
+ tagLines.length > 0
1012
+ ? parseTagLines(parseAnnotation, tagLines).tag
1013
+ : undefined;
1014
+ // A view is named for what the tile says about itself, else by its place.
1015
+ const view = unique(
1016
+ viewNameFor(tag?.text("label") ?? statement.caption) ??
1017
+ `tile_${tileCount + 1}`,
1018
+ );
1019
+ tileCount++;
1020
+ entries.push(`"${extension.name} -> ${view}"`);
1021
+ const lines = above.map(indented);
1022
+ if (statement.caption !== undefined) {
1023
+ const tagged =
1024
+ annotationTextProblem("caption", statement.caption) === undefined;
1025
+ if (tagged && !tag?.has("label"))
1026
+ lines.push(` # label=${tagString(statement.caption)}`);
1027
+ else if (tagged && !tag?.has("subtitle"))
1028
+ lines.push(` # subtitle=${tagString(statement.caption)}`);
1029
+ else lines.push(` #" ${statement.caption}`);
1030
+ }
1031
+ const body = resolved.body
1032
+ .split("\n")
1033
+ .map((l, i) => (i === 0 || l.trim() === "" ? l : ` ${l}`))
1034
+ .join("\n");
1035
+ extension.views.push([...lines, ` view: ${view} is ${body}`].join("\n"));
1036
+ dropped.add(index);
1037
+ if (lead) placed.set(index, lead.replace(/\n$/, ""));
1038
+ }
1039
+
1040
+ // Stitch: the header with its list, each cell's replacement, and the bytes between them as found.
1041
+ const close = (() => {
1042
+ let depth = 0;
1043
+ const tagText = artifact.text;
1044
+ for (let i = tagText.indexOf("{"); i < tagText.length; i++) {
1045
+ if (tagText[i] === '"') {
1046
+ for (i++; i < tagText.length && tagText[i] !== '"'; i++)
1047
+ if (tagText[i] === "\\") i++;
1048
+ } else if (tagText[i] === "{") depth++;
1049
+ else if (tagText[i] === "}" && --depth === 0) return i;
1050
+ }
1051
+ return -1;
1052
+ })();
1053
+ if (close < 0)
1054
+ return refuse(artifact.from, "the `## artifact { … }` tag never closes.");
1055
+ // The tag is written as a `##|` block with a tile on each line, which is how a layout is read and edited.
1056
+ const entryList =
1057
+ entries.length === 0
1058
+ ? "\n tiles=[]\n"
1059
+ : `\n tiles=[\n${entries.map((e) => ` ${e}`).join(",\n")}\n ]\n`;
1060
+ const rewritten = `${artifact.text
1061
+ .slice(0, close)
1062
+ .trimEnd()
1063
+ .replace(/^##(?!\|)/, "##|")}${entryList}${artifact.text.slice(close)}`;
1064
+ headerLines.splice(
1065
+ artifact.from,
1066
+ artifact.block ? artifact.to - artifact.from : 1,
1067
+ ...(artifact.block ? rewritten : `${rewritten}\n|##`).split("\n"),
1068
+ );
1069
+
1070
+ // Cells that left their place leave their gaps side by side; a run of blank lines is one, except inside a comment.
1071
+ const squeeze = (gap: { text: string; at: number[] }) => {
1072
+ const lines = gap.text.split("\n");
1073
+ const tail = lines.pop();
1074
+ const kept: string[] = [];
1075
+ let offset = 0;
1076
+ for (const line of lines) {
1077
+ const from = gap.at[offset] ?? -1;
1078
+ const inComment = comments.all.some(
1079
+ (c) => from >= c.start && from < c.end,
1080
+ );
1081
+ if (line.trim() !== "" || kept.at(-1)?.trim() !== "" || inComment)
1082
+ kept.push(line);
1083
+ offset += line.length + 1;
1084
+ }
1085
+ return kept.map((line) => `${line}\n`).join("") + tail;
1086
+ };
1087
+ const gap = { text: "", at: [] as number[] };
1088
+ const addGap = (from: number, to: number) => {
1089
+ gap.text += text.slice(from, to);
1090
+ for (let k = from; k < to; k++) gap.at.push(k);
1091
+ };
1092
+ let out = headerLines.join("\n");
1093
+ let cursor = header.end;
1094
+ for (const [index, cell] of cells.entries()) {
1095
+ addGap(cursor, cell.span.start);
1096
+ cursor = cell.span.end;
1097
+ const replacement = placed.get(index);
1098
+ if (replacement === undefined) continue;
1099
+ out +=
1100
+ squeeze(gap) +
1101
+ (replacement.endsWith("\n") ? replacement : `${replacement}\n`);
1102
+ gap.text = "";
1103
+ gap.at = [];
1104
+ }
1105
+ addGap(cursor, text.length);
1106
+ out = `${out.trimEnd()}\n` + (gap.text.trim() === "" ? "" : squeeze(gap));
1107
+ out = `${out.trimEnd()}\n`;
1108
+
1109
+ const blocks = [...extensions.values()].map(
1110
+ (extension) =>
1111
+ `source: ${extension.name} is ${extension.base} extend {\n${extension.views.join("\n\n")}\n}\n`,
1112
+ );
1113
+ if (blocks.length > 0) out += `\n${blocks.join("\n")}`;
1114
+ // The generated text is LF; a CRLF file gets CRLF throughout rather than a mix.
1115
+ if (text.includes("\r\n")) out = out.replace(/\r?\n/g, "\r\n");
1116
+ return { ok: true, text: out, tiles: entries.length };
1117
+ }