@bigmistqke/workpad 0.0.0-stage → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1526 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1202 -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 +2121 -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 +213 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +348 -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 +761 -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 +592 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +134 -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 +166 -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 +240 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +435 -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 +845 -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,845 @@
1
+ // A page on the server: a stored page → the HTML the reader sees. Markdown goes through remark with
2
+ // directives and fences handed to the plugins' blocks (markdown.ts); repository files show as highlighted
3
+ // code, folders as listings with their README on top; around all of it goes the page's frame.
4
+ // What the page draws itself is built with `html` (../html.ts), which escapes every value.
5
+ import { fileFilter } from '../files.ts'
6
+ import { FRONTMATTER } from '../site.ts'
7
+ import fs from 'node:fs'
8
+ import os from 'node:os'
9
+ import path from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { execFile, execFileSync } from 'node:child_process'
12
+ import { promisify } from 'node:util'
13
+ import { renderMarkdown, type Island, type MdNode } from './markdown.ts'
14
+ import { html, raw, type Html } from '../html.ts'
15
+ import { INBOX_ICON, awaitingLabel } from '../icons.ts'
16
+ import type { BlockGroup, Plugin, RenderContext, Rendered, StoredPage, TextLink } from '../define.ts'
17
+ import type { ResolvedBlock, ResolvedBlocks } from './blocks.ts'
18
+ import { ACTIVE_FOR, byProject, byState, total, withoutPages, type Card, type ProjectColumn, type Waiting } from './board.ts'
19
+
20
+ type PagesPage = Extract<StoredPage, { kind: 'pages' }>
21
+ type FolderPage = Extract<StoredPage, { kind: 'folder' }>
22
+ interface Content {
23
+ html: string | Html
24
+ title?: string | null
25
+ islands: Record<string, Island>
26
+ styles: string[]
27
+ problems?: string[]
28
+ }
29
+
30
+ const BASE_CSS = new URL('../client/page/base.css', import.meta.url)
31
+
32
+ // before the stylesheets, so the page never flashes the wrong theme, nor the shared server's
33
+ // overview the wrong columns (client/page/board.ts). A plain string, not part of an
34
+ // `html` template: the bundler writes `</script` in strings as `<\/script`, which in a tagged
35
+ // template would change the raw text the tag gets, so it rewrites the template into a helper call
36
+ const THEME_SCRIPT = raw(
37
+ `<script>try{const t=localStorage.getItem('wp-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t;const b=new URLSearchParams(location.search).get('columns')||localStorage.getItem('wp-board');if(b==='project')document.documentElement.dataset.wpBoard=b}catch{}</script>`,
38
+ )
39
+
40
+ const CODE_LANG: Record<string, string> = {
41
+ js: 'javascript',
42
+ mjs: 'javascript',
43
+ cjs: 'javascript',
44
+ ts: 'typescript',
45
+ tsx: 'tsx',
46
+ jsx: 'jsx',
47
+ json: 'json',
48
+ css: 'css',
49
+ html: 'html',
50
+ sh: 'bash',
51
+ zsh: 'bash',
52
+ py: 'python',
53
+ rs: 'rust',
54
+ go: 'go',
55
+ toml: 'toml',
56
+ yml: 'yaml',
57
+ yaml: 'yaml',
58
+ }
59
+
60
+ /** Frontmatter is the core's; the page starts after it (a page's own is cut off by the site: PageSource.body). */
61
+ const body = (source: string) => source.replace(FRONTMATTER, '')
62
+
63
+ /** A page's title: its first heading, else its name. */
64
+ export function titleOf(file: string, fallback: string) {
65
+ try {
66
+ return headingOf(fs.readFileSync(file, 'utf8')) ?? fallback
67
+ } catch {
68
+ return fallback
69
+ }
70
+ }
71
+
72
+ /** The first heading of a page's markdown, past its frontmatter; null when it has none. */
73
+ function headingOf(source: string): string | null {
74
+ const h1 = /^#\s+(.+)$/m.exec(body(source))
75
+ return h1 ? h1[1].replace(/[*_`]/g, '') : null
76
+ }
77
+
78
+ function crumbs(id: string, name: string, base: string, entry?: RenderContext['entry']) {
79
+ const parts = id ? id.split('/') : []
80
+ // under a shared server, the overview of every project comes first, by its own name
81
+ const above = entry ? html`<a href="/">workpad</a> / ` : ''
82
+ return html`${above}<a href="${base}/">${name}</a
83
+ >${parts.map((p, i) => html` / <a href="${base}/${parts.slice(0, i + 1).join('/')}">${p}</a>`)}`
84
+ }
85
+
86
+ const time = (ts: number) => html`<time data-ts="${ts}"></time>`
87
+
88
+ function pageList(pages: PagesPage['pages'], base: string) {
89
+ return html`<ul class="wp-index">
90
+ ${pages.map(
91
+ p =>
92
+ html`<li>
93
+ <a href="${base}/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${
94
+ p.awaiting > 0 &&
95
+ html` <a
96
+ class="wp-awaiting"
97
+ href="${base}/${p.id}#wp-waiting"
98
+ title="${awaitingLabel(p.awaiting)}"
99
+ aria-label="${awaitingLabel(p.awaiting)}"
100
+ >${raw(INBOX_ICON)}${p.awaiting}</a
101
+ >`
102
+ }
103
+ <span class="wp-meta"
104
+ ><code>${p.id}</code> · edited
105
+ ${time(p.mtime)}${p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}</span
106
+ >
107
+ </li>`,
108
+ )}
109
+ </ul>`
110
+ }
111
+
112
+ /** The folder's README, when it has one. */
113
+ function readmeOf(page: FolderPage) {
114
+ const name = ['README.md', 'readme.md', 'Readme.md'].find(n => page.entries.some(e => !e.dir && e.name === n))
115
+ if (!name) return null
116
+ const file = path.join(page.file, name)
117
+ return { file, source: fs.readFileSync(file, 'utf8') }
118
+ }
119
+
120
+ /** A stylesheet reference (URL, file: URL string, or absolute path) → absolute path. */
121
+ function stylePath(ref: URL | string | undefined) {
122
+ if (ref == null) return null
123
+ const file = ref instanceof URL || String(ref).startsWith('file:') ? fileURLToPath(ref) : String(ref)
124
+ if (!path.isAbsolute(file)) throw new Error(`style: use a URL, e.g. new URL('./style.css', import.meta.url)`)
125
+ if (!fs.existsSync(file)) throw new Error(`style: file not found: ${file}`)
126
+ return file
127
+ }
128
+
129
+ const SKIP = new Set(['node_modules', '.git', '.workpad', 'dist', 'build'])
130
+ const MARKDOWN = /\.(md|markdown)$/i
131
+
132
+ /**
133
+ * Every markdown file in the project, which renders as a page: the top folder's first,
134
+ * then by path. In a git repository, the files git knows (tracked, or new and not ignored), so
135
+ * built copies and dependencies stay out; elsewhere a walk that skips the usual build and
136
+ * dependency folders. The project's own pages (.workpad/) are listed apart.
137
+ */
138
+ function documentsIn(dir: string, shows: (rel: string) => boolean = rel => fileFilter().shows(rel)) {
139
+ let files: string[]
140
+ try {
141
+ files = execFileSync(
142
+ 'git',
143
+ ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'],
144
+ { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
145
+ )
146
+ .split('\n')
147
+ .filter(f => f && !f.startsWith('.workpad/') && fs.existsSync(path.join(dir, f)))
148
+ } catch {
149
+ files = []
150
+ const walk = (rel: string) => {
151
+ let entries: fs.Dirent[] = []
152
+ try {
153
+ entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true })
154
+ } catch {
155
+ return
156
+ }
157
+ for (const e of entries) {
158
+ if (e.isDirectory()) {
159
+ if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(path.posix.join(rel, e.name))
160
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
161
+ }
162
+ }
163
+ walk('')
164
+ }
165
+ const depth = (f: string) => f.split('/').length
166
+ // what the config's `files` leaves out isn't listed (src/files.ts)
167
+ return [...new Set(files)].filter(shows).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
168
+ }
169
+
170
+ /** A document as the overview lists it: its path in the project, its title, when its file last changed. */
171
+ interface Doc {
172
+ file: string
173
+ title: string
174
+ mtime: number
175
+ }
176
+
177
+ function docOf(dir: string, file: string): Doc {
178
+ const abs = path.join(dir, file)
179
+ let mtime = 0
180
+ try {
181
+ mtime = fs.statSync(abs).mtimeMs
182
+ } catch {
183
+ /* gone meanwhile */
184
+ }
185
+ return { file, title: titleOf(abs, path.posix.basename(file)), mtime }
186
+ }
187
+
188
+ /**
189
+ * Whether a project without pages has documents to read, without listing them: a markdown file in
190
+ * its top folder (a README). Cheap, so the overview can ask it of every project on each render;
191
+ * the files themselves are listed only when the reader opens the fold (filesFold).
192
+ */
193
+ export function hasTopDocs(dir: string): boolean {
194
+ try {
195
+ return fs.readdirSync(dir).some(n => MARKDOWN.test(n))
196
+ } catch {
197
+ return false
198
+ }
199
+ }
200
+
201
+ const run = promisify(execFile)
202
+
203
+ /**
204
+ * The files fold of a project without pages, listed when the reader opens it (GET /api/files on the
205
+ * shared server): documentsIn's list, but off the event loop. A checkout holds thousands of
206
+ * markdown files, and listing them on each render froze the shared server for many seconds.
207
+ */
208
+ export async function filesFold(dir: string, base: string): Promise<{ count: number; html: string }> {
209
+ let files: string[]
210
+ try {
211
+ const { stdout } = await run(
212
+ 'git',
213
+ ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'],
214
+ { cwd: dir, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
215
+ )
216
+ files = stdout.split('\n').filter(f => f && !f.startsWith('.workpad/'))
217
+ } catch {
218
+ files = []
219
+ const walk = async (rel: string) => {
220
+ let entries: fs.Dirent[] = []
221
+ try {
222
+ entries = await fs.promises.readdir(path.join(dir, rel), { withFileTypes: true })
223
+ } catch {
224
+ return
225
+ }
226
+ for (const e of entries) {
227
+ if (e.isDirectory()) {
228
+ if (!SKIP.has(e.name) && !e.name.startsWith('.')) await walk(path.posix.join(rel, e.name))
229
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
230
+ }
231
+ }
232
+ await walk('')
233
+ }
234
+ const shows = fileFilter().shows
235
+ const depth = (f: string) => f.split('/').length
236
+ files = [...new Set(files)].filter(f => shows(f)).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
237
+ // a title is in a file's first lines: read only those, a few files at a time
238
+ const docs: Doc[] = []
239
+ for (let i = 0; i < files.length; i += 32) {
240
+ const batch = await Promise.all(
241
+ files.slice(i, i + 32).map(async (file): Promise<Doc | null> => {
242
+ const abs = path.join(dir, file)
243
+ try {
244
+ const handle = await fs.promises.open(abs, 'r')
245
+ try {
246
+ const { mtimeMs } = await handle.stat()
247
+ const buf = Buffer.alloc(8192)
248
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0)
249
+ const name = path.posix.basename(file)
250
+ return { file, title: headingOf(buf.toString('utf8', 0, bytesRead)) ?? name, mtime: mtimeMs }
251
+ } finally {
252
+ await handle.close()
253
+ }
254
+ } catch {
255
+ return null // gone meanwhile (git also lists files deleted and not yet committed)
256
+ }
257
+ }),
258
+ )
259
+ for (const d of batch) if (d) docs.push(d)
260
+ }
261
+ return { count: docs.length, html: String(documentFolders(docs, dir, base, () => null)) }
262
+ }
263
+
264
+ /**
265
+ * The overview's list of the project's documents: each by its title, linked to its rendered page,
266
+ * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
267
+ * written here), by when last updated, or by title; each row carries what it is sorted by.
268
+ */
269
+ function documentList(ctx: RenderContext) {
270
+ return documentsOf(ctx.project.dir, ctx.base ?? '', ctx.urlFor, false, ctx.project.shows)
271
+ }
272
+
273
+ /**
274
+ * A project's documents by the folder they are in, each folder a fold with how many it holds, the
275
+ * top folder's own documents first: the shared server's overview, where a repository's many
276
+ * documents would otherwise be one long list. A folder holding only one folder is shown as one
277
+ * (`docs/adr/`), so the tree is no deeper than what tells folders apart.
278
+ */
279
+ function documentTree(
280
+ docs: Doc[],
281
+ dir: string,
282
+ base: string,
283
+ urlFor: (abs: string) => string | null,
284
+ open = false,
285
+ ) {
286
+ return html`<details class="wp-documents wp-folded-documents"${raw(open ? ' open' : '')}>
287
+ <summary>Files <span class="wp-meta">${docs.length}</span></summary>
288
+ ${documentFolders(docs, dir, base, urlFor)}
289
+ </details>`
290
+ }
291
+
292
+ /** The inside of a project's files fold: its documents by folder, a fold per folder with how many. */
293
+ function documentFolders(docs: Doc[], dir: string, base: string, urlFor: (abs: string) => string | null): Html {
294
+ interface Folder {
295
+ files: string[]
296
+ folders: Map<string, Folder>
297
+ count: number
298
+ }
299
+ const root: Folder = { files: [], folders: new Map(), count: 0 }
300
+ const byFile = new Map(docs.map(d => [d.file, d]))
301
+ for (const { file: f } of docs) {
302
+ let at = root
303
+ at.count++
304
+ const parts = f.split('/')
305
+ for (const part of parts.slice(0, -1)) {
306
+ if (!at.folders.has(part)) at.folders.set(part, { files: [], folders: new Map(), count: 0 })
307
+ at = at.folders.get(part)!
308
+ at.count++
309
+ }
310
+ at.files.push(f)
311
+ }
312
+ const row = (f: string) => {
313
+ const abs = path.join(dir, f)
314
+ const name = path.posix.basename(f)
315
+ const { title, mtime } = byFile.get(f)!
316
+ return html`<li>
317
+ <a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
318
+ <span class="wp-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
319
+ </li>`
320
+ }
321
+ const folder = (name: string, f: Folder): Html => {
322
+ // a folder with only one folder in it is shown as one
323
+ while (!f.files.length && f.folders.size === 1) {
324
+ const [inner, next] = [...f.folders][0]!
325
+ name = `${name}/${inner}`
326
+ f = next
327
+ }
328
+ return html`<details class="wp-folder">
329
+ <summary>${name}/ <span class="wp-meta">${f.count}</span></summary>
330
+ ${contents(f)}
331
+ </details>`
332
+ }
333
+ const contents = (f: Folder): Html =>
334
+ html`${
335
+ f.files.length > 0 &&
336
+ html`<ul class="wp-index">
337
+ ${f.files.map(row)}
338
+ </ul>`
339
+ }${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`
340
+ return contents(root)
341
+ }
342
+
343
+ /**
344
+ * A project's documents, as its overview lists them: from its folder, linked where it serves them.
345
+ * `folded`: in a fold that says how many (the shared server's overview, where each project has them).
346
+ */
347
+ function documentsOf(
348
+ dir: string,
349
+ base: string,
350
+ urlFor: (abs: string) => string | null,
351
+ folded = false,
352
+ shows?: (rel: string) => boolean,
353
+ open = false,
354
+ ) {
355
+ const docs = documentsIn(dir, shows).map(f => docOf(dir, f))
356
+ if (!docs.length) return ''
357
+ if (folded) return documentTree(docs, dir, base, urlFor, open)
358
+ const ctx = { project: { dir }, base, urlFor }
359
+ const rows = docs.map(({ file: f, title, mtime }, i) => {
360
+ const abs = path.join(ctx.project.dir, f)
361
+ // a file without a heading goes by its name, and the line under it says the folder it is in
362
+ const name = path.posix.basename(f)
363
+ const where = title === name ? path.posix.dirname(f) : f
364
+ return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
365
+ <a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ''}/-/${f}`}">${title}</a>
366
+ <span class="wp-meta"
367
+ >${where !== '.' && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span
368
+ >
369
+ </li>`
370
+ })
371
+ // in a section, so the heading isn't numbered like the page's own sections
372
+ return html`<section class="wp-documents">
373
+ <div class="wp-list-head">
374
+ <h2>Documents</h2>
375
+ <label class="wp-sort"
376
+ >sort
377
+ <select data-wp-sort="documents" aria-label="Sort the documents">
378
+ <option value="order">by folder</option>
379
+ <option value="updated">last updated</option>
380
+ <option value="title">by title</option>
381
+ </select></label
382
+ >
383
+ </div>
384
+ <ul class="wp-index">
385
+ ${rows}
386
+ </ul>
387
+ </section>`
388
+ }
389
+
390
+ type BoardProject = NonNullable<PagesPage['projects']>[number]
391
+
392
+ /** What waits on a page or a project, as small badges; nothing when nothing waits. */
393
+ function counts(w: Waiting, href: string | null) {
394
+ const badge = (kind: string, n: number, text: string, title: string) =>
395
+ n > 0 &&
396
+ (href
397
+ ? html`<a class="wp-count wp-count-${kind}" href="${href}" title="${title}">${n} ${text}</a>`
398
+ : html`<span class="wp-count wp-count-${kind}" title="${title}">${n} ${text}</span>`)
399
+ if (!total(w)) return ''
400
+ return html`<span class="wp-counts"
401
+ >${badge('open', w.open, 'open', w.open === 1 ? '1 question waiting for you' : `${w.open} questions waiting for you`)}${badge(
402
+ 'unread',
403
+ w.unread,
404
+ 'unread',
405
+ w.unread === 1 ? '1 message you haven’t read' : `${w.unread} messages you haven’t read`,
406
+ )}${badge(
407
+ 'unreceived',
408
+ w.unreceived,
409
+ 'not received',
410
+ w.unreceived === 1 ? '1 answer no agent received' : `${w.unreceived} answers no agent received`,
411
+ )}</span
412
+ >`
413
+ }
414
+
415
+ /** A page on the board: its title, what waits on it, and (in a column of states) its project. */
416
+ function card(c: Card<BoardProject>, withProject: boolean) {
417
+ return html`<li class="wp-board-card${total(c.waiting) > 0 ? ' wp-board-waits' : ''}">
418
+ <a class="wp-board-title" href="${c.page.url}">${c.page.title}</a>
419
+ ${counts(c.waiting, `${c.page.url}#wp-waiting`)}
420
+ ${withProject && html`<span class="wp-board-project">${c.project.label}</span>`}
421
+ <span class="wp-meta wp-board-when">edited ${time(c.page.mtime)}</span>
422
+ </li>`
423
+ }
424
+
425
+ function cards(list: Card<BoardProject>[], withProject: boolean) {
426
+ return list.length
427
+ ? html`<ul class="wp-board-cards">
428
+ ${list.map(c => card(c, withProject))}
429
+ </ul>`
430
+ : html`<p class="wp-meta wp-board-none">Nothing here.</p>`
431
+ }
432
+
433
+ const pagesCount = (n: number) => (n === 1 ? '1 page' : `${n} pages`)
434
+
435
+ /** The projects without pages, folded into one column at the end. */
436
+ function emptyColumn(projects: BoardProject[]) {
437
+ if (!projects.length) return ''
438
+ return html`<details class="wp-board-column wp-board-empty">
439
+ <summary>${projects.length} without pages</summary>
440
+ <ul>
441
+ ${projects.map(p => html`<li><a href="${p.base}/" title="${p.error ?? p.dir}">${p.label}</a></li>`)}
442
+ </ul>
443
+ </details>`
444
+ }
445
+
446
+ /**
447
+ * The shared server's overview: its projects' pages as columns you scroll sideways, a column per
448
+ * state (what waits for you, what changed lately, the rest) or a column per project; the reader
449
+ * switches between them (board.ts in the page), both are here. Projects without pages are folded
450
+ * at the end of either.
451
+ */
452
+ function board(projects: BoardProject[], now: number) {
453
+ const states = byState(projects, now)
454
+ // of the projects without pages, those with documents to read get a column of their own in the
455
+ // per-project view (a worktree's README and docs), and only the truly empty fold at the end. Which
456
+ // is which is a look at the top folder: listing a checkout's files (thousands, in a big repository)
457
+ // waits until the reader opens its fold (filesFold), so a render reads no project's files
458
+ const empty = withoutPages(projects)
459
+ const withDocs = empty.filter(p => p.files && hasTopDocs(p.dir))
460
+ const bare = empty.filter(p => !withDocs.includes(p))
461
+ const hours = ACTIVE_FOR / 3_600_000
462
+ const stateColumn = (key: keyof typeof states, title: string, note: string) =>
463
+ html`<section class="wp-board-column wp-board-${key}${key === 'waiting' && states.waiting.length ? ' wp-board-waits' : ''}">
464
+ <header class="wp-board-head">
465
+ <h2>${title}</h2>
466
+ <span class="wp-meta">${pagesCount(states[key].length)}${note && ` · ${note}`}</span>
467
+ </header>
468
+ ${cards(states[key], true)}
469
+ </section>`
470
+ const projectColumn = (col: ProjectColumn<BoardProject>) => {
471
+ const p = col.project
472
+ return html`<section class="wp-board-column${total(col.waiting) > 0 ? ' wp-board-waits' : ''}">
473
+ <header class="wp-board-head" title="${p.dir.replace(os.homedir(), '~')}">
474
+ <h2>${p.label}</h2>
475
+ <span class="wp-meta">edited ${time(p.active)} · ${pagesCount(col.cards.length)}</span>
476
+ ${counts(col.waiting, null)}
477
+ </header>
478
+ ${cards(col.cards, false)} ${p.files && documentsOf(p.dir, p.base, () => null, true)}
479
+ </section>`
480
+ }
481
+ // a project with documents and no pages: its column holds its files, listed when the fold opens
482
+ // (board.ts in the page asks /api/files for them)
483
+ const docsColumn = (p: BoardProject) =>
484
+ html`<section class="wp-board-column wp-board-docs">
485
+ <header class="wp-board-head" title="${p.dir.replace(os.homedir(), '~')}">
486
+ <h2><a href="${p.base}/">${p.label}</a></h2>
487
+ <span class="wp-meta">no pages</span>
488
+ </header>
489
+ <details class="wp-documents wp-folded-documents" data-wp-files="${p.base}">
490
+ <summary>Files <span class="wp-meta"></span></summary>
491
+ </details>
492
+ </section>`
493
+ return html`<div class="wp-board-bar">
494
+ <div class="wp-board-switch" role="group" aria-label="Columns">
495
+ <button type="button" data-wp-board="state">By state</button
496
+ ><button type="button" data-wp-board="project">By project</button>
497
+ </div>
498
+ <input
499
+ type="search"
500
+ class="wp-board-search"
501
+ placeholder="Search pages, projects, files /"
502
+ aria-label="Search the overview"
503
+ autocomplete="off"
504
+ spellcheck="false"
505
+ />
506
+ </div>
507
+ <p class="wp-board-nomatch" hidden>Nothing here matches.</p>
508
+ <div class="wp-board" data-board="state">
509
+ ${stateColumn('waiting', 'Waiting for you', '')}
510
+ ${stateColumn('active', 'Active', `changed in the last ${hours} hours`)}
511
+ ${stateColumn('quiet', 'Quiet', '')} ${emptyColumn(empty)}
512
+ </div>
513
+ <div class="wp-board" data-board="project">
514
+ ${byProject(projects).map(projectColumn)} ${withDocs.map(docsColumn)} ${emptyColumn(bare)}
515
+ </div>`
516
+ }
517
+
518
+ /** The plugins' text links for a project folder, asked once per folder. */
519
+ function textLinksOf(links: ((ctx: { dir: string }) => TextLink[])[]) {
520
+ const linksFor = new Map<string, TextLink[]>()
521
+ return (dir: string) => {
522
+ let got = linksFor.get(dir)
523
+ if (!got) {
524
+ got = links.flatMap(fn => {
525
+ try {
526
+ return fn({ dir })
527
+ } catch (err) {
528
+ console.error('links:', err)
529
+ return []
530
+ }
531
+ })
532
+ linksFor.set(dir, got)
533
+ }
534
+ return got
535
+ }
536
+ }
537
+
538
+ /**
539
+ * A message (a comment, a chat message) as HTML: markdown as on a page, but its raw HTML as text and
540
+ * its directives as written. Code fences go to the code block, so `styles` are what it needs linked.
541
+ */
542
+ /**
543
+ * An agent's chat message as a small page (Pages.agentMessage): every block, as on the page, in the
544
+ * chat it is in (RenderOptions.chat).
545
+ */
546
+ /** Islands as the browser loads them: each client module at the address the server serves it from. */
547
+ const served = (islands: Record<string, Island>, ctx: RenderContext) =>
548
+ Object.fromEntries(Object.entries(islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]))
549
+
550
+ export function createAgentMessageRender(
551
+ blocks: () => ResolvedBlocks,
552
+ links: ((ctx: { dir: string }) => TextLink[])[] = [],
553
+ composers: Map<string, NonNullable<Plugin['compose']>> = new Map(),
554
+ ) {
555
+ const textLinks = textLinksOf(links)
556
+ return async (
557
+ text: string,
558
+ ctx: RenderContext,
559
+ where: { page: string; file: string; chat: string; first: number; prefix: string },
560
+ ) => {
561
+ const { blocks: set, code, alert } = blocks()
562
+ const out = await renderMarkdown(String(text ?? ''), {
563
+ page: where.page,
564
+ file: where.file,
565
+ resolve: name => set.get(name) ?? null,
566
+ code,
567
+ alert: alert?.name ?? null,
568
+ linkFor: ctx.urlFor,
569
+ textLinks: textLinks(ctx.project.dir),
570
+ composers,
571
+ chat: { name: where.chat, first: where.first, prefix: where.prefix },
572
+ })
573
+ return { html: String(out.html), islands: served(out.islands, ctx), styles: out.styles.map(s => ctx.asset(s)) }
574
+ }
575
+ }
576
+
577
+ /**
578
+ * Markdown a plugin's client asks for (Api.blocks): every block, as on the page `where.page`, files
579
+ * resolved from it, its islands' ids starting with `where.prefix`.
580
+ */
581
+ export function createBlocksRender(
582
+ blocks: () => ResolvedBlocks,
583
+ links: ((ctx: { dir: string }) => TextLink[])[] = [],
584
+ composers: Map<string, NonNullable<Plugin['compose']>> = new Map(),
585
+ ) {
586
+ const textLinks = textLinksOf(links)
587
+ return async (text: string, ctx: RenderContext, where: { page: string; file: string; prefix: string }) => {
588
+ const { blocks: set, code, alert } = blocks()
589
+ const out = await renderMarkdown(String(text ?? ''), {
590
+ page: where.page,
591
+ file: where.file,
592
+ resolve: name => set.get(name) ?? null,
593
+ code,
594
+ alert: alert?.name ?? null,
595
+ linkFor: ctx.urlFor,
596
+ textLinks: textLinks(ctx.project.dir),
597
+ composers,
598
+ prefix: where.prefix,
599
+ })
600
+ return { html: String(out.html), islands: served(out.islands, ctx), styles: out.styles.map(s => ctx.asset(s)) }
601
+ }
602
+ }
603
+
604
+ export function createMessageRender(
605
+ blocks: () => ResolvedBlocks,
606
+ links: ((ctx: { dir: string }) => TextLink[])[] = [],
607
+ ) {
608
+ const textLinks = textLinksOf(links)
609
+ return async (text: string, ctx: RenderContext) => {
610
+ const out = await renderMarkdown(String(text ?? ''), {
611
+ page: '',
612
+ file: '',
613
+ // the blocks that take fences (a ```mermaid diagram), as on a page, the way a forge's comments
614
+ // draw them; directives stay as written (see message)
615
+ resolve: name => {
616
+ const block = blocks().blocks.get(name) ?? null
617
+ return block?.fences ? block : null
618
+ },
619
+ code: blocks().code,
620
+ textLinks: textLinks(ctx.project.dir),
621
+ message: true,
622
+ })
623
+ return { html: out.html, styles: out.styles.map(s => ctx.asset(s)) }
624
+ }
625
+ }
626
+
627
+ /** What a block left out of a build (RenderContext.skip) is: nothing, for its directives and fences alike. */
628
+ const skipped = (name: string): ResolvedBlock => ({
629
+ name,
630
+ code: false,
631
+ fences: true,
632
+ alerts: false,
633
+ attrs: null,
634
+ menu: null,
635
+ props: null,
636
+ html: () => '',
637
+ open: null,
638
+ client: null,
639
+ style: null,
640
+ source: 'build',
641
+ })
642
+
643
+ export function createRender(
644
+ blocks: () => ResolvedBlocks,
645
+ style?: URL | string,
646
+ pluginStyles: { plugin: string; file: URL | string }[] = [],
647
+ links: ((ctx: { dir: string }) => TextLink[])[] = [],
648
+ composers: Map<string, NonNullable<Plugin['compose']>> = new Map(),
649
+ ) {
650
+ const textLinks = textLinksOf(links)
651
+ const STYLE = stylePath(style)
652
+ const PLUGIN_STYLES = pluginStyles
653
+ .map(s => ({ plugin: s.plugin, file: stylePath(s.file) }))
654
+ .filter((s): s is { plugin: string; file: string } => !!s.file)
655
+ /** `content`: the markdown without its frontmatter. */
656
+ async function markdown(content: string, page: string, file: string, ctx: RenderContext) {
657
+ const { blocks: set, code, alert } = blocks()
658
+ const skip = ctx.skip
659
+ return renderMarkdown(content, {
660
+ page,
661
+ file,
662
+ resolve: name => {
663
+ const block = set.get(name) ?? null
664
+ if (skip && (skip.has(name) || (block && skip.has(block.source))))
665
+ return { ...skipped(name), alerts: block?.alerts ?? false }
666
+ return block
667
+ },
668
+ code,
669
+ alert: alert?.name ?? null,
670
+ linkFor: ctx.urlFor,
671
+ textLinks: textLinks(ctx.project.dir),
672
+ // a build leaves out a skipped plugin's composing too: the block as it is
673
+ composers: skip
674
+ ? new Map(
675
+ [...composers].map(([name, compose]) =>
676
+ skip.has(name) ? [name, ({ children }: { children: unknown }) => String(children)] : [name, compose],
677
+ ),
678
+ )
679
+ : composers,
680
+ })
681
+ }
682
+
683
+ async function content(page: StoredPage, ctx: RenderContext): Promise<Content> {
684
+ const { project } = ctx
685
+ switch (page.kind) {
686
+ case 'page':
687
+ return markdown(page.body, page.id, page.file, ctx)
688
+ case 'pages': {
689
+ // the shared server's overview: every project's pages as columns side by side
690
+ if (page.projects) {
691
+ const view = html`<h1>${project.name}</h1>
692
+ ${board(page.projects, Date.now())} ${page.note && html`<p class="wp-meta">${page.note}</p>`}`
693
+ return { html: view, title: project.name, islands: {}, styles: [] }
694
+ }
695
+ const list = page.pages.length
696
+ ? pageList(page.pages, ctx.base ?? '')
697
+ : html`<p class="wp-meta">No pages yet.</p>`
698
+ const view = page.id
699
+ ? html`<h1>${page.id}</h1>
700
+ ${list}
701
+ <p class="wp-meta">${page.file}</p>`
702
+ : html`<h1>${project.name}</h1>
703
+ ${list}${project.files && documentList(ctx)}
704
+ <p class="wp-meta">
705
+ <code>${project.dir}</code>${project.files && html` · <a href="${ctx.base ?? ''}/-/">files</a>`} ·
706
+ <a href="${ctx.base ?? ''}/_/docs">how to write pages</a>
707
+ </p>`
708
+ return { html: view, title: page.id || project.name, islands: {}, styles: [] }
709
+ }
710
+ case 'folder': {
711
+ const rel = page.id.slice(2)
712
+ const rows = page.entries.map(
713
+ e =>
714
+ html`<li>
715
+ <a href="${encodeURIComponent(e.name) + (e.dir ? '/' : '')}">${e.name + (e.dir ? '/' : '')}</a>
716
+ </li>`,
717
+ )
718
+ const listing = html`<h1>${rel || project.name}</h1>
719
+ <ul class="wp-files">
720
+ ${rel && html`<li><a href="../">../</a></li>`}${rows}
721
+ </ul>
722
+ <p class="wp-meta">${page.file} · <code>${page.id}</code></p>`
723
+ const readme = readmeOf(page)
724
+ if (!readme) return { html: listing, title: rel || project.name, islands: {}, styles: [] }
725
+ // markdown's output is HTML already
726
+ const r = await markdown(body(readme.source), page.id, readme.file, ctx)
727
+ return {
728
+ ...r,
729
+ html: html`${raw(r.html)}
730
+ <hr />
731
+ ${listing}`,
732
+ }
733
+ }
734
+ case 'file': {
735
+ // the file as one code block, rendered by the code block (or as plain code)
736
+ const { code } = blocks()
737
+ const ext = path.extname(page.file).slice(1).toLowerCase()
738
+ const tree: MdNode = {
739
+ type: 'root',
740
+ children: [{ type: 'code', lang: CODE_LANG[ext] ?? (ext || null), meta: null, value: page.source }],
741
+ }
742
+ const out = await renderMarkdown(tree, {
743
+ page: page.id,
744
+ file: page.file,
745
+ resolve: () => null,
746
+ code,
747
+ linkFor: ctx.urlFor,
748
+ })
749
+ const view = html`<h1 class="wp-code-title wp-wide">${page.id.slice(2)}</h1>
750
+ <div class="wp-code wp-wide">${raw(out.html)}</div>`
751
+ return { html: view, title: path.basename(page.file), islands: out.islands, styles: out.styles }
752
+ }
753
+ }
754
+ }
755
+
756
+ return async function render(page: StoredPage, ctx: RenderContext): Promise<Rendered> {
757
+ let out: Content
758
+ try {
759
+ out = await content(page, ctx)
760
+ } catch (err) {
761
+ // blocks that do not resolve (a bad block in a plugin)
762
+ out = { html: html`<pre class="wp-error">${(err as Error).message}</pre>`, islands: {}, styles: [] }
763
+ }
764
+ const islands = Object.fromEntries(
765
+ Object.entries(out.islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]),
766
+ )
767
+ const styles = out.styles.map(s => ctx.asset(s))
768
+ // a built page: the project's name and the theme; nothing of the server's (crumbs into its
769
+ // folders, when it was updated, whether it is live)
770
+ const nav =
771
+ ctx.live === false
772
+ ? html`<nav class="wp-nav">
773
+ <span>${ctx.project.name}</span><span data-wp-slot="header"></span
774
+ ><button
775
+ type="button"
776
+ class="wp-theme"
777
+ title="Theme: follow the system, light or dark"
778
+ aria-label="Theme"
779
+ ></button>
780
+ </nav>`
781
+ : html`<nav class="wp-nav">
782
+ <span>${crumbs(page.id, ctx.entry?.label || ctx.project.name, ctx.base ?? '', ctx.entry)}</span
783
+ >${page.mtime != null && html`<span class="wp-meta">updated <time id="wp-updated" data-ts="${page.mtime}"></time></span>`}<span
784
+ data-wp-slot="header"
785
+ ></span
786
+ ><button
787
+ type="button"
788
+ class="wp-theme"
789
+ title="Theme: follow the system, light or dark"
790
+ aria-label="Theme"
791
+ ></button
792
+ ><span class="wp-live" role="img" title="Connecting…" aria-label="Connecting…"></span>
793
+ </nav>`
794
+ // the page's own, the plugins' (every page), the blocks' on this page, then the project's
795
+ const links = [
796
+ ctx.asset(BASE_CSS),
797
+ ...PLUGIN_STYLES.filter(s => !ctx.skip?.has(s.plugin)).map(s => ctx.asset(s.file)),
798
+ ...styles,
799
+ ...(STYLE ? [ctx.asset(STYLE)] : []),
800
+ ]
801
+ return {
802
+ title: out.title || page.id || ctx.project.name,
803
+ head: html`${THEME_SCRIPT} ${links.map(href => html`<link rel="stylesheet" href="${href}" />`)}`,
804
+ // the page's content is HTML already: markdown's output, or what was built above
805
+ // the reading area: the content, and what the browser lists after it (chats and comments no
806
+ // longer on the page), which go in it as the content's siblings
807
+ html: html`${nav}
808
+ <div class="wp-body"><main id="wp-main">${raw(out.html)}</main></div>`,
809
+ // the client mounts `islands` and links `styles`
810
+ data: { islands, styles, mtime: page.mtime },
811
+ problems: out.problems ?? [],
812
+ }
813
+ }
814
+ }
815
+
816
+ /** The menu's groups, in order: what an agent writing a page is trying to do. */
817
+ const GROUPS: [BlockGroup, string][] = [
818
+ ['ask', 'Ask: get something back from the reader'],
819
+ ['show', 'Show: put something in front of the reader'],
820
+ ['arrange', 'Arrange: several things, or one out of the way'],
821
+ ['mark', 'Mark: how something stands, or how much it counts'],
822
+ ]
823
+
824
+ /**
825
+ * What `workpad docs` prints first: how pages are written, then the menu: a line per block that
826
+ * has one (Block.menu), under what it is for. How to write each is in its plugin's docs.
827
+ */
828
+ export function createDocs(blocks: () => ResolvedBlocks) {
829
+ return function docs(_ctx: RenderContext) {
830
+ const all = [...blocks().blocks.values()].filter(t => t.menu)
831
+ const width = Math.max(0, ...all.map(t => t.name.length)) + 3
832
+ const groups = GROUPS.map(([group, title]) => {
833
+ const lines = all.filter(t => t.menu!.group === group).map(t => ` ${t.name.padEnd(width)}${t.menu!.summary}`)
834
+ return lines.length ? `${title}\n${lines.join('\n')}` : ''
835
+ }).filter(Boolean)
836
+ return `# Pages
837
+
838
+ A page is markdown: GFM tables, \`<details>\`, raw HTML and a hand-written \`<form name="…">\` work as they are. Blocks: \`:::name\` around content, \`::name\` on a line, \`:name\` inside a line, and code fences (\`\`\`\` \`\`\`name \`\`\`\`). What the reader answers comes back as events: through your session's channel once \`workpad agent ping\` confirmed it (once a session), else with \`workpad listen\`. A block nobody brings renders its content, so a typo never breaks a page.
839
+
840
+ \`\`\`\`text
841
+ ${groups.join('\n\n')}
842
+ \`\`\`\`
843
+ `
844
+ }
845
+ }