@diegopluna/narvi 0.0.2 → 0.2.0

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 (313) hide show
  1. package/README.md +116 -44
  2. package/dist/base.css +96 -0
  3. package/dist/color.d.ts +1 -1
  4. package/dist/color.js +1 -1
  5. package/dist/components/activity/ActivityContent.svelte +3 -15
  6. package/dist/components/activity/ActivityStep.svelte +12 -12
  7. package/dist/components/activity/ActivityThought.svelte +4 -4
  8. package/dist/components/activity/ActivityTrigger.svelte +5 -6
  9. package/dist/components/app-shell/AppShellBar.svelte +89 -0
  10. package/dist/components/app-shell/AppShellBar.svelte.d.ts +20 -0
  11. package/dist/components/app-shell/AppShellHeader.svelte +17 -17
  12. package/dist/components/app-shell/AppShellHeader.svelte.d.ts +2 -2
  13. package/dist/components/app-shell/AppShellMain.svelte +4 -20
  14. package/dist/components/app-shell/AppShellPanel.svelte +21 -19
  15. package/dist/components/app-shell/AppShellPanes.svelte +58 -0
  16. package/dist/components/app-shell/AppShellPanes.svelte.d.ts +11 -0
  17. package/dist/components/app-shell/AppShellRail.svelte +85 -0
  18. package/dist/components/app-shell/AppShellRail.svelte.d.ts +11 -0
  19. package/dist/components/app-shell/AppShellRoot.svelte +50 -24
  20. package/dist/components/app-shell/AppShellRoot.svelte.d.ts +8 -6
  21. package/dist/components/app-shell/AppShellSheet.svelte +95 -0
  22. package/dist/components/app-shell/AppShellSheet.svelte.d.ts +17 -0
  23. package/dist/components/app-shell/AppShellSidebar.svelte +41 -65
  24. package/dist/components/app-shell/AppShellSidebar.svelte.d.ts +1 -5
  25. package/dist/components/app-shell/AppShellToggle.svelte +62 -23
  26. package/dist/components/app-shell/AppShellToggle.svelte.d.ts +2 -0
  27. package/dist/components/app-shell/context.d.ts +6 -0
  28. package/dist/components/app-shell/index.d.ts +9 -1
  29. package/dist/components/app-shell/index.js +5 -1
  30. package/dist/components/approval/Approval.svelte +99 -23
  31. package/dist/components/approval/Approval.svelte.d.ts +7 -0
  32. package/dist/components/avatar/AvatarFallback.svelte +1 -2
  33. package/dist/components/avatar/AvatarRoot.svelte +2 -2
  34. package/dist/components/badge/Badge.svelte +5 -5
  35. package/dist/components/button/Button.svelte +227 -51
  36. package/dist/components/button/Button.svelte.d.ts +38 -2
  37. package/dist/components/card/Card.svelte +19 -33
  38. package/dist/components/change-stats/ChangeStats.svelte +1 -2
  39. package/dist/components/changes-summary/ChangesSummary.svelte +14 -15
  40. package/dist/components/checkbox/Checkbox.svelte +31 -25
  41. package/dist/components/checkbox/Checkbox.svelte.d.ts +5 -0
  42. package/dist/components/code/Code.svelte +1 -2
  43. package/dist/components/collapsible/CollapsibleContent.svelte +38 -0
  44. package/dist/components/collapsible/CollapsibleContent.svelte.d.ts +11 -0
  45. package/dist/components/collapsible/CollapsibleRoot.svelte +44 -0
  46. package/dist/components/collapsible/CollapsibleRoot.svelte.d.ts +11 -0
  47. package/dist/components/collapsible/CollapsibleTrigger.svelte +83 -0
  48. package/dist/components/collapsible/CollapsibleTrigger.svelte.d.ts +13 -0
  49. package/dist/components/collapsible/context.d.ts +5 -0
  50. package/dist/components/collapsible/context.js +11 -0
  51. package/dist/components/collapsible/index.d.ts +7 -0
  52. package/dist/components/collapsible/index.js +4 -0
  53. package/dist/components/command/CommandItem.svelte +1 -1
  54. package/dist/components/command/styles.d.ts +3 -2
  55. package/dist/components/command/styles.js +15 -12
  56. package/dist/components/composer/ComposerAttachButton.svelte +1 -1
  57. package/dist/components/composer/ComposerAttachment.svelte +13 -18
  58. package/dist/components/composer/ComposerModelPicker.svelte +24 -28
  59. package/dist/components/composer/ComposerRoot.svelte +15 -13
  60. package/dist/components/composer/ComposerSubmit.svelte +12 -20
  61. package/dist/components/composer/ComposerTextarea.svelte +1 -1
  62. package/dist/components/composer/ComposerToggle.svelte +16 -18
  63. package/dist/components/composer/ComposerTray.svelte +78 -0
  64. package/dist/components/composer/ComposerTray.svelte.d.ts +15 -0
  65. package/dist/components/composer/index.d.ts +3 -1
  66. package/dist/components/composer/index.js +3 -2
  67. package/dist/components/conversation/ConversationContent.svelte +3 -2
  68. package/dist/components/conversation/ConversationEmpty.svelte +1 -1
  69. package/dist/components/conversation/ConversationScrollButton.svelte +9 -11
  70. package/dist/components/dialog/ConfirmDialog.svelte +1 -1
  71. package/dist/components/dialog/DialogContent.svelte +5 -1
  72. package/dist/components/dialog/styles.d.ts +2 -26
  73. package/dist/components/dialog/styles.js +12 -49
  74. package/dist/components/divider/Divider.svelte +3 -3
  75. package/dist/components/empty-state/EmptyState.svelte +4 -5
  76. package/dist/components/field/Field.svelte +4 -4
  77. package/dist/components/frame/Frame.svelte +6 -7
  78. package/dist/components/frame/Frame.svelte.d.ts +1 -1
  79. package/dist/components/grid/Grid.svelte +111 -0
  80. package/dist/components/grid/Grid.svelte.d.ts +27 -0
  81. package/dist/components/heading/Heading.svelte +2 -2
  82. package/dist/components/hover-card/HoverCardContent.svelte +50 -0
  83. package/dist/components/hover-card/HoverCardContent.svelte.d.ts +10 -0
  84. package/dist/components/hover-card/HoverCardRoot.svelte +22 -0
  85. package/dist/components/hover-card/HoverCardRoot.svelte.d.ts +5 -0
  86. package/dist/components/hover-card/index.d.ts +7 -0
  87. package/dist/components/hover-card/index.js +7 -0
  88. package/dist/components/kbd/Kbd.svelte +12 -7
  89. package/dist/components/link/Link.svelte +9 -7
  90. package/dist/components/link/Link.svelte.d.ts +4 -1
  91. package/dist/components/markdown/Markdown.svelte +714 -0
  92. package/dist/components/markdown/Markdown.svelte.d.ts +80 -0
  93. package/dist/components/markdown/MarkdownBlock.svelte +231 -0
  94. package/dist/components/markdown/MarkdownBlock.svelte.d.ts +11 -0
  95. package/dist/components/markdown/MarkdownBlocks.svelte +115 -0
  96. package/dist/components/markdown/MarkdownBlocks.svelte.d.ts +15 -0
  97. package/dist/components/markdown/MarkdownCode.svelte +583 -0
  98. package/dist/components/markdown/MarkdownCode.svelte.d.ts +23 -0
  99. package/dist/components/markdown/MarkdownDiagram.svelte +310 -0
  100. package/dist/components/markdown/MarkdownDiagram.svelte.d.ts +6 -0
  101. package/dist/components/markdown/MarkdownFile.svelte +134 -0
  102. package/dist/components/markdown/MarkdownFile.svelte.d.ts +19 -0
  103. package/dist/components/markdown/MarkdownFootnotes.svelte +61 -0
  104. package/dist/components/markdown/MarkdownFootnotes.svelte.d.ts +8 -0
  105. package/dist/components/markdown/MarkdownFresh.svelte +69 -0
  106. package/dist/components/markdown/MarkdownFresh.svelte.d.ts +6 -0
  107. package/dist/components/markdown/MarkdownHtml.svelte +72 -0
  108. package/dist/components/markdown/MarkdownHtml.svelte.d.ts +7 -0
  109. package/dist/components/markdown/MarkdownImage.svelte +150 -0
  110. package/dist/components/markdown/MarkdownImage.svelte.d.ts +8 -0
  111. package/dist/components/markdown/MarkdownInlines.svelte +225 -0
  112. package/dist/components/markdown/MarkdownInlines.svelte.d.ts +7 -0
  113. package/dist/components/markdown/MarkdownLink.svelte +120 -0
  114. package/dist/components/markdown/MarkdownLink.svelte.d.ts +25 -0
  115. package/dist/components/markdown/MarkdownMath.svelte +138 -0
  116. package/dist/components/markdown/MarkdownMath.svelte.d.ts +7 -0
  117. package/dist/components/markdown/MarkdownTable.svelte +265 -0
  118. package/dist/components/markdown/MarkdownTable.svelte.d.ts +17 -0
  119. package/dist/components/markdown/caret.d.ts +14 -0
  120. package/dist/components/markdown/caret.js +67 -0
  121. package/dist/components/markdown/context.d.ts +93 -0
  122. package/dist/components/markdown/context.js +128 -0
  123. package/dist/components/markdown/copy.d.ts +13 -0
  124. package/dist/components/markdown/copy.js +74 -0
  125. package/dist/components/markdown/hidden.d.ts +12 -0
  126. package/dist/components/markdown/hidden.js +31 -0
  127. package/dist/components/markdown/kept.d.ts +32 -0
  128. package/dist/components/markdown/kept.js +71 -0
  129. package/dist/components/markdown/labels.d.ts +46 -0
  130. package/dist/components/markdown/labels.js +35 -0
  131. package/dist/components/markdown/save.d.ts +11 -0
  132. package/dist/components/markdown/save.js +58 -0
  133. package/dist/components/markdown/scrollable.d.ts +24 -0
  134. package/dist/components/markdown/scrollable.js +152 -0
  135. package/dist/components/markdown/static.d.ts +37 -0
  136. package/dist/components/markdown/static.js +233 -0
  137. package/dist/components/markdown/styles.d.ts +328 -0
  138. package/dist/components/markdown/styles.js +302 -0
  139. package/dist/components/menu/MenuRadioItem.svelte +3 -3
  140. package/dist/components/menu/index.d.ts +23 -0
  141. package/dist/components/menu/index.js +3 -1
  142. package/dist/components/message/MessageAction.svelte +24 -5
  143. package/dist/components/message/MessageAction.svelte.d.ts +9 -0
  144. package/dist/components/message/MessageActions.svelte +2 -3
  145. package/dist/components/message/MessageContent.svelte +2 -3
  146. package/dist/components/message/MessageCopy.svelte +66 -8
  147. package/dist/components/message/MessageCopy.svelte.d.ts +17 -1
  148. package/dist/components/message/MessageHeader.svelte +3 -3
  149. package/dist/components/message/MessagePending.svelte +1 -1
  150. package/dist/components/message/MessageRoot.svelte +3 -4
  151. package/dist/components/message/MessageTime.svelte +3 -4
  152. package/dist/components/notice/Notice.svelte +14 -10
  153. package/dist/components/plan/Plan.svelte +25 -21
  154. package/dist/components/progress/Progress.svelte +34 -38
  155. package/dist/components/questionnaire/Questionnaire.svelte +19 -22
  156. package/dist/components/queued-message/QueuedMessage.svelte +14 -7
  157. package/dist/components/rail/RailItem.svelte +43 -40
  158. package/dist/components/rail/RailItem.svelte.d.ts +3 -1
  159. package/dist/components/rail/RailRoot.svelte +18 -4
  160. package/dist/components/rail/RailRoot.svelte.d.ts +1 -1
  161. package/dist/components/rail/RailSeparator.svelte +17 -0
  162. package/dist/components/rail/RailSeparator.svelte.d.ts +18 -0
  163. package/dist/components/rail/index.d.ts +2 -1
  164. package/dist/components/rail/index.js +2 -1
  165. package/dist/components/reasoning/ReasoningContent.svelte +4 -8
  166. package/dist/components/reasoning/ReasoningTrigger.svelte +4 -5
  167. package/dist/components/resize-handle/ResizeHandle.svelte +4 -7
  168. package/dist/components/reveal/Reveal.svelte +89 -0
  169. package/dist/components/reveal/Reveal.svelte.d.ts +17 -0
  170. package/dist/components/reveal/revealed.d.ts +38 -0
  171. package/dist/components/reveal/revealed.js +79 -0
  172. package/dist/components/segmented/SegmentedControl.svelte +11 -16
  173. package/dist/components/select/Select.svelte +1 -1
  174. package/dist/components/separator/Separator.svelte +1 -1
  175. package/dist/components/settings-row/SettingsRow.svelte +5 -5
  176. package/dist/components/sheet/SheetContent.svelte +63 -0
  177. package/dist/components/sheet/SheetContent.svelte.d.ts +18 -0
  178. package/dist/components/sheet/index.d.ts +12 -0
  179. package/dist/components/sheet/index.js +12 -0
  180. package/dist/components/sheet/styles.d.ts +51 -0
  181. package/dist/components/sheet/styles.js +65 -0
  182. package/dist/components/shimmer/Shimmer.svelte +41 -26
  183. package/dist/components/sidebar/SidebarContent.svelte +1 -1
  184. package/dist/components/sidebar/SidebarFolder.svelte +142 -0
  185. package/dist/components/sidebar/SidebarFolder.svelte.d.ts +19 -0
  186. package/dist/components/sidebar/SidebarFooter.svelte +1 -1
  187. package/dist/components/sidebar/SidebarGroup.svelte +41 -35
  188. package/dist/components/sidebar/SidebarGroup.svelte.d.ts +3 -3
  189. package/dist/components/sidebar/SidebarHeader.svelte +12 -6
  190. package/dist/components/sidebar/SidebarHeader.svelte.d.ts +4 -1
  191. package/dist/components/sidebar/SidebarItem.svelte +34 -38
  192. package/dist/components/sidebar/SidebarRoot.svelte +62 -0
  193. package/dist/components/sidebar/SidebarRoot.svelte.d.ts +14 -0
  194. package/dist/components/sidebar/index.d.ts +5 -1
  195. package/dist/components/sidebar/index.js +3 -1
  196. package/dist/components/skeleton/Skeleton.svelte +26 -15
  197. package/dist/components/slider/Slider.svelte +200 -0
  198. package/dist/components/slider/Slider.svelte.d.ts +55 -0
  199. package/dist/components/spinner/Spinner.svelte +4 -11
  200. package/dist/components/stack/Stack.svelte +37 -44
  201. package/dist/components/stack/Stack.svelte.d.ts +12 -6
  202. package/dist/components/status-indicator/StatusIndicator.svelte +1 -1
  203. package/dist/components/suggestions/SuggestionsItem.svelte +11 -13
  204. package/dist/components/switch/Switch.svelte +16 -25
  205. package/dist/components/tab-strip/TabStrip.svelte +340 -0
  206. package/dist/components/tab-strip/TabStrip.svelte.d.ts +31 -0
  207. package/dist/components/tabs/Tabs.svelte +15 -14
  208. package/dist/components/tabs/Tabs.svelte.d.ts +4 -0
  209. package/dist/components/text/Text.svelte +64 -14
  210. package/dist/components/text/Text.svelte.d.ts +13 -3
  211. package/dist/components/toast/Toaster.svelte +12 -10
  212. package/dist/components/toggle/Toggle.svelte +40 -0
  213. package/dist/components/toggle/Toggle.svelte.d.ts +15 -0
  214. package/dist/components/toggle-group/ToggleGroupItem.svelte +37 -0
  215. package/dist/components/toggle-group/ToggleGroupItem.svelte.d.ts +12 -0
  216. package/dist/components/toggle-group/ToggleGroupRoot.svelte +95 -0
  217. package/dist/components/toggle-group/ToggleGroupRoot.svelte.d.ts +33 -0
  218. package/dist/components/toggle-group/context.d.ts +6 -0
  219. package/dist/components/toggle-group/context.js +11 -0
  220. package/dist/components/toggle-group/index.d.ts +5 -0
  221. package/dist/components/toggle-group/index.js +3 -0
  222. package/dist/components/tool/ToolContent.svelte +3 -8
  223. package/dist/components/tool/ToolSection.svelte +4 -5
  224. package/dist/components/tool/ToolTrigger.svelte +14 -15
  225. package/dist/components/tooltip/TooltipContent.svelte +9 -6
  226. package/dist/components/work-fold/WorkFold.svelte +17 -34
  227. package/dist/components/work-fold/WorkFold.svelte.d.ts +1 -1
  228. package/dist/index.d.ts +38 -10
  229. package/dist/index.js +38 -12
  230. package/dist/internal/Chevron.svelte +2 -3
  231. package/dist/internal/Code.svelte +3 -4
  232. package/dist/internal/Collapse.svelte +6 -5
  233. package/dist/internal/Collapse.svelte.d.ts +2 -1
  234. package/dist/internal/Glyph.svelte +16 -0
  235. package/dist/internal/Glyph.svelte.d.ts +6 -0
  236. package/dist/internal/Tile.svelte +17 -37
  237. package/dist/internal/control.d.ts +4 -4
  238. package/dist/internal/control.js +21 -18
  239. package/dist/internal/layer.d.ts +3 -5
  240. package/dist/internal/layer.js +14 -18
  241. package/dist/internal/layout.d.ts +13 -0
  242. package/dist/internal/layout.js +453 -0
  243. package/dist/internal/markers.stylex.d.ts +8 -0
  244. package/dist/internal/markers.stylex.js +4 -0
  245. package/dist/internal/plugin-order.d.ts +8 -0
  246. package/dist/internal/plugin-order.js +16 -0
  247. package/dist/internal/responsive.d.ts +45 -0
  248. package/dist/internal/responsive.js +42 -0
  249. package/dist/internal/roving.js +5 -2
  250. package/dist/internal/shared.d.ts +8 -1
  251. package/dist/internal/shared.js +21 -5
  252. package/dist/internal/sx.d.ts +31 -4
  253. package/dist/internal/sx.js +17 -0
  254. package/dist/internal/toggle.d.ts +73 -0
  255. package/dist/internal/toggle.js +83 -0
  256. package/dist/internal/visible.d.ts +32 -0
  257. package/dist/internal/visible.js +44 -0
  258. package/dist/markdown/ast.d.ts +209 -0
  259. package/dist/markdown/ast.js +10 -0
  260. package/dist/markdown/blocks.d.ts +177 -0
  261. package/dist/markdown/blocks.js +1489 -0
  262. package/dist/markdown/code-info.d.ts +10 -0
  263. package/dist/markdown/code-info.js +16 -0
  264. package/dist/markdown/common.d.ts +25 -0
  265. package/dist/markdown/common.js +107 -0
  266. package/dist/markdown/diagrams.d.ts +2 -0
  267. package/dist/markdown/diagrams.js +18 -0
  268. package/dist/markdown/file-paths.d.ts +29 -0
  269. package/dist/markdown/file-paths.js +80 -0
  270. package/dist/markdown/files.d.ts +16 -0
  271. package/dist/markdown/files.js +133 -0
  272. package/dist/markdown/highlight.d.ts +30 -0
  273. package/dist/markdown/highlight.js +127 -0
  274. package/dist/markdown/html.d.ts +23 -0
  275. package/dist/markdown/html.js +289 -0
  276. package/dist/markdown/images.d.ts +15 -0
  277. package/dist/markdown/images.js +45 -0
  278. package/dist/markdown/index.d.ts +12 -0
  279. package/dist/markdown/index.js +5 -0
  280. package/dist/markdown/inlines.d.ts +48 -0
  281. package/dist/markdown/inlines.js +1714 -0
  282. package/dist/markdown/math.d.ts +2 -0
  283. package/dist/markdown/math.js +22 -0
  284. package/dist/markdown/parse.d.ts +81 -0
  285. package/dist/markdown/parse.js +204 -0
  286. package/dist/markdown/plugin.d.ts +178 -0
  287. package/dist/markdown/plugin.js +160 -0
  288. package/dist/markdown/sanitize.d.ts +78 -0
  289. package/dist/markdown/sanitize.js +522 -0
  290. package/dist/markdown/share.d.ts +12 -0
  291. package/dist/markdown/share.js +59 -0
  292. package/dist/markdown/table.d.ts +13 -0
  293. package/dist/markdown/table.js +60 -0
  294. package/dist/media.stylex.d.ts +52 -0
  295. package/dist/media.stylex.js +53 -0
  296. package/dist/preset.d.ts +40 -16
  297. package/dist/preset.js +169 -51
  298. package/dist/tokens.stylex.d.ts +70 -37
  299. package/dist/tokens.stylex.js +127 -62
  300. package/dist/typography.d.ts +48 -0
  301. package/dist/typography.js +55 -0
  302. package/dist/vite.d.ts +9 -1
  303. package/dist/vite.js +37 -4
  304. package/package.json +58 -6
  305. package/skills/building-ui/SKILL.md +242 -0
  306. package/skills/building-ui/references/components.md +207 -0
  307. package/skills/markdown/SKILL.md +452 -0
  308. package/skills/markdown/references/plugins.md +103 -0
  309. package/skills/setup/SKILL.md +191 -0
  310. package/skills/styling/SKILL.md +269 -0
  311. package/skills/theming/SKILL.md +184 -0
  312. package/dist/internal/loop.d.ts +0 -35
  313. package/dist/internal/loop.js +0 -72
@@ -0,0 +1,1489 @@
1
+ import { reNonSpace, replaceNul, unescapeString } from './common.js';
2
+ import { looksLikeCharClass, looksLikeTex, parseInlines, parseReferenceDefinition, tidyTail } from './inlines.js';
3
+ const CODE_INDENT = 4;
4
+ const C_TAB = 9;
5
+ const C_GREATERTHAN = 62;
6
+ const C_LESSTHAN = 60;
7
+ const C_SPACE = 32;
8
+ const C_OPEN_BRACKET = 91;
9
+ const reHtmlBlockOpen = [
10
+ /./, // dummy for index 0
11
+ /^<(?:script|pre|textarea|style)(?:\s|>|$)/i,
12
+ /^<!--/,
13
+ /^<[?]/,
14
+ /^<![A-Za-z]/,
15
+ /^<!\[CDATA\[/,
16
+ /^<[/]?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|[/]?[>]|$)/i,
17
+ new RegExp('^(?:' +
18
+ '<[A-Za-z][A-Za-z0-9-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^"\'=<>`\\x00-\\x20]+|\'[^\']*\'|"[^"]*"))?)*\\s*/?>' +
19
+ '|' +
20
+ '</[A-Za-z][A-Za-z0-9-]*\\s*[>]' +
21
+ ')\\s*$', 'i')
22
+ ];
23
+ const reHtmlBlockClose = [
24
+ /./, // dummy for index 0
25
+ /<\/(?:script|pre|textarea|style)>/i,
26
+ /-->/,
27
+ /\?>/,
28
+ />/,
29
+ /\]\]>/
30
+ ];
31
+ const reThematicBreak = /^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$|^(?:-[ \t]*){3,}$/;
32
+ const reMaybeSpecial = /^[#`~*+_=<>0-9|:[-]/;
33
+ const reBulletListMarker = /^[*+-]/;
34
+ const reOrderedListMarker = /^(\d{1,9})([.)])/;
35
+ const reATXHeadingMarker = /^#{1,6}(?:[ \t]+|$)/;
36
+ const reCodeFence = /^`{3,}(?!.*`)|^~{3,}/;
37
+ const reClosingCodeFence = /^(?:`{3,}|~{3,})(?=[ \t]*$)/;
38
+ const reSetextHeadingLine = /^(?:=+|-+)[ \t]*$/;
39
+ const reTaskListMarker = /^\[([ \t]|x|X)\](?=[ \t]|$)/;
40
+ const reDelimiterCell = /^[ \t]*:?-+:?[ \t]*$/;
41
+ /** How deep quotes, lists and footnotes may nest. Beyond it, their markers are text. */
42
+ const MAX_NESTING = 64;
43
+ /** A table has at most this many columns; a wider "table" is text. */
44
+ const MAX_COLUMNS = 128;
45
+ /**
46
+ * Whether a line is a table's delimiter row: cells of hyphens, each with an optional colon at
47
+ * either end, between pipes. Read cell by cell: one pattern for the whole row backtracks
48
+ * badly on a row with a long run of spaces.
49
+ */
50
+ function isDelimiterRow(line) {
51
+ let row = line.trim();
52
+ if (row === '')
53
+ return false;
54
+ if (row.startsWith('|'))
55
+ row = row.slice(1);
56
+ if (row.endsWith('|'))
57
+ row = row.slice(0, -1);
58
+ const cells = row.split('|');
59
+ return cells.length <= MAX_COLUMNS && cells.every((cell) => reDelimiterCell.test(cell));
60
+ }
61
+ function trimEndSpaces(s) {
62
+ let end = s.length;
63
+ while (end > 0 && (s.charCodeAt(end - 1) === 32 || s.charCodeAt(end - 1) === 9))
64
+ end--;
65
+ return end === s.length ? s : s.slice(0, end);
66
+ }
67
+ function nesting(node) {
68
+ let depth = 0;
69
+ for (let n = node; n; n = n.parent)
70
+ depth++;
71
+ return depth;
72
+ }
73
+ const reFootnoteDefinition = /^\[\^([^\]\s]+)\]:/;
74
+ /** A block while it is parsed. Converted to the immutable `ast.ts` nodes for the outside. */
75
+ class Node {
76
+ id;
77
+ type;
78
+ parent = null;
79
+ children = [];
80
+ open = true;
81
+ from;
82
+ to;
83
+ /** The lines it spans, from 0. */
84
+ startLine;
85
+ endLine;
86
+ /** Text gathered for a leaf: a paragraph, a heading or a code block. */
87
+ content = '';
88
+ /** The last line added to `content`, and where its text starts in the source. */
89
+ lastLine = '';
90
+ lastLineFrom = 0;
91
+ /** A paragraph that so far has opened a `$$` or a `\\[` it has not closed. */
92
+ dollarsOpen = false;
93
+ bracketOpen = false;
94
+ /** A paragraph whose text is taken as written: no link definitions are read from it. */
95
+ plain = false;
96
+ // Headings
97
+ level = 0;
98
+ setext = false;
99
+ // Code
100
+ fenced = false;
101
+ fenceChar = '';
102
+ fenceLength = 0;
103
+ fenceOffset = 0;
104
+ info = '';
105
+ /** A fenced block closed by its fence, not by the end of its container. */
106
+ closedByFence = false;
107
+ // HTML
108
+ htmlBlockType = 0;
109
+ // Math: the delimiter that closes it
110
+ mathClose = '';
111
+ // Lists and items
112
+ listData = null;
113
+ checked = null;
114
+ /** Where a task item's `[` is in the source. */
115
+ taskAt = -1;
116
+ // Tables
117
+ align = [];
118
+ rows = [];
119
+ /** Rows a preview added: the line still being written, which must not be kept. */
120
+ ephemeralRows = null;
121
+ // Footnote definitions
122
+ label = '';
123
+ /** Made while previewing the unfinished end: never cached. */
124
+ ephemeral = false;
125
+ /** The block the preview ends in, whose text may be unfinished. */
126
+ tail = false;
127
+ /** Still open when the preview was taken: more of it may arrive. */
128
+ live = false;
129
+ /** The lines of paragraphs that held only definitions and were taken out, for telling a loose list. */
130
+ ghosts = null;
131
+ /** The footnote definitions at or under this block, kept with its converted node. */
132
+ notes = null;
133
+ /** The converted node, once the block is closed. */
134
+ cache = null;
135
+ /** Reference labels a converted leaf looked up and did not find. */
136
+ missed = null;
137
+ constructor(type, id, from, line) {
138
+ this.type = type;
139
+ this.id = id;
140
+ this.from = from;
141
+ this.to = from;
142
+ this.startLine = line;
143
+ this.endLine = line;
144
+ }
145
+ appendChild(child) {
146
+ child.parent = this;
147
+ this.children.push(child);
148
+ }
149
+ get lastChild() {
150
+ return this.children[this.children.length - 1] ?? null;
151
+ }
152
+ unlink() {
153
+ if (!this.parent)
154
+ return;
155
+ const siblings = this.parent.children;
156
+ siblings.splice(siblings.indexOf(this), 1);
157
+ this.parent = null;
158
+ }
159
+ }
160
+ function isBlank(s) {
161
+ return !reNonSpace.test(s);
162
+ }
163
+ function isSpaceOrTab(c) {
164
+ return c === C_SPACE || c === C_TAB;
165
+ }
166
+ function peek(ln, pos) {
167
+ return pos < ln.length ? ln.charCodeAt(pos) : -1;
168
+ }
169
+ /** Whether a blank line separates a block from the next one, which makes a list loose. */
170
+ function endsWithBlankLine(block, next) {
171
+ return next !== undefined && block.endLine !== next.startLine - 1;
172
+ }
173
+ function parseListMarker(parser, container) {
174
+ const rest = parser.currentLine.slice(parser.nextNonspace);
175
+ let match;
176
+ let nextc;
177
+ const data = {
178
+ type: 'bullet',
179
+ tight: true,
180
+ bulletChar: '',
181
+ start: null,
182
+ delimiter: null,
183
+ padding: 0,
184
+ markerOffset: parser.indent
185
+ };
186
+ if (parser.indent >= 4)
187
+ return null;
188
+ if ((match = rest.match(reBulletListMarker))) {
189
+ data.type = 'bullet';
190
+ data.bulletChar = match[0][0];
191
+ }
192
+ else if ((match = rest.match(reOrderedListMarker)) &&
193
+ (container.type !== 'paragraph' || match[1] === '1')) {
194
+ data.type = 'ordered';
195
+ data.start = parseInt(match[1], 10);
196
+ data.delimiter = match[2];
197
+ }
198
+ else {
199
+ return null;
200
+ }
201
+ // The marker must be followed by a space, a tab or the end of the line
202
+ nextc = peek(parser.currentLine, parser.nextNonspace + match[0].length);
203
+ if (!(nextc === -1 || nextc === C_TAB || nextc === C_SPACE))
204
+ return null;
205
+ // An empty list item cannot interrupt a paragraph
206
+ if (container.type === 'paragraph' &&
207
+ !reNonSpace.test(parser.currentLine.slice(parser.nextNonspace + match[0].length))) {
208
+ return null;
209
+ }
210
+ // Past the marker, and the spaces that come with it
211
+ parser.advanceNextNonspace();
212
+ parser.advanceOffset(match[0].length, true);
213
+ const spacesStartCol = parser.column;
214
+ const spacesStartOffset = parser.offset;
215
+ do {
216
+ parser.advanceOffset(1, true);
217
+ nextc = peek(parser.currentLine, parser.offset);
218
+ } while (parser.column - spacesStartCol < 5 && isSpaceOrTab(nextc));
219
+ const blankItem = peek(parser.currentLine, parser.offset) === -1;
220
+ const spacesAfterMarker = parser.column - spacesStartCol;
221
+ if (spacesAfterMarker >= 5 || spacesAfterMarker < 1 || blankItem) {
222
+ data.padding = match[0].length + 1;
223
+ parser.column = spacesStartCol;
224
+ parser.offset = spacesStartOffset;
225
+ if (isSpaceOrTab(peek(parser.currentLine, parser.offset)))
226
+ parser.advanceOffset(1, true);
227
+ }
228
+ else {
229
+ data.padding = match[0].length + spacesAfterMarker;
230
+ }
231
+ return data;
232
+ }
233
+ function listsMatch(a, b) {
234
+ return a.type === b.type && a.delimiter === b.delimiter && a.bulletChar === b.bulletChar;
235
+ }
236
+ /** Splits a table row into cell texts, honouring `\|` escapes. */
237
+ export function splitTableRow(text) {
238
+ let s = text.trim();
239
+ if (s.startsWith('|'))
240
+ s = s.slice(1);
241
+ if (s.endsWith('|') && !s.endsWith('\\|'))
242
+ s = s.slice(0, -1);
243
+ const cells = [];
244
+ let cell = '';
245
+ for (let i = 0; i < s.length; i++) {
246
+ const ch = s[i];
247
+ if (ch === '\\' && s[i + 1] === '|') {
248
+ cell += '|';
249
+ i++;
250
+ }
251
+ else if (ch === '|') {
252
+ cells.push(cell.trim());
253
+ cell = '';
254
+ }
255
+ else {
256
+ cell += ch;
257
+ }
258
+ }
259
+ cells.push(cell.trim());
260
+ return cells;
261
+ }
262
+ function parseAlignment(text) {
263
+ return splitTableRow(text).map((cell) => {
264
+ const left = cell.startsWith(':');
265
+ const right = cell.endsWith(':');
266
+ return left && right ? 'center' : left ? 'left' : right ? 'right' : null;
267
+ });
268
+ }
269
+ const behaviours = {
270
+ document: {
271
+ continue: () => 0,
272
+ finalize: () => { },
273
+ canContain: (t) => t !== 'item',
274
+ acceptsLines: false
275
+ },
276
+ list: {
277
+ continue: () => 0,
278
+ finalize(_parser, block) {
279
+ const data = block.listData;
280
+ const items = block.children;
281
+ // Loose when a blank line separates two items, or two blocks inside an item. A
282
+ // paragraph of definitions that was taken out still counts as a block that was there.
283
+ outer: for (let i = 0; i < items.length; i++) {
284
+ const item = items[i];
285
+ if (endsWithBlankLine(item, items[i + 1])) {
286
+ data.tight = false;
287
+ break;
288
+ }
289
+ const ranges = item.children.map((c) => [c.startLine, c.endLine]);
290
+ if (item.ghosts) {
291
+ ranges.push(...item.ghosts);
292
+ ranges.sort((x, y) => x[0] - y[0]);
293
+ }
294
+ for (let j = 0; j + 1 < ranges.length; j++) {
295
+ if (ranges[j][1] !== ranges[j + 1][0] - 1) {
296
+ data.tight = false;
297
+ break outer;
298
+ }
299
+ }
300
+ }
301
+ const last = block.lastChild;
302
+ if (last) {
303
+ block.endLine = last.endLine;
304
+ block.to = last.to;
305
+ }
306
+ },
307
+ canContain: (t) => t === 'item',
308
+ acceptsLines: false
309
+ },
310
+ blockquote: {
311
+ continue(parser) {
312
+ const ln = parser.currentLine;
313
+ if (!parser.indented && peek(ln, parser.nextNonspace) === C_GREATERTHAN) {
314
+ parser.advanceNextNonspace();
315
+ parser.advanceOffset(1, false);
316
+ if (isSpaceOrTab(peek(ln, parser.offset)))
317
+ parser.advanceOffset(1, true);
318
+ return 0;
319
+ }
320
+ return 1;
321
+ },
322
+ finalize: () => { },
323
+ canContain: (t) => t !== 'item',
324
+ acceptsLines: false
325
+ },
326
+ item: {
327
+ continue(parser, block) {
328
+ const data = block.listData;
329
+ if (parser.blank) {
330
+ // An item that starts with a blank line takes no more than one
331
+ if (block.children.length === 0)
332
+ return 1;
333
+ parser.advanceNextNonspace();
334
+ }
335
+ else if (parser.indent >= data.markerOffset + data.padding) {
336
+ parser.advanceOffset(data.markerOffset + data.padding, true);
337
+ }
338
+ else {
339
+ return 1;
340
+ }
341
+ return 0;
342
+ },
343
+ finalize(_parser, block) {
344
+ const last = block.lastChild;
345
+ let end = last ? last.endLine : block.startLine;
346
+ // A paragraph of definitions that was taken out was still part of the item
347
+ for (const ghost of block.ghosts ?? [])
348
+ end = Math.max(end, ghost[1]);
349
+ block.endLine = end;
350
+ if (last && last.endLine === end)
351
+ block.to = last.to;
352
+ },
353
+ canContain: (t) => t !== 'item',
354
+ acceptsLines: false
355
+ },
356
+ footnote: {
357
+ continue(parser) {
358
+ if (parser.blank) {
359
+ parser.advanceNextNonspace();
360
+ return 0;
361
+ }
362
+ if (parser.indent >= 4) {
363
+ parser.advanceOffset(4, true);
364
+ return 0;
365
+ }
366
+ return 1;
367
+ },
368
+ finalize(_parser, block) {
369
+ const last = block.lastChild;
370
+ if (last) {
371
+ block.endLine = last.endLine;
372
+ block.to = last.to;
373
+ }
374
+ else {
375
+ block.endLine = block.startLine;
376
+ }
377
+ },
378
+ canContain: (t) => t !== 'item',
379
+ acceptsLines: false
380
+ },
381
+ heading: {
382
+ continue: () => 1,
383
+ finalize: () => { },
384
+ canContain: () => false,
385
+ acceptsLines: false
386
+ },
387
+ thematicBreak: {
388
+ continue: () => 1,
389
+ finalize: () => { },
390
+ canContain: () => false,
391
+ acceptsLines: false
392
+ },
393
+ code: {
394
+ continue(parser, block) {
395
+ const ln = parser.currentLine;
396
+ const indent = parser.indent;
397
+ if (block.fenced) {
398
+ const match = indent <= 3 &&
399
+ ln.charAt(parser.nextNonspace) === block.fenceChar &&
400
+ ln.slice(parser.nextNonspace).match(reClosingCodeFence);
401
+ if (match && match[0].length >= block.fenceLength) {
402
+ // The closing fence
403
+ parser.lastLineLength = parser.offset + indent + match[0].length;
404
+ block.closedByFence = true;
405
+ parser.finalize(block, parser.lineNumber);
406
+ return 2;
407
+ }
408
+ // Skip as much of the fence's own indent as the line has
409
+ let i = block.fenceOffset;
410
+ while (i > 0 && isSpaceOrTab(peek(ln, parser.offset))) {
411
+ parser.advanceOffset(1, true);
412
+ i--;
413
+ }
414
+ }
415
+ else if (indent >= CODE_INDENT) {
416
+ parser.advanceOffset(CODE_INDENT, true);
417
+ }
418
+ else if (parser.blank) {
419
+ parser.advanceNextNonspace();
420
+ }
421
+ else {
422
+ return 1;
423
+ }
424
+ return 0;
425
+ },
426
+ finalize(parser, block) {
427
+ if (block.fenced) {
428
+ // The first line is the info string
429
+ const content = block.content;
430
+ const newline = content.indexOf('\n');
431
+ const first = content.slice(0, newline);
432
+ block.info = unescapeString(first.trim());
433
+ block.content = content.slice(newline + 1);
434
+ }
435
+ else {
436
+ // Trailing blank lines are not part of indented code
437
+ const lines = block.content.split('\n');
438
+ // The split leaves an empty piece after the last line ending, which is not a line
439
+ let blank = -1;
440
+ while (lines.length > 0 && isBlank(lines[lines.length - 1])) {
441
+ lines.pop();
442
+ blank++;
443
+ }
444
+ block.content = lines.length > 0 ? lines.join('\n') + '\n' : '';
445
+ // The block ends at its last line of code, so a blank line after it shows as one
446
+ if (blank > 0) {
447
+ block.endLine = Math.max(block.startLine, block.endLine - blank);
448
+ block.to = parser.lineEndOf(block.endLine);
449
+ }
450
+ }
451
+ },
452
+ canContain: () => false,
453
+ acceptsLines: true
454
+ },
455
+ html: {
456
+ continue(parser, block) {
457
+ return parser.blank && (block.htmlBlockType === 6 || block.htmlBlockType === 7) ? 1 : 0;
458
+ },
459
+ finalize(_parser, block) {
460
+ // Trailing blank lines go; walked back by hand, as a pattern for it is slow on thousands
461
+ let end = block.content.length;
462
+ for (;;) {
463
+ let i = end;
464
+ while (i > 0 &&
465
+ (block.content.charCodeAt(i - 1) === 32 || block.content.charCodeAt(i - 1) === 9))
466
+ i--;
467
+ if (i > 0 && block.content.charCodeAt(i - 1) === 10)
468
+ end = i - 1;
469
+ else
470
+ break;
471
+ }
472
+ block.content = block.content.slice(0, end);
473
+ },
474
+ canContain: () => false,
475
+ acceptsLines: true
476
+ },
477
+ math: {
478
+ continue(parser, block) {
479
+ // A formula has no blank line in it. One that meets a blank line before its closing
480
+ // delimiter was never a formula: without this, a stray `$$` on a line of its own
481
+ // would take the rest of the document with it.
482
+ if (parser.blank)
483
+ return 1;
484
+ const line = parser.currentLine.slice(parser.offset);
485
+ const rest = line.trim();
486
+ const close = block.mathClose;
487
+ if (rest.endsWith(close)) {
488
+ // The closing delimiter ends the line; what is before it is the formula's last line
489
+ block.content += rest.slice(0, -close.length) + '\n';
490
+ block.closedByFence = true;
491
+ parser.lastLineLength = parser.currentLine.length;
492
+ parser.finalize(block, parser.lineNumber);
493
+ return 2;
494
+ }
495
+ if (rest.startsWith(close)) {
496
+ // `$$.` or `$$ (1)`: the formula ends here, and what follows it on the line is text
497
+ block.closedByFence = true;
498
+ parser.finalize(block, parser.lineNumber);
499
+ parser.advanceOffset(line.indexOf(close) + close.length, false);
500
+ return 1;
501
+ }
502
+ return 0;
503
+ },
504
+ finalize(_parser, block) {
505
+ // Ended without its closing delimiter, and not because the text is still arriving:
506
+ // it is a paragraph that starts with the delimiter
507
+ if (block.closedByFence || block.live)
508
+ return;
509
+ block.type = 'paragraph';
510
+ block.content =
511
+ (block.mathClose === '$$' ? '$$' : '\\[') + '\n' + block.content.replace(/^\n/, '');
512
+ },
513
+ canContain: () => false,
514
+ acceptsLines: true
515
+ },
516
+ paragraph: {
517
+ continue: (parser) => (parser.blank ? 1 : 0),
518
+ finalize(parser, block) {
519
+ // Link reference definitions at the start of a paragraph are taken out of it. Not
520
+ // from a task's text, though: `- [ ] [API]: done` is a task that says so.
521
+ let content = block.content;
522
+ while (!block.plain && content.charCodeAt(0) === C_OPEN_BRACKET) {
523
+ const definition = parseReferenceDefinition(content);
524
+ if (!definition)
525
+ break;
526
+ parser.define(definition.label, { url: definition.url, title: definition.title });
527
+ content = content.slice(definition.end);
528
+ }
529
+ block.content = content;
530
+ if (isBlank(content)) {
531
+ const parent = block.parent;
532
+ if (parent && parent.type === 'item')
533
+ (parent.ghosts ??= []).push([block.startLine, block.endLine]);
534
+ block.unlink();
535
+ }
536
+ },
537
+ canContain: () => false,
538
+ acceptsLines: true
539
+ },
540
+ table: {
541
+ continue: (parser) => (parser.blank ? 1 : 0),
542
+ finalize: () => { },
543
+ canContain: () => false,
544
+ acceptsLines: false
545
+ }
546
+ };
547
+ const blockStarts = [
548
+ // Block quote
549
+ (parser, container) => {
550
+ if (!parser.indented &&
551
+ peek(parser.currentLine, parser.nextNonspace) === C_GREATERTHAN &&
552
+ nesting(container) < MAX_NESTING) {
553
+ parser.advanceNextNonspace();
554
+ parser.advanceOffset(1, false);
555
+ if (isSpaceOrTab(peek(parser.currentLine, parser.offset)))
556
+ parser.advanceOffset(1, true);
557
+ parser.closeUnmatchedBlocks();
558
+ parser.addChild('blockquote', parser.nextNonspace);
559
+ return 1;
560
+ }
561
+ return 0;
562
+ },
563
+ // ATX heading
564
+ (parser) => {
565
+ let match;
566
+ if (!parser.indented &&
567
+ (match = parser.currentLine.slice(parser.nextNonspace).match(reATXHeadingMarker))) {
568
+ parser.advanceNextNonspace();
569
+ parser.advanceOffset(match[0].length, false);
570
+ parser.closeUnmatchedBlocks();
571
+ const block = parser.addChild('heading', parser.nextNonspace);
572
+ block.level = match[0].trim().length;
573
+ // Drop the closing sequence
574
+ // Drop the closing sequence: `#`s at the end, after a space or as the whole of it
575
+ let text = trimEndSpaces(parser.currentLine.slice(parser.offset));
576
+ let hashes = text.length;
577
+ while (hashes > 0 && text.charCodeAt(hashes - 1) === 35)
578
+ hashes--;
579
+ if (hashes < text.length && (hashes === 0 || isSpaceOrTab(text.charCodeAt(hashes - 1))))
580
+ text = trimEndSpaces(text.slice(0, hashes));
581
+ block.content = text;
582
+ parser.advanceOffset(parser.currentLine.length - parser.offset);
583
+ return 2;
584
+ }
585
+ return 0;
586
+ },
587
+ // A formula on lines of its own: `$$` … `$$` or `\\[` … `\\]`. It opens with its delimiter
588
+ // alone on a line, or is a whole formula on one line. A line that merely starts with `$$`
589
+ // ("$$ - moderate", "$$props is deprecated") opens nothing.
590
+ (parser, container) => {
591
+ if (!parser.options.math || parser.indented)
592
+ return 0;
593
+ const rest = parser.currentLine.slice(parser.nextNonspace).trimEnd();
594
+ const dollars = rest.startsWith('$$');
595
+ if (!dollars && !rest.startsWith('\\['))
596
+ return 0;
597
+ const close = dollars ? '$$' : '\\]';
598
+ const after = rest.slice(2);
599
+ const end = after.indexOf(close);
600
+ let value = '';
601
+ if (end >= 0) {
602
+ // A whole formula on the line, with nothing after it
603
+ if (end !== after.length - close.length)
604
+ return 0;
605
+ value = after.slice(0, end);
606
+ if (!/[A-Za-z0-9\\]/.test(value) ||
607
+ (!dollars && (!looksLikeTex(value) || looksLikeCharClass(value))))
608
+ return 0;
609
+ }
610
+ else if (after.trim() !== '') {
611
+ return 0;
612
+ }
613
+ // Inside a paragraph that has opened a formula of its own, this line is that one's end
614
+ if (container.type === 'paragraph') {
615
+ if (dollars ? container.dollarsOpen : container.bracketOpen)
616
+ return 0;
617
+ }
618
+ parser.closeUnmatchedBlocks();
619
+ const block = parser.addChild('math', parser.nextNonspace);
620
+ block.mathClose = close;
621
+ block.content = value.trim() === '' ? '' : value + '\n';
622
+ parser.advanceOffset(parser.currentLine.length - parser.offset, false);
623
+ if (end >= 0) {
624
+ block.closedByFence = true;
625
+ parser.finalize(block, parser.lineNumber);
626
+ }
627
+ return 2;
628
+ },
629
+ // Fenced code
630
+ (parser) => {
631
+ let match;
632
+ if (!parser.indented &&
633
+ (match = parser.currentLine.slice(parser.nextNonspace).match(reCodeFence))) {
634
+ const fenceLength = match[0].length;
635
+ parser.closeUnmatchedBlocks();
636
+ const block = parser.addChild('code', parser.nextNonspace);
637
+ block.fenced = true;
638
+ block.fenceLength = fenceLength;
639
+ block.fenceChar = match[0][0];
640
+ block.fenceOffset = parser.indent;
641
+ parser.advanceNextNonspace();
642
+ parser.advanceOffset(fenceLength, false);
643
+ return 2;
644
+ }
645
+ return 0;
646
+ },
647
+ // HTML block
648
+ (parser, container) => {
649
+ if (!parser.indented && peek(parser.currentLine, parser.nextNonspace) === C_LESSTHAN) {
650
+ const s = parser.currentLine.slice(parser.nextNonspace);
651
+ for (let type = 1; type <= 7; type++) {
652
+ if (reHtmlBlockOpen[type].test(s) &&
653
+ (type < 7 ||
654
+ (container.type !== 'paragraph' &&
655
+ !(!parser.allClosed && !parser.blank && parser.tip.type === 'paragraph')))) {
656
+ parser.closeUnmatchedBlocks();
657
+ // The line is added as content, so the offset stays where it is
658
+ const block = parser.addChild('html', parser.offset);
659
+ block.htmlBlockType = type;
660
+ return 2;
661
+ }
662
+ }
663
+ }
664
+ return 0;
665
+ },
666
+ // Setext heading, and a GFM table's delimiter row: both turn the paragraph above into something else
667
+ (parser, container) => {
668
+ if (parser.indented || container.type !== 'paragraph')
669
+ return 0;
670
+ const rest = parser.currentLine.slice(parser.nextNonspace);
671
+ if (parser.options.gfm &&
672
+ // A row of hyphens alone is a setext underline; a delimiter row has a pipe or a colon
673
+ (rest.includes('|') || rest.includes(':')) &&
674
+ // `- |` is a list item: a hyphen and a space start one, as markdown-it has it too
675
+ !/^-[ \t]/.test(rest) &&
676
+ isDelimiterRow(rest)) {
677
+ // The header row is the paragraph's last line, which the paragraph keeps to hand:
678
+ // splitting its whole text here made every such line cost the paragraph's length
679
+ const header = container.lastLine;
680
+ const above = container.content.length - header.length - 1;
681
+ const align = parseAlignment(rest);
682
+ if (splitTableRow(header).length === align.length) {
683
+ parser.closeUnmatchedBlocks();
684
+ const headerLine = parser.lineNumber - 1;
685
+ const headerFrom = container.lastLineFrom;
686
+ const table = new Node('table', parser.nextId(), headerFrom, headerLine);
687
+ table.ephemeral = parser.ephemeral;
688
+ table.align = align;
689
+ const headerRow = {
690
+ text: header,
691
+ from: headerFrom,
692
+ to: parser.lineEndOf(headerLine),
693
+ id: parser.nextId()
694
+ };
695
+ table.rows.push(headerRow);
696
+ if (parser.ephemeral)
697
+ (table.ephemeralRows ??= new Set()).add(headerRow);
698
+ const parent = container.parent;
699
+ if (above > 0) {
700
+ // The lines above the header row stay a paragraph
701
+ container.content = container.content.slice(0, above);
702
+ parser.finalize(container, headerLine - 1);
703
+ parent.appendChild(table);
704
+ }
705
+ else {
706
+ parent.children.splice(parent.children.indexOf(container), 1, table);
707
+ table.parent = parent;
708
+ container.parent = null;
709
+ }
710
+ parser.tip = table;
711
+ parser.advanceOffset(parser.currentLine.length - parser.offset, false);
712
+ return 2;
713
+ }
714
+ }
715
+ let match;
716
+ if ((match = rest.match(reSetextHeadingLine))) {
717
+ parser.closeUnmatchedBlocks();
718
+ // Definitions at the start of the paragraph are not part of the heading
719
+ let content = container.content;
720
+ while (content.charCodeAt(0) === C_OPEN_BRACKET) {
721
+ const definition = parseReferenceDefinition(content);
722
+ if (!definition)
723
+ break;
724
+ parser.define(definition.label, { url: definition.url, title: definition.title });
725
+ content = content.slice(definition.end);
726
+ }
727
+ if (content.length > 0) {
728
+ const heading = new Node('heading', container.id, container.from, container.startLine);
729
+ heading.ephemeral = parser.ephemeral;
730
+ heading.level = match[0][0] === '=' ? 1 : 2;
731
+ heading.setext = true;
732
+ heading.content = content;
733
+ container.parent.children.splice(container.parent.children.indexOf(container), 1, heading);
734
+ heading.parent = container.parent;
735
+ container.parent = null;
736
+ parser.tip = heading;
737
+ parser.advanceOffset(parser.currentLine.length - parser.offset, false);
738
+ return 2;
739
+ }
740
+ return 0;
741
+ }
742
+ return 0;
743
+ },
744
+ // Thematic break
745
+ (parser) => {
746
+ if (!parser.indented && reThematicBreak.test(parser.currentLine.slice(parser.nextNonspace))) {
747
+ parser.closeUnmatchedBlocks();
748
+ parser.addChild('thematicBreak', parser.nextNonspace);
749
+ parser.advanceOffset(parser.currentLine.length - parser.offset, false);
750
+ return 2;
751
+ }
752
+ return 0;
753
+ },
754
+ // GFM footnote definition
755
+ (parser, container) => {
756
+ if (!parser.options.gfm || parser.indented || nesting(container) >= MAX_NESTING)
757
+ return 0;
758
+ const match = parser.currentLine.slice(parser.nextNonspace).match(reFootnoteDefinition);
759
+ if (!match)
760
+ return 0;
761
+ parser.closeUnmatchedBlocks();
762
+ const block = parser.addChild('footnote', parser.nextNonspace);
763
+ block.label = match[1];
764
+ parser.advanceNextNonspace();
765
+ parser.advanceOffset(match[0].length, false);
766
+ if (isSpaceOrTab(peek(parser.currentLine, parser.offset)))
767
+ parser.advanceOffset(1, true);
768
+ parser.defineFootnote(block.label);
769
+ return 1;
770
+ },
771
+ // List item
772
+ (parser, container) => {
773
+ if (container.type === 'list' && parser.indented)
774
+ return 0;
775
+ if (nesting(container) >= MAX_NESTING)
776
+ return 0;
777
+ const data = parseListMarker(parser, container);
778
+ if (!data)
779
+ return 0;
780
+ parser.closeUnmatchedBlocks();
781
+ // A list item of another kind starts a new list
782
+ if (parser.tip.type !== 'list' || !listsMatch(container.listData, data)) {
783
+ const list = parser.addChild('list', parser.nextNonspace);
784
+ list.listData = data;
785
+ }
786
+ const item = parser.addChild('item', parser.nextNonspace);
787
+ item.listData = data;
788
+ // A GFM task item: `[ ]` or `[x]` and a space at the start of its first paragraph
789
+ const task = parser.options.gfm
790
+ ? parser.currentLine.slice(parser.offset).match(reTaskListMarker)
791
+ : null;
792
+ if (task && reNonSpace.test(parser.currentLine.slice(parser.offset + task[0].length))) {
793
+ item.checked = task[1] !== ' ' && task[1] !== '\t';
794
+ item.taskAt = parser.lineStartOf(parser.lineNumber) + parser.offset;
795
+ parser.advanceOffset(task[0].length, false);
796
+ if (isSpaceOrTab(peek(parser.currentLine, parser.offset)))
797
+ parser.advanceOffset(1, true);
798
+ // What follows the box is the task's text, whatever it starts with: `- [ ] # 12`
799
+ parser.plainRest = true;
800
+ }
801
+ return 1;
802
+ },
803
+ // Indented code
804
+ (parser) => {
805
+ if (parser.indented && parser.tip.type !== 'paragraph' && !parser.blank) {
806
+ parser.advanceOffset(CODE_INDENT, true);
807
+ parser.closeUnmatchedBlocks();
808
+ parser.addChild('code', parser.offset);
809
+ return 2;
810
+ }
811
+ return 0;
812
+ }
813
+ ];
814
+ export class BlockParser {
815
+ doc;
816
+ tip;
817
+ oldtip;
818
+ currentLine = '';
819
+ /** The current line's number, from 0. */
820
+ lineNumber = -1;
821
+ /** Where each line starts and ends in the source, before its line ending. */
822
+ lineStarts = [];
823
+ lineEnds = [];
824
+ /** A fork's own last line, which the shared arrays above do not hold. */
825
+ forkLine = null;
826
+ offset = 0;
827
+ column = 0;
828
+ nextNonspace = 0;
829
+ nextNonspaceColumn = 0;
830
+ indent = 0;
831
+ indented = false;
832
+ blank = false;
833
+ partiallyConsumedTab = false;
834
+ /** Set by a block start to make the rest of the line plain text. */
835
+ plainRest = false;
836
+ /** The paragraph this line starts is a task's text. */
837
+ plainParagraph = false;
838
+ allClosed = true;
839
+ lastMatchedContainer;
840
+ lastLineLength = 0;
841
+ definitions = new Map();
842
+ footnoteLabels = new Set();
843
+ /** Leaves that missed a label, by label, so a later definition can convert them again. */
844
+ missedBy = new Map();
845
+ ids = 0;
846
+ ephemeral = false;
847
+ options;
848
+ constructor(options = {}) {
849
+ this.options = { gfm: true, math: false, singleTilde: false, ...options };
850
+ this.doc = new Node('document', this.nextId(), 0, 0);
851
+ this.tip = this.doc;
852
+ this.oldtip = this.doc;
853
+ this.lastMatchedContainer = this.doc;
854
+ }
855
+ nextId() {
856
+ return this.ids++;
857
+ }
858
+ lineStartOf(line) {
859
+ if (this.forkLine && line === this.forkLine.number)
860
+ return this.forkLine.start;
861
+ return this.lineStarts[line] ?? 0;
862
+ }
863
+ lineEndOf(line) {
864
+ if (line < 0)
865
+ return 0;
866
+ if (this.forkLine && line === this.forkLine.number)
867
+ return this.forkLine.end;
868
+ return this.lineEnds[line] ?? this.lineEnds[this.lineEnds.length - 1] ?? 0;
869
+ }
870
+ define(label, definition) {
871
+ if (this.definitions.has(label))
872
+ return;
873
+ this.definitions.set(label, definition);
874
+ this.invalidate(label);
875
+ }
876
+ defineFootnote(label) {
877
+ const key = '^' + label.toLowerCase().toUpperCase();
878
+ if (this.footnoteLabels.has(key))
879
+ return;
880
+ this.footnoteLabels.add(key);
881
+ this.invalidate(key);
882
+ }
883
+ /** Converts again the blocks that looked for this label and did not find it. */
884
+ invalidate(label) {
885
+ if (this.ephemeral)
886
+ return;
887
+ const blocks = this.missedBy.get(label);
888
+ if (!blocks)
889
+ return;
890
+ this.missedBy.delete(label);
891
+ for (const block of blocks) {
892
+ for (let b = block; b; b = b.parent)
893
+ b.cache = null;
894
+ }
895
+ }
896
+ addLine() {
897
+ let pad = '';
898
+ if (this.partiallyConsumedTab) {
899
+ this.offset += 1;
900
+ pad = ' '.repeat(4 - (this.column % 4));
901
+ }
902
+ const tip = this.tip;
903
+ const text = pad + this.currentLine.slice(this.offset);
904
+ tip.content += text + '\n';
905
+ tip.lastLine = text;
906
+ tip.lastLineFrom = this.lineStartOf(this.lineNumber) + this.offset;
907
+ // Whether the paragraph has a formula open is kept as lines arrive: asking its whole
908
+ // text on every line made a long paragraph of formulas slow
909
+ if (this.options.math && tip.type === 'paragraph') {
910
+ for (let at = text.indexOf('$$'); at >= 0; at = text.indexOf('$$', at + 2))
911
+ tip.dollarsOpen = !tip.dollarsOpen;
912
+ const opened = text.lastIndexOf('\\[');
913
+ const closed = text.lastIndexOf('\\]');
914
+ if (opened >= 0 || closed >= 0)
915
+ tip.bracketOpen = opened > closed;
916
+ }
917
+ }
918
+ addChild(type, offset) {
919
+ while (!behaviours[this.tip.type].canContain(type)) {
920
+ this.finalize(this.tip, this.lineNumber - 1);
921
+ }
922
+ const block = new Node(type, this.nextId(), this.lineStartOf(this.lineNumber) + offset, this.lineNumber);
923
+ block.ephemeral = this.ephemeral;
924
+ this.tip.appendChild(block);
925
+ this.tip = block;
926
+ return block;
927
+ }
928
+ closeUnmatchedBlocks() {
929
+ if (!this.allClosed) {
930
+ while (this.oldtip !== this.lastMatchedContainer) {
931
+ const parent = this.oldtip.parent;
932
+ this.finalize(this.oldtip, this.lineNumber - 1);
933
+ this.oldtip = parent;
934
+ }
935
+ this.allClosed = true;
936
+ }
937
+ }
938
+ findNextNonspace() {
939
+ const ln = this.currentLine;
940
+ let i = this.offset;
941
+ let cols = this.column;
942
+ let c;
943
+ while ((c = ln.charAt(i)) !== '') {
944
+ if (c === ' ') {
945
+ i++;
946
+ cols++;
947
+ }
948
+ else if (c === '\t') {
949
+ i++;
950
+ cols += 4 - (cols % 4);
951
+ }
952
+ else {
953
+ break;
954
+ }
955
+ }
956
+ this.blank = c === '\n' || c === '\r' || c === '';
957
+ this.nextNonspace = i;
958
+ this.nextNonspaceColumn = cols;
959
+ this.indent = this.nextNonspaceColumn - this.column;
960
+ this.indented = this.indent >= CODE_INDENT;
961
+ }
962
+ advanceNextNonspace() {
963
+ this.offset = this.nextNonspace;
964
+ this.column = this.nextNonspaceColumn;
965
+ this.partiallyConsumedTab = false;
966
+ }
967
+ advanceOffset(count, columns = false) {
968
+ const ln = this.currentLine;
969
+ let c;
970
+ while (count > 0 && (c = ln.charAt(this.offset)) !== '') {
971
+ if (c === '\t') {
972
+ const charsToTab = 4 - (this.column % 4);
973
+ if (columns) {
974
+ this.partiallyConsumedTab = charsToTab > count;
975
+ const charsToAdvance = charsToTab > count ? count : charsToTab;
976
+ this.column += charsToAdvance;
977
+ this.offset += this.partiallyConsumedTab ? 0 : 1;
978
+ count -= charsToAdvance;
979
+ }
980
+ else {
981
+ this.partiallyConsumedTab = false;
982
+ this.column += charsToTab;
983
+ this.offset += 1;
984
+ count -= 1;
985
+ }
986
+ }
987
+ else {
988
+ this.partiallyConsumedTab = false;
989
+ this.offset += 1;
990
+ this.column += 1;
991
+ count -= 1;
992
+ }
993
+ }
994
+ }
995
+ /** Reads one line, without its line ending, that starts at `start` in the source. */
996
+ incorporateLine(line, start) {
997
+ let container = this.doc;
998
+ this.oldtip = this.tip;
999
+ this.offset = 0;
1000
+ this.column = 0;
1001
+ this.blank = false;
1002
+ this.partiallyConsumedTab = false;
1003
+ this.plainParagraph = false;
1004
+ this.lineNumber++;
1005
+ if (this.ephemeral) {
1006
+ this.forkLine = { number: this.lineNumber, start, end: start + line.length };
1007
+ }
1008
+ else {
1009
+ this.lineStarts.push(start);
1010
+ this.lineEnds.push(start + line.length);
1011
+ }
1012
+ this.currentLine = replaceNul(line);
1013
+ // Which open blocks does the line continue?
1014
+ let lastChild;
1015
+ while ((lastChild = container.lastChild) && lastChild.open) {
1016
+ container = lastChild;
1017
+ this.findNextNonspace();
1018
+ const result = behaviours[container.type].continue(this, container);
1019
+ if (result === 0)
1020
+ continue;
1021
+ if (result === 1) {
1022
+ container = container.parent;
1023
+ break;
1024
+ }
1025
+ // The line ended a fenced code block and is used up
1026
+ this.lastLineLength = line.length;
1027
+ return;
1028
+ }
1029
+ this.allClosed = container === this.oldtip;
1030
+ this.lastMatchedContainer = container;
1031
+ let matchedLeaf = container.type !== 'paragraph' && behaviours[container.type].acceptsLines;
1032
+ // Does it start new blocks?
1033
+ while (!matchedLeaf) {
1034
+ this.findNextNonspace();
1035
+ // A quick check that the line could start anything
1036
+ const rest = this.currentLine.slice(this.nextNonspace);
1037
+ if (!this.indented &&
1038
+ !reMaybeSpecial.test(rest) &&
1039
+ !(this.options.math && (rest.startsWith('$$') || rest.startsWith('\\[')))) {
1040
+ this.advanceNextNonspace();
1041
+ break;
1042
+ }
1043
+ let started = false;
1044
+ for (const start of blockStarts) {
1045
+ const result = start(this, container);
1046
+ if (result === 0)
1047
+ continue;
1048
+ container = this.tip;
1049
+ started = true;
1050
+ if (result === 2)
1051
+ matchedLeaf = true;
1052
+ break;
1053
+ }
1054
+ if (!started) {
1055
+ this.advanceNextNonspace();
1056
+ break;
1057
+ }
1058
+ if (this.plainRest) {
1059
+ this.plainRest = false;
1060
+ this.plainParagraph = true;
1061
+ this.findNextNonspace();
1062
+ break;
1063
+ }
1064
+ }
1065
+ // What is left of the line is text
1066
+ if (!this.allClosed && !this.blank && this.tip.type === 'paragraph') {
1067
+ // Lazy continuation of a paragraph
1068
+ this.addLine();
1069
+ }
1070
+ else {
1071
+ this.closeUnmatchedBlocks();
1072
+ const t = container.type;
1073
+ if (t === 'table') {
1074
+ // The delimiter row is used up by the table's start
1075
+ if (!this.blank && this.offset < line.length) {
1076
+ const tableLine = {
1077
+ text: this.currentLine.slice(this.offset),
1078
+ from: start + this.offset,
1079
+ to: start + line.length,
1080
+ id: this.nextId()
1081
+ };
1082
+ container.rows.push(tableLine);
1083
+ if (this.ephemeral)
1084
+ (container.ephemeralRows ??= new Set()).add(tableLine);
1085
+ }
1086
+ }
1087
+ else if (behaviours[t].acceptsLines) {
1088
+ this.addLine();
1089
+ // An HTML block of types 1 to 5 ends at its closing marker
1090
+ if (t === 'html' && container.htmlBlockType >= 1 && container.htmlBlockType <= 5) {
1091
+ if (reHtmlBlockClose[container.htmlBlockType].test(this.currentLine.slice(this.offset))) {
1092
+ this.lastLineLength = line.length;
1093
+ this.finalize(container, this.lineNumber);
1094
+ }
1095
+ }
1096
+ }
1097
+ else if (this.offset < line.length && !this.blank) {
1098
+ // A new paragraph
1099
+ this.addChild('paragraph', this.offset).plain = this.plainParagraph;
1100
+ this.advanceNextNonspace();
1101
+ this.addLine();
1102
+ }
1103
+ }
1104
+ this.lastLineLength = line.length;
1105
+ // A heading or a rule is whole at the end of its line: closed now, it keeps its object
1106
+ // from here on, where it would otherwise be rebuilt until the next line arrives
1107
+ // Not in a preview, though: there the line is still being written, and its end is tidied
1108
+ if (!this.ephemeral && (this.tip.type === 'heading' || this.tip.type === 'thematicBreak'))
1109
+ this.finalize(this.tip, this.lineNumber);
1110
+ }
1111
+ /** Closes a block whose last line is `line`. */
1112
+ finalize(block, line) {
1113
+ const above = block.parent;
1114
+ // Already closed by its own last line (a formula that ended with text after it)
1115
+ if (!block.open) {
1116
+ this.tip = above ?? this.doc;
1117
+ return;
1118
+ }
1119
+ block.open = false;
1120
+ block.endLine = Math.max(block.startLine, line);
1121
+ block.to = this.lineEndOf(block.endLine);
1122
+ behaviours[block.type].finalize(this, block);
1123
+ this.tip = above ?? this.doc;
1124
+ }
1125
+ /** Marks the deepest open block as the one the preview ends in. */
1126
+ markTail() {
1127
+ const type = this.tip.type;
1128
+ if (type === 'paragraph' || type === 'heading' || type === 'table')
1129
+ this.tip.tail = true;
1130
+ for (let node = this.tip; node; node = node.parent)
1131
+ node.live = true;
1132
+ }
1133
+ /** Closes every open block, as at the end of the document. */
1134
+ closeAll() {
1135
+ while (this.tip !== this.doc)
1136
+ this.finalize(this.tip, this.lineNumber);
1137
+ this.doc.open = false;
1138
+ this.doc.endLine = Math.max(0, this.lineNumber);
1139
+ this.doc.to = this.lineEndOf(this.lineNumber);
1140
+ }
1141
+ /** A copy that shares every closed block, for previewing the unfinished end. */
1142
+ fork() {
1143
+ const copy = Object.create(BlockParser.prototype);
1144
+ Object.assign(copy, this);
1145
+ copy.definitions = new Map(this.definitions);
1146
+ copy.footnoteLabels = new Set(this.footnoteLabels);
1147
+ copy.ephemeral = true;
1148
+ const map = new Map();
1149
+ const cloneOpen = (node, parent) => {
1150
+ const clone = Object.assign(Object.create(Node.prototype), node);
1151
+ clone.parent = parent;
1152
+ clone.children = node.children.slice();
1153
+ clone.ephemeral = true;
1154
+ clone.cache = null;
1155
+ if (node.listData)
1156
+ clone.listData = { ...node.listData };
1157
+ if (node.type === 'table') {
1158
+ clone.rows = node.rows.slice();
1159
+ clone.ephemeralRows = null;
1160
+ }
1161
+ map.set(node, clone);
1162
+ const last = node.lastChild;
1163
+ if (last && last.open)
1164
+ clone.children[clone.children.length - 1] = cloneOpen(last, clone);
1165
+ return clone;
1166
+ };
1167
+ copy.doc = cloneOpen(this.doc, null);
1168
+ copy.tip = map.get(this.tip) ?? copy.doc;
1169
+ copy.oldtip = map.get(this.oldtip) ?? copy.tip;
1170
+ copy.lastMatchedContainer = map.get(this.lastMatchedContainer) ?? copy.doc;
1171
+ return copy;
1172
+ }
1173
+ // Conversion to the public tree
1174
+ toDocument(base, tidy = false) {
1175
+ // Labels only the preview knows: blocks that missed one are converted afresh
1176
+ let extra = null;
1177
+ if (base) {
1178
+ for (const label of this.definitions.keys()) {
1179
+ if (!base.definitions.has(label))
1180
+ (extra ??= new Set()).add(label);
1181
+ }
1182
+ for (const label of this.footnoteLabels) {
1183
+ if (!base.footnoteLabels.has(label))
1184
+ (extra ??= new Set()).add(label);
1185
+ }
1186
+ }
1187
+ if (extra && base) {
1188
+ // Convert once with the real definitions first, so blocks converted for the first time
1189
+ // are cached as they really are, and remember what they missed
1190
+ const real = {
1191
+ parser: base,
1192
+ inline: {
1193
+ definitions: base.definitions,
1194
+ footnotes: base.footnoteLabels,
1195
+ gfm: this.options.gfm,
1196
+ math: this.options.math,
1197
+ singleTilde: this.options.singleTilde
1198
+ },
1199
+ extra: null,
1200
+ footnotes: []
1201
+ };
1202
+ for (const child of this.doc.children)
1203
+ convert(child, real);
1204
+ }
1205
+ const context = {
1206
+ parser: base ?? this,
1207
+ inline: {
1208
+ definitions: this.definitions,
1209
+ footnotes: this.footnoteLabels,
1210
+ gfm: this.options.gfm,
1211
+ math: this.options.math,
1212
+ singleTilde: this.options.singleTilde
1213
+ },
1214
+ extra,
1215
+ footnotes: [],
1216
+ tidy
1217
+ };
1218
+ const children = this.doc.children.map((child) => convert(child, context));
1219
+ return {
1220
+ type: 'document',
1221
+ id: this.doc.id,
1222
+ from: 0,
1223
+ to: this.doc.to,
1224
+ children: children.filter((child) => child.type !== 'footnoteDefinition'),
1225
+ // The first definition of a label is the one that counts
1226
+ footnotes: firstOfEachLabel(context.footnotes)
1227
+ };
1228
+ }
1229
+ }
1230
+ function firstOfEachLabel(notes) {
1231
+ const seen = new Set();
1232
+ return notes.filter((note) => {
1233
+ const key = note.label.toLowerCase();
1234
+ if (seen.has(key))
1235
+ return false;
1236
+ seen.add(key);
1237
+ return true;
1238
+ });
1239
+ }
1240
+ function missedExtra(block, context) {
1241
+ if (!context.extra)
1242
+ return false;
1243
+ const stack = [block];
1244
+ while (stack.length > 0) {
1245
+ const b = stack.pop();
1246
+ if (b.missed)
1247
+ for (const label of b.missed)
1248
+ if (context.extra.has(label))
1249
+ return true;
1250
+ stack.push(...b.children);
1251
+ }
1252
+ return false;
1253
+ }
1254
+ function inlines(block, content, context) {
1255
+ const result = parseInlines(content, context.inline);
1256
+ // Only a block that will be cached remembers what it missed
1257
+ if (context.record) {
1258
+ block.missed = result.missed.size > 0 ? result.missed : null;
1259
+ for (const label of result.missed) {
1260
+ let set = context.parser.missedBy.get(label);
1261
+ if (!set)
1262
+ context.parser.missedBy.set(label, (set = new Set()));
1263
+ set.add(block);
1264
+ }
1265
+ }
1266
+ return result.children;
1267
+ }
1268
+ function convert(block, context) {
1269
+ // A block that missed a label only the preview knows is converted afresh, and not cached
1270
+ const fresh = missedExtra(block, context);
1271
+ if (block.cache && !fresh) {
1272
+ // The footnotes under a kept block are kept with it, wherever in it they are
1273
+ if (block.notes)
1274
+ context.footnotes.push(...block.notes);
1275
+ return block.cache;
1276
+ }
1277
+ const cacheable = !fresh && !block.open && !block.ephemeral;
1278
+ const mark = context.footnotes.length;
1279
+ const node = build(block, { ...context, record: cacheable });
1280
+ if (cacheable) {
1281
+ block.cache = node;
1282
+ block.notes = context.footnotes.length > mark ? context.footnotes.slice(mark) : null;
1283
+ }
1284
+ return node;
1285
+ }
1286
+ const reAlert = /^\[!(note|tip|important|warning|caution)\]$/i;
1287
+ /**
1288
+ * A GitHub alert: a block quote whose first line is `[!NOTE]`, `[!TIP]`, `[!IMPORTANT]`,
1289
+ * `[!WARNING]` or `[!CAUTION]`. The marker is taken out, and the quote says which it is.
1290
+ */
1291
+ function asAlert(quote) {
1292
+ const first = quote.children[0];
1293
+ if (!first || first.type !== 'paragraph')
1294
+ return quote;
1295
+ const [marker, after, ...rest] = first.children;
1296
+ if (!marker || marker.type !== 'text')
1297
+ return quote;
1298
+ const kind = reAlert.exec(marker.value)?.[1]?.toLowerCase();
1299
+ if (!kind || (after && after.type !== 'softBreak' && after.type !== 'break'))
1300
+ return quote;
1301
+ const children = rest.length > 0
1302
+ ? [{ ...first, children: rest }, ...quote.children.slice(1)]
1303
+ : quote.children.slice(1);
1304
+ return { ...quote, alert: kind, children };
1305
+ }
1306
+ function build(block, context) {
1307
+ const base = { id: block.id, from: block.from, to: block.to };
1308
+ // A footnote's definition belongs to the document's footnotes, not to where it was written
1309
+ const children = () => block.children
1310
+ .map((child) => convert(child, context))
1311
+ .filter((child) => child.type !== 'footnoteDefinition');
1312
+ switch (block.type) {
1313
+ case 'paragraph': {
1314
+ let text = block.content.endsWith('\n') ? block.content.slice(0, -1) : block.content;
1315
+ text = trimEndSpaces(text).replace(/^[ \t]+/, '');
1316
+ if (context.tidy && block.tail) {
1317
+ // The lines of a table in the making are held back: a header row of pipes waiting
1318
+ // for its delimiter row, and a delimiter row that is still being written
1319
+ const lines = text.split('\n');
1320
+ const last = lines.length - 1;
1321
+ if (context.inline.gfm &&
1322
+ /^[\s|:-]+$/.test(lines[last]) &&
1323
+ /[-|:]/.test(lines[last]) &&
1324
+ last > 0 &&
1325
+ lines[last - 1].includes('|')) {
1326
+ lines.length = last - 1;
1327
+ }
1328
+ else if (context.inline.gfm && /^\s*\|/.test(lines[last])) {
1329
+ lines.pop();
1330
+ }
1331
+ text = tidyTail(lines.join('\n'), context.inline);
1332
+ }
1333
+ return {
1334
+ ...base,
1335
+ type: 'paragraph',
1336
+ children: inlines(block, text, context)
1337
+ };
1338
+ }
1339
+ case 'heading': {
1340
+ let text = block.content.trim();
1341
+ if (context.tidy && block.tail)
1342
+ text = tidyTail(text, context.inline);
1343
+ return {
1344
+ ...base,
1345
+ type: 'heading',
1346
+ depth: block.level,
1347
+ children: inlines(block, text, context)
1348
+ };
1349
+ }
1350
+ case 'thematicBreak':
1351
+ return { ...base, type: 'thematicBreak' };
1352
+ case 'blockquote': {
1353
+ const quote = { ...base, type: 'blockquote', children: children() };
1354
+ return context.inline.gfm ? asAlert(quote) : quote;
1355
+ }
1356
+ case 'list': {
1357
+ const data = block.listData;
1358
+ return {
1359
+ ...base,
1360
+ type: 'list',
1361
+ ordered: data.type === 'ordered',
1362
+ start: data.start,
1363
+ tight: data.tight,
1364
+ children: children()
1365
+ };
1366
+ }
1367
+ case 'item':
1368
+ return {
1369
+ ...base,
1370
+ type: 'listItem',
1371
+ checked: block.checked,
1372
+ checkedAt: block.checked === null ? null : block.taskAt,
1373
+ children: children()
1374
+ };
1375
+ case 'code': {
1376
+ let lang = null;
1377
+ let meta = null;
1378
+ let value = block.content;
1379
+ if (block.fenced) {
1380
+ let info = block.info;
1381
+ if (block.open) {
1382
+ // Still streaming, or closed by its container: the first line is the info string
1383
+ const newline = value.indexOf('\n');
1384
+ info = unescapeString((newline < 0 ? value : value.slice(0, newline)).trim());
1385
+ value = newline < 0 ? '' : value.slice(newline + 1);
1386
+ }
1387
+ // The language is the first word, up to a `:` or `{`: models write `ts:src/app.ts`
1388
+ // and `js{1,3}`. What follows it, there or after a space, is the meta.
1389
+ const word = /^[^\s:{]*/.exec(info)[0];
1390
+ lang = word || null;
1391
+ meta = info.slice(word.length).replace(/^:/, '').trim() || null;
1392
+ }
1393
+ return {
1394
+ ...base,
1395
+ type: 'code',
1396
+ lang,
1397
+ meta,
1398
+ value,
1399
+ open: block.fenced && !block.closedByFence
1400
+ };
1401
+ }
1402
+ case 'html':
1403
+ return { ...base, type: 'html', value: block.content };
1404
+ case 'math':
1405
+ return {
1406
+ ...base,
1407
+ type: 'math',
1408
+ value: block.content.replace(/\n$/, '').trim(),
1409
+ open: !block.closedByFence
1410
+ };
1411
+ case 'table': {
1412
+ const last = block.rows.length - 1;
1413
+ let missedLabels = null;
1414
+ const rows = block.rows.map((row, r) => {
1415
+ // A finished row is read once: a long table costs no more at its end than at its start
1416
+ if (row.cache)
1417
+ return row.cache;
1418
+ let cells = splitTableRow(row.text);
1419
+ // Every row has as many cells as the header: extra ones are dropped, missing ones empty
1420
+ cells = cells.slice(0, block.align.length);
1421
+ // The row being written: its last cell is tidied, as the end of a paragraph is
1422
+ const tidy = context.tidy && block.tail && r === last && r > 0;
1423
+ if (tidy && cells.length > 0) {
1424
+ const end = cells.length - 1;
1425
+ cells[end] = tidyTail(cells[end], context.inline);
1426
+ }
1427
+ while (cells.length < block.align.length)
1428
+ cells.push('');
1429
+ let missed = false;
1430
+ const tableRow = {
1431
+ type: 'tableRow',
1432
+ id: row.id,
1433
+ from: row.from,
1434
+ to: row.to,
1435
+ children: cells.map((text, c) => {
1436
+ const result = parseInlines(text, context.inline);
1437
+ if (result.missed.size > 0) {
1438
+ missed = true;
1439
+ for (const label of result.missed)
1440
+ (missedLabels ??= new Set()).add(label);
1441
+ }
1442
+ return {
1443
+ type: 'tableCell',
1444
+ id: r * 1000 + c,
1445
+ from: row.from,
1446
+ to: row.to,
1447
+ source: text,
1448
+ children: result.children
1449
+ };
1450
+ })
1451
+ };
1452
+ // Kept only when nothing in it waits on a definition, and it is a whole line of the document
1453
+ // And only when read with the document's own definitions, not ones a preview alone knows
1454
+ if (!missed && !tidy && context.extra === null && !block.ephemeralRows?.has(row))
1455
+ row.cache = tableRow;
1456
+ return tableRow;
1457
+ });
1458
+ // A table whose cell looked up a label that is not defined yet is read again when it is
1459
+ if (context.record) {
1460
+ block.missed = missedLabels;
1461
+ for (const label of missedLabels ?? []) {
1462
+ let set = context.parser.missedBy.get(label);
1463
+ if (!set)
1464
+ context.parser.missedBy.set(label, (set = new Set()));
1465
+ set.add(block);
1466
+ }
1467
+ }
1468
+ return {
1469
+ ...base,
1470
+ type: 'table',
1471
+ align: block.align,
1472
+ open: block.live,
1473
+ children: rows
1474
+ };
1475
+ }
1476
+ case 'footnote': {
1477
+ const node = {
1478
+ ...base,
1479
+ type: 'footnoteDefinition',
1480
+ label: block.label,
1481
+ children: children()
1482
+ };
1483
+ context.footnotes.push(node);
1484
+ return node;
1485
+ }
1486
+ case 'document':
1487
+ throw new Error('A document is not converted as a block');
1488
+ }
1489
+ }