@bigmistqke/whiteboard 0.5.0 → 0.6.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 (106) hide show
  1. package/README.md +125 -25
  2. package/bin/whiteboard.ts +299 -16
  3. package/dist/bin/whiteboard.js +247 -17
  4. package/dist/client/runtime.js +22 -10
  5. package/dist/plugins/ansi/README.md +36 -0
  6. package/dist/plugins/ansi/index.js +64 -0
  7. package/dist/plugins/ansi/public/style.css +28 -0
  8. package/dist/plugins/badge/README.md +28 -0
  9. package/dist/plugins/badge/index.js +24 -0
  10. package/dist/plugins/badge/public/style.css +30 -0
  11. package/dist/plugins/chat/public/style.css +7 -2
  12. package/dist/plugins/code/README.md +4 -2
  13. package/dist/plugins/code/diff.js +12 -2
  14. package/dist/plugins/grid/README.md +12 -12
  15. package/dist/plugins/grid/index.js +7 -19
  16. package/dist/plugins/grid/public/style.css +4 -33
  17. package/dist/plugins/iframe/README.md +7 -7
  18. package/dist/plugins/iframe/index.js +11 -11
  19. package/dist/plugins/iframe/public/style.css +15 -0
  20. package/dist/plugins/index.js +7 -3
  21. package/dist/plugins/lightbox/README.md +22 -0
  22. package/dist/plugins/lightbox/index.js +20 -0
  23. package/dist/plugins/lightbox/public/client.js +4 -0
  24. package/dist/plugins/lightbox/public/style.css +66 -0
  25. package/dist/plugins/steps/README.md +3 -3
  26. package/dist/plugins/steps/index.js +3 -42
  27. package/dist/plugins/steps/public/client.js +1 -1
  28. package/dist/plugins/terminal/host.js +1 -1
  29. package/dist/plugins/terminal/public/client.js +1 -1
  30. package/dist/plugins/window/README.md +34 -14
  31. package/dist/plugins/window/index.js +21 -13
  32. package/dist/src/auth.js +4 -3
  33. package/dist/src/client/page/base.css +61 -1
  34. package/dist/src/client/page/main.js +60 -14
  35. package/dist/src/entries.js +211 -0
  36. package/dist/src/events.js +1 -1
  37. package/dist/src/hub.js +272 -0
  38. package/dist/src/loader.js +4 -1
  39. package/dist/src/package.js +23 -1
  40. package/dist/src/pages/blocks.js +1 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +87 -33
  43. package/dist/src/pages/render.js +116 -14
  44. package/dist/src/pages/window.js +16 -18
  45. package/dist/src/running.js +37 -2
  46. package/dist/src/serve.js +111 -2
  47. package/dist/src/server.js +49 -14
  48. package/package.json +1 -1
  49. package/plugins/ansi/README.md +36 -0
  50. package/plugins/ansi/index.ts +95 -0
  51. package/plugins/ansi/public/style.css +28 -0
  52. package/plugins/badge/README.md +28 -0
  53. package/plugins/badge/index.ts +35 -0
  54. package/plugins/badge/public/style.css +30 -0
  55. package/plugins/chat/public/style.css +7 -2
  56. package/plugins/code/README.md +4 -2
  57. package/plugins/code/diff.ts +14 -2
  58. package/plugins/grid/README.md +12 -12
  59. package/plugins/grid/index.ts +11 -26
  60. package/plugins/grid/public/style.css +4 -33
  61. package/plugins/iframe/README.md +7 -7
  62. package/plugins/iframe/index.ts +15 -15
  63. package/plugins/iframe/public/style.css +15 -0
  64. package/plugins/index.ts +6 -2
  65. package/plugins/lightbox/README.md +22 -0
  66. package/plugins/lightbox/client.ts +99 -0
  67. package/plugins/lightbox/index.ts +25 -0
  68. package/plugins/lightbox/public/style.css +66 -0
  69. package/plugins/steps/README.md +3 -3
  70. package/plugins/steps/client.ts +15 -6
  71. package/plugins/steps/index.ts +3 -46
  72. package/plugins/terminal/client.ts +16 -7
  73. package/plugins/window/README.md +34 -14
  74. package/plugins/window/index.ts +20 -13
  75. package/skills/whiteboard/SKILL.md +18 -10
  76. package/src/auth.ts +5 -3
  77. package/src/client/base.ts +19 -0
  78. package/src/client/forms.ts +2 -1
  79. package/src/client/markdown.ts +2 -1
  80. package/src/client/page/base.css +61 -1
  81. package/src/client/page/elsewhere.ts +72 -16
  82. package/src/client/page/fresh.ts +2 -1
  83. package/src/client/page/sort.ts +2 -1
  84. package/src/client/runtime.ts +11 -9
  85. package/src/define.ts +66 -7
  86. package/src/entries.ts +258 -0
  87. package/src/events.ts +2 -1
  88. package/src/hub.ts +355 -0
  89. package/src/loader.ts +7 -1
  90. package/src/package.ts +22 -0
  91. package/src/pages/blocks.ts +3 -0
  92. package/src/pages/index.ts +4 -2
  93. package/src/pages/markdown.ts +89 -32
  94. package/src/pages/render.ts +134 -13
  95. package/src/pages/window.ts +16 -25
  96. package/src/running.ts +47 -1
  97. package/src/serve.ts +114 -1
  98. package/src/server.ts +80 -14
  99. package/dist/plugins/gallery/README.md +0 -30
  100. package/dist/plugins/gallery/index.js +0 -75
  101. package/dist/plugins/gallery/public/client.js +0 -1
  102. package/dist/plugins/gallery/public/style.css +0 -90
  103. package/plugins/gallery/README.md +0 -30
  104. package/plugins/gallery/client.tsx +0 -70
  105. package/plugins/gallery/index.ts +0 -89
  106. package/plugins/gallery/public/style.css +0 -90
package/src/entries.ts ADDED
@@ -0,0 +1,258 @@
1
+ // The machine's entries: the projects one shared server serves, found from include and exclude globs
2
+ // in the machine config (`config.json` in the machine folder, see machineDir).
3
+ //
4
+ // { "port": 4777,
5
+ // "entries": { "rg": {
6
+ // "include": ["~/rg/develop", "~/rg/develop/.claude/worktrees/*", "~/rg/worksite/jobs/*"],
7
+ // "exclude": ["~/rg/worksite/archive/**"] } } }
8
+ //
9
+ // Every folder an include matches, that no exclude matches and that has a `.whiteboard/` folder, is
10
+ // a project of that entry. It is served at /<entry>/<path>/: <path> is the include's last literal
11
+ // folder and what its wildcards matched (`develop`, `worktrees/cmux`, `jobs/2026-11-19-x`), with
12
+ // `-2`, `-3` on a collision. Discovery is a pure function of the config and the disk, so the server
13
+ // runs it again to see projects come and go.
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+
18
+ /** One entry of the machine config: which folders are its projects. */
19
+ export interface EntryConfig {
20
+ include: string[]
21
+ exclude?: string[]
22
+ }
23
+
24
+ /** The machine config: the shared server's port and its entries. */
25
+ export interface MachineConfig {
26
+ port?: number
27
+ entries: Record<string, EntryConfig>
28
+ }
29
+
30
+ /** A project found for an entry: its folder, and the path it is served under (`/rg/develop`). */
31
+ export interface EntryProject {
32
+ entry: string
33
+ /** the include's last plain folder: what kind of checkout it is (`develop`, `worktrees`, `jobs`) */
34
+ group: string
35
+ /** what its wildcards matched (`cmux`); '' for an include without any */
36
+ name: string
37
+ dir: string
38
+ /** the URL path it is served under, without a trailing slash: /<entry>/<path> */
39
+ base: string
40
+ }
41
+
42
+ /**
43
+ * The machine folder: the machine config, `config.json`. `$WHITEBOARD_HOME`, else
44
+ * `$XDG_CONFIG_HOME/whiteboard`, else `~/.config/whiteboard`. The shared server only reads it: what
45
+ * runs in the server (any project's plugins) must not change which folders it serves, nor how it is
46
+ * started (see Entries in DESIGN.md).
47
+ */
48
+ export function machineDir(env: NodeJS.ProcessEnv = process.env): string {
49
+ if (env.WHITEBOARD_HOME) return path.resolve(env.WHITEBOARD_HOME)
50
+ const xdg = env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
51
+ return path.join(xdg, 'whiteboard')
52
+ }
53
+
54
+ /**
55
+ * The shared server's own folder, which it writes: its record (`server.json`), its log, the lock of
56
+ * a start, and the overview's project. `$WHITEBOARD_STATE`, else `state/` in `$WHITEBOARD_HOME`
57
+ * when that is set (a throwaway machine, in tests), else `$XDG_STATE_HOME/whiteboard`, else
58
+ * `~/.local/state/whiteboard`.
59
+ */
60
+ export function stateDir(env: NodeJS.ProcessEnv = process.env): string {
61
+ if (env.WHITEBOARD_STATE) return path.resolve(env.WHITEBOARD_STATE)
62
+ if (env.WHITEBOARD_HOME) return path.join(path.resolve(env.WHITEBOARD_HOME), 'state')
63
+ const xdg = env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state')
64
+ return path.join(xdg, 'whiteboard')
65
+ }
66
+
67
+ export const machineConfigFile = (dir = machineDir()) => path.join(dir, 'config.json')
68
+ export const machineServerFile = (dir = stateDir()) => path.join(dir, 'server.json')
69
+ export const machineLogFile = (dir = stateDir()) => path.join(dir, 'server.log')
70
+
71
+ const NAME = /^[a-z0-9][a-z0-9._-]*$/i
72
+ // a served path's first part is an entry's name: these are the server's own
73
+ const RESERVED = new Set(['api', '_', '-'])
74
+
75
+ /** The machine config, checked; null when there is none. Throws on one that is malformed. */
76
+ export function readMachineConfig(dir = machineDir()): MachineConfig | null {
77
+ const file = machineConfigFile(dir)
78
+ let text: string
79
+ try {
80
+ text = fs.readFileSync(file, 'utf8')
81
+ } catch {
82
+ return null
83
+ }
84
+ let raw: any
85
+ try {
86
+ raw = JSON.parse(text)
87
+ } catch (err) {
88
+ throw new Error(`${file}: ${(err as Error).message}`)
89
+ }
90
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${file}: must be an object`)
91
+ const entries: Record<string, EntryConfig> = {}
92
+ for (const [name, e] of Object.entries((raw.entries ?? {}) as Record<string, any>)) {
93
+ if (!NAME.test(name) || RESERVED.has(name))
94
+ throw new Error(`${file}: entry name ${JSON.stringify(name)}: letters, digits, . _ - only, and not api, _ or -`)
95
+ const list = (v: unknown, what: string): string[] => {
96
+ if (v == null) return []
97
+ if (!Array.isArray(v) || v.some(x => typeof x !== 'string'))
98
+ throw new Error(`${file}: entries.${name}.${what} must be a list of globs`)
99
+ return v
100
+ }
101
+ entries[name] = { include: list(e?.include, 'include'), exclude: list(e?.exclude, 'exclude') }
102
+ }
103
+ const port = raw.port == null ? undefined : Number(raw.port)
104
+ if (port !== undefined && !(Number.isInteger(port) && port > 0 && port < 65536))
105
+ throw new Error(`${file}: port must be a port number`)
106
+ return { ...(port !== undefined && { port }), entries }
107
+ }
108
+
109
+ /** `~` and `~/…` as the home folder; the rest resolved, with / separators. */
110
+ export const expandHome = (p: string, home = os.homedir()): string =>
111
+ path
112
+ .resolve(p.replace(/^~(?=$|[\\/])/, home))
113
+ .split(path.sep)
114
+ .join('/')
115
+
116
+ const isGlobPart = (part: string) => /[*?[\]{}!]/.test(part)
117
+
118
+ const hasWhiteboard = (dir: string) => {
119
+ try {
120
+ return fs.statSync(path.join(dir, '.whiteboard')).isDirectory()
121
+ } catch {
122
+ return false
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Where a folder an include matched goes in its entry: its group, the include's last plain folder
128
+ * before the first wildcard (`worktrees`), and its name, what the wildcards matched (`cmux`). An
129
+ * include without wildcards is a group of one, named by the folder (`develop`).
130
+ */
131
+ function placeOf(include: string, dir: string): { group: string; name: string } {
132
+ const parts = include.split('/')
133
+ const wild = parts.findIndex(isGlobPart)
134
+ if (wild < 0) return { group: path.basename(dir), name: '' }
135
+ const literal = parts.slice(0, wild).join('/')
136
+ return { group: parts[wild - 1] ?? '', name: path.relative(literal, dir).split(path.sep).join('/') }
137
+ }
138
+
139
+ /** Is this folder one an exclude glob leaves out (the folder itself, or one it is inside)? */
140
+ const excluded = (dir: string, excludes: string[]) =>
141
+ excludes.some(g => {
142
+ for (let d = dir; ; d = path.posix.dirname(d)) {
143
+ if (path.posix.matchesGlob(d, g)) return true
144
+ if (path.posix.dirname(d) === d) return false
145
+ }
146
+ })
147
+
148
+ /**
149
+ * Every project of the machine config's entries, in config order: the folders an include matches,
150
+ * no exclude matches, with a `.whiteboard/` folder. A folder two includes match is one project, the
151
+ * first include's. `home`: what `~` means (for tests).
152
+ */
153
+ export function discover(config: MachineConfig, { home = os.homedir() }: { home?: string } = {}): EntryProject[] {
154
+ const out: EntryProject[] = []
155
+ const seen = new Set<string>()
156
+ const taken = new Set<string>()
157
+ for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
158
+ const excludes = exclude.map(g => expandHome(g, home))
159
+ for (const glob of include.map(g => expandHome(g, home))) {
160
+ const dirs = glob.split('/').some(isGlobPart)
161
+ ? fs
162
+ .globSync(glob)
163
+ .map(d => path.resolve(d))
164
+ .toSorted()
165
+ : [glob]
166
+ for (const dir of dirs) {
167
+ const posix = dir.split(path.sep).join('/')
168
+ if (seen.has(dir) || excluded(posix, excludes) || !hasWhiteboard(dir)) continue
169
+ seen.add(dir)
170
+ const place = placeOf(glob, posix)
171
+ const wanted = `/${entry}/${[place.group, place.name].filter(Boolean).join('/')}`
172
+ let base = wanted
173
+ let n = 1
174
+ while (taken.has(base)) base = `${wanted}-${++n}`
175
+ taken.add(base)
176
+ // a second one wanting the same path is named apart the same way
177
+ const name = n > 1 ? (place.name ? `${place.name}-${n}` : '') : place.name
178
+ out.push({ entry, group: n > 1 && !place.name ? `${place.group}-${n}` : place.group, name, dir, base })
179
+ }
180
+ }
181
+ }
182
+ return out
183
+ }
184
+
185
+ /** Does any include of the machine config match this folder, no exclude leaving it out? Cheap: no globbing of the disk. */
186
+ export function matchesEntries(config: MachineConfig, dir: string, { home = os.homedir() } = {}): string | null {
187
+ const posix = path.resolve(dir).split(path.sep).join('/')
188
+ for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
189
+ const excludes = exclude.map(g => expandHome(g, home))
190
+ if (include.some(g => path.posix.matchesGlob(posix, expandHome(g, home))) && !excluded(posix, excludes))
191
+ return entry
192
+ }
193
+ return null
194
+ }
195
+
196
+ /**
197
+ * Follow the entries' projects: `onChange` gets the projects each time the set changes. Watching
198
+ * globs over the disk in general would mean watching every folder they could match, so it looks
199
+ * again every `interval` ms (cheap: a few folder listings), and at once when told (`rescan`).
200
+ */
201
+ export function followEntries(
202
+ read: () => MachineConfig | null,
203
+ onChange: (projects: EntryProject[]) => void,
204
+ { interval = 1500, home }: { interval?: number; home?: string } = {},
205
+ ) {
206
+ let last = ''
207
+ let current: EntryProject[] = []
208
+ const rescan = () => {
209
+ let projects: EntryProject[] = []
210
+ try {
211
+ const config = read()
212
+ projects = config ? discover(config, { home }) : []
213
+ } catch (err) {
214
+ console.error(`whiteboard: entries: ${(err as Error).message}`)
215
+ return current
216
+ }
217
+ const key = JSON.stringify(projects)
218
+ if (key !== last) {
219
+ last = key
220
+ current = projects
221
+ onChange(projects)
222
+ }
223
+ return current
224
+ }
225
+ rescan()
226
+ const timer = setInterval(rescan, interval)
227
+ timer.unref()
228
+ return { rescan, projects: () => current, stop: () => clearInterval(timer) }
229
+ }
230
+
231
+ /**
232
+ * The folders the entries' projects can be in: each include up to its first wildcard (all of it
233
+ * when it has none), without those inside another. What the shared server must be able to write,
234
+ * whatever folders appear below them later.
235
+ */
236
+ export function entryFolders(config: MachineConfig, { home = os.homedir() }: { home?: string } = {}): string[] {
237
+ const roots = Object.values(config.entries).flatMap(e =>
238
+ e.include.map(g => {
239
+ const parts = expandHome(g, home).split('/')
240
+ const wild = parts.findIndex(isGlobPart)
241
+ return wild < 0 ? parts.join('/') : parts.slice(0, wild).join('/') || '/'
242
+ }),
243
+ )
244
+ const unique = [...new Set(roots)].toSorted()
245
+ return unique.filter(r => !unique.some(o => o !== r && (r.startsWith(o + '/') || o === '/')))
246
+ }
247
+
248
+ /**
249
+ * What the shared server needs of the disk, for whatever boxes it in (a sandbox wrapper, see
250
+ * `whiteboard paths`): `write`, the entries' folders and its own state folder; `read`, the machine
251
+ * config and whiteboard itself.
252
+ */
253
+ export function serverPaths(
254
+ config: MachineConfig,
255
+ { home, packageDir, env = process.env }: { home?: string; packageDir: string; env?: NodeJS.ProcessEnv },
256
+ ): { write: string[]; read: string[] } {
257
+ return { write: [...entryFolders(config, { home }), stateDir(env)], read: [machineDir(env), packageDir] }
258
+ }
package/src/events.ts CHANGED
@@ -348,7 +348,8 @@ export function handOut(
348
348
  const hand = (e: WbEvent) => {
349
349
  onEvent(e)
350
350
  pick(file, e)
351
- return ++got < count
351
+ // onEvent may have aborted it (a hand-out over several logs that has enough)
352
+ return ++got < count && !signal?.aborted
352
353
  }
353
354
  // the events left for now (skip), by id
354
355
  const left = new Map<string, WbEvent>()
package/src/hub.ts ADDED
@@ -0,0 +1,355 @@
1
+ // The shared server: one per machine, serving every project of the machine config's entries, each
2
+ // under its own path (see entries.ts). A request handler like a project's server, so tests make one
3
+ // for a throwaway machine folder and send it requests; listening and its record are serve.ts.
4
+ //
5
+ // / the overview: every project's pages, by project, what waits for the reader first;
6
+ // a project of the server's own (overview/ in the machine folder), rendered and
7
+ // live like any project's overview
8
+ // /<entry>/<path>/… a project, as its own server serves it at / (createServer with a base)
9
+ // /api/health { hub: true, pid, version, projects }; `?rescan` looks for projects first
10
+ // /api/index every project's pages and what is open on them, as JSON (?entry=: one entry's),
11
+ // for a page's menu of what waits elsewhere
12
+ // /api/shutdown POST { version }: a newer whiteboard takes over; an older one is refused
13
+ // /api/listen?entry=<name>&command=wait|watch
14
+ // the fallback of a whole entry, for as long as the connection is open: one per
15
+ // entry, held on every page of its projects, also those that appear meanwhile
16
+ //
17
+ // A project's server is made when the project is found and closed when it goes, so a project
18
+ // appears and disappears without a restart. Each keeps its own state, config and log, as it would
19
+ // on a port of its own: the shared server only routes.
20
+ import fs from 'node:fs'
21
+ import path from 'node:path'
22
+ import type { IncomingMessage, ServerResponse } from 'node:http'
23
+ import { project as projectAt, type Project } from './config.ts'
24
+ import { followEntries, machineDir, readMachineConfig, stateDir, type EntryProject } from './entries.ts'
25
+ import { compareVersions, VERSION } from './package.ts'
26
+ import { createServer, type WhiteboardServer } from './server.ts'
27
+ import type { Listener, PageStatus } from './define.ts'
28
+
29
+ export interface HubOptions {
30
+ /** the machine folder (its config.json), which the server only reads; default machineDir() */
31
+ dir?: string
32
+ /** the server's own folder, which it writes (the overview's project); default stateDir() */
33
+ state?: string
34
+ /** what `~` means in the globs (tests) */
35
+ home?: string
36
+ /** how often to look for projects coming and going, in ms */
37
+ interval?: number
38
+ /** a newer whiteboard asked this one to make way (POST /api/shutdown) */
39
+ onShutdown?: () => void
40
+ /** the version this server says it is (tests); default the package's */
41
+ version?: string
42
+ }
43
+
44
+ /** A project the shared server serves: where, and its own server. */
45
+ interface Served extends EntryProject {
46
+ project: Project
47
+ server: WhiteboardServer
48
+ /** removes the entry's fallback from this project, while it holds one */
49
+ fallback?: () => void
50
+ }
51
+
52
+ /** A page, as /api/index gives it. */
53
+ export interface IndexPage {
54
+ page: string
55
+ title: string
56
+ url: string
57
+ /** when its file last changed, in ms */
58
+ mtime: number
59
+ /** its questions waiting for the reader */
60
+ open: string[]
61
+ /** the agent's messages on it the reader hasn't read */
62
+ unread: number
63
+ /** the reader's answers no agent picked up */
64
+ unpicked: number
65
+ }
66
+
67
+ /** A project, as /api/index gives it. */
68
+ export interface IndexProject {
69
+ entry: string
70
+ group: string
71
+ name: string
72
+ /** how the reader knows it: `develop`, `worktrees › cmux` */
73
+ label: string
74
+ dir: string
75
+ base: string
76
+ /** its pages, the latest changed first */
77
+ pages: IndexPage[]
78
+ /** when one of its pages last changed; 0 without pages */
79
+ active: number
80
+ error?: string
81
+ }
82
+
83
+ export interface Hub {
84
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>
85
+ /** the projects it serves now */
86
+ projects(): EntryProject[]
87
+ /** look for projects coming and going now */
88
+ rescan(): EntryProject[]
89
+ close(): void
90
+ }
91
+
92
+ export function createHub({
93
+ dir = machineDir(),
94
+ state = stateDir(),
95
+ home,
96
+ interval,
97
+ onShutdown,
98
+ version = VERSION,
99
+ }: HubOptions = {}): Hub {
100
+ const served = new Map<string, Served>()
101
+ // each entry's fallback, while one runs: the listener its projects hold
102
+ const fallbacks = new Map<string, Listener>()
103
+
104
+ function sync(projects: EntryProject[]) {
105
+ // projects come and go: the overview lists them
106
+ setImmediate(() => touch())
107
+ const wanted = new Map(projects.map(p => [`${p.base}\n${p.dir}`, p]))
108
+ for (const [key, s] of served)
109
+ if (!wanted.has(key)) {
110
+ s.server.close()
111
+ served.delete(key)
112
+ console.log(`whiteboard: ${s.base} is gone (${s.dir})`)
113
+ }
114
+ for (const [key, p] of wanted) {
115
+ if (served.has(key)) continue
116
+ const project = projectAt(p.dir)
117
+ if (!project) continue
118
+ const server = createServer(project, {
119
+ base: p.base,
120
+ entry: p.entry,
121
+ label: [p.group, p.name].filter(Boolean).join(' › '),
122
+ onChange: () => touch(),
123
+ })
124
+ const fallback = fallbacks.get(p.entry)
125
+ served.set(key, { ...p, project, server, ...(fallback && { fallback: server.addListener(fallback) }) })
126
+ console.log(`whiteboard: ${p.base} → ${p.dir}`)
127
+ }
128
+ }
129
+
130
+ // the overview at /: a project of the shared server's own, in the machine folder, whose overview
131
+ // lists every project's pages; rendered and live like any project's, so it looks like one
132
+ const overviewDir = path.join(state, 'overview')
133
+ fs.mkdirSync(path.join(overviewDir, '.whiteboard', 'pages'), { recursive: true })
134
+ const root = createServer(projectAt(overviewDir)!, {
135
+ name: 'whiteboard',
136
+ files: false,
137
+ overview: async () => {
138
+ const all = await Promise.all(
139
+ [...served.values()].map(async s => ({
140
+ title: [s.group, s.name].filter(Boolean).join(' › '),
141
+ base: s.base,
142
+ dir: s.dir,
143
+ ...(await s.server.overview().catch(() => ({ pages: [], files: false }))),
144
+ })),
145
+ )
146
+ const boxed = (process.env.WHITEBOARD_SANDBOX ?? '').split(':').filter(Boolean)
147
+ return {
148
+ groups: all.filter(g => g.pages.length).toSorted((a, b) => (b.pages[0]?.mtime ?? 0) - (a.pages[0]?.mtime ?? 0)),
149
+ empty: all.filter(g => !g.pages.length).map(({ title, base }) => ({ title, base })),
150
+ note: `whiteboard ${version} · ${boxed.length ? `boxed: ${boxed.join(', ')}` : 'not boxed'} · ${dir}/config.json`,
151
+ }
152
+ },
153
+ })
154
+ // what the overview lists changed: told a moment later, once for several changes
155
+ let touching: ReturnType<typeof setTimeout> | undefined
156
+ const touch = () => {
157
+ clearTimeout(touching)
158
+ touching = setTimeout(() => root.touch(), 150)
159
+ }
160
+
161
+ const entries = followEntries(() => readMachineConfig(dir), sync, { interval, home })
162
+
163
+ /** The project a path is under: the longest base that is the path or a folder above it. */
164
+ const owner = (p: string): Served | null => {
165
+ let best: Served | null = null
166
+ for (const s of served.values())
167
+ if ((p === s.base || p.startsWith(s.base + '/')) && (!best || s.base.length > best.base.length)) best = s
168
+ return best
169
+ }
170
+
171
+ async function index(): Promise<IndexProject[]> {
172
+ return Promise.all(
173
+ [...served.values()].map(async (s): Promise<IndexProject> => {
174
+ const at = {
175
+ entry: s.entry,
176
+ group: s.group,
177
+ name: s.name,
178
+ label: [s.group, s.name].filter(Boolean).join(' › '),
179
+ dir: s.dir,
180
+ base: s.base,
181
+ }
182
+ let statuses: PageStatus[]
183
+ try {
184
+ statuses = await s.server.status()
185
+ } catch (err) {
186
+ return { ...at, pages: [], active: 0, error: (err as Error).message }
187
+ }
188
+ const pages = statuses
189
+ .map((p): IndexPage => ({
190
+ page: p.page,
191
+ title: p.title,
192
+ url: `${s.base}/${p.page.split('/').map(encodeURIComponent).join('/')}`,
193
+ mtime: mtimeOf(p.file),
194
+ open: p.open,
195
+ unread: p.unread.length,
196
+ unpicked: p.unpicked.length,
197
+ }))
198
+ .toSorted((a, b) => b.mtime - a.mtime)
199
+ return { ...at, pages, active: pages[0]?.mtime ?? 0 }
200
+ }),
201
+ )
202
+ }
203
+
204
+ const send = (res: ServerResponse, status: number, body: string, type = 'text/html; charset=utf-8') => {
205
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
206
+ res.end(body)
207
+ }
208
+ const sendJson = (res: ServerResponse, status: number, data: unknown) =>
209
+ send(res, status, JSON.stringify(data), 'application/json')
210
+ const list = () =>
211
+ [...served.values()].map(({ entry, group, name, dir, base }) => ({ entry, group, name, dir, base }))
212
+
213
+ function readBody(req: IncomingMessage): Promise<string> {
214
+ return new Promise((resolve, reject) => {
215
+ let body = ''
216
+ req.setEncoding('utf8')
217
+ req.on('data', c => {
218
+ body += c
219
+ if (body.length > 1e4) req.destroy()
220
+ })
221
+ req.on('end', () => resolve(body))
222
+ req.on('error', reject)
223
+ })
224
+ }
225
+
226
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
227
+ try {
228
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
229
+ const p = decodeURIComponent(url.pathname)
230
+ if (p === '/api/health') {
231
+ if (url.searchParams.has('rescan')) entries.rescan()
232
+ return sendJson(res, 200, { ok: true, hub: true, pid: process.pid, version, dir, projects: list() })
233
+ }
234
+ if (p === '/api/index') {
235
+ const entry = url.searchParams.get('entry')
236
+ return sendJson(
237
+ res,
238
+ 200,
239
+ (await index()).filter(x => !entry || x.entry === entry),
240
+ )
241
+ }
242
+ if (p === '/api/shutdown' && req.method === 'POST') {
243
+ // only from the command line: a page of a project has an Origin
244
+ if (req.headers.origin) return sendJson(res, 403, { error: 'not from a browser' })
245
+ let asker = ''
246
+ try {
247
+ asker = String(JSON.parse(await readBody(req)).version ?? '')
248
+ } catch {}
249
+ // an older whiteboard never replaces a newer one, nor one as new
250
+ if (!asker || compareVersions(asker, version) <= 0)
251
+ return sendJson(res, 409, { error: `whiteboard ${version} runs here; ${asker || 'that'} is not newer` })
252
+ sendJson(res, 200, { ok: true, version })
253
+ setImmediate(() => onShutdown?.())
254
+ return
255
+ }
256
+ if (p === '/api/listen' && url.searchParams.has('entry')) return listenEntry(req, res, url.searchParams)
257
+ if (p === '/favicon.ico') {
258
+ res.writeHead(204)
259
+ return void res.end()
260
+ }
261
+ let s = owner(p)
262
+ let rest: string
263
+ if (s) {
264
+ // the project's overview is at its folder: /rg/develop/
265
+ if (p === s.base) {
266
+ res.writeHead(302, { location: `${s.base}/${url.search}` })
267
+ return void res.end()
268
+ }
269
+ // the path less the project's part, encoded again for the project's server to decode
270
+ rest = p.slice(s.base.length).split('/').map(encodeURIComponent).join('/') + url.search
271
+ } else {
272
+ // A plugin's browser module that writes `/api/<name>/…` itself, from before api.url: the page
273
+ // that asked is in the Referer, and the request is that project's.
274
+ const from = req.headers.referer ? new URL(req.headers.referer).pathname : null
275
+ s = /^\/(api|_)\//.test(p) && from ? owner(decodeURIComponent(from)) : null
276
+ // anything else outside the projects is the overview's: /, its page, its files and live channel
277
+ if (!s) return root.handle(req, res)
278
+ rest = (req.url ?? '/').replace(/^\/+/, '/')
279
+ }
280
+ req.url = rest
281
+ return s.server.handle(req, res)
282
+ } catch (err) {
283
+ console.error(err)
284
+ send(res, 500, String((err as Error)?.stack || err), 'text/plain')
285
+ }
286
+ }
287
+
288
+ /**
289
+ * The fallback of a whole entry (a `wait` or `watch` without --page in one of its projects): one
290
+ * per entry, refused (409) while another runs, or while a project of it has a fallback of its own
291
+ * (from a whiteboard before entries). Each project holds it as a listener, so its pages say an
292
+ * agent listens; the command itself reads the projects' logs.
293
+ */
294
+ function listenEntry(req: IncomingMessage, res: ServerResponse, q: URLSearchParams) {
295
+ const entry = q.get('entry')!
296
+ const projects = [...served.values()].filter(s => s.entry === entry)
297
+ if (fallbacks.has(entry)) return sendJson(res, 409, { error: `another agent is the fallback of ${entry} already` })
298
+ const own = projects.find(s => s.server.listeners().some(x => x.fallback))
299
+ if (own)
300
+ return sendJson(res, 409, {
301
+ error: `${own.base} has a fallback of its own already (a wait or watch without --page)`,
302
+ })
303
+ const l: Listener = {
304
+ page: '',
305
+ type: q.get('type') || null,
306
+ command: q.get('command') === 'wait' ? 'wait' : 'watch',
307
+ fallback: true,
308
+ }
309
+ fallbacks.set(entry, l)
310
+ for (const s of projects) s.fallback = s.server.addListener(l)
311
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
312
+ res.write(': listening\n\n')
313
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
314
+ const end = () => {
315
+ clearInterval(ping)
316
+ if (fallbacks.get(entry) !== l) return
317
+ fallbacks.delete(entry)
318
+ for (const s of served.values()) {
319
+ s.fallback?.()
320
+ delete s.fallback
321
+ }
322
+ }
323
+ closers.add(() => {
324
+ end()
325
+ res.end()
326
+ })
327
+ req.on('close', end)
328
+ }
329
+ const closers = new Set<() => void>()
330
+
331
+ return {
332
+ handle,
333
+ projects: list,
334
+ rescan() {
335
+ entries.rescan()
336
+ return list()
337
+ },
338
+ close() {
339
+ clearTimeout(touching)
340
+ root.close()
341
+ for (const c of closers) c()
342
+ entries.stop()
343
+ for (const s of served.values()) s.server.close()
344
+ served.clear()
345
+ },
346
+ }
347
+ }
348
+
349
+ const mtimeOf = (file: string) => {
350
+ try {
351
+ return fs.statSync(file).mtimeMs
352
+ } catch {
353
+ return 0
354
+ }
355
+ }
package/src/loader.ts CHANGED
@@ -51,6 +51,7 @@ export const BUILTIN_COMMANDS = new Set([
51
51
  'build',
52
52
  'edit',
53
53
  'skill',
54
+ 'paths',
54
55
  'help',
55
56
  ])
56
57
  // folders in .whiteboard/ that are the core's or meant for the project's own plugins (a plugin's own
@@ -135,7 +136,12 @@ export function createConfigLoader(proj: Project, { pages: withPages = true } =
135
136
  .filter(p => p.style)
136
137
  .map(p => ({ plugin: p.name, file: inPublic(publicDirs.get(p.name)!, p.style!, `plugin ${p.name}: style`) }))
137
138
  const links = plugins.flatMap(p => (p.links ? [p.links.bind(p)] : []))
138
- const pages = withPages ? createPages({ blocks, style: config?.style, styles, links }) : null
139
+ // the plugins that compose themselves around other blocks (Plugin.compose): a block with an
140
+ // attribute of their name
141
+ const composers = new Map(
142
+ plugins.flatMap(p => (typeof p.compose === 'function' ? [[p.name, p.compose.bind(p)] as const] : [])),
143
+ )
144
+ const pages = withPages ? createPages({ blocks, style: config?.style, styles, links, composers }) : null
139
145
  const declared = (flag: 'handOut' | 'forReader') =>
140
146
  new Set(
141
147
  plugins.flatMap(p =>
package/src/package.ts CHANGED
@@ -38,3 +38,25 @@ export const FROM_SOURCE = fileURLToPath(import.meta.url).endsWith('.ts')
38
38
  */
39
39
  /** A built-in plugin's public folder: its built browser modules and copied styles (build.ts). */
40
40
  export const builtinPublic = (name: string): string => packagePath('dist', 'plugins', name, 'public')
41
+
42
+ /** This package's version, from its package.json: what a shared server records, and its takeover compares. */
43
+ export const VERSION: string = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, 'package.json'), 'utf8')).version
44
+
45
+ /** Compare two versions, x.y.z with an optional -pre: < 0 when a is older, 0 when the same, > 0 when newer. */
46
+ export function compareVersions(a: string, b: string): number {
47
+ const parse = (v: string) => {
48
+ const [main, pre] = String(v).split('-', 2)
49
+ return { nums: main!.split('.').map(n => Number(n) || 0), pre: pre ?? null }
50
+ }
51
+ const x = parse(a)
52
+ const y = parse(b)
53
+ for (let i = 0; i < Math.max(x.nums.length, y.nums.length); i++) {
54
+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0)
55
+ if (d) return Math.sign(d)
56
+ }
57
+ // a release is newer than its pre-releases
58
+ if (x.pre === y.pre) return 0
59
+ if (x.pre == null) return 1
60
+ if (y.pre == null) return -1
61
+ return x.pre < y.pre ? -1 : 1
62
+ }