@bigmistqke/whiteboard 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +125 -25
- package/bin/whiteboard.ts +299 -16
- package/dist/bin/whiteboard.js +247 -17
- package/dist/client/runtime.js +22 -10
- package/dist/plugins/ansi/README.md +36 -0
- package/dist/plugins/ansi/index.js +64 -0
- package/dist/plugins/ansi/public/style.css +28 -0
- package/dist/plugins/badge/README.md +28 -0
- package/dist/plugins/badge/index.js +24 -0
- package/dist/plugins/badge/public/style.css +30 -0
- package/dist/plugins/chat/public/style.css +7 -2
- package/dist/plugins/code/README.md +4 -2
- package/dist/plugins/code/diff.js +12 -2
- package/dist/plugins/grid/README.md +12 -12
- package/dist/plugins/grid/index.js +7 -19
- package/dist/plugins/grid/public/style.css +4 -33
- package/dist/plugins/iframe/README.md +7 -7
- package/dist/plugins/iframe/index.js +11 -11
- package/dist/plugins/iframe/public/style.css +15 -0
- package/dist/plugins/index.js +7 -3
- package/dist/plugins/lightbox/README.md +22 -0
- package/dist/plugins/lightbox/index.js +20 -0
- package/dist/plugins/lightbox/public/client.js +4 -0
- package/dist/plugins/lightbox/public/style.css +66 -0
- package/dist/plugins/steps/README.md +3 -3
- package/dist/plugins/steps/index.js +3 -42
- package/dist/plugins/steps/public/client.js +1 -1
- package/dist/plugins/terminal/host.js +1 -1
- package/dist/plugins/terminal/public/client.js +1 -1
- package/dist/plugins/window/README.md +34 -14
- package/dist/plugins/window/index.js +21 -13
- package/dist/src/auth.js +4 -3
- package/dist/src/client/page/base.css +61 -1
- package/dist/src/client/page/main.js +60 -14
- package/dist/src/entries.js +217 -0
- package/dist/src/events.js +1 -1
- package/dist/src/hub.js +272 -0
- package/dist/src/loader.js +4 -1
- package/dist/src/package.js +23 -1
- package/dist/src/pages/blocks.js +1 -0
- package/dist/src/pages/index.js +1 -1
- package/dist/src/pages/markdown.js +87 -33
- package/dist/src/pages/render.js +116 -14
- package/dist/src/pages/window.js +16 -18
- package/dist/src/running.js +37 -2
- package/dist/src/serve.js +111 -2
- package/dist/src/server.js +49 -14
- package/package.json +1 -1
- package/plugins/ansi/README.md +36 -0
- package/plugins/ansi/index.ts +95 -0
- package/plugins/ansi/public/style.css +28 -0
- package/plugins/badge/README.md +28 -0
- package/plugins/badge/index.ts +35 -0
- package/plugins/badge/public/style.css +30 -0
- package/plugins/chat/public/style.css +7 -2
- package/plugins/code/README.md +4 -2
- package/plugins/code/diff.ts +14 -2
- package/plugins/grid/README.md +12 -12
- package/plugins/grid/index.ts +11 -26
- package/plugins/grid/public/style.css +4 -33
- package/plugins/iframe/README.md +7 -7
- package/plugins/iframe/index.ts +15 -15
- package/plugins/iframe/public/style.css +15 -0
- package/plugins/index.ts +6 -2
- package/plugins/lightbox/README.md +22 -0
- package/plugins/lightbox/client.ts +99 -0
- package/plugins/lightbox/index.ts +25 -0
- package/plugins/lightbox/public/style.css +66 -0
- package/plugins/steps/README.md +3 -3
- package/plugins/steps/client.ts +15 -6
- package/plugins/steps/index.ts +3 -46
- package/plugins/terminal/client.ts +16 -7
- package/plugins/window/README.md +34 -14
- package/plugins/window/index.ts +20 -13
- package/skills/whiteboard/SKILL.md +17 -10
- package/src/auth.ts +5 -3
- package/src/client/base.ts +19 -0
- package/src/client/forms.ts +2 -1
- package/src/client/markdown.ts +2 -1
- package/src/client/page/base.css +61 -1
- package/src/client/page/elsewhere.ts +72 -16
- package/src/client/page/fresh.ts +2 -1
- package/src/client/page/sort.ts +2 -1
- package/src/client/runtime.ts +11 -9
- package/src/define.ts +66 -7
- package/src/entries.ts +269 -0
- package/src/events.ts +2 -1
- package/src/hub.ts +355 -0
- package/src/loader.ts +7 -1
- package/src/package.ts +22 -0
- package/src/pages/blocks.ts +3 -0
- package/src/pages/index.ts +4 -2
- package/src/pages/markdown.ts +89 -32
- package/src/pages/render.ts +134 -13
- package/src/pages/window.ts +16 -25
- package/src/running.ts +47 -1
- package/src/serve.ts +114 -1
- package/src/server.ts +80 -14
- package/dist/plugins/gallery/README.md +0 -30
- package/dist/plugins/gallery/index.js +0 -75
- package/dist/plugins/gallery/public/client.js +0 -1
- package/dist/plugins/gallery/public/style.css +0 -90
- package/plugins/gallery/README.md +0 -30
- package/plugins/gallery/client.tsx +0 -70
- package/plugins/gallery/index.ts +0 -89
- package/plugins/gallery/public/style.css +0 -90
package/src/entries.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
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
|
+
/**
|
|
76
|
+
* The machine config, checked; null when there is none. Throws on one that is malformed, and on one
|
|
77
|
+
* that is there but can't be read (a sandbox without a grant for it), rather than taking it for none.
|
|
78
|
+
*/
|
|
79
|
+
export function readMachineConfig(dir = machineDir()): MachineConfig | null {
|
|
80
|
+
const file = machineConfigFile(dir)
|
|
81
|
+
let text: string
|
|
82
|
+
try {
|
|
83
|
+
text = fs.readFileSync(file, 'utf8')
|
|
84
|
+
} catch (err) {
|
|
85
|
+
const code = (err as NodeJS.ErrnoException).code
|
|
86
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') return null
|
|
87
|
+
// there, but not to be read: most likely a sandbox without a grant for it. Taken for absent, a
|
|
88
|
+
// command would start a server of the project's own beside the shared one that serves it
|
|
89
|
+
if (code === 'EPERM' || code === 'EACCES')
|
|
90
|
+
throw new Error(
|
|
91
|
+
`cannot read ${file} (${code}): if this runs in a sandbox, it needs a read grant for ${dir}. Without it, whiteboard can't tell which server serves this project`,
|
|
92
|
+
)
|
|
93
|
+
throw err
|
|
94
|
+
}
|
|
95
|
+
let raw: any
|
|
96
|
+
try {
|
|
97
|
+
raw = JSON.parse(text)
|
|
98
|
+
} catch (err) {
|
|
99
|
+
throw new Error(`${file}: ${(err as Error).message}`)
|
|
100
|
+
}
|
|
101
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${file}: must be an object`)
|
|
102
|
+
const entries: Record<string, EntryConfig> = {}
|
|
103
|
+
for (const [name, e] of Object.entries((raw.entries ?? {}) as Record<string, any>)) {
|
|
104
|
+
if (!NAME.test(name) || RESERVED.has(name))
|
|
105
|
+
throw new Error(`${file}: entry name ${JSON.stringify(name)}: letters, digits, . _ - only, and not api, _ or -`)
|
|
106
|
+
const list = (v: unknown, what: string): string[] => {
|
|
107
|
+
if (v == null) return []
|
|
108
|
+
if (!Array.isArray(v) || v.some(x => typeof x !== 'string'))
|
|
109
|
+
throw new Error(`${file}: entries.${name}.${what} must be a list of globs`)
|
|
110
|
+
return v
|
|
111
|
+
}
|
|
112
|
+
entries[name] = { include: list(e?.include, 'include'), exclude: list(e?.exclude, 'exclude') }
|
|
113
|
+
}
|
|
114
|
+
const port = raw.port == null ? undefined : Number(raw.port)
|
|
115
|
+
if (port !== undefined && !(Number.isInteger(port) && port > 0 && port < 65536))
|
|
116
|
+
throw new Error(`${file}: port must be a port number`)
|
|
117
|
+
return { ...(port !== undefined && { port }), entries }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `~` and `~/…` as the home folder; the rest resolved, with / separators. */
|
|
121
|
+
export const expandHome = (p: string, home = os.homedir()): string =>
|
|
122
|
+
path
|
|
123
|
+
.resolve(p.replace(/^~(?=$|[\\/])/, home))
|
|
124
|
+
.split(path.sep)
|
|
125
|
+
.join('/')
|
|
126
|
+
|
|
127
|
+
const isGlobPart = (part: string) => /[*?[\]{}!]/.test(part)
|
|
128
|
+
|
|
129
|
+
const hasWhiteboard = (dir: string) => {
|
|
130
|
+
try {
|
|
131
|
+
return fs.statSync(path.join(dir, '.whiteboard')).isDirectory()
|
|
132
|
+
} catch {
|
|
133
|
+
return false
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Where a folder an include matched goes in its entry: its group, the include's last plain folder
|
|
139
|
+
* before the first wildcard (`worktrees`), and its name, what the wildcards matched (`cmux`). An
|
|
140
|
+
* include without wildcards is a group of one, named by the folder (`develop`).
|
|
141
|
+
*/
|
|
142
|
+
function placeOf(include: string, dir: string): { group: string; name: string } {
|
|
143
|
+
const parts = include.split('/')
|
|
144
|
+
const wild = parts.findIndex(isGlobPart)
|
|
145
|
+
if (wild < 0) return { group: path.basename(dir), name: '' }
|
|
146
|
+
const literal = parts.slice(0, wild).join('/')
|
|
147
|
+
return { group: parts[wild - 1] ?? '', name: path.relative(literal, dir).split(path.sep).join('/') }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Is this folder one an exclude glob leaves out (the folder itself, or one it is inside)? */
|
|
151
|
+
const excluded = (dir: string, excludes: string[]) =>
|
|
152
|
+
excludes.some(g => {
|
|
153
|
+
for (let d = dir; ; d = path.posix.dirname(d)) {
|
|
154
|
+
if (path.posix.matchesGlob(d, g)) return true
|
|
155
|
+
if (path.posix.dirname(d) === d) return false
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Every project of the machine config's entries, in config order: the folders an include matches,
|
|
161
|
+
* no exclude matches, with a `.whiteboard/` folder. A folder two includes match is one project, the
|
|
162
|
+
* first include's. `home`: what `~` means (for tests).
|
|
163
|
+
*/
|
|
164
|
+
export function discover(config: MachineConfig, { home = os.homedir() }: { home?: string } = {}): EntryProject[] {
|
|
165
|
+
const out: EntryProject[] = []
|
|
166
|
+
const seen = new Set<string>()
|
|
167
|
+
const taken = new Set<string>()
|
|
168
|
+
for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
|
|
169
|
+
const excludes = exclude.map(g => expandHome(g, home))
|
|
170
|
+
for (const glob of include.map(g => expandHome(g, home))) {
|
|
171
|
+
const dirs = glob.split('/').some(isGlobPart)
|
|
172
|
+
? fs
|
|
173
|
+
.globSync(glob)
|
|
174
|
+
.map(d => path.resolve(d))
|
|
175
|
+
.toSorted()
|
|
176
|
+
: [glob]
|
|
177
|
+
for (const dir of dirs) {
|
|
178
|
+
const posix = dir.split(path.sep).join('/')
|
|
179
|
+
if (seen.has(dir) || excluded(posix, excludes) || !hasWhiteboard(dir)) continue
|
|
180
|
+
seen.add(dir)
|
|
181
|
+
const place = placeOf(glob, posix)
|
|
182
|
+
const wanted = `/${entry}/${[place.group, place.name].filter(Boolean).join('/')}`
|
|
183
|
+
let base = wanted
|
|
184
|
+
let n = 1
|
|
185
|
+
while (taken.has(base)) base = `${wanted}-${++n}`
|
|
186
|
+
taken.add(base)
|
|
187
|
+
// a second one wanting the same path is named apart the same way
|
|
188
|
+
const name = n > 1 ? (place.name ? `${place.name}-${n}` : '') : place.name
|
|
189
|
+
out.push({ entry, group: n > 1 && !place.name ? `${place.group}-${n}` : place.group, name, dir, base })
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return out
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Does any include of the machine config match this folder, no exclude leaving it out? Cheap: no globbing of the disk. */
|
|
197
|
+
export function matchesEntries(config: MachineConfig, dir: string, { home = os.homedir() } = {}): string | null {
|
|
198
|
+
const posix = path.resolve(dir).split(path.sep).join('/')
|
|
199
|
+
for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
|
|
200
|
+
const excludes = exclude.map(g => expandHome(g, home))
|
|
201
|
+
if (include.some(g => path.posix.matchesGlob(posix, expandHome(g, home))) && !excluded(posix, excludes))
|
|
202
|
+
return entry
|
|
203
|
+
}
|
|
204
|
+
return null
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Follow the entries' projects: `onChange` gets the projects each time the set changes. Watching
|
|
209
|
+
* globs over the disk in general would mean watching every folder they could match, so it looks
|
|
210
|
+
* again every `interval` ms (cheap: a few folder listings), and at once when told (`rescan`).
|
|
211
|
+
*/
|
|
212
|
+
export function followEntries(
|
|
213
|
+
read: () => MachineConfig | null,
|
|
214
|
+
onChange: (projects: EntryProject[]) => void,
|
|
215
|
+
{ interval = 1500, home }: { interval?: number; home?: string } = {},
|
|
216
|
+
) {
|
|
217
|
+
let last = ''
|
|
218
|
+
let current: EntryProject[] = []
|
|
219
|
+
const rescan = () => {
|
|
220
|
+
let projects: EntryProject[] = []
|
|
221
|
+
try {
|
|
222
|
+
const config = read()
|
|
223
|
+
projects = config ? discover(config, { home }) : []
|
|
224
|
+
} catch (err) {
|
|
225
|
+
console.error(`whiteboard: entries: ${(err as Error).message}`)
|
|
226
|
+
return current
|
|
227
|
+
}
|
|
228
|
+
const key = JSON.stringify(projects)
|
|
229
|
+
if (key !== last) {
|
|
230
|
+
last = key
|
|
231
|
+
current = projects
|
|
232
|
+
onChange(projects)
|
|
233
|
+
}
|
|
234
|
+
return current
|
|
235
|
+
}
|
|
236
|
+
rescan()
|
|
237
|
+
const timer = setInterval(rescan, interval)
|
|
238
|
+
timer.unref()
|
|
239
|
+
return { rescan, projects: () => current, stop: () => clearInterval(timer) }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The folders the entries' projects can be in: each include up to its first wildcard (all of it
|
|
244
|
+
* when it has none), without those inside another. What the shared server must be able to write,
|
|
245
|
+
* whatever folders appear below them later.
|
|
246
|
+
*/
|
|
247
|
+
export function entryFolders(config: MachineConfig, { home = os.homedir() }: { home?: string } = {}): string[] {
|
|
248
|
+
const roots = Object.values(config.entries).flatMap(e =>
|
|
249
|
+
e.include.map(g => {
|
|
250
|
+
const parts = expandHome(g, home).split('/')
|
|
251
|
+
const wild = parts.findIndex(isGlobPart)
|
|
252
|
+
return wild < 0 ? parts.join('/') : parts.slice(0, wild).join('/') || '/'
|
|
253
|
+
}),
|
|
254
|
+
)
|
|
255
|
+
const unique = [...new Set(roots)].toSorted()
|
|
256
|
+
return unique.filter(r => !unique.some(o => o !== r && (r.startsWith(o + '/') || o === '/')))
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* What the shared server needs of the disk, for whatever boxes it in (a sandbox wrapper, see
|
|
261
|
+
* `whiteboard paths`): `write`, the entries' folders and its own state folder; `read`, the machine
|
|
262
|
+
* config and whiteboard itself.
|
|
263
|
+
*/
|
|
264
|
+
export function serverPaths(
|
|
265
|
+
config: MachineConfig,
|
|
266
|
+
{ home, packageDir, env = process.env }: { home?: string; packageDir: string; env?: NodeJS.ProcessEnv },
|
|
267
|
+
): { write: string[]; read: string[] } {
|
|
268
|
+
return { write: [...entryFolders(config, { home }), stateDir(env)], read: [machineDir(env), packageDir] }
|
|
269
|
+
}
|
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
|
-
|
|
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
|
-
|
|
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
|
+
}
|