@bigmistqke/whiteboard 0.7.0 → 0.8.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 (66) hide show
  1. package/README.md +10 -209
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +66 -7
  5. package/dist/plugins/chat/public/style.css +10 -6
  6. package/dist/plugins/code/README.md +10 -0
  7. package/dist/plugins/code/index.js +31 -22
  8. package/dist/plugins/code/public/client.js +1 -0
  9. package/dist/plugins/code/public/style.css +33 -2
  10. package/dist/plugins/comments/public/client.js +1 -1
  11. package/dist/plugins/form/public/style.css +2 -0
  12. package/dist/plugins/iframe/index.js +2 -2
  13. package/dist/plugins/lightbox/public/client.js +1 -1
  14. package/dist/plugins/terminal/index.js +7 -9
  15. package/dist/plugins/terminal/public/client.js +1 -1
  16. package/dist/plugins/terminal/public/style.css +3 -3
  17. package/dist/plugins/toc/index.js +1 -1
  18. package/dist/plugins/toc/public/client.js +1 -1
  19. package/dist/plugins/window/index.js +4 -4
  20. package/dist/src/build.js +159 -0
  21. package/dist/src/client/page/main.js +1 -1
  22. package/dist/src/document.js +93 -0
  23. package/dist/src/events.js +3 -13
  24. package/dist/src/hub.js +47 -35
  25. package/dist/src/listen.js +100 -0
  26. package/dist/src/listeners.js +67 -0
  27. package/dist/src/pages/index.js +1 -1
  28. package/dist/src/pages/markdown.js +23 -11
  29. package/dist/src/pages/render.js +13 -8
  30. package/dist/src/server.js +166 -514
  31. package/dist/src/site.js +173 -0
  32. package/dist/src/status.js +63 -1
  33. package/package.json +1 -1
  34. package/plugins/README.md +258 -0
  35. package/plugins/chat/public/style.css +10 -6
  36. package/plugins/code/README.md +10 -0
  37. package/plugins/code/client.ts +73 -0
  38. package/plugins/code/index.ts +38 -26
  39. package/plugins/code/public/style.css +33 -2
  40. package/plugins/comments/client.ts +8 -1
  41. package/plugins/form/public/style.css +2 -0
  42. package/plugins/iframe/index.ts +2 -2
  43. package/plugins/lightbox/client.ts +13 -3
  44. package/plugins/terminal/client.ts +10 -2
  45. package/plugins/terminal/index.ts +8 -6
  46. package/plugins/terminal/public/style.css +3 -3
  47. package/plugins/toc/client.ts +9 -2
  48. package/plugins/toc/index.ts +1 -1
  49. package/plugins/window/index.ts +4 -4
  50. package/skills/whiteboard/SKILL.md +3 -1
  51. package/src/build.ts +213 -0
  52. package/src/client/page/elsewhere.ts +2 -1
  53. package/src/client/runtime.ts +88 -10
  54. package/src/client/toast.ts +1 -1
  55. package/src/define.ts +34 -18
  56. package/src/document.ts +191 -0
  57. package/src/events.ts +11 -16
  58. package/src/hub.ts +48 -34
  59. package/src/listen.ts +125 -0
  60. package/src/listeners.ts +95 -0
  61. package/src/pages/index.ts +1 -1
  62. package/src/pages/markdown.ts +29 -18
  63. package/src/pages/render.ts +13 -8
  64. package/src/server.ts +165 -609
  65. package/src/site.ts +165 -0
  66. package/src/status.ts +100 -0
package/src/hub.ts CHANGED
@@ -12,7 +12,8 @@
12
12
  // /api/shutdown POST { version }: a newer whiteboard takes over; an older one is refused
13
13
  // /api/listen?entry=<name>&command=wait|watch
14
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
15
+ // entry, held on every page of its projects, also those that appear meanwhile;
16
+ // its stream is told each project with who listens there (listeners.ts)
16
17
  //
17
18
  // A project's server is made when the project is found and closed when it goes, so a project
18
19
  // appears and disappears without a restart. Each keeps its own state, config and log, as it would
@@ -26,6 +27,7 @@ import { followEntries, machineDir, readMachineConfig, stateDir, type EntryProje
26
27
  import { compareVersions, VERSION } from './package.ts'
27
28
  import { createServer, type WhiteboardServer } from './server.ts'
28
29
  import type { Listener, PageStatus } from './define.ts'
30
+ import { holdStream, listenerOf } from './listeners.ts'
29
31
 
30
32
  export interface HubOptions {
31
33
  /** the machine folder (its config.json), which the server only reads; default machineDir() */
@@ -101,8 +103,20 @@ export function createHub({
101
103
  version = VERSION,
102
104
  }: HubOptions = {}): Hub {
103
105
  const served = new Map<string, Served>()
104
- // each entry's fallback, while one runs: the listener its projects hold
105
- const fallbacks = new Map<string, Listener>()
106
+ // each entry's fallback, while one runs: the listener its projects hold, and what tells its stream
107
+ const fallbacks = new Map<string, { listener: Listener; tell: () => void }>()
108
+ /** An entry's fallback held on one of its projects, followed there; false when the project refuses it. */
109
+ function hold(s: Served, fb: { listener: Listener; tell: () => void }): boolean {
110
+ const off = s.server.addListener(fb.listener)
111
+ if (!off) return false
112
+ const unfollow = s.server.onListeners(() => fb.tell())
113
+ s.fallback = () => {
114
+ unfollow()
115
+ off()
116
+ delete s.fallback
117
+ }
118
+ return true
119
+ }
106
120
 
107
121
  function sync(projects: EntryProject[]) {
108
122
  // projects come and go: the overview lists them
@@ -110,6 +124,7 @@ export function createHub({
110
124
  const wanted = new Map(projects.map(p => [`${p.base}\n${p.dir}`, p]))
111
125
  for (const [key, s] of served)
112
126
  if (!wanted.has(key)) {
127
+ s.fallback?.()
113
128
  s.server.close()
114
129
  served.delete(key)
115
130
  console.log(`whiteboard: ${s.base} is gone (${s.dir})`)
@@ -124,10 +139,14 @@ export function createHub({
124
139
  label: [p.group, p.name].filter(Boolean).join(' › '),
125
140
  onChange: () => changed(p.base),
126
141
  })
127
- const fallback = fallbacks.get(p.entry)
128
- served.set(key, { ...p, project, server, ...(fallback && { fallback: server.addListener(fallback) }) })
142
+ const s: Served = { ...p, project, server }
143
+ served.set(key, s)
144
+ const fb = fallbacks.get(p.entry)
145
+ if (fb) hold(s, fb)
129
146
  console.log(`whiteboard: ${p.base} → ${p.dir}`)
130
147
  }
148
+ // an entry's fallback follows its projects coming and going
149
+ for (const fb of fallbacks.values()) fb.tell()
131
150
  }
132
151
 
133
152
  // the overview at /: a project of the shared server's own, in the machine folder, whose overview
@@ -320,42 +339,37 @@ export function createHub({
320
339
  * The fallback of a whole entry (a `wait` or `watch` without --page in one of its projects): one
321
340
  * per entry, refused (409) while another runs, or while a project of it has a fallback of its own
322
341
  * (from a whiteboard before entries). Each project holds it as a listener, so its pages say an
323
- * agent listens; the command itself reads the projects' logs.
342
+ * agent listens; its stream is told each project of the entry with who listens there, at once and
343
+ * whenever that or the projects change. The command itself reads the projects' logs.
324
344
  */
325
345
  function listenEntry(req: IncomingMessage, res: ServerResponse, q: URLSearchParams) {
326
346
  const entry = q.get('entry')!
327
- const projects = [...served.values()].filter(s => s.entry === entry)
328
347
  if (fallbacks.has(entry)) return sendJson(res, 409, { error: `another agent is the fallback of ${entry} already` })
329
- const own = projects.find(s => s.server.listeners().some(x => x.fallback))
330
- if (own)
331
- return sendJson(res, 409, {
332
- error: `${own.base} has a fallback of its own already (a wait or watch without --page)`,
333
- })
334
- const l: Listener = {
335
- page: '',
336
- type: q.get('type') || null,
337
- command: q.get('command') === 'wait' ? 'wait' : 'watch',
338
- fallback: true,
339
- }
340
- fallbacks.set(entry, l)
341
- for (const s of projects) s.fallback = s.server.addListener(l)
342
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
343
- res.write(': listening\n\n')
344
- const ping = setInterval(() => res.write(': ping\n\n'), 25000)
345
- const end = () => {
346
- clearInterval(ping)
347
- if (fallbacks.get(entry) !== l) return
348
- fallbacks.delete(entry)
349
- for (const s of served.values()) {
350
- s.fallback?.()
351
- delete s.fallback
348
+ const mine = () => [...served.values()].filter(s => s.entry === entry)
349
+ const fb = { listener: listenerOf(q, true), tell: () => {} }
350
+ const held: Served[] = []
351
+ for (const s of mine()) {
352
+ if (!hold(s, fb)) {
353
+ for (const h of held) h.fallback?.()
354
+ return sendJson(res, 409, {
355
+ error: `${s.base} has a fallback of its own already (a wait or watch without --page)`,
356
+ })
352
357
  }
358
+ held.push(s)
353
359
  }
354
- closers.add(() => {
355
- end()
356
- res.end()
360
+ fallbacks.set(entry, fb)
361
+ const stream = holdStream(req, res, () => {
362
+ closers.delete(stream.end)
363
+ if (fallbacks.get(entry) !== fb) return
364
+ fallbacks.delete(entry)
365
+ for (const s of mine()) s.fallback?.()
357
366
  })
358
- req.on('close', end)
367
+ fb.tell = () =>
368
+ stream.send('listeners', {
369
+ projects: mine().map(s => ({ dir: s.dir, base: s.base, listeners: s.server.listeners() })),
370
+ })
371
+ closers.add(stream.end)
372
+ fb.tell()
359
373
  }
360
374
  const closers = new Set<() => void>()
361
375
 
package/src/listen.ts ADDED
@@ -0,0 +1,125 @@
1
+ // The command's side of listening (`whiteboard wait` and `watch`): holding a listener at a server,
2
+ // and the fallback. A wait or watch on a page registers at its project's server first and only then
3
+ // reads the log, so from its first answer on the server knows it listens. A fallback (one without
4
+ // --page) registers too, and its stream is told who else listens on each project it covers
5
+ // (listeners.ts): a project's own server names that project, the shared server each project of the
6
+ // entry. The fallback hands out from each project's log what no other listener there would take.
7
+ import http from 'node:http'
8
+ import type { Listener } from './define.ts'
9
+ import type { HandOutOptions } from './events.ts'
10
+ import type { Followed, Snapshot } from './listeners.ts'
11
+ import { takenByOther } from './status.ts'
12
+
13
+ export interface ListenOptions {
14
+ /** the server's base URL; null (or a throw) while none runs, tried again */
15
+ at: () => Promise<string | null>
16
+ /** what to ask /api/listen for: page, type, command, and `fallback` or `entry` */
17
+ query: Record<string, string>
18
+ /** a fallback: who listens on each project it covers, at once and on every change */
19
+ onSnapshot?: (snapshot: Snapshot) => void
20
+ /** the server refused it (another fallback holds it): the reason it gave */
21
+ onRefused: (reason: string) => void
22
+ }
23
+
24
+ /**
25
+ * Hold a listener at a server for as long as the process runs, and again after the server restarts.
26
+ * Resolves once the server holds it; with `orNone`, also after a first try that found no server
27
+ * running (a wait reads the log all the same, and registers once one appears).
28
+ */
29
+ export function listen({ at, query, onSnapshot, onRefused }: ListenOptions, { orNone = false } = {}): Promise<void> {
30
+ return new Promise(settled => {
31
+ const connect = async () => {
32
+ let base: string | null = null
33
+ try {
34
+ base = await at()
35
+ } catch {
36
+ /* none runs */
37
+ }
38
+ if (!base) {
39
+ if (orNone) settled()
40
+ return setTimeout(connect, 2000).unref()
41
+ }
42
+ let again = false
43
+ const retry = (ms: number) => {
44
+ if (!again) {
45
+ again = true
46
+ setTimeout(connect, ms).unref()
47
+ }
48
+ }
49
+ const req = http.get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
50
+ res.setEncoding('utf8')
51
+ if (res.statusCode === 409) {
52
+ let body = ''
53
+ res.on('data', (d: string) => (body += d))
54
+ res.on('end', () => {
55
+ let reason = ''
56
+ try {
57
+ reason = JSON.parse(body).error ?? ''
58
+ } catch {}
59
+ onRefused(reason || 'another agent is the fallback already')
60
+ })
61
+ return
62
+ }
63
+ settled()
64
+ let buf = ''
65
+ res.on('data', (chunk: string) => {
66
+ buf += chunk
67
+ // an event ends at a blank line: `event: listeners` and its data
68
+ let end
69
+ while ((end = buf.indexOf('\n\n')) >= 0) {
70
+ const block = buf.slice(0, end)
71
+ buf = buf.slice(end + 2)
72
+ const event = /^event: (.*)$/m.exec(block)?.[1]
73
+ const data = /^data: (.*)$/m.exec(block)?.[1]
74
+ if (event === 'listeners' && data && onSnapshot) onSnapshot(JSON.parse(data) as Snapshot)
75
+ }
76
+ })
77
+ res.on('close', () => retry(1000))
78
+ })
79
+ req.on('error', () => retry(2000))
80
+ // the connection alone does not keep the command running
81
+ req.on('socket', socket => socket.unref())
82
+ }
83
+ void connect()
84
+ })
85
+ }
86
+
87
+ /** What the fallback hands a project's hand-out: what it leaves to others, and when to look again. */
88
+ export type FallbackHandOut = Required<Pick<HandOutOptions, 'skip' | 'recheck' | 'signal' | 'unpicked'>>
89
+
90
+ /**
91
+ * The fallback over the projects a server names: `start` is called once for each project as it
92
+ * appears, to hand out from its log what no other listener there takes (`skip`) and nobody picked
93
+ * up (`unpicked`), looked at again (`recheck`) whenever who listens there changes; a project no
94
+ * longer named is stopped (`signal`).
95
+ * @returns what takes each snapshot the server sends
96
+ */
97
+ export function fallback(start: (project: Followed, handOut: FallbackHandOut) => void): (snapshot: Snapshot) => void {
98
+ const followed = new Map<string, { listeners: Listener[]; stop: AbortController; recheck: () => void }>()
99
+ return ({ projects }) => {
100
+ for (const p of projects) {
101
+ const known = followed.get(p.dir)
102
+ if (known) {
103
+ known.listeners = p.listeners
104
+ known.recheck()
105
+ continue
106
+ }
107
+ const f = { listeners: p.listeners, stop: new AbortController(), recheck: () => {} }
108
+ followed.set(p.dir, f)
109
+ start(p, {
110
+ skip: e => takenByOther(f.listeners, e),
111
+ recheck: again => {
112
+ f.recheck = again
113
+ },
114
+ signal: f.stop.signal,
115
+ // what another listener picked up is never the fallback's, however late it sees it
116
+ unpicked: true,
117
+ })
118
+ }
119
+ for (const [dir, f] of followed)
120
+ if (!projects.some(p => p.dir === dir)) {
121
+ f.stop.abort()
122
+ followed.delete(dir)
123
+ }
124
+ }
125
+ }
@@ -0,0 +1,95 @@
1
+ // Who listens, as a server holds it. An agent waiting for answers (`whiteboard wait` or `watch`)
2
+ // holds a connection to /api/listen for as long as it runs: that connection is the listener, gone
3
+ // when the command is. A project's server keeps its listeners in a registry; the shared server adds
4
+ // an entry's fallback to the registry of each project of the entry. The fallback (a wait or watch
5
+ // without --page) takes only what no other listener would, so its stream is told who else listens
6
+ // (`listeners`, a Snapshot), at once and on every change.
7
+ import type { IncomingMessage, ServerResponse } from 'node:http'
8
+ import type { Listener } from './define.ts'
9
+ import { covers } from './status.ts'
10
+
11
+ /** The listeners of one project, and the rule that one fallback holds it at a time. */
12
+ export interface Registry {
13
+ /** the listeners, those covering `page` when given; each a copy */
14
+ list(page?: string | null): Listener[]
15
+ /** hold `l` until the returned function is called; null when refused: a second fallback */
16
+ add(l: Listener): (() => void) | null
17
+ /** call `fn` whenever a listener comes or goes; returns what stops it */
18
+ onChange(fn: () => void): () => void
19
+ }
20
+
21
+ export function createRegistry(): Registry {
22
+ const listeners = new Set<Listener>()
23
+ const watchers = new Set<() => void>()
24
+ const changed = () => {
25
+ for (const fn of watchers) fn()
26
+ }
27
+ return {
28
+ list: (page = null) =>
29
+ [...listeners]
30
+ .filter(l => page == null || covers(l, page))
31
+ .map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) })),
32
+ add(l) {
33
+ // one fallback per project: two would split what nobody else takes between them
34
+ if (l.fallback && [...listeners].some(x => x.fallback)) return null
35
+ listeners.add(l)
36
+ changed()
37
+ return () => {
38
+ if (listeners.delete(l)) changed()
39
+ }
40
+ },
41
+ onChange(fn) {
42
+ watchers.add(fn)
43
+ return () => watchers.delete(fn)
44
+ },
45
+ }
46
+ }
47
+
48
+ /** A project as a fallback's stream names it, with who listens there. */
49
+ export interface Followed {
50
+ /** the project's folder */
51
+ dir: string
52
+ /** where the server serves it: '' for a project's own server, `/rg/develop` under the shared one */
53
+ base: string
54
+ listeners: Listener[]
55
+ }
56
+
57
+ /** What a fallback's stream is told (`event: listeners`): every project it covers, now. */
58
+ export interface Snapshot {
59
+ projects: Followed[]
60
+ }
61
+
62
+ /** The listener a /api/listen request asks for. */
63
+ export const listenerOf = (q: URLSearchParams, fallback = q.has('fallback')): Listener => ({
64
+ page: q.get('page') || '',
65
+ type: q.get('type') || null,
66
+ command: q.get('command') === 'wait' ? 'wait' : 'watch',
67
+ ...(fallback && { fallback }),
68
+ })
69
+
70
+ /**
71
+ * Hold a /api/listen connection open as an event stream (with a ping, so nothing between closes it
72
+ * as idle). `send` writes an event on it; `onEnd` runs once, when the agent goes or `end` is called.
73
+ */
74
+ export function holdStream(req: IncomingMessage, res: ServerResponse, onEnd: () => void) {
75
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
76
+ res.write(': listening\n\n')
77
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
78
+ let ended = false
79
+ const finish = () => {
80
+ if (ended) return
81
+ ended = true
82
+ clearInterval(ping)
83
+ onEnd()
84
+ }
85
+ req.on('close', finish)
86
+ return {
87
+ send(event: string, data: unknown) {
88
+ if (!ended) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
89
+ },
90
+ end() {
91
+ finish()
92
+ res.end()
93
+ },
94
+ }
95
+ }
@@ -39,6 +39,6 @@ export function createPages(options: PagesOptions): Pages {
39
39
  render: createRender(blocks, options.style, options.styles ?? [], options.links ?? [], options.composers),
40
40
  message: createMessageRender(blocks, options.links ?? []),
41
41
  docs: createDocs(blocks),
42
- questions: page => formNames(page.source),
42
+ questions: page => formNames(page.body),
43
43
  }
44
44
  }
@@ -177,25 +177,35 @@ function linkText(tree: MdNode, links: TextLink[]) {
177
177
  walk(tree)
178
178
  }
179
179
 
180
+ /**
181
+ * The address of something named relative to the page (a link, an image, a block's `src`): resolved
182
+ * from the page's folder and handed to `linkFor`. A URL, an address from the root, an anchor, or
183
+ * something nothing serves stays as written.
184
+ */
185
+ function addressOf(ref: string, file: string, linkFor?: LinkFor): string {
186
+ if (!linkFor || !file || !ref || SCHEME.test(ref) || /^[/#]/.test(ref)) return ref
187
+ const [, target, rest] = /^([^?#]*)(.*)$/s.exec(ref)!
188
+ let decoded = target
189
+ try {
190
+ decoded = decodeURIComponent(target)
191
+ } catch {
192
+ /* keep as written */
193
+ }
194
+ const url = decoded && linkFor(path.resolve(path.dirname(file), decoded))
195
+ return url ? url + rest : ref
196
+ }
197
+
198
+ /** Raw HTML's references to files beside the page (`<img src>`, `<video poster>`, `<a href>`). */
199
+ const HTML_REFS = /(\b(?:src|href|poster)=")([^"]*)(")/g
200
+
180
201
  function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
181
202
  if (!linkFor || !file) return
182
203
  const walk = (node: MdNode) => {
183
- if (
184
- (node.type === 'link' || node.type === 'image' || node.type === 'definition') &&
185
- node.url &&
186
- !SCHEME.test(node.url) &&
187
- !/^[/#]/.test(node.url)
188
- ) {
189
- const [, target, rest] = /^([^?#]*)(.*)$/s.exec(node.url)!
190
- let decoded = target
191
- try {
192
- decoded = decodeURIComponent(target)
193
- } catch {
194
- /* keep as written */
195
- }
196
- const url = decoded && linkFor(path.resolve(path.dirname(file), decoded))
197
- if (url) node.url = url + rest
198
- }
204
+ if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && node.url)
205
+ node.url = addressOf(node.url as string, file, linkFor)
206
+ // raw HTML the page writes itself, as the markdown it is in: before it is a string
207
+ if (node.type === 'html' && typeof node.value === 'string')
208
+ node.value = node.value.replace(HTML_REFS, (_, open, ref, close) => open + addressOf(ref, file, linkFor) + close)
199
209
  node.children?.forEach(walk)
200
210
  }
201
211
  walk(tree)
@@ -226,7 +236,7 @@ function literalDirective(node: MdNode, label: MdNode[] | null) {
226
236
  * code block doesn't count.
227
237
  */
228
238
  export function formNames(source: string) {
229
- const tree = parseMarkdown(String(source ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ''))
239
+ const tree = parseMarkdown(String(source ?? ''))
230
240
  const names: string[] = []
231
241
  const walk = (node: MdNode) => {
232
242
  if (node.type === 'containerDirective' && node.name === 'form') {
@@ -415,7 +425,8 @@ plugin "${name}" failed to compose around block "${block.name}": ${(err as Error
415
425
  }
416
426
  const markdown = async (src: string) => toHtml(parse(src).children ?? [])
417
427
  const inline = async (src: string) => (await markdown(src)).trim().replace(/^<p>([\s\S]*)<\/p>$/, '$1')
418
- const base = { page, file, dir: path.dirname(file), parseAttrs, toHtml, toString, markdown, inline }
428
+ const fileUrl = (src: string) => addressOf(src, file, linkFor)
429
+ const base = { page, file, dir: path.dirname(file), parseAttrs, toHtml, toString, markdown, inline, fileUrl }
419
430
 
420
431
  async function directive(node: MdNode): Promise<MdNode> {
421
432
  const { label, children } = splitLabel(node)
@@ -2,6 +2,7 @@
2
2
  // directives and fences handed to the plugins' blocks (markdown.ts); repository files show as highlighted
3
3
  // code, folders as listings with their README on top; around all of it goes the page's frame.
4
4
  // What the page draws itself is built with `html` (../html.ts), which escapes every value.
5
+ import { FRONTMATTER } from '../site.ts'
5
6
  import fs from 'node:fs'
6
7
  import os from 'node:os'
7
8
  import path from 'node:path'
@@ -51,8 +52,8 @@ const CODE_LANG: Record<string, string> = {
51
52
  yaml: 'yaml',
52
53
  }
53
54
 
54
- /** Frontmatter is the core's; the page starts after it. */
55
- const body = (source: string) => source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')
55
+ /** Frontmatter is the core's; the page starts after it (a page's own is cut off by the site: PageSource.body). */
56
+ const body = (source: string) => source.replace(FRONTMATTER, '')
56
57
 
57
58
  /** A page's title: its first heading, else its name. */
58
59
  export function titleOf(file: string, fallback: string) {
@@ -342,10 +343,11 @@ export function createRender(
342
343
  const PLUGIN_STYLES = pluginStyles
343
344
  .map(s => ({ plugin: s.plugin, file: stylePath(s.file) }))
344
345
  .filter((s): s is { plugin: string; file: string } => !!s.file)
345
- async function markdown(source: string, page: string, file: string, ctx: RenderContext) {
346
+ /** `content`: the markdown without its frontmatter. */
347
+ async function markdown(content: string, page: string, file: string, ctx: RenderContext) {
346
348
  const { blocks: set, code } = blocks()
347
349
  const skip = ctx.skip
348
- return renderMarkdown(body(source), {
350
+ return renderMarkdown(content, {
349
351
  page,
350
352
  file,
351
353
  resolve: name => {
@@ -371,7 +373,7 @@ export function createRender(
371
373
  const { project } = ctx
372
374
  switch (page.kind) {
373
375
  case 'page':
374
- return markdown(page.source, page.id, page.file, ctx)
376
+ return markdown(page.body, page.id, page.file, ctx)
375
377
  case 'pages': {
376
378
  // the shared server's overview: every project's pages, by project, the projects with
377
379
  // something waiting first, and in each the pages waiting first
@@ -436,7 +438,7 @@ export function createRender(
436
438
  const readme = readmeOf(page)
437
439
  if (!readme) return { html: listing, title: rel || project.name, islands: {}, styles: [] }
438
440
  // markdown's output is HTML already
439
- const r = await markdown(readme.source, page.id, readme.file, ctx)
441
+ const r = await markdown(body(readme.source), page.id, readme.file, ctx)
440
442
  return {
441
443
  ...r,
442
444
  html: html`${raw(r.html)}
@@ -483,7 +485,7 @@ export function createRender(
483
485
  const nav =
484
486
  ctx.live === false
485
487
  ? html`<nav class="wb-nav">
486
- <span>${ctx.project.name}</span
488
+ <span>${ctx.project.name}</span><span data-wb-slot="header"></span
487
489
  ><button
488
490
  type="button"
489
491
  class="wb-theme"
@@ -493,7 +495,10 @@ export function createRender(
493
495
  </nav>`
494
496
  : html`<nav class="wb-nav">
495
497
  <span>${crumbs(page.id, ctx.entry?.label || ctx.project.name, ctx.base ?? '', ctx.entry)}</span
496
- >${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button
498
+ >${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<span
499
+ data-wb-slot="header"
500
+ ></span
501
+ ><button
497
502
  type="button"
498
503
  class="wb-theme"
499
504
  title="Theme: follow the system, light or dark"