@bigmistqke/workpad 0.0.0-stage → 0.18.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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1509 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1190 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2098 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +211 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +341 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +665 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +588 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +133 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +137 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +238 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +426 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +748 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
@@ -0,0 +1,976 @@
1
+ // Markdown → HTML, with directives and fences handed to blocks.
2
+ //
3
+ // A block with a component becomes an island:
4
+ // <div class="wp-island" data-wp-island="3">fallback html</div>
5
+ // and its props go into the `islands` map the page embeds for the client to mount.
6
+ // A block with only server.ts html() is inlined as static HTML.
7
+ import path from 'node:path'
8
+ import crypto from 'node:crypto'
9
+ import { unified } from 'unified'
10
+ import remarkParse from 'remark-parse'
11
+ import remarkGfm from 'remark-gfm'
12
+ import remarkDirective from 'remark-directive'
13
+ import remarkRehype from 'remark-rehype'
14
+ import rehypeStringify from 'rehype-stringify'
15
+ import { toString } from 'mdast-util-to-string'
16
+ import { html, raw, type Html } from '../html.ts'
17
+ import { anchorsOf, slugText } from '../anchors.ts'
18
+ import { agentMessagesIn, isQuestionName } from '../status.ts'
19
+ import type { ResolvedBlock } from './blocks.ts'
20
+ import type { Plugin, TextLink, WpEvent } from '../define.ts'
21
+
22
+ /**
23
+ * An mdast node, loosely: the pipeline hands nodes between remark, the directive plugin and
24
+ * blocks, and replaces some in place with `html` nodes.
25
+ */
26
+ export interface MdNode {
27
+ type: string
28
+ children?: MdNode[]
29
+ value?: string
30
+ [key: string]: any
31
+ }
32
+
33
+ type LinkFor = (absolutePath: string) => string | null
34
+
35
+ const parser = unified().use(remarkParse).use(remarkGfm).use(remarkDirective).freeze()
36
+
37
+ // A line starting with `:::` inside a code fence would close the container directive around the
38
+ // fence: the directive parser looks for its closing fence on every line before the code fence's
39
+ // content. So inside code fences, a line's leading colons are hidden from it (as a character no
40
+ // page uses), and put back in the parsed tree.
41
+ const HIDDEN_COLON = '\uE000'
42
+ const FENCE = /^(\s*)(`{3,}|~{3,})/
43
+
44
+ function hideColonsInFences(source: string): string {
45
+ let open: { char: string; length: number } | null = null
46
+ return source
47
+ .split('\n')
48
+ .map(line => {
49
+ const fence = FENCE.exec(line)
50
+ if (!open) {
51
+ if (fence) open = { char: fence[2][0], length: fence[2].length }
52
+ return line
53
+ }
54
+ if (fence && fence[2][0] === open.char && fence[2].length >= open.length && !line.slice(fence[0].length).trim()) {
55
+ open = null
56
+ return line
57
+ }
58
+ return line.replace(
59
+ /^(\s*)(:+)/,
60
+ (_, space: string, colons: string) => space + HIDDEN_COLON.repeat(colons.length),
61
+ )
62
+ })
63
+ .join('\n')
64
+ }
65
+
66
+ function showColons(node: MdNode) {
67
+ if (typeof node.value === 'string' && node.value.includes(HIDDEN_COLON))
68
+ node.value = node.value.replaceAll(HIDDEN_COLON, ':')
69
+ node.children?.forEach(showColons)
70
+ }
71
+
72
+ /** A message's raw HTML, as text: it shows as written, and runs nothing. */
73
+ function asText(node: MdNode) {
74
+ if (node.type === 'html') {
75
+ node.type = 'text'
76
+ return
77
+ }
78
+ node.children?.forEach(asText)
79
+ }
80
+
81
+ /**
82
+ * A heading's anchor as GitHub and GitLab make it: lowercased, punctuation dropped, spaces as
83
+ * hyphens. `taken` holds those given out on the page: a repeat gets -1, -2 and on.
84
+ */
85
+ export function slug(text: string, taken: Map<string, number>): string {
86
+ const base = slugText(text)
87
+ let id = base
88
+ if (taken.has(base)) {
89
+ let n = taken.get(base)!
90
+ do id = `${base}-${++n}`
91
+ while (taken.has(id))
92
+ taken.set(base, n)
93
+ }
94
+ taken.set(id, 0)
95
+ return id
96
+ }
97
+
98
+ /** Markdown → mdast: GFM and directives, with code fences safe inside containers. */
99
+ export function parseMarkdown(source: string): MdNode {
100
+ const tree = parser.parse(hideColonsInFences(source)) as MdNode
101
+ showColons(tree)
102
+ return tree
103
+ }
104
+ const toHast = unified()
105
+ .use(remarkRehype, { allowDangerousHtml: true })
106
+ .use(rehypeStringify, { allowDangerousHtml: true })
107
+ .freeze()
108
+
109
+ /**
110
+ * `cols=3 open title="a b"` → { cols: '3', open: '', title: 'a b' } (bare words get '' like directive
111
+ * attrs). In braces too, as a fence writes them: `{compose=window}` (an unquoted value ends at `}`).
112
+ */
113
+ export function parseAttrs(s: unknown) {
114
+ const out: Record<string, string> = {}
115
+ for (const m of String(s ?? '').matchAll(/([\w-]+)(?:=("[^"]*"|'[^']*'|[^\s}]+))?/g))
116
+ out[m[1]] = m[2] ? m[2].replace(/^["']|["']$/g, '') : ''
117
+ return out
118
+ }
119
+
120
+ /** A heading's text as a key: lowercase, words joined by - */
121
+ const slugOf = (text: string) =>
122
+ text
123
+ .toLowerCase()
124
+ .trim()
125
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
126
+ .replace(/^-|-$/g, '')
127
+
128
+ /** The blocks that, directly inside a block that takes items (a grid), are an item as they are: their label its title. */
129
+ const ITEM_BLOCKS = new Set(['form', 'details'])
130
+ /** The containers whose label is a title, where an inline block ending it (a badge) sits at its right (endTitles). */
131
+ const TITLED = new Set(['item', 'form'])
132
+
133
+ const DIRECTIVES = new Set(['containerDirective', 'leafDirective', 'textDirective'])
134
+ const PHRASING = new Set([
135
+ 'text',
136
+ 'emphasis',
137
+ 'strong',
138
+ 'delete',
139
+ 'inlineCode',
140
+ 'break',
141
+ 'link',
142
+ 'linkReference',
143
+ 'image',
144
+ 'imageReference',
145
+ 'footnoteReference',
146
+ 'textDirective',
147
+ ])
148
+
149
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
150
+
151
+ /**
152
+ * Point relative links and images at what they name on disk: each is resolved from the markdown
153
+ * file's own folder and handed to `linkFor(absolutePath)`, which returns the URL that serves it
154
+ * (or null to leave the link as written).
155
+ */
156
+ // where text is not linked: it is code, a link already, or an inline directive (a button, a field)
157
+ const NO_TEXT_LINKS = new Set(['link', 'linkReference', 'inlineCode', 'code', 'html', 'textDirective', 'definition'])
158
+
159
+ /** Turn the plugins' text links (`#12`) into links, in plain text only. */
160
+ function linkText(tree: MdNode, links: TextLink[]) {
161
+ if (!links.length) return
162
+ const split = (text: string): MdNode[] => {
163
+ let parts: MdNode[] = [{ type: 'text', value: text }]
164
+ for (const link of links) {
165
+ const flags = link.pattern.flags.includes('g') ? link.pattern.flags : link.pattern.flags + 'g'
166
+ parts = parts.flatMap(part => {
167
+ if (part.type !== 'text') return [part]
168
+ const out: MdNode[] = []
169
+ const value = part.value as string
170
+ const re = new RegExp(link.pattern.source, flags)
171
+ let at = 0
172
+ for (let m = re.exec(value); m; m = re.exec(value)) {
173
+ if (!m[0]) {
174
+ re.lastIndex++
175
+ continue
176
+ }
177
+ const href = link.href(m)
178
+ if (!href) continue
179
+ if (m.index > at) out.push({ type: 'text', value: value.slice(at, m.index) })
180
+ out.push({
181
+ type: 'link',
182
+ url: href,
183
+ title: link.title?.(m) ?? null,
184
+ children: [{ type: 'text', value: m[0] }],
185
+ })
186
+ at = m.index + m[0].length
187
+ }
188
+ if (at < value.length) out.push({ type: 'text', value: value.slice(at) })
189
+ return out
190
+ })
191
+ }
192
+ return parts
193
+ }
194
+ const walk = (node: MdNode) => {
195
+ if (!node.children || NO_TEXT_LINKS.has(node.type)) return
196
+ node.children = node.children.flatMap(child =>
197
+ child.type === 'text' ? split(child.value as string) : (walk(child), [child]),
198
+ )
199
+ }
200
+ walk(tree)
201
+ }
202
+
203
+ /**
204
+ * The address of something named relative to the page (a link, an image, a block's `src`): resolved
205
+ * from the page's folder and handed to `linkFor`. A URL, an address from the root, an anchor, or
206
+ * something nothing serves stays as written.
207
+ */
208
+ function addressOf(ref: string, file: string, linkFor?: LinkFor): string {
209
+ if (!linkFor || !file || !ref || SCHEME.test(ref) || /^[/#]/.test(ref)) return ref
210
+ const [, target, rest] = /^([^?#]*)(.*)$/s.exec(ref)!
211
+ let decoded = target
212
+ try {
213
+ decoded = decodeURIComponent(target)
214
+ } catch {
215
+ /* keep as written */
216
+ }
217
+ const url = decoded && linkFor(path.resolve(path.dirname(file), decoded))
218
+ return url ? url + rest : ref
219
+ }
220
+
221
+ /** Raw HTML's references to files beside the page (`<img src>`, `<video poster>`, `<a href>`). */
222
+ const HTML_REFS = /(\b(?:src|href|poster)=")([^"]*)(")/g
223
+
224
+ function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
225
+ if (!linkFor || !file) return
226
+ const walk = (node: MdNode) => {
227
+ if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && node.url)
228
+ node.url = addressOf(node.url as string, file, linkFor)
229
+ // raw HTML the page writes itself, as the markdown it is in: before it is a string
230
+ if (node.type === 'html' && typeof node.value === 'string')
231
+ node.value = node.value.replace(HTML_REFS, (_, open, ref, close) => open + addressOf(ref, file, linkFor) + close)
232
+ node.children?.forEach(walk)
233
+ }
234
+ walk(tree)
235
+ }
236
+
237
+ /**
238
+ * A quote that is an alert, `> [!WARNING] A title` and its lines below (GitHub's, and Obsidian's
239
+ * title and fold marker): as the container directive its block renders, `[!TYPE]` its `type`, the
240
+ * title its label, the rest its content. Else null: a quote like any other.
241
+ */
242
+ function alertOf(quote: MdNode): ((name: string) => MdNode) | null {
243
+ const [first, ...rest] = quote.children ?? []
244
+ const head = first?.type === 'paragraph' ? first.children?.[0] : null
245
+ const text = head?.type === 'text' ? (head.value ?? '') : ''
246
+ const m = /^\[!([A-Za-z]+)\][+-]?[ \t]*/.exec(text)
247
+ if (!m) return null
248
+ // the paragraph's nodes after [!TYPE]: up to its first line break the title, the rest content
249
+ const after = [{ ...head!, value: text.slice(m[0].length) }, ...(first!.children ?? []).slice(1)]
250
+ const title: MdNode[] = []
251
+ const body: MdNode[] = []
252
+ for (const node of after) {
253
+ if (body.length) body.push(node)
254
+ else if (node.type === 'break') body.push({ type: 'text', value: '' })
255
+ else if (node.type === 'text' && node.value?.includes('\n')) {
256
+ const at = node.value.indexOf('\n')
257
+ if (at > 0) title.push({ ...node, value: node.value.slice(0, at) })
258
+ body.push({ ...node, value: node.value.slice(at + 1) })
259
+ } else title.push(node)
260
+ }
261
+ const label = title.filter(n => n.type !== 'text' || n.value?.trim())
262
+ const content = body.filter(n => n.type !== 'text' || n.value !== '')
263
+ const children = [
264
+ ...(label.length ? [{ type: 'paragraph', data: { directiveLabel: true }, children: label }] : []),
265
+ ...(content.length ? [{ type: 'paragraph', children: content }] : []),
266
+ ...rest,
267
+ ]
268
+ return name => ({ type: 'containerDirective', name, attributes: { type: m[1].toLowerCase() }, children })
269
+ }
270
+
271
+ /** Separate a directive's `[label]` (remark-directive stores it as a flagged first paragraph). */
272
+ function splitLabel(node: MdNode): { label: MdNode[] | null; children: MdNode[] } {
273
+ const [head, ...rest] = node.children ?? []
274
+ if (node.type === 'containerDirective' && head?.data?.directiveLabel)
275
+ return { label: head.children ?? null, children: rest }
276
+ if (node.type !== 'containerDirective') return { label: node.children?.length ? node.children : null, children: [] }
277
+ return { label: null, children: node.children ?? [] }
278
+ }
279
+
280
+ const MARKER: Record<string, string> = { textDirective: ':', leafDirective: '::', containerDirective: ':::' }
281
+
282
+ function literalDirective(node: MdNode, label: MdNode[] | null) {
283
+ const marker = MARKER[node.type]
284
+ const attrs = Object.entries(node.attributes ?? {})
285
+ .map(([k, v]) => (v ? `${k}="${v}"` : k))
286
+ .join(' ')
287
+ return `${marker}${node.name}${label ? `[${toString({ type: 'root', children: label } as any)}]` : ''}${attrs ? `{${attrs}}` : ''}`
288
+ }
289
+
290
+ /**
291
+ * A title's own words, as plain text: a heading's, an item's label. The inline blocks in it (a
292
+ * badge, a `:when`) are left out: they mark the title rather than say it, so what is made of its
293
+ * words (a heading's anchor, an item's key) stays while a status or a date changes. An inline
294
+ * directive no block brings (the `:59` in `19:59`) is words, as written.
295
+ */
296
+ export function titleWords(nodes: MdNode[], resolve: (name: string) => unknown): string {
297
+ // where a block was, a mark: the spaces around it become one
298
+ const GONE = '\u0000'
299
+ const words = (node: MdNode): string => {
300
+ if (node.type === 'textDirective')
301
+ return resolve(node.name) ? GONE : literalDirective(node, node.children?.length ? node.children : null)
302
+ if (typeof node.value === 'string') return node.value
303
+ if (typeof node.alt === 'string') return node.alt
304
+ return (node.children ?? []).map(words).join('')
305
+ }
306
+ return nodes
307
+ .map(words)
308
+ .join('')
309
+ .replace(/\s*\u0000[\s\u0000]*/g, ' ')
310
+ .trim()
311
+ }
312
+
313
+ /**
314
+ * The forms a page asks the reader to answer, by name: `:::form{name=…}` containers and
315
+ * hand-written <form name="…"> without an action. Parsed, so a form shown as an example inside a
316
+ * code block doesn't count.
317
+ */
318
+ export function formNames(source: string) {
319
+ const tree = parseMarkdown(String(source ?? ''))
320
+ const names: string[] = []
321
+ const walk = (node: MdNode) => {
322
+ if (node.type === 'containerDirective' && node.name === 'form') {
323
+ const attrs = node.attributes ?? {}
324
+ names.push(attrs.name || attrs.id || 'form')
325
+ } else if (node.type === 'html') {
326
+ for (const m of (node.value ?? '').matchAll(/<form\b([^>]*)>/gi)) {
327
+ if (/\baction\s*=/i.test(m[1])) continue
328
+ const name = /\bname\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[1])
329
+ if (name) names.push(name[2] ?? name[3] ?? name[4])
330
+ }
331
+ }
332
+ for (const child of node.children ?? []) walk(child)
333
+ }
334
+ walk(tree)
335
+ // a slash is a chat message's form's (`<chat>/<name>`), never a page's
336
+ return [...new Set(names)].filter(n => isQuestionName(n) && !n.includes('/'))
337
+ }
338
+
339
+ /**
340
+ * The `:::form`s in a source by the name they are written with, null for one without; in order, and
341
+ * not those shown in a code fence. For a message's forms, which are named in their chat.
342
+ */
343
+ export function formsIn(source: string): { name: string | null; markdown: string }[] {
344
+ const text = String(source ?? '')
345
+ const out: { name: string | null; markdown: string }[] = []
346
+ const walk = (node: MdNode) => {
347
+ if (node.type === 'containerDirective' && node.name === 'form') {
348
+ const attrs = node.attributes ?? {}
349
+ const [start, end] = [node.position?.start?.offset, node.position?.end?.offset]
350
+ out.push({
351
+ name: attrs.name || attrs.id || null,
352
+ markdown: typeof start === 'number' ? text.slice(start, end) : '',
353
+ })
354
+ }
355
+ for (const child of node.children ?? []) walk(child)
356
+ }
357
+ walk(parseMarkdown(text))
358
+ return out
359
+ }
360
+
361
+ /** One option of a form's question, as written: `:radio[Label]{name=field value=… recommended other}`. */
362
+ export interface FormOption {
363
+ /** the field it sets: its `name` */
364
+ field: string
365
+ /** what it says, as plain text */
366
+ label: string
367
+ /** what it sends: its `value`, else its label ('' for an other-option, which sends what was typed) */
368
+ value: string
369
+ /** a radio, or a checkbox */
370
+ kind: 'radio' | 'checkbox'
371
+ recommended: boolean
372
+ /** an answer not on the list: it sends what the reader types */
373
+ other: boolean
374
+ }
375
+
376
+ /** What a form asks, as written: the question, its options and its buttons. */
377
+ export interface FormDetail {
378
+ /** the form's name as written (`form` for one without) */
379
+ name: string
380
+ /** its label (`:::form[…]`), else its first paragraph of text, as plain text; null without either */
381
+ question: string | null
382
+ options: FormOption[]
383
+ /** the labels of its buttons (`:button[…]`); a form without one has a Send button */
384
+ buttons: string[]
385
+ }
386
+
387
+ /** The text of nodes without the inline blocks in them (a form's inputs). */
388
+ const plainText = (nodes: MdNode[]): string =>
389
+ nodes
390
+ .map(n => (n.type === 'textDirective' || n.type === 'leafDirective' ? ' ' : n.children ? plainText(n.children) : (n.value ?? '')))
391
+ .join('')
392
+ .replace(/\s+/g, ' ')
393
+ .trim()
394
+
395
+ /** What one `:::form` node asks (FormDetail). */
396
+ function describeForm(node: MdNode): FormDetail {
397
+ const attrs = node.attributes ?? {}
398
+ const children = node.children ?? []
399
+ const label = children[0]?.data?.directiveLabel ? plainText(children[0].children ?? []) : ''
400
+ const first = children.find(c => c.type === 'paragraph' && !c.data?.directiveLabel && plainText(c.children ?? []))
401
+ const options: FormOption[] = []
402
+ const buttons: string[] = []
403
+ const walk = (n: MdNode) => {
404
+ if (n.type === 'containerDirective' && n.name === 'form' && n !== node) return
405
+ if (n.type === 'textDirective' || n.type === 'leafDirective') {
406
+ const a = n.attributes ?? {}
407
+ const text = toString(n as any).trim()
408
+ if ((n.name === 'radio' || n.name === 'checkbox') && a.name)
409
+ options.push({
410
+ field: a.name,
411
+ label: text || ('other' in a ? 'Other' : ''),
412
+ value: 'other' in a ? '' : (a.value ?? text),
413
+ kind: n.name,
414
+ recommended: 'recommended' in a,
415
+ other: 'other' in a,
416
+ })
417
+ if (n.name === 'button') buttons.push(text || 'Send')
418
+ }
419
+ for (const c of n.children ?? []) walk(c)
420
+ }
421
+ children.forEach(walk)
422
+ return {
423
+ name: attrs.name || attrs.id || 'form',
424
+ question: label || (first ? plainText(first.children ?? []) : null),
425
+ options,
426
+ buttons,
427
+ }
428
+ }
429
+
430
+ /** What each `:::form` in a source asks, in order (not those shown in a code fence). */
431
+ export function formDetails(source: string): FormDetail[] {
432
+ const out: FormDetail[] = []
433
+ const walk = (node: MdNode) => {
434
+ if (node.type === 'containerDirective' && node.name === 'form') out.push(describeForm(node))
435
+ for (const child of node.children ?? []) walk(child)
436
+ }
437
+ walk(parseMarkdown(String(source ?? '')))
438
+ return out
439
+ }
440
+
441
+ /**
442
+ * The forms in the agent's messages in `chats` (a page's chats, chatNames), by their names there:
443
+ * `<chat>/<name>`, an unnamed one numbered in its chat (Api.message). They are questions of the
444
+ * page as much as its own forms are.
445
+ */
446
+ export function messageForms(events: WpEvent[], page: string, chats: string[]): string[] {
447
+ return [...new Set(chats.flatMap(chat => chatForms(events, page, chat).map(f => f.name)))]
448
+ }
449
+
450
+ /**
451
+ * The forms in the agent's messages in one chat, in order: each by its name there (`<chat>/<name>`,
452
+ * or its number), as written, and the message it is in.
453
+ */
454
+ export function chatForms(
455
+ events: WpEvent[],
456
+ page: string,
457
+ chat: string,
458
+ ): { name: string; markdown: string; message: WpEvent }[] {
459
+ const out: { name: string; markdown: string; message: WpEvent }[] = []
460
+ let n = 1
461
+ for (const message of agentMessagesIn(events, page, chat))
462
+ for (const form of formsIn(String(message.data.text ?? ''))) {
463
+ // a name the form block refuses (a colon, a slash) makes no form
464
+ if (form.name && (!isQuestionName(form.name) || form.name.includes('/'))) continue
465
+ out.push({ name: `${chat}/${form.name ?? n++}`, markdown: form.markdown, message })
466
+ }
467
+ return out
468
+ }
469
+
470
+ /**
471
+ * The chats a page shows, by name: the one under every form (by the form's name, see formNames) and
472
+ * each chat block, `:::chat{name=…}` or `::chat{name=…}`. A chat message (`data.chat`) of any other name is in a chat no longer
473
+ * on the page.
474
+ */
475
+ export function chatNames(source: string) {
476
+ const tree = parseMarkdown(String(source ?? ''))
477
+ const names: string[] = formNames(source)
478
+ // a form without its chat (`chat=false`): no chat of that name
479
+ const without = new Set<string>()
480
+ const walk = (node: MdNode) => {
481
+ if (node.type === 'containerDirective' && node.name === 'form' && node.attributes?.chat === 'false')
482
+ without.add(node.attributes.name ?? '')
483
+ // `:::chat{name=…}` around what it says, or `::chat{name=…}` alone: a bare chat
484
+ if ((node.type === 'containerDirective' || node.type === 'leafDirective') && node.name === 'chat') {
485
+ const attrs = node.attributes ?? {}
486
+ names.push(attrs.name || attrs.id || 'chat')
487
+ }
488
+ for (const child of node.children ?? []) walk(child)
489
+ }
490
+ walk(tree)
491
+ return [...new Set(names)].filter(name => !without.has(name))
492
+ }
493
+
494
+ /**
495
+ * The form `name` as written on a page: its markdown (the container, fences and all) and the text of
496
+ * the last heading before it, for an answer shown with its question (`workpad thread`). Null when
497
+ * the page has no `:::form` of that name.
498
+ */
499
+ export function formSource(source: string, name: string): { heading: string | null; markdown: string } | null {
500
+ const text = String(source ?? '')
501
+ const tree = parseMarkdown(text)
502
+ let heading: string | null = null
503
+ let found: { heading: string | null; markdown: string } | null = null
504
+ const walk = (node: MdNode) => {
505
+ if (found) return
506
+ if (node.type === 'heading') heading = toString(node as any)
507
+ if (node.type === 'containerDirective' && node.name === 'form') {
508
+ const attrs = node.attributes ?? {}
509
+ if ((attrs.name || attrs.id || 'form') === name) {
510
+ const start = node.position?.start?.offset
511
+ const end = node.position?.end?.offset
512
+ found = { heading, markdown: typeof start === 'number' ? text.slice(start, end) : '' }
513
+ return
514
+ }
515
+ }
516
+ for (const child of node.children ?? []) walk(child)
517
+ }
518
+ walk(tree)
519
+ return found
520
+ }
521
+
522
+ export interface RenderOptions {
523
+ page: string
524
+ file: string
525
+ /** a block by name, resolved (see blocks.ts) */
526
+ resolve: (name: string) => ResolvedBlock | null
527
+ /** the block for fences no block claims by name; without one they render as plain code */
528
+ code?: ResolvedBlock | null
529
+ /** the name of the block for `> [!TYPE]` alerts (Block.alert), resolved as any; without one they are quotes */
530
+ alert?: string | null
531
+ /** the URL that serves a file on disk, for relative links */
532
+ linkFor?: LinkFor
533
+ /** the plugins' text links (`#12` → an issue), applied to plain text */
534
+ textLinks?: TextLink[]
535
+ /**
536
+ * a message (a comment, a chat message), not a page: raw HTML shows as text, and directives as
537
+ * written (no buttons or forms in a message); code fences (a diagram's too) and text links work as
538
+ * on a page
539
+ */
540
+ message?: boolean
541
+ /** the plugins that compose themselves around blocks (Plugin.compose), by name: a block names them in `compose` */
542
+ composers?: Map<string, NonNullable<Plugin['compose']>>
543
+ /**
544
+ * An agent's message, rendered as a page in the chat `name` (BaseContext.chat): its headings get
545
+ * no ids (the page's own would clash), its islands' ids start with `prefix`, and its unnamed forms
546
+ * are numbered in the chat from `first`.
547
+ */
548
+ chat?: { name: string; first: number; prefix: string }
549
+ /** blocks rendered for a plugin's client (Api.blocks), not a page: its islands' ids start with this */
550
+ prefix?: string
551
+ }
552
+
553
+ export interface Island {
554
+ block: string
555
+ client: string
556
+ props: unknown
557
+ }
558
+
559
+ /**
560
+ * Markdown (or an mdast root, rendered as it is) → HTML, with directives and fences handed to
561
+ * blocks. Returns the page's HTML, its first heading, the islands to mount and the blocks'
562
+ * stylesheets.
563
+ */
564
+ export async function renderMarkdown(
565
+ source: string | MdNode,
566
+ { page, file, resolve, code = null, alert = null, linkFor, textLinks = [], message = false, composers, chat, prefix }: RenderOptions,
567
+ ) {
568
+ let nextId = 0
569
+ const islands: Record<string, Island> = {}
570
+ // what is wrong on the page, for whoever wrote it (Rendered.problems): shown above the page, and
571
+ // listed by `workpad check`. Not in a message: nobody there can fix it
572
+ const problems: string[] = []
573
+ const problem = (text: string) => {
574
+ if (!message && !problems.includes(text)) problems.push(text)
575
+ }
576
+ const keyCount: Record<string, number> = {}
577
+ const used = new Map<string, ResolvedBlock>()
578
+
579
+ const stringify = (nodes: MdNode[], inline = nodes.length > 0 && nodes.every(n => PHRASING.has(n.type))): string => {
580
+ // inline content (a label, say) is one line: as children of the root, each node would be a block
581
+ // of its own, separated by newlines, which show as spaces
582
+ if (inline) {
583
+ const out = toHast.stringify(
584
+ toHast.runSync({ type: 'root', children: [{ type: 'paragraph', children: nodes }] } as any),
585
+ )
586
+ return out.replace(/^<p>([\s\S]*)<\/p>$/, '$1')
587
+ }
588
+ return toHast.stringify(toHast.runSync({ type: 'root', children: nodes } as any))
589
+ }
590
+ /** Render mdast nodes to HTML. Transforms nested directives first; safe to call twice on the same nodes. */
591
+ const toHtml = async (nodes: MdNode[]) => {
592
+ // inline as written: its directives render as HTML, which is no longer seen as inline (a label's badge)
593
+ const inline = nodes.length > 0 && nodes.every(n => PHRASING.has(n.type))
594
+ await transform({ type: 'root', children: nodes })
595
+ return stringify(nodes, inline)
596
+ }
597
+
598
+ /**
599
+ * A block's items (DirectiveContext.items): each `:::item[Title]` container directly in it, its
600
+ * label the title (none: untitled), its content any markdown, headings too. A `:::form` or a
601
+ * `:::details` directly in it is an item as it is: its label the title, the block itself the
602
+ * content. Anything else directly in it shows as an untitled item of its own, and is a problem: a
603
+ * heading or a `---` starts no item. Renders the items once; afterwards the block's children are
604
+ * the items' HTML, so rendering them as they are (Block.html's fallback, defaults()) shows the same.
605
+ */
606
+ async function itemsOf(children: MdNode[]) {
607
+ type Group = { label: MdNode[] | null; body: MdNode[]; block: string | null; loose?: true }
608
+ const groups: Group[] = []
609
+ let loose: Group | null = null
610
+ for (const n of children) {
611
+ if (n.type === 'text' && !String(n.value ?? '').trim()) continue
612
+ // a comment shows nothing: no item of its own
613
+ if (n.type === 'html' && /^\s*<!--[\s\S]*-->\s*$/.test(String(n.value ?? ''))) continue
614
+ if (n.type === 'containerDirective' && n.name === 'item') {
615
+ const { label, children: body } = splitLabel(n)
616
+ groups.push({ label, body, block: null })
617
+ loose = null
618
+ } else if (n.type === 'containerDirective' && ITEM_BLOCKS.has(n.name) && resolve(n.name)) {
619
+ groups.push({ label: splitLabel(n).label, body: [n], block: n.name })
620
+ loose = null
621
+ } else {
622
+ if (!loose) groups.push((loose = { label: null, body: [], block: null, loose: true }))
623
+ loose.body.push(n)
624
+ }
625
+ }
626
+ const taken = new Map<string, number>()
627
+ const items = []
628
+ for (const [i, g] of groups.entries()) {
629
+ // as written, before it renders: for a block that takes it apart (a timeline's `:when`)
630
+ const label = g.label && structuredClone(g.label)
631
+ // its own words, without the inline blocks in it (a badge, a `:when`): the key stays while a status changes
632
+ const text = g.label ? titleWords(g.label, resolve) : null
633
+ // a block's own label renders with it too: the title from a copy
634
+ const title = g.label && (await toHtml(g.block ? structuredClone(g.label) : g.label))
635
+ const base = (text && slugOf(text)) || String(i + 1)
636
+ const n = (taken.get(base) ?? 0) + 1
637
+ taken.set(base, n)
638
+ const html = await toHtml(g.body)
639
+ items.push({
640
+ title,
641
+ text: text || null,
642
+ label,
643
+ html,
644
+ nodes: g.body,
645
+ block: g.block,
646
+ key: n > 1 ? `${base}-${n}` : base,
647
+ })
648
+ }
649
+ children.splice(0, children.length, ...items.map(item => htmlNode(item.html)))
650
+ return { items, loose: groups.some(g => g.loose) }
651
+ }
652
+
653
+ /** HTML into the markdown tree, where the rest of the pipeline takes it as it is: the one place it becomes a string. */
654
+ const htmlNode = (markup: Html | string): MdNode => ({ type: 'html', value: String(markup) })
655
+
656
+ /**
657
+ * A block's output for one directive or fence: static HTML, or an island around it; then put in
658
+ * what the plugins its `compose` attribute names compose around it (Plugin.compose), in the order
659
+ * written, the first innermost: `{compose=lightbox,window}`. A name no plugin composes is said in
660
+ * place. Not inline blocks, not a block of the composing plugin's own name, not one that renders
661
+ * nothing (left out of a build), and not one that says what's wrong with it instead.
662
+ */
663
+ async function run(block: ResolvedBlock, ctx: any, fallback: () => Promise<Html | string>): Promise<Html> {
664
+ let out = await output(block, ctx, fallback)
665
+ const attrs: Record<string, string> = ctx.attrs ?? {}
666
+ const names = String(attrs.compose ?? '')
667
+ .split(/[\s,]+/)
668
+ .filter(Boolean)
669
+ const shown = String(out).trim()
670
+ if (!names.length || ctx.kind === 'textDirective' || !shown || shown.startsWith('<pre class="wp-error"')) return out
671
+ let open: string | null | undefined
672
+ for (const name of names) {
673
+ if (block.name === name) continue
674
+ const compose = composers?.get(name)
675
+ if (!compose) {
676
+ out = html`<pre class="wp-error">compose: no plugin named "${name}" composes around blocks</pre>
677
+ ${out}`
678
+ continue
679
+ }
680
+ try {
681
+ open ??= block.open?.(ctx) ?? null
682
+ out = raw(String(await compose({ children: out, block: block.name, attrs, label: ctx.label ?? null, open })))
683
+ } catch (err) {
684
+ console.error(`plugin ${name}: compose:`, err)
685
+ out = html`<pre class="wp-error">
686
+ plugin "${name}" failed to compose around block "${block.name}": ${(err as Error).message}</pre>`
687
+ }
688
+ }
689
+ return out
690
+ }
691
+
692
+ async function output(block: ResolvedBlock, ctx: any, fallback: () => Promise<Html | string>): Promise<Html> {
693
+ used.set(block.name, block)
694
+ try {
695
+ // a block may return a string or an `html` result: either is HTML
696
+ const own = block.html ? await block.html(ctx) : null
697
+ const body = raw(own ?? (await fallback()))
698
+ // the element is span or div, chosen here, never from input
699
+ const tag = raw(ctx.kind === 'textDirective' ? 'span' : 'div')
700
+ if (!block.client) return own != null ? body : html`<${tag} data-block="${ctx.name}">${body}</${tag}>`
701
+ const props = block.props ? await block.props(ctx) : await ctx.defaults()
702
+ const id = `${chat?.prefix ?? prefix ?? ''}${++nextId}`
703
+ islands[id] = { block: block.name, client: block.client, props }
704
+ // stable across re-renders while block + props are unchanged, so the client keeps the mounted island
705
+ const hash = crypto
706
+ .createHash('sha1')
707
+ .update(block.name + '\0' + JSON.stringify(props))
708
+ .digest('hex')
709
+ .slice(0, 12)
710
+ const key = `${hash}-${(keyCount[hash] = (keyCount[hash] ?? 0) + 1)}`
711
+ // an island can carry the id a block asked for (`anchor` attribute: a form's chat), so a link reaches it
712
+ const anchorId = ctx.attrs?.anchor ? html` id="${ctx.attrs.anchor}"` : ''
713
+ return html`<${tag} class="wp-island" data-block="${ctx.name}" data-wp-island="${id}" data-wp-key="${key}"${anchorId}>${body}</${tag}>`
714
+ } catch (err) {
715
+ console.error(`block ${block.name}:`, err)
716
+ return html`<pre class="wp-error">block "${block.name}" failed: ${(err as Error).message}</pre>`
717
+ }
718
+ }
719
+
720
+ // a page's headings get anchors (#<slug>), as on a forge; a message's don't, so they never clash
721
+ // with the page's own. The slug is the heading's own words (titleWords): a badge or a `:when` in
722
+ // it is not, so a link to it holds while its status changes
723
+ const slugs = new Map<string, number>()
724
+ const anchorHeadings = (node: MdNode) => {
725
+ if (node.type === 'heading') {
726
+ const id = slug(titleWords(node.children ?? [], resolve), slugs)
727
+ // the page's own ids (wp-main, wp-updated) stay its own
728
+ if (id && !id.startsWith('wp-')) node.data = { ...node.data, hProperties: { ...node.data?.hProperties, id } }
729
+ }
730
+ node.children?.forEach(anchorHeadings)
731
+ }
732
+ /**
733
+ * An inline block that ends a heading (a badge: `### Parser :badge[done]`), or the label of an item
734
+ * or a form (`:::item[Parser :badge[done]]`, TITLED), sits at the title's
735
+ * right, on its first line, the title wrapping beside it: it moves to the heading's start, where a
736
+ * float rises to the first line (at the end it floats on the last, under a title that fills its
737
+ * first). Wrapped as it renders
738
+ * (`wp-title-end`, see `directive`).
739
+ */
740
+ const endTitles = (node: MdNode) => {
741
+ // a heading, and the label of a container whose label is a title: an item's, a form's
742
+ const title =
743
+ node.type === 'heading'
744
+ ? node
745
+ : node.type === 'containerDirective' && TITLED.has(node.name) && node.children?.[0]?.data?.directiveLabel
746
+ ? node.children[0]
747
+ : null
748
+ if (title?.children?.length) {
749
+ const kids = title.children
750
+ let at = kids.length - 1
751
+ while (at > 0 && kids[at].type === 'text' && !kids[at].value?.trim()) at--
752
+ const end = kids[at]
753
+ if (at > 0 && end.type === 'textDirective' && resolve(end.name)) {
754
+ end.data = { ...end.data, titleEnd: true }
755
+ kids.splice(at, 1)
756
+ kids.unshift(end)
757
+ // the space it ended after goes with it
758
+ const last = kids[kids.length - 1]
759
+ if (last?.type === 'text' && last.value) last.value = last.value.replace(/\s+$/, '')
760
+ }
761
+ }
762
+ node.children?.forEach(endTitles)
763
+ }
764
+ const parse = (src: string) => {
765
+ const tree = parseMarkdown(String(src ?? ''))
766
+ if (message) asText(tree)
767
+ else if (!chat) anchorHeadings(tree)
768
+ if (!message) endTitles(tree)
769
+ rewriteLinks(tree, file, linkFor)
770
+ linkText(tree, textLinks)
771
+ return tree
772
+ }
773
+ const markdown = async (src: string) => toHtml(parse(src).children ?? [])
774
+ const inline = async (src: string) => (await markdown(src)).trim().replace(/^<p>([\s\S]*)<\/p>$/, '$1')
775
+ const fileUrl = (src: string) => addressOf(src, file, linkFor)
776
+ // the ids blocks asked for (BaseContext.anchor), and for a repeat of each, the last number given
777
+ const anchors = new Map<string, number>()
778
+ const anchor = (type: string, name: string, { numbered = false } = {}): string | null => {
779
+ if (!name || message) return null
780
+ // in a chat message, under its chat, as its forms are named: never one of the page's
781
+ if (chat && !name.startsWith(`${chat.name}/`)) name = `${chat.name}/${name}`
782
+ const base = `${type}:${name}`
783
+ if (!anchors.has(base)) {
784
+ anchors.set(base, 0)
785
+ return base
786
+ }
787
+ if (!numbered) return null
788
+ let n = anchors.get(base)!
789
+ let id: string
790
+ do id = `${base}-${++n}`
791
+ while (anchors.has(id))
792
+ anchors.set(base, n)
793
+ anchors.set(id, 0)
794
+ return id
795
+ }
796
+ // in a message, the chat it is in; its unnamed forms take the next number there
797
+ let unnamed = chat?.first ?? 1
798
+ const inChat = chat ? { name: chat.name, next: () => unnamed++ } : null
799
+ const base = {
800
+ page,
801
+ file,
802
+ dir: path.dirname(file),
803
+ parseAttrs,
804
+ toHtml,
805
+ toString,
806
+ markdown,
807
+ inline,
808
+ fileUrl,
809
+ anchor,
810
+ chat: inChat,
811
+ }
812
+
813
+ /**
814
+ * Attributes a block doesn't read (Block.attrs), when it says which it does: a typo, or one from
815
+ * another block (`wide` on a grid). Those every block takes: `compose` and the composers' own names
816
+ * (and `title`, a window's label), `id`, `class`. A block composed is left be: its composers read
817
+ * attributes of their own (`wide`, `height`).
818
+ */
819
+ function unread(block: ResolvedBlock, attrs: Record<string, unknown> | undefined, written: string) {
820
+ // composed (a window around it): the composers read what they read
821
+ if (!block.attrs || (attrs && 'compose' in attrs)) return
822
+ const unknown = Object.keys(attrs ?? {}).filter(
823
+ k => !block.attrs!.includes(k) && !['compose', 'title', 'id', 'class'].includes(k) && !composers?.has(k),
824
+ )
825
+ for (const k of unknown) problem(`\`${written}\` doesn't read \`${k}\`: it does nothing there`)
826
+ }
827
+
828
+ /**
829
+ * Before rendering, what only the whole tree shows: a form's input outside any form (a container
830
+ * inside the form one colon short closes it early: what follows shows, and sends nothing), and the
831
+ * links to an anchor on this page (checked once the page is rendered).
832
+ */
833
+ const links: string[] = []
834
+ function survey(node: MdNode, inForm: boolean) {
835
+ const form = resolve('form')
836
+ for (const child of node.children ?? []) {
837
+ if (child.type === 'link' && typeof child.url === 'string' && child.url.startsWith('#')) links.push(child.url)
838
+ const within = inForm || (child.type === 'containerDirective' && child.name === 'form')
839
+ if (child.type === 'textDirective' && !within && form && child.name !== 'form') {
840
+ const block = resolve(child.name)
841
+ if (block && block.source === form.source)
842
+ problem(
843
+ `\`:${child.name}\` is outside any form: it shows, and sends nothing. A block inside the form needs fewer colons than the form (\`::::form\` around \`:::details\`)`,
844
+ )
845
+ }
846
+ survey(child, within)
847
+ }
848
+ }
849
+
850
+ async function directive(node: MdNode, quoted = false): Promise<MdNode> {
851
+ const { label, children } = splitLabel(node)
852
+ // a message has no directives: no buttons or forms in it, so they show as written; the alerts'
853
+ // block takes quotes, never a directive of its name
854
+ const found = message ? null : resolve(node.name)
855
+ const block = found && !!found.alerts !== quoted ? null : found
856
+ if (!block) {
857
+ // written as a block (a container, a line, or inline with a label or attributes): a block
858
+ // nobody brings. Not `10:30` or `e.g.:x`, which only look like one
859
+ if (node.type === 'containerDirective' && node.name === 'item')
860
+ problem(
861
+ '`:::item` is an item of a grid, tabs or a timeline, directly inside one: it shows its content as it is here. The block around items takes one colon more than they do (`::::grid` around `:::item`)',
862
+ )
863
+ else if (node.type !== 'textDirective' || label || Object.keys(node.attributes ?? {}).length)
864
+ problem(
865
+ `no block \`${MARKER[node.type]}${node.name}\` here: it shows its content as it is. \`workpad docs\` lists the blocks`,
866
+ )
867
+ if (node.type === 'textDirective') return { type: 'text', value: literalDirective(node, label) }
868
+ // an unknown directive still shows its content: a typo never breaks the page
869
+ const labelHtml = label && html`<p class="wp-label"><strong>${raw(await toHtml(label))}</strong></p>`
870
+ return htmlNode(
871
+ html`<div class="wp-unknown" data-directive="${node.name}">${labelHtml}${raw(await toHtml(children))}</div>`,
872
+ )
873
+ }
874
+ unread(block, node.attributes, `${MARKER[node.type]}${node.name}`)
875
+ const labelHtml = label ? await toHtml(label) : null
876
+ let defaults: Promise<Record<string, unknown>> | undefined
877
+ // rendered once: afterwards the children are the items' HTML (itemsOf)
878
+ let split: ReturnType<typeof itemsOf> | undefined
879
+ const itemsOnce = async () => (await (split ??= itemsOf(children))).items
880
+ const ctx = {
881
+ ...base,
882
+ kind: node.type,
883
+ name: node.name,
884
+ attrs: { ...node.attributes },
885
+ label: labelHtml,
886
+ labelText: label ? toString({ type: 'root', children: label } as any) : null,
887
+ children,
888
+ node,
889
+ // what is outside an item is a problem for a block that takes items, not for one whose
890
+ // client gets them only by default (defaults())
891
+ items: async () => {
892
+ const { items, loose } = await (split ??= itemsOf(children))
893
+ if (loose)
894
+ problem(
895
+ `\`:::${node.name}\` takes its items as \`:::item[Title]\` containers (the block one colon more: \`::::${node.name}\`): what is outside one shows as an untitled item, and a heading or a \`---\` starts none`,
896
+ )
897
+ return items
898
+ },
899
+ defaults: () =>
900
+ (defaults ??= (async () => {
901
+ // the items before the content: rendering them makes the children their HTML (itemsOf)
902
+ const list = (await itemsOnce()).map(({ nodes: _, label: _label, ...item }) => item)
903
+ return {
904
+ name: node.name,
905
+ attrs: { ...node.attributes },
906
+ label: labelHtml,
907
+ html: await toHtml(children),
908
+ items: list,
909
+ }
910
+ })()),
911
+ }
912
+ const out = await run(block, ctx, () => toHtml(children))
913
+ // one that ended a heading: at its right (endTitles)
914
+ return htmlNode(node.data?.titleEnd ? html`<span class="wp-title-end">${raw(String(out))}</span>` : out)
915
+ }
916
+
917
+ async function fence(node: MdNode): Promise<MdNode> {
918
+ const lang: string | null = node.lang || null
919
+ const plain = async () => html`<pre><code${lang && html` class="language-${lang}"`}>${node.value}</code></pre>`
920
+ // a fence goes to the block of its language only if that block takes fences: ```text is code,
921
+ // not the text field of the same name
922
+ const named = lang ? resolve(lang) : null
923
+ const block = (named?.fences ? named : null) || code
924
+ if (!block) return htmlNode(await plain())
925
+ const name = code && block === code && lang !== code.name ? code.name : lang
926
+ const attrs = parseAttrs(node.meta)
927
+ if (named?.fences) unread(block, attrs, `\`\`\`${lang}`)
928
+ const ctx = {
929
+ ...base,
930
+ kind: 'fence',
931
+ name,
932
+ lang,
933
+ attrs,
934
+ text: node.value,
935
+ node,
936
+ defaults: async () => ({ name, attrs, text: node.value }),
937
+ }
938
+ return htmlNode(await run(block, ctx, plain))
939
+ }
940
+
941
+ async function transform(parent: MdNode) {
942
+ const kids = parent.children
943
+ if (!kids) return
944
+ for (let i = 0; i < kids.length; i++) {
945
+ const node = kids[i]
946
+ if (DIRECTIVES.has(node.type)) kids[i] = await directive(node)
947
+ else if (node.type === 'code') kids[i] = await fence(node)
948
+ else if (node.type === 'blockquote' && alert && !message && alertOf(node)) kids[i] = await directive(alertOf(node)!(alert), true)
949
+ else await transform(node)
950
+ }
951
+ }
952
+
953
+ const tree = typeof source === 'string' ? parse(source) : source
954
+ const h1 = tree.children?.find(n => n.type === 'heading' && n.depth === 1)
955
+ const title = h1 ? toString(h1 as any) : null
956
+ if (!message && !chat) survey(tree, false)
957
+ await transform(tree)
958
+ const out = stringify(tree.children ?? [])
959
+ // a link to a place on this page that isn't there; a chat message's (#message:) are drawn later
960
+ if (links.length) {
961
+ const ids = new Set(anchorsOf(String(out)).map(a => a.id))
962
+ for (const url of links) {
963
+ let id = url.slice(1)
964
+ try {
965
+ id = decodeURIComponent(id)
966
+ } catch {
967
+ /* as written */
968
+ }
969
+ if (id && !id.startsWith('message:') && !ids.has(id))
970
+ problem(`a link to \`${url}\`, which this page doesn't have: \`workpad anchors\` lists what it has`)
971
+ }
972
+ }
973
+ // blocks of one plugin can share a stylesheet (the form and its fields): linked once
974
+ const styles = [...new Set([...used.values()].map(t => t.style).filter((s): s is string => !!s))]
975
+ return { html: out, title, islands, styles, problems }
976
+ }