@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
package/src/server.ts ADDED
@@ -0,0 +1,1385 @@
1
+ // The server of one project, as a request handler: `createServer(project)` gives one, and
2
+ // `start` in serve.ts makes it listen on a port. Nothing happens on import, and a server's state
3
+ // (listeners, open pages, watchers) lives in it, so tests can make one for a throwaway project and
4
+ // send it requests.
5
+ //
6
+ // / the overview: the project's pages
7
+ // /<page> a page from .workpad/pages/<page>.md
8
+ // /-/<path> a file of the project, from the repository (unless the config sets files: false)
9
+ // /_/docs how to write pages here: markdown, and each plugin's docs
10
+ // /_/file/<path> a file a plugin asked to serve (its client, a stylesheet)
11
+ // /_/auth sets the project's token as a cookie (see auth.ts)
12
+ // /api/<ext>/… a plugin's own routes (see Plugin in define.ts)
13
+ // /api/… the stored page, its render, events, live changes; and the API onto the
14
+ // project's state (state.ts, the README's API section): its pages, forms, chats,
15
+ // agents, a stream of its events, and what an agent writes (a page, a form's state)
16
+ //
17
+ // The core reads pages as they are stored and renders them as markdown, with the blocks the project's
18
+ // plugins bring (pages.ts). When the config fails to load, a page shows as its raw
19
+ // text.
20
+ import type { IncomingMessage, ServerResponse } from 'node:http'
21
+ import type { Duplex } from 'node:stream'
22
+ import fs from 'node:fs'
23
+ import crypto from 'node:crypto'
24
+ import { stripTypeScriptTypes } from 'node:module'
25
+ import path from 'node:path'
26
+ import type { Project } from './config.ts'
27
+ import {
28
+ appendEvent,
29
+ isEventId,
30
+ readEvents,
31
+ read as readLog,
32
+ follow,
33
+ handle as handleEvent,
34
+ matches,
35
+ receivedIds,
36
+ handledIds,
37
+ forAgent,
38
+ namesOf,
39
+ subscriptions,
40
+ SUBSCRIBE,
41
+ } from './events.ts'
42
+ import {
43
+ after,
44
+ agentsOf,
45
+ chatsOf,
46
+ formsOf,
47
+ live,
48
+ matchesQuery,
49
+ pageUrl,
50
+ pagesOf,
51
+ subscriptionsOf,
52
+ type EventQuery,
53
+ type LiveEvent,
54
+ type ProjectInfo,
55
+ type StateSource,
56
+ } from './state.ts'
57
+ import { FormStateError, holdForms, releaseForms, settleForms } from './formstate.ts'
58
+ import { anchorsOf } from './anchors.ts'
59
+ import type { FormDetail } from './pages/markdown.ts'
60
+ import { html, raw } from './html.ts'
61
+ import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
62
+ import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage } from './plugins.ts'
63
+ import { createAuth, sameSite } from './auth.ts'
64
+ import { accept, refuse } from './ws.ts'
65
+ import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
66
+ import { SCROLL, agentMessagesIn, awaiting, isAgentMessage, projectStatus, type ProjectStatus } from './status.ts'
67
+ import { formsIn, messageForms } from './pages/markdown.ts'
68
+ import { fileFilter, type FileFilter } from './files.ts'
69
+ import { titleOf } from './pages/render.ts'
70
+ import { createRegistry, holdStream, listenerOf } from './listeners.ts'
71
+ import { inPublic } from './public.ts'
72
+ import { build, type BuildResult } from './build.ts'
73
+ import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts, type Render, type SetUp } from './document.ts'
74
+ import { inside, isRepoId, pageSource, servedSite, within } from './site.ts'
75
+ import type {
76
+ Listener,
77
+ PageSource,
78
+ PageStatus,
79
+ Rendered,
80
+ StoredPage,
81
+ PagesSource,
82
+ BuildConfig,
83
+ WpEvent,
84
+ } from './define.ts'
85
+
86
+ const ENGINE_DIR = PACKAGE_DIR
87
+ const MIME: Record<string, string> = {
88
+ '.css': 'text/css',
89
+ '.js': 'text/javascript',
90
+ '.mjs': 'text/javascript',
91
+ '.json': 'application/json',
92
+ '.png': 'image/png',
93
+ '.jpg': 'image/jpeg',
94
+ '.jpeg': 'image/jpeg',
95
+ '.gif': 'image/gif',
96
+ '.webp': 'image/webp',
97
+ '.avif': 'image/avif',
98
+ '.svg': 'image/svg+xml',
99
+ '.pdf': 'application/pdf',
100
+ '.mp4': 'video/mp4',
101
+ '.webm': 'video/webm',
102
+ '.woff': 'font/woff',
103
+ '.woff2': 'font/woff2',
104
+ '.txt': 'text/plain; charset=utf-8',
105
+ '.md': 'text/markdown; charset=utf-8',
106
+ '.csv': 'text/csv; charset=utf-8',
107
+ '.html': 'text/html; charset=utf-8',
108
+ }
109
+ // files in .workpad/ that are the server's own bookkeeping, not content
110
+ const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
111
+
112
+ export type { BuildResult }
113
+
114
+ /** A project's server: its request handler, and what it knows. */
115
+ export interface WorkpadServer {
116
+ /** answer one request */
117
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>
118
+ /** answer one upgrade request (the HTTP server's 'upgrade' event): the page's live channel */
119
+ upgrade(req: IncomingMessage, conn: Duplex, head: Buffer): void
120
+ /** what is open on each page (or on `page` and below), as /api/status gives it */
121
+ status(page?: string | null): Promise<PageStatus[]>
122
+ /**
123
+ * A list the API answers with (state.ts), as GET /api/<what> gives it: `projects`, `pages`,
124
+ * `forms`, `chats`, `subscriptions` or `agents`, filtered by the query. The shared server asks
125
+ * each project for its own and puts them together.
126
+ */
127
+ read(what: ApiList, query: Record<string, string>): Promise<unknown[]>
128
+ /**
129
+ * Follow the log, as GET /api/stream does: each new event that matches `query` to `send`, with
130
+ * those after `query.since` first when it is given. Returns what stops it.
131
+ */
132
+ stream(query: EventQuery, send: (event: LiveEvent) => void): () => void
133
+ /** the project's config, loaded */
134
+ config(): Promise<LoadedConfig>
135
+ /** a static site of some pages (`workpad build`); options over the config's `build` */
136
+ build(options?: BuildConfig): Promise<BuildResult>
137
+ /**
138
+ * Hold a listener that is not a connection to this server: the shared server's listen over a
139
+ * whole entry, which covers every page of each of its projects. Pages are told, as for any
140
+ * listener. @returns what removes it
141
+ */
142
+ addListener(l: Listener): () => void
143
+ /** call `fn` whenever a listener comes or goes; returns what stops it */
144
+ onListeners(fn: () => void): () => void
145
+ /** who listens now: the running listens and channels, and an entry's listens held for it */
146
+ listeners(): Listener[]
147
+ /** whether it serves its files (its config read first) */
148
+ files(): Promise<boolean>
149
+ /** tell the open overviews (`/`) that what they list changed */
150
+ touch(): void
151
+ /** tell the open pages that what waits in another project of the shared server changed */
152
+ elsewhere(): void
153
+ /** stop watching and end the live connections; the server answers nothing after */
154
+ close(): void
155
+ }
156
+
157
+ /** The lists the API answers with, by the path they are at: GET /api/<what>. */
158
+ export const API_LISTS = ['projects', 'pages', 'forms', 'chats', 'subscriptions', 'agents'] as const
159
+ export type ApiList = (typeof API_LISTS)[number]
160
+
161
+ /** How a server is mounted: on a port of its own (the default), or under a path of a shared server. */
162
+ export interface ServerOptions {
163
+ /** the path every URL it makes starts with, without a trailing slash: '' (its own port) or `/rg/develop` */
164
+ base?: string
165
+ /** the entry of a shared server the project is in */
166
+ entry?: string
167
+ /** how the project is known in its entry: `worktrees › cmux` (default: its name) */
168
+ label?: string
169
+ /** what the project is called, over its folder's or config's name (the shared server's own: workpad) */
170
+ name?: string
171
+ /** serve and watch the project's files, over the config's `files` */
172
+ files?: boolean
173
+ /** serve and watch the project's files when its config doesn't say (its entry's `files`); default true */
174
+ filesDefault?: boolean
175
+ /** the overview at / lists these instead of the project's pages (the shared server's own project) */
176
+ overview?: () => Promise<Pick<PagesSource, 'projects' | 'note'>>
177
+ /** a page of the project changed, or its log grew: the shared server's overview follows it */
178
+ onChange?: () => void
179
+ /** the origins besides localhost its pages may be at (the machine config's `origins`), asked each time */
180
+ origins?: () => readonly string[]
181
+ }
182
+
183
+ export function createServer(
184
+ project: Project,
185
+ {
186
+ base = '',
187
+ entry,
188
+ label,
189
+ name,
190
+ files: filesOption,
191
+ filesDefault,
192
+ overview,
193
+ onChange,
194
+ origins = () => [],
195
+ }: ServerOptions = {},
196
+ ): WorkpadServer {
197
+ const projectName = () => name ?? project.name
198
+ const loader = createConfigLoader(project, { files: filesDefault })
199
+ const auth = createAuth(project.wp, base, origins)
200
+ // what close() stops: watchers, and the live connections' pings and responses
201
+ const watchers = new Set<fs.FSWatcher>()
202
+ const streams = new Set<() => void>()
203
+ const watch = (dir: string, options: fs.WatchOptions, fn: (name: string) => void) => {
204
+ try {
205
+ watchers.add(
206
+ fs.watch(dir, options, (_evt, name) => {
207
+ if (name) fn(String(name))
208
+ }),
209
+ )
210
+ } catch {
211
+ /* gone, or not built */
212
+ }
213
+ }
214
+
215
+ // ---- plugins --------------------------------------------------------------------------------
216
+ // Behaviour on every page: each one's setup runs once per loaded config.
217
+
218
+ const setups = new WeakMap<LoadedConfig, Promise<SetUp[]>>()
219
+ // the plugins' own folders in .workpad/: changes in them reload nothing
220
+ const pluginDirs = new Set<string>()
221
+
222
+ /** The hooks of the loaded config's plugins, set up once per config. */
223
+ async function pluginHooks(): Promise<SetUp[]> {
224
+ const c = await config()
225
+ if (!setups.has(c)) {
226
+ setups.set(
227
+ c,
228
+ Promise.all(
229
+ c.plugins.map(async (e): Promise<SetUp> => {
230
+ try {
231
+ pluginDirs.add(e.name)
232
+ const dataDir = pluginDir(project.wp, e.name)
233
+ // what it serves is in its public folder: its client, named in its hooks
234
+ const dir = c.publicDirs.get(e.name)!
235
+ const hooks =
236
+ (await e.setup?.({
237
+ project: { name: project.name, dir: project.dir, wp: project.wp },
238
+ dataDir,
239
+ authorized: auth.authorized,
240
+ })) ?? {}
241
+ const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : undefined
242
+ return { name: e.name, ...hooks, client, table: mountRoutes(e.name, hooks.routes), plugin: e }
243
+ } catch (err) {
244
+ console.error(`plugin ${e.name}:`, err)
245
+ return { name: e.name, table: [], plugin: e, error: err as Error }
246
+ }
247
+ }),
248
+ ),
249
+ )
250
+ }
251
+ return setups.get(c)!
252
+ }
253
+
254
+ /** A page as the server serves it: the render with what the plugins add, their failures among its notices. */
255
+ async function page(req: IncomingMessage, stored: StoredPage, rendered: Render): Promise<string> {
256
+ const notices = [...rendered.notices]
257
+ const parts = await pluginParts(await pluginHooks(), req, {
258
+ asset,
259
+ messages: [...(await config()).forReader],
260
+ failed: message => {
261
+ console.error(message)
262
+ notices.push(message)
263
+ },
264
+ })
265
+ return pageDocument(stored, { ...rendered, notices }, parts, {
266
+ live: true,
267
+ base,
268
+ asset,
269
+ runtime: `${base}/_/runtime.js`,
270
+ title: projectName(),
271
+ stamps: stamps(),
272
+ })
273
+ }
274
+
275
+ /** The loaded config. Also applies its `files` setting to what is served and watched. */
276
+ async function config(): Promise<LoadedConfig> {
277
+ const c = await loader.config()
278
+ setFiles(filesOption ?? c.files, c.fileFilter)
279
+ publicDirs = [...c.publicDirs.values()]
280
+ return c
281
+ }
282
+
283
+ // ---- assets: the browser's files ----------------------------------------------------------------
284
+ // Served at /_/file/<absolute path>, and only these: the files the core names (its page module and
285
+ // styles, the project's stylesheet), and what is inside a plugin's public folder (public.ts): its
286
+ // client modules, styles, images, fonts. Nothing else of a plugin, and nothing beside its public
287
+ // folder: not its server code, not the project's token, log or config. TypeScript there is
288
+ // served with its types stripped (Node's own type stripping, as for server code: erasable syntax
289
+ // only, positions kept). The folders of what is served are watched from then on.
290
+
291
+ const assets = new Set<string>()
292
+ const assetDirs = new Set<string>()
293
+ const TYPESCRIPT = /\.m?ts$/i
294
+ const typeScriptModule = (file: string): string => stripTypeScriptTypes(fs.readFileSync(file, 'utf8'))
295
+ // the plugins' public folders, as the config last loaded them
296
+ let publicDirs: string[] = []
297
+ const servable = (file: string) => assets.has(file) || publicDirs.some(dir => within(file, dir) && file !== dir)
298
+
299
+ function asset(ref: string | URL): string {
300
+ const file = toPath(ref)
301
+ if (!assets.has(file)) {
302
+ assets.add(file)
303
+ const dir = path.dirname(file)
304
+ if (!assetDirs.has(dir)) {
305
+ assetDirs.add(dir)
306
+ // .workpad/ itself is watched already (setFiles), and so are the engine's own files
307
+ if (!within(dir, project.wp) && !ENGINE_WATCHED.some(d => within(dir, d))) {
308
+ watch(dir, {}, name => onSourceChange(path.join(dir, name)))
309
+ }
310
+ }
311
+ }
312
+ return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
313
+ }
314
+
315
+ // ---- stored pages: the site (site.ts) --------------------------------------------------------------
316
+ const site = servedSite(project, { base, files: () => !!FILES, filter: () => FILTER })
317
+ const stored = site.page
318
+ const pagesIn = site.pagesIn
319
+ const urlFor = site.urlFor
320
+
321
+ // ---- rendering ---------------------------------------------------------------------------------
322
+
323
+ /** A config that failed to load: the page as stored, as text, under the error. */
324
+ function rawRender(page: StoredPage): Rendered {
325
+ const list = (items: [string, string][]) =>
326
+ html`<ul>
327
+ ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
328
+ </ul>`
329
+ if (page.kind === 'pages') return { html: list(page.pages.map(p => [`${base}/${p.id}`, p.id])) }
330
+ if (page.kind === 'folder') {
331
+ return {
332
+ html: list(
333
+ page.entries.map(
334
+ e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string],
335
+ ),
336
+ ),
337
+ }
338
+ }
339
+ return { html: html`<pre>${page.source}</pre>` }
340
+ }
341
+
342
+ const context = () => ({
343
+ project: { name: projectName(), dir: project.dir, files: !!FILES, shows: (rel: string) => FILTER.shows(rel) },
344
+ asset,
345
+ urlFor,
346
+ base,
347
+ ...(entry && { entry: { name: entry, label } }),
348
+ })
349
+
350
+ /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
351
+ async function render(page: StoredPage): Promise<Render> {
352
+ const { pages, errors } = await config()
353
+ const notices = errors.map(e => `config: ${(e as Error).message}`)
354
+ if (page.kind === 'page' && page.frontmatterError) notices.push(`frontmatter: ${page.frontmatterError}`)
355
+ let out: Rendered
356
+ let rendered = !!pages
357
+ try {
358
+ out = pages ? await pages.render(page, context()) : rawRender(page)
359
+ } catch (err) {
360
+ console.error('render:', err)
361
+ notices.push(`the page failed to render: ${(err as Error).message}`)
362
+ out = rawRender(page)
363
+ rendered = false
364
+ }
365
+ // what is wrong on the page (Rendered.problems): told above it, as a config error is
366
+ for (const p of out.problems ?? []) notices.push(p)
367
+ // HTML built with `html`: from here on it is a string, for the shell and for /api/render's JSON alike
368
+ const strings = { ...out, html: String(out.html ?? ''), ...(out.head != null ? { head: String(out.head) } : {}) }
369
+ return { page: rendered, out: strings, notices }
370
+ }
371
+
372
+ /**
373
+ * The project's status (status.ts): the pages, below `only` when given, with their questions, the
374
+ * log read once, and who listens. What `workpad status`, the hooks, the page lists and the log's
375
+ * picked-up marks take.
376
+ */
377
+ // Each page's questions and title, kept while its file and the config stay as they are: parsing
378
+ // every page's markdown on each ask was most of what a status cost.
379
+ const asked = new Map<
380
+ string,
381
+ {
382
+ file: string
383
+ mtime: number
384
+ size: number
385
+ renderer: unknown
386
+ title: string
387
+ asks: string[]
388
+ chats?: string[]
389
+ details: FormDetail[]
390
+ born: number
391
+ }
392
+ >()
393
+ function questionsOf(
394
+ renderer: LoadedConfig['pages'],
395
+ id: string,
396
+ file: string,
397
+ ): { title: string; asks: string[]; chats?: string[]; details: FormDetail[]; born?: number } {
398
+ let stat: fs.Stats
399
+ try {
400
+ stat = fs.statSync(file)
401
+ } catch {
402
+ return { title: path.basename(id), asks: [], details: [] }
403
+ }
404
+ const kept = asked.get(id)
405
+ if (
406
+ kept &&
407
+ kept.file === file &&
408
+ kept.mtime === stat.mtimeMs &&
409
+ kept.size === stat.size &&
410
+ kept.renderer === renderer
411
+ )
412
+ return kept
413
+ let asks: string[] = []
414
+ // unknown (no config, or the page failed to parse): every chat's messages count
415
+ let chats: string[] | undefined
416
+ // what each form asks, for the API
417
+ let details: FormDetail[] = []
418
+ try {
419
+ const source = pageSource(id, file)
420
+ asks = renderer?.questions(source) ?? []
421
+ chats = renderer?.chats(source)
422
+ details = renderer?.forms(source) ?? []
423
+ } catch (err) {
424
+ console.error('questions:', err)
425
+ }
426
+ const now = {
427
+ file,
428
+ mtime: stat.mtimeMs,
429
+ size: stat.size,
430
+ renderer,
431
+ title: titleOf(file, path.basename(id)),
432
+ asks,
433
+ chats,
434
+ details,
435
+ // when the page was made: a file system without it says the change before
436
+ born: stat.birthtimeMs || stat.mtimeMs,
437
+ }
438
+ asked.set(id, now)
439
+ return now
440
+ }
441
+
442
+ async function snapshot(listed: PagesSource['pages']): Promise<ProjectStatus> {
443
+ const { pages: renderer, handedOut, forReader } = await config()
444
+ const events = readEvents(project.eventsFile)
445
+ const pages = listed.map(p => {
446
+ const page = { id: p.id, file: p.file, ...questionsOf(renderer, p.id, p.file) }
447
+ // the forms in the agent's messages in the page's chats are its questions too
448
+ return { ...page, asks: [...page.asks, ...messageForms(events, p.id, page.chats ?? [])] }
449
+ })
450
+ return projectStatus({
451
+ pages,
452
+ events,
453
+ listeners: listenersFor,
454
+ forAgent: forAgent(handedOut),
455
+ forReader: type => forReader.has(type),
456
+ })
457
+ }
458
+
459
+ /** Per page, below `only` when given: what `workpad status` and the hooks report (see snapshot). */
460
+ const status = async (only: string | null): Promise<PageStatus[]> =>
461
+ (await snapshot(pagesIn(project.pagesDir).filter(p => !only || p.id === only || p.id.startsWith(only + '/')))).pages
462
+
463
+ /** A list of pages, with when each was last answered and how much waits on it, from one status. */
464
+ async function withStatus(pages: PagesSource['pages']): Promise<PagesSource['pages']> {
465
+ const s = await snapshot(pages)
466
+ pages.forEach((p, i) => {
467
+ p.awaiting = awaiting(s.pages[i]!)
468
+ p.lastEvent = s.lastAnswered(p.id)
469
+ })
470
+ return pages
471
+ }
472
+
473
+ // ---- the API onto the project's state (state.ts) ----------------------------------------------
474
+
475
+ /** The pages below `only` (a page and those below it), as listed. */
476
+ const listed = (only: string | null) =>
477
+ pagesIn(project.pagesDir).filter(p => !only || p.id === only || p.id.startsWith(only + '/'))
478
+
479
+ /** What the API's lists are made from, for the pages below `only`. */
480
+ async function stateSource(only: string | null): Promise<StateSource> {
481
+ const pages = listed(only)
482
+ const statuses = (await snapshot(pages)).pages
483
+ const { pages: renderer } = await config()
484
+ const kept = (id: string) => {
485
+ const p = pages.find(x => x.id === id)
486
+ return p ? questionsOf(renderer, p.id, p.file) : null
487
+ }
488
+ return {
489
+ base,
490
+ statuses,
491
+ events: readEvents(project.eventsFile),
492
+ details: id => kept(id)?.details ?? [],
493
+ times: id => {
494
+ const p = pages.find(x => x.id === id)
495
+ const born = kept(id)?.born
496
+ return p ? { born: born ?? p.mtime, modified: p.mtime } : null
497
+ },
498
+ listeners: listenersFor(null),
499
+ }
500
+ }
501
+
502
+ /** This project, as GET /api/projects lists it. */
503
+ const projectInfo = (): ProjectInfo => ({
504
+ base,
505
+ name: projectName(),
506
+ label: label ?? projectName(),
507
+ dir: project.dir,
508
+ entry: entry ?? null,
509
+ })
510
+
511
+ const listOf = (q: Record<string, string>, key: string) => (q[key] ? q[key].split(',').filter(Boolean) : [])
512
+
513
+ async function readList(what: ApiList, q: Record<string, string>): Promise<unknown[]> {
514
+ if (what === 'projects') return [projectInfo()]
515
+ const only = q.page || null
516
+ if (what === 'subscriptions' || what === 'agents') {
517
+ const events = readEvents(project.eventsFile)
518
+ const under = (page: string) => !only || page === '' || page === only || page.startsWith(only + '/') || only.startsWith(page + '/')
519
+ if (what === 'subscriptions')
520
+ return subscriptionsOf({ base, events }).filter(x => under(x.page) && (!q.agent || x.agent === q.agent))
521
+ return agentsOf({ base, events, listeners: listenersFor(null) })
522
+ }
523
+ const source = await stateSource(only)
524
+ if (what === 'pages') return pagesOf(source)
525
+ if (what === 'chats') return chatsOf(source).filter(c => !q.chat || c.chat === q.chat)
526
+ const states = listOf(q, 'state')
527
+ const names = listOf(q, 'name')
528
+ return formsOf(source).filter(f => (!states.length || states.includes(f.state)) && (!names.length || names.includes(f.name)))
529
+ }
530
+
531
+ function stream(q: EventQuery, send: (event: LiveEvent) => void): () => void {
532
+ const { events, end } = readLog(project.eventsFile)
533
+ if (q.since) for (const e of after(events, q.since)) if (matchesQuery(e, q)) send(live(e, base))
534
+ return follow(project.eventsFile, end, e => {
535
+ if (matchesQuery(e, q)) send(live(e, base))
536
+ })
537
+ }
538
+
539
+ /** A write of the API: it needs the project's token; its JSON body; and who writes it (`agent`). */
540
+ async function writeOf(req: IncomingMessage, res: ServerResponse): Promise<{ body: Record<string, unknown>; by: string | null } | null> {
541
+ if (!auth.authorized(req)) {
542
+ sendJson(res, 403, { error: "this needs the project's token: send it as the header x-workpad-token (.workpad/token)" })
543
+ return null
544
+ }
545
+ let body: unknown
546
+ try {
547
+ body = JSON.parse((await readBody(req)) || '{}')
548
+ } catch {
549
+ sendJson(res, 400, { error: 'the body is not JSON' })
550
+ return null
551
+ }
552
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
553
+ sendJson(res, 400, { error: 'the body must be a JSON object' })
554
+ return null
555
+ }
556
+ const b = body as Record<string, unknown>
557
+ return { body: b, by: typeof b.agent === 'string' && b.agent ? b.agent : null }
558
+ }
559
+
560
+ /** The names of forms in a body: `forms`, a list of names. */
561
+ const formsIn_ = (b: Record<string, unknown>): string[] | null =>
562
+ Array.isArray(b.forms) && b.forms.every(f => typeof f === 'string') ? (b.forms as string[]) : null
563
+
564
+ /** POST /api/forms/<hold|release|settle>: { page, forms, reason?, all?, agent? } */
565
+ async function formWrite(action: string, req: IncomingMessage, res: ServerResponse) {
566
+ const w = await writeOf(req, res)
567
+ if (!w) return
568
+ const { body, by } = w
569
+ if (typeof body.page !== 'string') return sendJson(res, 400, { error: 'page: the page the forms are on' })
570
+ const p = (await status(body.page)).find(x => x.page === body.page)
571
+ if (!p) return sendJson(res, 404, { error: `no page ${body.page}` })
572
+ const forms = formsIn_(body)
573
+ try {
574
+ if (action === 'settle') {
575
+ if (!forms && body.all !== true) return sendJson(res, 400, { error: 'forms: the names to settle, or all: true' })
576
+ const { event, forms: settled, skipped } = settleForms(project.eventsFile, p, forms ?? 'all', by)
577
+ return sendJson(res, 200, { event, forms: settled, skipped })
578
+ }
579
+ if (!forms) return sendJson(res, 400, { error: 'forms: a list of form names' })
580
+ if (action === 'hold') {
581
+ if (typeof body.reason !== 'string') return sendJson(res, 400, { error: 'reason: why they are held' })
582
+ return sendJson(res, 200, { event: holdForms(project.eventsFile, p, forms, body.reason, by) })
583
+ }
584
+ return sendJson(res, 200, { event: releaseForms(project.eventsFile, p, forms, by) })
585
+ } catch (err) {
586
+ if (err instanceof FormStateError) return sendJson(res, err.status, { error: err.message })
587
+ throw err
588
+ }
589
+ }
590
+
591
+ /** POST /api/handled: { ids, agent? } → { handled, already } */
592
+ async function handledWrite(req: IncomingMessage, res: ServerResponse) {
593
+ const w = await writeOf(req, res)
594
+ if (!w) return
595
+ const ids = w.body.ids
596
+ if (!Array.isArray(ids) || !ids.every(i => typeof i === 'string')) return sendJson(res, 400, { error: 'ids: a list of event ids' })
597
+ const events = readEvents(project.eventsFile)
598
+ const done = handledIds(events)
599
+ const missing = ids.filter(id => !events.some(e => e.id === id))
600
+ if (missing.length) return sendJson(res, 404, { error: `no event ${missing.join(', ')} in the log` })
601
+ const handled = ids.filter(id => !done.has(id)).map(id => handleEvent(project.eventsFile, events.find(e => e.id === id)!, w.by))
602
+ return sendJson(res, 200, { handled, already: ids.filter(id => done.has(id)) })
603
+ }
604
+
605
+ /** POST /api/page: { page, markdown, agent? } → { page, file, url, created }. A page made is its writer's (subscribed). */
606
+ async function pageWrite(req: IncomingMessage, res: ServerResponse) {
607
+ const w = await writeOf(req, res)
608
+ if (!w) return
609
+ const { page: id, markdown } = w.body
610
+ if (typeof markdown !== 'string') return sendJson(res, 400, { error: 'markdown: the page as text' })
611
+ const name = typeof id === 'string' ? id.replace(/\.md$/, '').replace(/^\/+|\/+$/g, '') : ''
612
+ const file = name && !name.split('/').some(part => !part || part === '.' || part === '..' || part === '-' || part === '_')
613
+ ? inside(project.pagesDir, `${name}.md`)
614
+ : null
615
+ if (!file) return sendJson(res, 400, { error: 'page: a page name like plan or task/plan' })
616
+ const created = !fs.existsSync(file)
617
+ fs.mkdirSync(path.dirname(file), { recursive: true })
618
+ fs.writeFileSync(file, markdown)
619
+ if (created && w.by && !subscriptions(readEvents(project.eventsFile)).some(e => e.page === name && e.by === w.by))
620
+ appendEvent(project.eventsFile, { page: name, type: SUBSCRIBE }, 'cli', w.by)
621
+ return sendJson(res, 200, { page: name, file, url: pageUrl(base, name), created })
622
+ }
623
+
624
+ /** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
625
+ async function docs() {
626
+ const { pages, errors } = await config()
627
+ // what each plugin declares: its routes (for an agent that wants to call them) and commands
628
+ const plugins = await Promise.all(
629
+ (await pluginHooks()).map(async h => ({
630
+ name: h.name,
631
+ error: h.error?.message ?? null,
632
+ docs: h.plugin.docs ? await h.plugin.docs() : null,
633
+ // the blocks it brings, and whether any is on the menu: `workpad docs <block>` finds it by them
634
+ blocks: Object.keys(h.plugin.blocks ?? {}),
635
+ menu: Object.values(h.plugin.blocks ?? {}).some(b => b?.menu),
636
+ routes: describeRoutes(h.table),
637
+ commands: pluginCommands(h.plugin).map(c => ({
638
+ name: c.name,
639
+ usage: usage(c.command),
640
+ description: c.command.description,
641
+ })),
642
+ events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({
643
+ type,
644
+ handOut: !!spec?.handOut,
645
+ description: spec?.description ?? '',
646
+ })),
647
+ })),
648
+ )
649
+ return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
650
+ }
651
+
652
+ /**
653
+ * What the browser runs and how it looks, as two stamps: one over its code (the runtime, the page's
654
+ * module, the plugins' scripts), one over its stylesheets (the engine's, the plugins', the
655
+ * project's in .workpad/). A page gets them with its HTML and asks again when its live channel
656
+ * is back: what changed while it was away (a restart, a background tab whose browser held its
657
+ * timers), it would otherwise never hear of. Made from the files themselves, not from what was
658
+ * served since the server started, so a fresh server gives the same stamps for the same files.
659
+ */
660
+ function stamps(): { code: string; style: string } {
661
+ const files: string[] = [RUNTIME]
662
+ const add = (dir: string, deep: boolean) => {
663
+ let entries: fs.Dirent[]
664
+ try {
665
+ entries = fs.readdirSync(dir, { withFileTypes: true })
666
+ } catch {
667
+ return
668
+ }
669
+ for (const e of entries) {
670
+ const full = path.join(dir, e.name)
671
+ if (e.isDirectory()) {
672
+ if (deep) add(full, deep)
673
+ } else files.push(full)
674
+ }
675
+ }
676
+ add(path.dirname(PAGE_CLIENT), false)
677
+ for (const dir of publicDirs) add(dir, true)
678
+ for (const f of fs.readdirSync(project.wp).filter(f => f.endsWith('.css'))) files.push(path.join(project.wp, f))
679
+ const of = (list: string[]) => {
680
+ const hash = crypto.createHash('sha1')
681
+ for (const f of [...new Set(list)].toSorted()) {
682
+ try {
683
+ const st = fs.statSync(f)
684
+ hash.update(`${f}\0${st.mtimeMs}\0${st.size}\n`)
685
+ } catch {
686
+ /* gone */
687
+ }
688
+ }
689
+ return hash.digest('hex').slice(0, 16)
690
+ }
691
+ return { code: of(files.filter(f => !f.endsWith('.css'))), style: of(files.filter(f => f.endsWith('.css'))) }
692
+ }
693
+
694
+ // ---- listeners ---------------------------------------------------------------------------------
695
+ // An agent waiting for answers holds a connection to /api/listen (listeners.ts). Pages show what an
696
+ // agent is waiting for from these, so nothing depends on the agent marking it.
697
+ const registry = createRegistry()
698
+ /** The agents' names (`workpad agent name`), as the log says now; told to the pages when they change. */
699
+ let names = namesOf(readEvents(project.eventsFile))
700
+ // each with the name its agent gave itself, for the page's list of who listens
701
+ const listenersFor = (page: string | null): Listener[] =>
702
+ registry.list(page).map(l => (l.agent && names.has(l.agent) ? { ...l, name: names.get(l.agent) } : l))
703
+
704
+ // ---- channels ----------------------------------------------------------------------------------
705
+ // A plugin that pushes answers into an agent session (a channel) holds a line to /api/channel for
706
+ // it. Whether its messages reach the agent only the agent can say: `workpad agent ping` sends the
707
+ // session's channels a ping with a code each (/api/ping { session }), the channel pushes it into
708
+ // the session as a pong, and the agent confirms with the code (/api/ping { code }). Until then a
709
+ // channel listens on no page (it registers its page listeners once confirmed), so the pages and
710
+ // `workpad status` say nobody listens, and a wait can take them.
711
+ interface Channel {
712
+ session: string
713
+ confirmed: boolean
714
+ send(event: string, data?: unknown): void
715
+ }
716
+ const channels = new Map<string, Channel>()
717
+ /** the codes of pings sent and not confirmed yet: the channel each went to */
718
+ const pings = new Map<string, string>()
719
+ const pingCode = () => crypto.randomBytes(3).toString('hex')
720
+
721
+ // ---- live changes ------------------------------------------------------------------------------
722
+ // The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
723
+ // page changed; `events`: the log grew; `listeners`: an agent started or stopped waiting; `style`:
724
+ // a stylesheet changed; `reload`: browser code changed; `scroll`: an agent shows the reader a place
725
+ // on the page ({ to }); `elsewhere`: under a shared server, what waits in another project changed.
726
+ // /api/watch says the same as server-sent events, for a tab opened before
727
+ // /api/live: it tells it to reload first, so it moves to the WebSocket (see ws.ts for why).
728
+
729
+ /** A browser following its page; `pending`: what it will be told in a moment. */
730
+ interface WatchClient {
731
+ send(event: string, data?: unknown): void
732
+ page: string
733
+ isDir: boolean
734
+ pending?: Set<string>
735
+ }
736
+
737
+ const clients = new Set<WatchClient>()
738
+ /** what the browser appended lately, by id: a send it retries is answered with what it got */
739
+ const appended = new Map<string, WpEvent>()
740
+ function notify(client: WatchClient, kind: string) {
741
+ client.pending ??= new Set()
742
+ if (client.pending.size === 0)
743
+ setTimeout(() => {
744
+ for (const k of client.pending!) client.send(k)
745
+ client.pending!.clear()
746
+ }, 60)
747
+ client.pending.add(kind)
748
+ }
749
+ const notifyAll = (kind: string) => {
750
+ for (const c of clients) notify(c, kind)
751
+ }
752
+ // who listens shows on this project's pages, and, under a shared server, on the others' (onChange)
753
+ registry.onChange(() => {
754
+ notifyAll('listeners')
755
+ onChange?.()
756
+ })
757
+
758
+ function pageChanged(id: string) {
759
+ onChange?.()
760
+ for (const c of clients) {
761
+ if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
762
+ notify(c, 'change')
763
+ }
764
+ // the overview lists every page
765
+ for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
766
+ }
767
+
768
+ /** A file in the project changed; `f` is its path relative to the project folder, with / separators. */
769
+ function fileChanged(f: string) {
770
+ if (!f.startsWith('.workpad/') && !FILTER.shows(f)) return
771
+ if (f.startsWith('.workpad/')) {
772
+ const inner = f.slice('.workpad/'.length)
773
+ if (inner === 'events.ndjson') {
774
+ onChange?.()
775
+ // an agent named itself: the pages' lists of who listens say so
776
+ const now = namesOf(readEvents(project.eventsFile))
777
+ if (JSON.stringify([...now]) !== JSON.stringify([...names])) {
778
+ names = now
779
+ notifyAll('listeners')
780
+ }
781
+ return notifyAll('events')
782
+ }
783
+ if (inner.startsWith('pages/')) {
784
+ if (inner.endsWith('.md')) pageChanged(inner.slice('pages/'.length).replace(/\.md$/, ''))
785
+ return
786
+ }
787
+ if (OWN_FILES.has(inner) || pluginDirs.has(inner.split('/')[0]!)) return
788
+ // the config, or something it imports
789
+ return onSourceChange(path.join(project.dir, f))
790
+ }
791
+ if (!FILES) return
792
+ // a repository file; its folder's listing shows it too
793
+ pageChanged(`-/${f}`)
794
+ const parent = f.includes('/') ? f.slice(0, f.lastIndexOf('/')) : ''
795
+ pageChanged(`-${parent ? '/' + parent : ''}`)
796
+ }
797
+
798
+ // With files on, the whole project folder is watched (repository views stay live); with files off,
799
+ // only .workpad/, so a project in a large folder such as the home folder stays cheap. A folder
800
+ // that holds nothing shown (node_modules, .git, what the config's `files` leaves out: src/files.ts)
801
+ // is never watched: an install or a checkout changes thousands of files there that nothing shows,
802
+ // and on Linux a recursive watch holds a watch for every folder below it. So the project folder
803
+ // itself is watched without recursing, and each folder in it that can hold something shown
804
+ // recursively, one made later too. One left out deeper down (a package's own node_modules) is
805
+ // watched, its changes passed over (fileChanged).
806
+ let FILES: boolean | null = null
807
+ // which of the project's files are shown (the config's `files`, src/files.ts)
808
+ let FILTER: FileFilter = fileFilter()
809
+ let projectWatchers = new Map<string, fs.FSWatcher>()
810
+ function setFiles(files: boolean, filter: FileFilter = fileFilter()) {
811
+ if (files === FILES && filter.key === FILTER.key) return
812
+ FILES = files
813
+ FILTER = filter
814
+ for (const w of projectWatchers.values()) {
815
+ w.close()
816
+ watchers.delete(w)
817
+ }
818
+ projectWatchers = new Map()
819
+ const add = (key: string, dir: string, recursive: boolean, prefix: string) => {
820
+ try {
821
+ const w = fs.watch(dir, { recursive }, (evt, filename) => {
822
+ if (!filename) return
823
+ const name = filename.toString().replace(/\\/g, '/')
824
+ fileChanged(prefix + name)
825
+ // a folder made, removed or made again in the project folder: watched afresh, if it is there
826
+ if (!recursive && evt === 'rename') {
827
+ const old = projectWatchers.get(name)
828
+ if (old) {
829
+ old.close()
830
+ watchers.delete(old)
831
+ projectWatchers.delete(name)
832
+ }
833
+ watchFolder(name)
834
+ }
835
+ })
836
+ // a folder that goes: its watcher with it
837
+ w.on('error', () => {
838
+ w.close()
839
+ watchers.delete(w)
840
+ projectWatchers.delete(key)
841
+ })
842
+ projectWatchers.set(key, w)
843
+ watchers.add(w)
844
+ } catch {
845
+ /* gone meanwhile */
846
+ }
847
+ }
848
+ const watchFolder = (name: string) => {
849
+ // .workpad always; of the rest, a folder that can hold something shown
850
+ if (projectWatchers.has(name) || name.includes('/') || (name !== '.workpad' && !FILTER.mayHold(name))) return
851
+ const dir = path.join(project.dir, name)
852
+ let isDir = false
853
+ try {
854
+ isDir = fs.statSync(dir).isDirectory()
855
+ } catch {}
856
+ if (isDir) add(name, dir, true, name + '/')
857
+ }
858
+ if (!files) return add('.workpad', project.wp, true, '.workpad/')
859
+ add('', project.dir, false, '')
860
+ for (const ent of fs.readdirSync(project.dir, { withFileTypes: true })) if (ent.isDirectory()) watchFolder(ent.name)
861
+ }
862
+
863
+ // A served page's folder is watched on its own too, once the page is served (opened, or followed
864
+ // over its live channel), besides the watch over .workpad/ as a whole: on some file systems (a
865
+ // container's mount, as OrbStack's) that watch hears nothing of a folder made and written into at
866
+ // once, so a page there would never go live. A folder not there yet is watched through the nearest
867
+ // one above it in the pages folder, and itself once it is made, its pages then told they changed
868
+ // (what was written before its watch began). Twice told is once: notify gathers what it tells.
869
+ const pageFolders = new Map<string, fs.FSWatcher>()
870
+ // a folder watched → the folders below it that served pages wait for
871
+ const awaitedIn = new Map<string, Set<string>>()
872
+ const isFolder = (dir: string) => {
873
+ try {
874
+ return fs.statSync(dir).isDirectory()
875
+ } catch {
876
+ return false
877
+ }
878
+ }
879
+ /** Watch the folder of page `id` (and the folder `id` names, when it is one). */
880
+ function watchPage(id: string) {
881
+ const target = inside(project.pagesDir, id)
882
+ if (!target) return
883
+ watchPageFolder(target === project.pagesDir ? target : path.dirname(target))
884
+ if (target !== project.pagesDir && isFolder(target)) watchPageFolder(target)
885
+ }
886
+ function watchPageFolder(folder: string, made = false) {
887
+ let at = folder
888
+ while (at !== project.pagesDir && within(at, project.pagesDir) && !isFolder(at)) at = path.dirname(at)
889
+ if (!within(at, project.pagesDir)) return
890
+ if (at !== folder) {
891
+ if (!awaitedIn.has(at)) awaitedIn.set(at, new Set())
892
+ awaitedIn.get(at)!.add(folder)
893
+ }
894
+ if (pageFolders.has(at)) return
895
+ const rel = (name: string) => path.relative(project.dir, path.join(at, name)).split(path.sep).join('/')
896
+ let w: fs.FSWatcher
897
+ try {
898
+ w = fs.watch(at, {}, (_evt, name) => {
899
+ if (name) fileChanged(rel(String(name)))
900
+ // gone: watched again once a page in it is served
901
+ if (!isFolder(at)) return drop()
902
+ // a folder a served page waits for may be there now
903
+ const awaited = awaitedIn.get(at)
904
+ if (awaited) {
905
+ awaitedIn.delete(at)
906
+ for (const f of awaited) watchPageFolder(f, true)
907
+ }
908
+ })
909
+ } catch {
910
+ return
911
+ }
912
+ const drop = () => {
913
+ w.close()
914
+ watchers.delete(w)
915
+ if (pageFolders.get(at) === w) pageFolders.delete(at)
916
+ }
917
+ w.on('error', drop)
918
+ pageFolders.set(at, w)
919
+ watchers.add(w)
920
+ // made a moment ago: what was written in it before its watch began
921
+ if (made)
922
+ for (const name of fs.readdirSync(at)) if (name.endsWith('.md')) fileChanged(rel(name))
923
+ }
924
+
925
+ // What a plugin or the config is made of changed. A stylesheet reloads in place; a browser module
926
+ // reloads the pages; anything else loads the config afresh and re-renders open pages.
927
+ let reloadTimer: ReturnType<typeof setTimeout> | undefined
928
+ async function onSourceChange(file: string) {
929
+ if (within(file, project.pagesDir)) return
930
+ if (path.dirname(file) === project.wp && OWN_FILES.has(path.basename(file))) return
931
+ if ([...pluginDirs].some(name => within(file, path.join(project.wp, name)))) return
932
+ if (file.endsWith('.css')) return notifyAll('style')
933
+ if (file.endsWith('.md')) return notifyAll('change')
934
+ if (file === RUNTIME || assets.has(file)) return notifyAll('reload')
935
+ // a build writes several files at once: load the config once they are all there
936
+ clearTimeout(reloadTimer)
937
+ reloadTimer = setTimeout(() => {
938
+ loader.invalidate()
939
+ config().then(() => notifyAll('change'))
940
+ }, 80)
941
+ }
942
+
943
+ // The engine's own files, when it runs from source: what a config loads from it runs from source
944
+ // too (the plugins), and the browser code from its build (npm run dev). A change to
945
+ // either reloads what it is made of, like a project's own files.
946
+ const ENGINE_BUILD = path.join(ENGINE_DIR, 'dist')
947
+ const ENGINE_WATCHED = !FROM_SOURCE ? [] : [ENGINE_BUILD, ...['plugins'].map(d => path.join(ENGINE_DIR, d))]
948
+ for (const dir of ENGINE_WATCHED) watch(dir, { recursive: true }, name => onSourceChange(path.join(dir, name)))
949
+
950
+ // ---- http --------------------------------------------------------------------------------------
951
+
952
+ function send(res: ServerResponse, status: number, body: string | Buffer, type = 'text/html; charset=utf-8') {
953
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
954
+ res.end(body)
955
+ }
956
+ const sendJson = (res: ServerResponse, status: number, data: unknown) =>
957
+ send(res, status, JSON.stringify(data), 'application/json')
958
+ const sendFile = (res: ServerResponse, file: string) =>
959
+ send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
960
+
961
+ function readBody(req: IncomingMessage): Promise<string> {
962
+ return new Promise((resolve, reject) => {
963
+ const chunks: Buffer[] = []
964
+ let size = 0
965
+ req.on('data', (c: Buffer) => {
966
+ size += c.length
967
+ if (size > 1e6) {
968
+ reject(new Error('body too large'))
969
+ req.destroy()
970
+ } else chunks.push(c)
971
+ })
972
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
973
+ req.on('error', reject)
974
+ })
975
+ }
976
+
977
+ /** What a page id resolves to, or why it does not: the response to send instead. */
978
+ type Resolved = { page: StoredPage } | { raw: string } | { redirect: string } | { notFound: string }
979
+
980
+ async function resolve(id: string, requested: string): Promise<Resolved> {
981
+ await config()
982
+ if (!isRepoId(id) && !id.startsWith('_/')) watchPage(id)
983
+ if (isRepoId(id) && !FILES)
984
+ return { notFound: 'This project does not serve its files: its config sets files: false.' }
985
+ if (id === '_/docs') {
986
+ // how pages are written, then each plugin's own docs, with their examples rendered live
987
+ const { pages, plugins } = await docs()
988
+ const source = [
989
+ pages ?? '',
990
+ ...plugins.filter(p => p.docs).map(p => `<a id="plugin-${p.name}"></a>\n\n${p.docs}`),
991
+ ].join('\n\n---\n\n')
992
+ return {
993
+ page: {
994
+ kind: 'page',
995
+ id,
996
+ file: path.join(project.pagesDir, '_docs.md'),
997
+ mtime: null,
998
+ source,
999
+ body: source,
1000
+ frontmatter: {},
1001
+ },
1002
+ }
1003
+ }
1004
+ const found = stored(id)
1005
+ if (!found)
1006
+ return {
1007
+ notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.`,
1008
+ }
1009
+ if ('raw' in found) return found
1010
+ // a folder is served at /dir/, so relative links resolve inside it
1011
+ if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/'))
1012
+ return { redirect: `${base}/${id}/` }
1013
+ // a list of pages says which await the reader: where their questions stand takes the config
1014
+ if (found.kind === 'pages') {
1015
+ await withStatus(found.pages)
1016
+ if (!found.id && overview) Object.assign(found, await overview())
1017
+ }
1018
+ return { page: found }
1019
+ }
1020
+
1021
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
1022
+ try {
1023
+ // a path like //x would otherwise read as a host
1024
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
1025
+ const p = decodeURIComponent(url.pathname)
1026
+ const q = Object.fromEntries(url.searchParams)
1027
+
1028
+ if (p === '/favicon.ico') {
1029
+ res.writeHead(204)
1030
+ res.end()
1031
+ return
1032
+ }
1033
+ if (p === '/_/runtime.js') return sendFile(res, RUNTIME)
1034
+ if (auth.handle(req, res, p, q)) return
1035
+ if (p.startsWith('/api/')) {
1036
+ const hooks = await pluginHooks()
1037
+ for (const h of hooks) if (await dispatch(h.table, req, res, url, auth.authorized)) return
1038
+ // under a plugin's name, but none of its routes
1039
+ const owner = hooks.find(h => p.startsWith(`/api/${h.name}/`) || p === `/api/${h.name}`)
1040
+ if (owner) return sendJson(res, 404, { error: `plugin ${owner.name} has no route ${req.method} ${p}` })
1041
+ }
1042
+ if (p.startsWith('/_/file/')) {
1043
+ await config()
1044
+ const file = path.resolve(p.slice('/_/file'.length))
1045
+ if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile())
1046
+ return send(res, 404, 'not found', 'text/plain')
1047
+ // watched from now on, so a change to it reloads the pages that use it
1048
+ asset(file)
1049
+ if (TYPESCRIPT.test(file)) {
1050
+ try {
1051
+ return send(res, 200, typeScriptModule(file), 'text/javascript; charset=utf-8')
1052
+ } catch (err) {
1053
+ // syntax only types can't express (an enum, a namespace) or a mistake: the browser says why
1054
+ return send(
1055
+ res,
1056
+ 200,
1057
+ `throw new SyntaxError(${JSON.stringify(`${path.basename(file)}: ${(err as Error).message}`)})`,
1058
+ 'text/javascript; charset=utf-8',
1059
+ )
1060
+ }
1061
+ }
1062
+ return sendFile(res, file)
1063
+ }
1064
+ if (p === '/api/health')
1065
+ return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid, version: VERSION, base })
1066
+ if (p === '/api/events' && req.method === 'POST') {
1067
+ const body = JSON.parse(await readBody(req))
1068
+ if (!body.type) return sendJson(res, 400, { error: 'event type required' })
1069
+ // the browser sends it again when it heard nothing back: appended once, the same answer twice
1070
+ const again = isEventId(body.id) ? appended.get(body.id) : undefined
1071
+ if (again) return sendJson(res, 200, again)
1072
+ const event = appendEvent(project.eventsFile, body)
1073
+ appended.set(event.id, event)
1074
+ if (appended.size > 1000) appended.delete(appended.keys().next().value!)
1075
+ return sendJson(res, 200, event)
1076
+ }
1077
+ // an agent shows the reader a place on a page: every tab with it open scrolls there
1078
+ // ({ page, to }: a heading's text, a form's name or any text) → { tabs }
1079
+ if (p === '/api/scroll' && req.method === 'POST') {
1080
+ const { page: id, to } = JSON.parse(await readBody(req)) as { page?: unknown; to?: unknown }
1081
+ if (typeof id !== 'string' || typeof to !== 'string' || !to.trim())
1082
+ return sendJson(res, 400, { error: 'page and to required' })
1083
+ // in the log, so a tab that isn't connected now (a server restarting, a background tab
1084
+ // whose browser holds its timers) still scrolls there once it is back; a page loaded later
1085
+ // doesn't (see the runtime)
1086
+ appendEvent(project.eventsFile, { page: id, type: SCROLL, data: { to } }, 'cli')
1087
+ let tabs = 0
1088
+ for (const c of clients) if (!c.isDir && (c.page === id || c.page + '/index' === id)) tabs++
1089
+ return sendJson(res, 200, { tabs })
1090
+ }
1091
+ // messages (comments, chat) written in markdown, as HTML: { texts } → { html, styles }
1092
+ if (p === '/api/markdown' && req.method === 'POST') {
1093
+ const { texts } = JSON.parse(await readBody(req)) as { texts?: unknown }
1094
+ if (!Array.isArray(texts)) return sendJson(res, 400, { error: 'texts: an array of strings' })
1095
+ const { pages } = await config()
1096
+ const out = await Promise.all(
1097
+ texts.map(t =>
1098
+ pages
1099
+ ? pages.message(String(t ?? ''), context())
1100
+ : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] }),
1101
+ ),
1102
+ )
1103
+ return sendJson(res, 200, { html: out.map(o => o.html), styles: [...new Set(out.flatMap(o => o.styles))] })
1104
+ }
1105
+ // markdown a plugin's client puts in what it draws (Api.blocks), rendered with every block as
1106
+ // on the page: { page, texts } → { html, islands, styles }
1107
+ if (p === '/api/blocks' && req.method === 'POST') {
1108
+ const { page: id, texts } = JSON.parse(await readBody(req)) as { page?: unknown; texts?: unknown }
1109
+ if (typeof id !== 'string' || !Array.isArray(texts))
1110
+ return sendJson(res, 400, { error: 'page: a page id; texts: an array of strings' })
1111
+ const { pages } = await config()
1112
+ if (!pages) return sendJson(res, 200, { html: texts.map(() => ''), islands: {}, styles: [] })
1113
+ // the page's file, which relative files resolve from: never one outside the project
1114
+ const file = id.startsWith('-/') ? inside(project.dir, id.slice(2)) : inside(project.pagesDir, `${id}.md`)
1115
+ if (!file) return sendJson(res, 400, { error: `no page ${id}` })
1116
+ const out = await Promise.all(
1117
+ texts.map(t => {
1118
+ const text = String(t ?? '')
1119
+ // islands keyed by the text, so the same text asked again mounts the same way
1120
+ const prefix = `b${crypto.createHash('sha1').update(text).digest('hex').slice(0, 10)}-`
1121
+ return pages.blocks(text, context(), { page: id, file, prefix })
1122
+ }),
1123
+ )
1124
+ return sendJson(res, 200, {
1125
+ html: out.map(o => o.html),
1126
+ islands: Object.assign({}, ...out.map(o => o.islands)),
1127
+ styles: [...new Set(out.flatMap(o => o.styles))],
1128
+ })
1129
+ }
1130
+ if (p === '/api/messages' && req.method === 'POST') {
1131
+ // the agent's chat messages, by id, each as a small page (Pages.agentMessage); '' for an id
1132
+ // that is no message of the agent's
1133
+ const { ids } = JSON.parse(await readBody(req)) as { ids?: unknown }
1134
+ if (!Array.isArray(ids)) return sendJson(res, 400, { error: 'ids: an array of event ids' })
1135
+ const { pages } = await config()
1136
+ const events = readEvents(project.eventsFile)
1137
+ const out = await Promise.all(
1138
+ ids.map(async raw => {
1139
+ const e = events.find(x => x.id === String(raw))
1140
+ if (!pages || !e || !isAgentMessage(e)) return null
1141
+ const chat = String(e.data.chat)
1142
+ // its unnamed forms are numbered after those of the agent's earlier messages in the chat
1143
+ const shown = agentMessagesIn(events, e.page, chat)
1144
+ const first =
1145
+ 1 +
1146
+ shown
1147
+ .slice(0, shown.indexOf(e))
1148
+ .reduce((n, x) => n + formsIn(String(x.data.text ?? '')).filter(f => !f.name).length, 0)
1149
+ const file = e.page.startsWith('-/')
1150
+ ? path.join(project.dir, e.page.slice(2))
1151
+ : path.join(project.pagesDir, `${e.page}.md`)
1152
+ return pages.agentMessage(String(e.data.text ?? ''), context(), {
1153
+ page: e.page,
1154
+ file,
1155
+ chat,
1156
+ first,
1157
+ prefix: `m${e.id}-`,
1158
+ })
1159
+ }),
1160
+ )
1161
+ return sendJson(res, 200, {
1162
+ html: out.map(o => o?.html ?? ''),
1163
+ islands: Object.assign({}, ...out.map(o => o?.islands ?? {})),
1164
+ styles: [...new Set(out.flatMap(o => o?.styles ?? []))],
1165
+ })
1166
+ }
1167
+ // the API's lists (state.ts): projects, pages, forms, chats, subscriptions, agents
1168
+ const list = /^\/api\/(\w+)$/.exec(p)?.[1]
1169
+ if (req.method === 'GET' && list && (API_LISTS as readonly string[]).includes(list))
1170
+ return sendJson(res, 200, await readList(list as ApiList, q))
1171
+ if (req.method === 'POST' && /^\/api\/forms\/(hold|release|settle)$/.test(p))
1172
+ return formWrite(p.slice('/api/forms/'.length), req, res)
1173
+ if (p === '/api/handled' && req.method === 'POST') return handledWrite(req, res)
1174
+ if (p === '/api/page' && req.method === 'POST') return pageWrite(req, res)
1175
+ if (p === '/api/anchors') {
1176
+ const r = await resolve(q.page ?? '', '/')
1177
+ if (!('page' in r)) return sendJson(res, 404, { error: 'notFound' in r ? r.notFound : 'not a page' })
1178
+ return sendJson(res, 200, anchorsOf(String((await render(r.page)).out.html)))
1179
+ }
1180
+ // the log as it grows, as server-sent events (`event: event`, its data a LiveEvent)
1181
+ if (p === '/api/stream') {
1182
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
1183
+ res.write(': streaming\n\n')
1184
+ const stop = stream(q, e => res.write(`event: event\nid: ${e.id}\ndata: ${JSON.stringify(e)}\n\n`))
1185
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
1186
+ const end = () => {
1187
+ stop()
1188
+ clearInterval(ping)
1189
+ streams.delete(close)
1190
+ }
1191
+ const close = () => {
1192
+ end()
1193
+ res.end()
1194
+ }
1195
+ streams.add(close)
1196
+ req.on('close', end)
1197
+ return
1198
+ }
1199
+ if (p === '/api/events') {
1200
+ const all = after(readEvents(project.eventsFile), q.since)
1201
+ // what became of each: received by a wait, handled by the agent (status.ts)
1202
+ const received = receivedIds(all)
1203
+ const handled = handledIds(all)
1204
+ return sendJson(
1205
+ res,
1206
+ 200,
1207
+ all
1208
+ // `type` and `kind` may be several, comma-separated (state.ts); `page` and `exact` as ever
1209
+ .filter(e => matches(e, { ...q, type: null }) && matchesQuery(e, q))
1210
+ .map(e => ({
1211
+ ...e,
1212
+ ...(received.has(e.id) && { received: true }),
1213
+ ...(handled.has(e.id) && { handled: true }),
1214
+ })),
1215
+ )
1216
+ }
1217
+ if (p === '/api/docs') return sendJson(res, 200, await docs())
1218
+ if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
1219
+ if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
1220
+ if (p === '/api/stamps') return sendJson(res, 200, stamps())
1221
+ if (p === '/api/listen') {
1222
+ // any number listen on a page; each is a listener for as long as its connection is open
1223
+ const remove = registry.add(listenerOf(url.searchParams))
1224
+ const stream = holdStream(req, res, () => {
1225
+ remove()
1226
+ streams.delete(stream.end)
1227
+ })
1228
+ streams.add(stream.end)
1229
+ return
1230
+ }
1231
+ // the channels open now, for `workpad claude doctor`: whose session, and whether a ping confirmed it
1232
+ if (p === '/api/channels')
1233
+ return sendJson(
1234
+ res,
1235
+ 200,
1236
+ [...channels.values()].map(c => ({ session: c.session, confirmed: c.confirmed })),
1237
+ )
1238
+ if (p === '/api/channel') {
1239
+ const id = q.id
1240
+ if (!id || !q.session) return sendJson(res, 400, { error: 'id and session required' })
1241
+ const stream = holdStream(req, res, () => {
1242
+ if (channels.get(id) === channel) channels.delete(id)
1243
+ streams.delete(stream.end)
1244
+ })
1245
+ // one that was confirmed before (this server restarted) says so
1246
+ const channel: Channel = { session: q.session, confirmed: 'confirmed' in q, send: stream.send }
1247
+ channels.set(id, channel)
1248
+ streams.add(stream.end)
1249
+ return
1250
+ }
1251
+ // { session }: ping its channels → { sent } or { confirmed } (one is already); { code }: the
1252
+ // agent got the pong → { confirmed }
1253
+ if (p === '/api/ping' && req.method === 'POST') {
1254
+ const body = JSON.parse(await readBody(req)) as { session?: unknown; code?: unknown }
1255
+ if (typeof body.code === 'string') {
1256
+ const id = pings.get(body.code)
1257
+ const channel = id ? channels.get(id) : undefined
1258
+ if (!channel) return sendJson(res, 404, { error: `no ping with code ${body.code} waits` })
1259
+ for (const [code, to] of pings) if (to === id) pings.delete(code)
1260
+ channel.confirmed = true
1261
+ channel.send('confirmed', {})
1262
+ return sendJson(res, 200, { confirmed: true })
1263
+ }
1264
+ if (typeof body.session !== 'string') return sendJson(res, 400, { error: 'session or code required' })
1265
+ const theirs = [...channels].filter(([, c]) => c.session === body.session)
1266
+ if (theirs.some(([, c]) => c.confirmed)) return sendJson(res, 200, { confirmed: true })
1267
+ for (const [id, c] of theirs) {
1268
+ const code = pingCode()
1269
+ pings.set(code, id)
1270
+ c.send('ping', { code })
1271
+ }
1272
+ return sendJson(res, 200, { sent: theirs.length })
1273
+ }
1274
+ if (p === '/api/page' || p === '/api/render') {
1275
+ const r = await resolve(q.page ?? '', '/')
1276
+ if (!('page' in r)) return sendJson(res, 404, { error: 'notFound' in r ? r.notFound : 'not a page' })
1277
+ if (p === '/api/page') return sendJson(res, 200, r.page)
1278
+ const { out, notices } = await render(r.page)
1279
+ return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime, frontmatter: frontmatterOf(r.page) })
1280
+ }
1281
+ if (p === '/api/watch') {
1282
+ res.writeHead(200, {
1283
+ 'content-type': 'text/event-stream',
1284
+ 'cache-control': 'no-store',
1285
+ connection: 'keep-alive',
1286
+ })
1287
+ res.write(': connected\n\n')
1288
+ const client: WatchClient = {
1289
+ send: (event, data = {}) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
1290
+ page: q.page || '',
1291
+ isDir: 'dir' in q,
1292
+ }
1293
+ clients.add(client)
1294
+ // a tab from before /api/live: onto the WebSocket, which leaves its connection free
1295
+ client.send('reload')
1296
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
1297
+ const end = () => {
1298
+ clearInterval(ping)
1299
+ clients.delete(client)
1300
+ streams.delete(end)
1301
+ }
1302
+ streams.add(() => {
1303
+ end()
1304
+ res.end()
1305
+ })
1306
+ req.on('close', end)
1307
+ return
1308
+ }
1309
+
1310
+ const path_ = p.replace(/^\/+/, '').replace(/\/+$/, '')
1311
+ // a page is named without .md; a repository path is the file's own
1312
+ const id = isRepoId(path_) ? path_ : path_.replace(/\.md$/, '')
1313
+ const r = await resolve(id, p)
1314
+ if ('redirect' in r) {
1315
+ res.writeHead(302, { location: r.redirect + url.search })
1316
+ res.end()
1317
+ return
1318
+ }
1319
+ if ('raw' in r) return sendFile(res, r.raw)
1320
+ if ('notFound' in r) {
1321
+ // rendered as a page, with the page's styles and the plugins', and live: it becomes the page
1322
+ // once the page is there. The message holds the path from the URL: escaped, so it shows as
1323
+ // written and makes no markup or block
1324
+ const said = r.notFound.replace(/[\\`*_[\]{}()<>#!:|~&-]/g, '\\$&')
1325
+ const md = `# Not found\n\n${said}\n`
1326
+ const missing: PageSource = { kind: 'page', id, file: '', mtime: null, source: md, body: md, frontmatter: {} }
1327
+ return send(res, 404, await page(req, missing, await render(missing)))
1328
+ }
1329
+ return send(res, 200, await page(req, r.page, await render(r.page)))
1330
+ } catch (err) {
1331
+ console.error(err)
1332
+ send(res, 500, String((err as Error)?.stack || err), 'text/plain')
1333
+ }
1334
+ }
1335
+
1336
+ /** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
1337
+ function upgrade(req: IncomingMessage, conn: Duplex, _head: Buffer) {
1338
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
1339
+ if (decodeURIComponent(url.pathname) !== '/api/live') return refuse(conn, 404, 'Not Found')
1340
+ // no CORS for a WebSocket: any site could open one to localhost, so the origin is checked here
1341
+ if (!sameSite(req, origins())) return refuse(conn, 403, 'Forbidden')
1342
+ const socket = accept(req, conn)
1343
+ if (!socket) return
1344
+ const client: WatchClient = {
1345
+ send: (event, data = {}) => socket.send(JSON.stringify({ event, data })),
1346
+ page: url.searchParams.get('page') ?? '',
1347
+ isDir: url.searchParams.has('dir'),
1348
+ }
1349
+ if (!isRepoId(client.page) && !client.page.startsWith('_/')) watchPage(client.page)
1350
+ clients.add(client)
1351
+ const stop = () => socket.close()
1352
+ streams.add(stop)
1353
+ socket.onClose(() => {
1354
+ clients.delete(client)
1355
+ streams.delete(stop)
1356
+ })
1357
+ }
1358
+
1359
+ return {
1360
+ handle,
1361
+ upgrade,
1362
+ listeners: () => listenersFor(null),
1363
+ async files() {
1364
+ await config()
1365
+ return !!FILES
1366
+ },
1367
+ touch() {
1368
+ for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
1369
+ },
1370
+ elsewhere: () => notifyAll('elsewhere'),
1371
+ addListener: l => registry.add(l),
1372
+ onListeners: fn => registry.onChange(fn),
1373
+ status: (page = null) => status(page),
1374
+ read: readList,
1375
+ stream,
1376
+ config,
1377
+ build: options => build({ project, config, hooks: pluginHooks, files: () => !!FILES }, options),
1378
+ close() {
1379
+ for (const w of watchers) w.close()
1380
+ watchers.clear()
1381
+ for (const stop of [...streams]) stop()
1382
+ clearTimeout(reloadTimer)
1383
+ },
1384
+ }
1385
+ }