@malloy-publisher/sdk 0.9.1 → 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 +77 -47
  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,80 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ loadMalloy,
7
+ loadMalloyTag,
8
+ loadQueryBuilder,
9
+ unwrapMalloy,
10
+ unwrapMalloyTag,
11
+ unwrapQueryBuilder,
12
+ } from "./loadMalloy";
13
+
14
+ type Namespace = Parameters<typeof unwrapMalloy>[0];
15
+
16
+ describe("unwrapMalloy", () => {
17
+ class MalloyTranslator {}
18
+
19
+ it("returns an ESM-style namespace as it is", () => {
20
+ const ns = { MalloyTranslator, default: { other: 1 } };
21
+ expect(unwrapMalloy(ns as unknown as Namespace)).toBe(
22
+ ns as unknown as Namespace,
23
+ );
24
+ });
25
+
26
+ it("unwraps a default-only namespace from a bundled CommonJS import", () => {
27
+ const cjs = { MalloyTranslator };
28
+ const unwrapped = unwrapMalloy({ default: cjs } as unknown as Namespace);
29
+ expect(unwrapped.MalloyTranslator as unknown).toBe(MalloyTranslator);
30
+ });
31
+
32
+ it("loads the real package with a constructible translator", async () => {
33
+ const malloy = await loadMalloy();
34
+ expect(typeof malloy.MalloyTranslator).toBe("function");
35
+ });
36
+ });
37
+
38
+ describe("unwrapMalloyTag", () => {
39
+ type Tag = Parameters<typeof unwrapMalloyTag>[0];
40
+ const parseAnnotation = () => {};
41
+
42
+ it("returns an ESM-style namespace as it is", () => {
43
+ const ns = { parseAnnotation, default: { other: 1 } } as unknown as Tag;
44
+ expect(unwrapMalloyTag(ns)).toBe(ns);
45
+ });
46
+
47
+ it("unwraps a default-only namespace from a bundled CommonJS import", () => {
48
+ const unwrapped = unwrapMalloyTag({
49
+ default: { parseAnnotation },
50
+ } as unknown as Tag);
51
+ expect(unwrapped.parseAnnotation as unknown).toBe(parseAnnotation);
52
+ });
53
+
54
+ it("loads the real package with a callable parser", async () => {
55
+ const tag = await loadMalloyTag();
56
+ expect(typeof tag.parseAnnotation).toBe("function");
57
+ });
58
+ });
59
+
60
+ describe("unwrapQueryBuilder", () => {
61
+ type Builder = Parameters<typeof unwrapQueryBuilder>[0];
62
+ class ASTQuery {}
63
+
64
+ it("returns an ESM-style namespace as it is", () => {
65
+ const ns = { ASTQuery, default: { other: 1 } } as unknown as Builder;
66
+ expect(unwrapQueryBuilder(ns)).toBe(ns);
67
+ });
68
+
69
+ it("unwraps a default-only namespace from a bundled CommonJS import", () => {
70
+ const unwrapped = unwrapQueryBuilder({
71
+ default: { ASTQuery },
72
+ } as unknown as Builder);
73
+ expect(unwrapped.ASTQuery as unknown).toBe(ASTQuery);
74
+ });
75
+
76
+ it("loads the real package with a constructible query", async () => {
77
+ const builder = await loadQueryBuilder();
78
+ expect(typeof builder.ASTQuery).toBe("function");
79
+ });
80
+ });
@@ -0,0 +1,39 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ type Malloy = typeof import("@malloydata/malloy");
5
+ type MalloyTag = typeof import("@malloydata/malloy-tag");
6
+ type QueryBuilder = typeof import("@malloydata/malloy-query-builder");
7
+
8
+ // A bundler's CommonJS interop (Vite's dep optimizer) can hand back a namespace holding only `default`.
9
+ function unwrapNamespace<T extends object>(ns: T, probe: keyof T): T {
10
+ if (ns[probe]) return ns;
11
+ const inner = (ns as unknown as { default?: T }).default;
12
+ return inner?.[probe] ? inner : ns;
13
+ }
14
+
15
+ export const unwrapMalloy = (ns: Malloy): Malloy =>
16
+ unwrapNamespace(ns, "MalloyTranslator");
17
+
18
+ export const unwrapMalloyTag = (ns: MalloyTag): MalloyTag =>
19
+ unwrapNamespace(ns, "parseAnnotation");
20
+
21
+ export const unwrapQueryBuilder = (ns: QueryBuilder): QueryBuilder =>
22
+ unwrapNamespace(ns, "ASTQuery");
23
+
24
+ /**
25
+ * Imported dynamically, never statically: `builder-entry.ts` installs the
26
+ * `process.env` shim the parser's dependencies read at module scope, and a
27
+ * static import would be evaluated before that shim runs.
28
+ */
29
+ export async function loadMalloy(): Promise<Malloy> {
30
+ return unwrapMalloy(await import("@malloydata/malloy"));
31
+ }
32
+
33
+ export async function loadMalloyTag(): Promise<MalloyTag> {
34
+ return unwrapMalloyTag(await import("@malloydata/malloy-tag"));
35
+ }
36
+
37
+ export async function loadQueryBuilder(): Promise<QueryBuilder> {
38
+ return unwrapQueryBuilder(await import("@malloydata/malloy-query-builder"));
39
+ }
@@ -4,10 +4,16 @@
4
4
  import { describe, expect, it } from "bun:test";
5
5
  import {
6
6
  artifactLine,
7
+ artifactTag,
7
8
  blockSpans,
8
9
  closesBlock,
10
+ isBareName,
9
11
  isIdentifier,
12
+ isStrictName,
13
+ malloyPath,
14
+ readPath,
10
15
  markdownNote,
16
+ splitSourceLines,
11
17
  tileSteps,
12
18
  } from "./malloyText";
13
19
 
@@ -112,3 +118,45 @@ describe("blockSpans", () => {
112
118
  expect(blockSpans(lines, (i) => i >= 4)).toEqual([[0, 3]]);
113
119
  });
114
120
  });
121
+
122
+ describe("unclosed block openers", () => {
123
+ it("are scanned in linear time", () => {
124
+ const MB = 1024 * 1024;
125
+ const flat = "##| x\n".repeat(MB / 6);
126
+ let indented = "";
127
+ for (let i = 0; indented.length < MB; i++)
128
+ indented += `${" ".repeat(i % 64)}##| x\n`;
129
+ for (const source of [flat, indented]) {
130
+ const started = performance.now();
131
+ expect(artifactTag(splitSourceLines(source))).toBeUndefined();
132
+ expect(performance.now() - started).toBeLessThan(2000);
133
+ }
134
+ });
135
+ });
136
+
137
+ describe("reserved words", () => {
138
+ it("keeps statement keywords bare as source and view names, but not as given names or fields", () => {
139
+ for (const name of ["top", "index", "type", "limit", "view", "where"]) {
140
+ expect(isBareName(name)).toBe(true);
141
+ expect(isStrictName(name)).toBe(false);
142
+ }
143
+ for (const name of ["date", "Source", "IS", "year"]) {
144
+ expect(isBareName(name)).toBe(false);
145
+ expect(isStrictName(name)).toBe(false);
146
+ }
147
+ expect(isStrictName("revenue")).toBe(true);
148
+ });
149
+
150
+ it("back-quotes only a lone reserved field name", () => {
151
+ expect(malloyPath("date")).toBe("`date`");
152
+ // A dotted path stays verbatim: `.year` is reserved and is an accessor, not a name.
153
+ expect(malloyPath("orders.type.name")).toBe("orders.type.name");
154
+ expect(malloyPath("created_at.year")).toBe("created_at.year");
155
+ expect(malloyPath("type")).toBe("type");
156
+ expect(readPath("`date`")).toBe("date");
157
+ expect(readPath("lower(`date`)")).toBe("lower(`date`)");
158
+ expect(readPath("a.`b`")).toBe("a.`b`");
159
+ expect(malloyPath("products.category")).toBe("products.category");
160
+ expect(malloyPath("`odd name`.x")).toBe("`odd name`.x");
161
+ });
162
+ });
@@ -9,11 +9,94 @@
9
9
 
10
10
  const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
11
11
 
12
+ /** A file's lines, whatever its line endings: a CRLF line otherwise keeps a `\r` that a `$` anchor trips on. */
13
+ export const splitSourceLines = (source: string): string[] =>
14
+ source.split(/\r\n|\r|\n/);
15
+
12
16
  export const isIdentifier = (text: string) =>
13
17
  new RegExp(`^${IDENT}$`).test(text);
14
18
 
15
- /** The server's rule for the tag line: `## artifact` at the start of a line. */
16
- export const ARTIFACT_LINE = /^##[ \t]*artifact\b/;
19
+ /** Statement keywords: they lex as keywords only before `:` (`where: …`), so they stand bare as a source, view or tile name but not as a given name or filter field. */
20
+ const STATEMENT_KEYWORDS = new Set(
21
+ `accept aggregate calculate calculation connection declare dimension drill except given group_by grouped_by having index join_cross join_many join_one limit measure nest order_by partition_by primary_key query rename run sample select timezone top type view where`.split(
22
+ " ",
23
+ ),
24
+ );
25
+
26
+ /** Keywords that fail to compile as a bare name anywhere (case-insensitive), from Malloy's lexer. Static so the main entry never imports the compiler. */
27
+ const ALWAYS_RESERVED = new Set(
28
+ `all and as asc avg boolean by case cast compose count date day desc distinct else end exclude export extend false filter for from full has hour import in include inner internal is json left like max min minute month not now null number on or pick private public quarter right second source sql string sum table then this timestamp timestamptz to true virtual week when with year`.split(
29
+ " ",
30
+ ),
31
+ );
32
+
33
+ /** A name that can stand bare as a source, view or tile name: identifier-shaped and never reserved. */
34
+ export const isBareName = (text: string) =>
35
+ isIdentifier(text) && !ALWAYS_RESERVED.has(text.toLowerCase());
36
+
37
+ /** A name that can stand bare as a given name: also not a statement keyword, since `NAME ::` is not a statement. */
38
+ export const isStrictName = (text: string) =>
39
+ isBareName(text) && !STATEMENT_KEYWORDS.has(text.toLowerCase());
40
+
41
+ /** A filter field as written after `where:`: a lone reserved name is back-quoted; a dotted path (`.year` is reserved too) or an expression stays verbatim. */
42
+ export const malloyPath = (path: string) =>
43
+ isIdentifier(path) && !isBareName(path) ? `\`${path}\`` : path;
44
+
45
+ /**
46
+ * Whether a `##` note or `##|` block sets `artifact` as a top-level property, anywhere among its
47
+ * properties, as the tag parser reads it: not inside a string, a nested `{…}` or `[…]`, or a `#`
48
+ * comment, and not as a value (`title=artifact`) or a dotted path's tail. The server's rule too.
49
+ */
50
+ export function setsArtifactProperty(note: string): boolean {
51
+ // Malloy's route rule: a routed note (`##(markdown)`, `##"`, `##artifact`) or a flag (`##!`) is never a tag.
52
+ const prefix = /^##\|?(?:[ \t\r\n]|$)/.exec(note);
53
+ if (!prefix) return false;
54
+ // The tag parser's bare-name characters: digits, ASCII and Latin-extended letters, `_`.
55
+ const bare = /[0-9A-Za-z_\u00C0-\u024F\u1E00-\u1EFF]+/y;
56
+ let depth = 0;
57
+ let before = "";
58
+ for (let i = prefix[0].length; i < note.length; i++) {
59
+ const c = note[i];
60
+ if (/\s/.test(c)) continue;
61
+ // `-...` clears every property; its dots are no path for a name after it.
62
+ if (note.startsWith("-...", i)) {
63
+ i += 3;
64
+ before = "";
65
+ continue;
66
+ }
67
+ bare.lastIndex = i;
68
+ const word = bare.exec(note)?.[0];
69
+ if (c === '"' || c === "'") {
70
+ const fence = note.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
71
+ i += fence.length;
72
+ while (i < note.length && !note.startsWith(fence, i))
73
+ i += note[i] === "\\" ? 2 : 1;
74
+ i += fence.length - 1;
75
+ } else if (c === "`") {
76
+ // A backtick string is a name, so `` `artifact` `` sets the property.
77
+ let end = i + 1;
78
+ while (end < note.length && note[end] !== "`" && note[end] !== "\n")
79
+ end += note[end] === "\\" ? 2 : 1;
80
+ const name = note.slice(i + 1, end);
81
+ if (depth === 0 && name === "artifact" && !/[=.-]/.test(before))
82
+ return true;
83
+ i = end;
84
+ } else if (c === "#") {
85
+ const eol = note.indexOf("\n", i);
86
+ if (eol < 0) return false;
87
+ i = eol;
88
+ continue;
89
+ } else if (c === "{" || c === "[") depth++;
90
+ else if (c === "}" || c === "]") depth--;
91
+ else if (word) {
92
+ if (depth === 0 && word === "artifact" && !/[=.-]/.test(before))
93
+ return true;
94
+ i += word.length - 1;
95
+ }
96
+ before = c;
97
+ }
98
+ return false;
99
+ }
17
100
 
18
101
  /**
19
102
  * A note's markdown route, by Malloy's prefix rule: the first whitespace-delimited token is
@@ -58,18 +141,33 @@ export function blockSpans(
58
141
  lines: string[],
59
142
  skip?: (line: number) => boolean,
60
143
  ): [number, number][] {
144
+ // Each closer's lines by its column, so a file of unclosed openers is not rescanned to its end per opener.
145
+ const closers = new Map<string, number[]>();
146
+ lines.forEach((line, at) => {
147
+ const indent = /^[ \t]*/.exec(line)?.[0].length ?? 0;
148
+ for (const closer of ["|##", "|#"] as const)
149
+ if (closesBlock(line, indent, closer)) {
150
+ const key = `${indent}${closer}`;
151
+ const ats = closers.get(key);
152
+ if (ats) ats.push(at);
153
+ else closers.set(key, [at]);
154
+ break;
155
+ }
156
+ });
157
+ const cursor = new Map<string, number>();
61
158
  const spans: [number, number][] = [];
62
159
  for (let i = 0; i < lines.length; i++) {
63
160
  if (skip?.(i)) continue;
64
161
  const opener = /^([ \t]*)(#{1,2})\|/.exec(lines[i]);
65
162
  if (!opener) continue;
66
- const closer = opener[2] === "#" ? "|#" : "|##";
67
- for (let j = i + 1; j < lines.length; j++) {
68
- if (closesBlock(lines[j], opener[1].length, closer)) {
69
- spans.push([i, j]);
70
- i = j;
71
- break;
72
- }
163
+ const key = `${opener[1].length}${opener[2] === "#" ? "|#" : "|##"}`;
164
+ const ats = closers.get(key) ?? [];
165
+ let k = cursor.get(key) ?? 0;
166
+ while (k < ats.length && ats[k] <= i) k++;
167
+ cursor.set(key, k);
168
+ if (k < ats.length) {
169
+ spans.push([i, ats[k]]);
170
+ i = ats[k];
73
171
  }
74
172
  }
75
173
  return spans;
@@ -108,13 +206,55 @@ export function markdownLines(
108
206
  return out;
109
207
  }
110
208
 
111
- /** The line carrying the model-level `## artifact` tag, or -1. */
112
- export const artifactLine = (lines: string[]) => {
209
+ /** Where the model-level artifact tag sits, written as one `## artifact { … }` line or as a `##|` … `|##` block. */
210
+ export interface ArtifactTag {
211
+ /** The tag's first line: the `## artifact` line, or a block's `##|` opener. */
212
+ from: number;
213
+ /** The last line the tag occupies: the same line when single, else the `|##` closer. */
214
+ to: number;
215
+ block: boolean;
216
+ /** The tag as written: its line, or a block's lines from the opener up to, not including, the closer. */
217
+ text: string;
218
+ }
219
+
220
+ export function artifactTag(lines: string[]): ArtifactTag | undefined {
113
221
  const inBlock = blockLines(lines);
114
- return lines.findIndex(
115
- (l, i) => !inBlock.has(i) && ARTIFACT_LINE.test(l.trim()),
222
+ const single = lines.findIndex(
223
+ (l, i) =>
224
+ !inBlock.has(i) &&
225
+ // An unclosed `##|` opener holds no block, so it is no tag either.
226
+ !/^\s*##\|/.test(l) &&
227
+ setsArtifactProperty(l.trim()),
116
228
  );
117
- };
229
+ const span = blockSpans(lines).find(([from, to]) =>
230
+ setsArtifactProperty(lines.slice(from, to).join("\n").trim()),
231
+ );
232
+ if (span && (single < 0 || span[0] < single))
233
+ return {
234
+ from: span[0],
235
+ to: span[1],
236
+ block: true,
237
+ text: lines.slice(span[0], span[1]).join("\n"),
238
+ };
239
+ return single < 0
240
+ ? undefined
241
+ : { from: single, to: single, block: false, text: lines[single] };
242
+ }
243
+
244
+ /** Whether `artifact { … }` is the tag's first property, the one spelling the builder's tag rewrites can edit. */
245
+ export const artifactLeads = (tagText: string) =>
246
+ /^\s*##(?:\|\s*|[ \t]*)artifact\b/.test(tagText);
247
+
248
+ /** Why a tag the server serves is not opened when `artifact` is not its first property. */
249
+ export const ARTIFACT_NOT_FIRST =
250
+ "The `artifact` property is not the first on its tag, so the builder cannot rewrite the tag without risking the properties before it. Move `artifact { … }` first on the tag to edit this file here.";
251
+
252
+ /** The line carrying the model-level artifact tag (a block's opener), or -1. */
253
+ export const artifactLine = (lines: string[]) => artifactTag(lines)?.from ?? -1;
254
+
255
+ /** A tag's text as the annotation parser takes it: one `#` annotation, whatever the spelling. */
256
+ export const tagAnnotation = (tagText: string) =>
257
+ tagText.replace(/^\s*##\|?\s*/, "# ");
118
258
 
119
259
  /** An unnamed `"` note line; `##"word` is a malformed route Malloy drops. */
120
260
  const DOC_NOTE = /^##"([ \t]|$)/;
@@ -171,19 +311,29 @@ export function descriptionNotes(lines: string[]): {
171
311
  };
172
312
  }
173
313
 
174
- /** Whether `tiles=[…]` holds an entry that is not a quoted run expression, such as a `kind=text` tile. */
175
- export function hasNonQuotedTiles(artifactText: string): boolean {
176
- const key = artifactText.search(/tiles\s*=\s*\[/);
177
- if (key < 0) return false;
178
- const open = artifactText.indexOf("[", key);
179
- const close = artifactText.indexOf("]", open);
180
- if (close < 0) return false;
181
- return (
182
- artifactText
183
- .slice(open + 1, close)
184
- .replace(/"[^"]*"/g, "")
185
- .replace(/[\s,]/g, "").length > 0
186
- );
314
+ /** A text tile's name: a bare word, as the server reads a `tiles=[…]` entry. */
315
+ export const TEXT_TILE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
316
+
317
+ /**
318
+ * A floating `##|(markdown)` / `##|(text)` opener line: its route, and what follows the route.
319
+ * `name` is that text when it is a lone bare word; any other text on the opener is body.
320
+ */
321
+ export function textBlockOpener(
322
+ line: string,
323
+ ): { route: "markdown" | "text"; rest: string; name?: string } | undefined {
324
+ const trimmed = line.trim();
325
+ const token = trimmed.split(/[ \t\r]/, 1)[0];
326
+ const m =
327
+ /^##\|(?:\((markdown|text)\)|<(markdown|text)>|\[(markdown|text)\]|\{(markdown|text)\})$/.exec(
328
+ token,
329
+ );
330
+ if (!m) return undefined;
331
+ const rest = trimmed.slice(token.length).trim();
332
+ return {
333
+ route: (m[1] ?? m[2] ?? m[3] ?? m[4]) as "markdown" | "text",
334
+ rest,
335
+ ...(TEXT_TILE_NAME.test(rest) ? { name: rest } : {}),
336
+ };
187
337
  }
188
338
 
189
339
  /** A tile expression's steps: `orders -> by_brand + { limit: 2 }`. */
@@ -212,3 +362,7 @@ export function tileSteps(
212
362
  ...(refinement === undefined ? {} : { refinement }),
213
363
  };
214
364
  }
365
+
366
+ /** The inverse of {@link malloyPath}: a field that is exactly one back-quoted identifier is read as the plain name; anything else is verbatim. */
367
+ export const readPath = (path: string) =>
368
+ /^`([A-Za-z_][A-Za-z0-9_]*)`$/.test(path) ? path.slice(1, -1) : path;
@@ -20,7 +20,8 @@
20
20
  * minifiers leave alone.
21
21
  */
22
22
 
23
- import { blockSpans, markdownLines } from "./malloyText";
23
+ import { blockSpans, markdownLines, textBlockOpener } from "./malloyText";
24
+ import { loadMalloy } from "./loadMalloy";
24
25
 
25
26
  /** A half-open range of UTF-16 offsets into the source text. */
26
27
  export interface Span {
@@ -151,6 +152,17 @@ export interface TreeImport extends Positioned {
151
152
  statement: Span;
152
153
  }
153
154
 
155
+ /** A floating `##|(markdown) [name]` … `|##` block, which a dashboard reads as a text tile's body. */
156
+ export interface TreeTextBlock extends Positioned {
157
+ /** Absent when the opener has no name, or more than one word after the route. */
158
+ name?: string;
159
+ route: "markdown" | "text";
160
+ /** Text on the opener line (unless it is only the name), then the body lines; no trailing newline. */
161
+ body: string;
162
+ /** From the opener's line start through the closer's newline: the whole-line extent a writer replaces or removes. */
163
+ span: Span;
164
+ }
165
+
154
166
  export interface ParsedMalloy {
155
167
  text: string;
156
168
  /** 0-based line -> offset of its first character. */
@@ -158,6 +170,8 @@ export interface ParsedMalloy {
158
170
  imports: TreeImport[];
159
171
  sources: TreeSource[];
160
172
  givens: TreeGiven[];
173
+ /** The closed floating `(markdown)` / `(text)` blocks, in file order. */
174
+ textBlocks: TreeTextBlock[];
161
175
  /** The comment token on `line`, if the line ends with one. */
162
176
  trailingComment(line: number): Span | undefined;
163
177
  /**
@@ -198,14 +212,14 @@ export const parseRefused = (r: ParseResult): r is ParseRefusal =>
198
212
  /* Node identity */
199
213
  /* ------------------------------------------------------------------ */
200
214
 
201
- interface TokenStream {
215
+ export interface TokenStream {
202
216
  tokenSource?: {
203
217
  vocabulary?: { getSymbolicName(type: number): string | undefined };
204
218
  };
205
219
  getTokens?(): Array<{ type: number; startIndex: number; stopIndex: number }>;
206
220
  }
207
221
 
208
- type Ctx = Record<string, unknown> & {
222
+ export type Ctx = Record<string, unknown> & {
209
223
  ruleIndex?: number;
210
224
  childCount?: number;
211
225
  getChild(i: number): Ctx;
@@ -219,7 +233,7 @@ const has = (c: unknown, ...accessors: string[]): boolean =>
219
233
  );
220
234
 
221
235
  /** A rule context we can take a range from; terminals and empties are not. */
222
- const isRule = (c: Ctx | undefined): boolean =>
236
+ export const isRule = (c: Ctx | undefined): boolean =>
223
237
  c !== undefined && c.ruleIndex !== undefined && (c.childCount ?? 0) > 0;
224
238
 
225
239
  const IS = {
@@ -283,7 +297,7 @@ function lineStartsOf(text: string): number[] {
283
297
 
284
298
  /* ------------------------------------------------------------------ */
285
299
 
286
- class Reader {
300
+ export class Reader {
287
301
  private readonly map: Int32Array;
288
302
  readonly lineStarts: number[];
289
303
  /**
@@ -531,6 +545,8 @@ function readViewBody(r: Reader, vExpr: Ctx): TreeViewBody {
531
545
  return { kind: "unsupported", why: "a chained refinement" };
532
546
  base = inner[0];
533
547
  }
548
+ if (base && IS.segParen(base))
549
+ return { kind: "unsupported", why: "a parenthesized expression" };
534
550
  if (!base || !IS.segField(base))
535
551
  return {
536
552
  kind: "unsupported",
@@ -812,6 +828,7 @@ export async function parseMalloy(text: string): Promise<ParseResult> {
812
828
  imports: readImports(r, root),
813
829
  sources,
814
830
  givens: readGivens(r, root),
831
+ textBlocks: readTextBlocks(r, tokenStream),
815
832
  trailingComment: (line) => comments.trailing.get(line),
816
833
  comments: comments.all,
817
834
  commentLine: (line) => comments.lines.has(line),
@@ -829,6 +846,8 @@ export async function parseMalloy(text: string): Promise<ParseResult> {
829
846
  export interface MalloyProblem {
830
847
  code?: string;
831
848
  message?: string;
849
+ /** 0-based. */
850
+ at?: { range?: { start?: { line?: number } } };
832
851
  }
833
852
 
834
853
  /** One parse of one file, stopped at the parse step. */
@@ -854,7 +873,7 @@ export async function translate(
854
873
  // Imported dynamically, never statically: `builder-entry.ts` installs the
855
874
  // `process.env` shim the parser's dependencies read at module scope, and a
856
875
  // static import would be evaluated before that shim runs.
857
- const { MalloyTranslator } = await import("@malloydata/malloy");
876
+ const { MalloyTranslator } = await loadMalloy();
858
877
  const translator = new MalloyTranslator(url, null, {
859
878
  urls: { [url]: text },
860
879
  }) as unknown as {
@@ -882,7 +901,7 @@ export async function translate(
882
901
  * that follows code is a trailing comment, and anything appended to that line
883
902
  * has to go before it.
884
903
  */
885
- function commentIndex(
904
+ export function commentIndex(
886
905
  r: Reader,
887
906
  tokenStream: TokenStream,
888
907
  ): { trailing: Map<number, Span>; lines: Set<number>; all: Span[] } {
@@ -976,3 +995,132 @@ function blockStart(
976
995
  }
977
996
  return start;
978
997
  }
998
+
999
+ /* ------------------------------------------------------------------ */
1000
+ /* Text tiles */
1001
+ /* ------------------------------------------------------------------ */
1002
+
1003
+ /** The closed `##|(markdown)` / `##|(text)` blocks, read from the lexer's own tokens so a `|##` in a string or comment never closes one. */
1004
+ function readTextBlocks(r: Reader, stream: TokenStream): TreeTextBlock[] {
1005
+ const tokens = stream.getTokens?.() ?? [];
1006
+ const vocabulary = stream.tokenSource?.vocabulary;
1007
+ const symbolOf = (token: { type: number }) =>
1008
+ vocabulary?.getSymbolicName(token.type);
1009
+ const tokenText = (token: { startIndex: number; stopIndex: number }) =>
1010
+ r.text.slice(
1011
+ r.utf16(token.startIndex) ?? 0,
1012
+ r.utf16(token.stopIndex + 1) ?? r.text.length,
1013
+ );
1014
+ const blocks: TreeTextBlock[] = [];
1015
+ for (let i = 0; i < tokens.length; i++) {
1016
+ if (symbolOf(tokens[i]) !== "DOC_BLOCK_ANNOTATION_BEGIN") continue;
1017
+ const opener = textBlockOpener(
1018
+ tokenText(tokens[i]).replace(/\r?\n$/, ""),
1019
+ );
1020
+ if (!opener) continue;
1021
+ const lines: string[] = [];
1022
+ let j = i + 1;
1023
+ for (; symbolOf(tokens[j] ?? tokens[i]) === "BLOCK_ANNOTATION_TEXT"; j++)
1024
+ lines.push(tokenText(tokens[j]));
1025
+ const closer = tokens[j];
1026
+ if (!closer || symbolOf(closer) !== "BLOCK_ANNOTATION_END") continue;
1027
+ const first = r.line(r.utf16(tokens[i].startIndex) ?? 0);
1028
+ const end = r.utf16(closer.stopIndex + 1) ?? r.text.length;
1029
+ const onOpener =
1030
+ opener.name === undefined && opener.rest ? [`${opener.rest}\n`] : [];
1031
+ blocks.push({
1032
+ ...(opener.name === undefined ? {} : { name: opener.name }),
1033
+ route: opener.route,
1034
+ body: [...onOpener, ...lines]
1035
+ .join("")
1036
+ .replace(/\r\n?/g, "\n")
1037
+ .replace(/\n$/, ""),
1038
+ span: { start: r.lineStarts[first], end },
1039
+ line: first,
1040
+ });
1041
+ i = j;
1042
+ }
1043
+ return blocks;
1044
+ }
1045
+
1046
+ /** One `tiles=[…]` entry, exactly as written, with where it sits in the line. */
1047
+ export interface TileEntry {
1048
+ text: string;
1049
+ span: Span;
1050
+ }
1051
+
1052
+ export interface TileList {
1053
+ /** Offsets of `[` and the matching `]` in the line. */
1054
+ open: number;
1055
+ close: number;
1056
+ entries: TileEntry[];
1057
+ }
1058
+
1059
+ /** The index of the quote closing the string that opens at `open`. */
1060
+ function stringEnd(line: string, open: number): number {
1061
+ for (let i = open + 1; i < line.length; i++) {
1062
+ if (line[i] === "\\") i++;
1063
+ else if (line[i] === '"') return i;
1064
+ }
1065
+ return line.length;
1066
+ }
1067
+
1068
+ /**
1069
+ * The `tiles=[…]` list of a one-line `## artifact { … }` tag, as written: quoted run expressions
1070
+ * and `name { kind=text … }` entries alike. Undefined when the tag has no list or it never closes.
1071
+ * Strings and nested braces are skipped, so a title containing `tiles=[` or a `]` is not the list.
1072
+ */
1073
+ export function readTileList(line: string): TileList | undefined {
1074
+ let depth = 0;
1075
+ let groups = 0;
1076
+ for (let i = 0; i < line.length; i++) {
1077
+ const c = line[i];
1078
+ if (c === '"') i = stringEnd(line, i);
1079
+ else if (c === "{" || c === "[") {
1080
+ if (depth++ === 0) groups++;
1081
+ } else if (c === "}" || c === "]") depth--;
1082
+ else if (
1083
+ groups === 1 &&
1084
+ depth === 1 &&
1085
+ line.startsWith("tiles", i) &&
1086
+ !/[A-Za-z0-9_]/.test(line[i - 1] ?? " ")
1087
+ ) {
1088
+ const key = /^tiles\s*=\s*\[/.exec(line.slice(i));
1089
+ if (key) return scanTileList(line, i + key[0].length - 1);
1090
+ }
1091
+ }
1092
+ return undefined;
1093
+ }
1094
+
1095
+ function scanTileList(line: string, open: number): TileList | undefined {
1096
+ const entries: TileEntry[] = [];
1097
+ let depth = 0;
1098
+ let from = open + 1;
1099
+ const push = (to: number) => {
1100
+ const text = line.slice(from, to);
1101
+ const lead = text.length - text.trimStart().length;
1102
+ const trimmed = text.trim();
1103
+ if (trimmed !== "")
1104
+ entries.push({
1105
+ text: trimmed,
1106
+ span: { start: from + lead, end: from + lead + trimmed.length },
1107
+ });
1108
+ };
1109
+ for (let i = open + 1; i < line.length; i++) {
1110
+ const c = line[i];
1111
+ if (c === '"') i = stringEnd(line, i);
1112
+ else if (c === "{" || c === "[") depth++;
1113
+ else if (c === "}") depth--;
1114
+ else if (c === "]") {
1115
+ if (depth === 0) {
1116
+ push(i);
1117
+ return { open, close: i, entries };
1118
+ }
1119
+ depth--;
1120
+ } else if (c === "," && depth === 0) {
1121
+ push(i);
1122
+ from = i + 1;
1123
+ }
1124
+ }
1125
+ return undefined;
1126
+ }