@bigmistqke/whiteboard 0.6.1 → 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.
- package/README.md +23 -216
- package/bin/whiteboard.ts +82 -239
- package/dist/bin/whiteboard.js +70 -200
- package/dist/client/runtime.js +297 -61
- package/dist/plugins/badge/README.md +3 -1
- package/dist/plugins/badge/public/style.css +17 -0
- package/dist/plugins/chat/public/client.js +2 -2
- package/dist/plugins/chat/public/style.css +19 -6
- package/dist/plugins/code/README.md +10 -0
- package/dist/plugins/code/index.js +31 -22
- package/dist/plugins/code/public/client.js +1 -0
- package/dist/plugins/code/public/style.css +33 -2
- package/dist/plugins/comments/public/client.js +7 -2
- package/dist/plugins/comments/public/style.css +4 -0
- package/dist/plugins/form/public/style.css +2 -0
- package/dist/plugins/grid/public/style.css +0 -5
- package/dist/plugins/iframe/index.js +2 -2
- package/dist/plugins/index.js +5 -1
- package/dist/plugins/lightbox/public/client.js +1 -1
- package/dist/plugins/terminal/index.js +7 -9
- package/dist/plugins/terminal/public/client.js +1 -1
- package/dist/plugins/terminal/public/style.css +3 -3
- package/dist/plugins/timeline/README.md +40 -0
- package/dist/plugins/timeline/index.js +82 -0
- package/dist/plugins/timeline/public/style.css +118 -0
- package/dist/plugins/toc/README.md +13 -13
- package/dist/plugins/toc/index.js +6 -4
- package/dist/plugins/toc/public/client.js +1 -1
- package/dist/plugins/toc/public/style.css +19 -2
- package/dist/plugins/window/index.js +4 -4
- package/dist/solid/index.js +2 -1
- package/dist/src/auth.js +7 -3
- package/dist/src/build.js +159 -0
- package/dist/src/client/page/base.css +74 -35
- package/dist/src/client/page/main.js +16 -5
- package/dist/src/document.js +93 -0
- package/dist/src/events.js +7 -15
- package/dist/src/hub.js +90 -53
- package/dist/src/listen.js +100 -0
- package/dist/src/listeners.js +67 -0
- package/dist/src/pages/index.js +1 -1
- package/dist/src/pages/markdown.js +23 -11
- package/dist/src/pages/render.js +13 -8
- package/dist/src/serve.js +2 -0
- package/dist/src/server.js +204 -514
- package/dist/src/site.js +173 -0
- package/dist/src/status.js +63 -1
- package/dist/src/ws.js +128 -0
- package/package.json +1 -1
- package/plugins/README.md +258 -0
- package/plugins/badge/README.md +3 -1
- package/plugins/badge/public/style.css +17 -0
- package/plugins/chat/client.tsx +34 -6
- package/plugins/chat/public/style.css +19 -6
- package/plugins/code/README.md +10 -0
- package/plugins/code/client.ts +73 -0
- package/plugins/code/index.ts +38 -26
- package/plugins/code/public/style.css +33 -2
- package/plugins/comments/client.ts +56 -6
- package/plugins/comments/public/style.css +4 -0
- package/plugins/form/public/style.css +2 -0
- package/plugins/grid/public/style.css +0 -5
- package/plugins/iframe/index.ts +2 -2
- package/plugins/index.ts +6 -1
- package/plugins/lightbox/client.ts +13 -3
- package/plugins/terminal/client.ts +10 -2
- package/plugins/terminal/index.ts +8 -6
- package/plugins/terminal/public/style.css +3 -3
- package/plugins/timeline/README.md +40 -0
- package/plugins/timeline/index.ts +92 -0
- package/plugins/timeline/public/style.css +118 -0
- package/plugins/toc/README.md +13 -13
- package/plugins/toc/client.ts +58 -32
- package/plugins/toc/index.ts +13 -13
- package/plugins/toc/public/style.css +19 -2
- package/plugins/window/index.ts +4 -4
- package/skills/whiteboard/SKILL.md +3 -1
- package/solid/index.tsx +3 -0
- package/src/auth.ts +7 -2
- package/src/build.ts +213 -0
- package/src/client/forms.ts +102 -5
- package/src/client/page/base.css +74 -35
- package/src/client/page/elsewhere.ts +14 -4
- package/src/client/page/waiting.ts +10 -5
- package/src/client/read.ts +16 -3
- package/src/client/runtime.ts +219 -52
- package/src/client/toast.ts +36 -6
- package/src/define.ts +44 -18
- package/src/document.ts +191 -0
- package/src/events.ts +18 -17
- package/src/hub.ts +102 -56
- package/src/listen.ts +125 -0
- package/src/listeners.ts +95 -0
- package/src/pages/index.ts +1 -1
- package/src/pages/markdown.ts +29 -18
- package/src/pages/render.ts +13 -8
- package/src/serve.ts +2 -0
- package/src/server.ts +223 -611
- package/src/site.ts +165 -0
- package/src/status.ts +100 -0
- package/src/ws.ts +155 -0
package/src/server.ts
CHANGED
|
@@ -16,37 +16,38 @@
|
|
|
16
16
|
// plugins bring (pages.ts). When the config fails to load, a page shows as its raw
|
|
17
17
|
// text.
|
|
18
18
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
19
|
+
import type { Duplex } from 'node:stream'
|
|
19
20
|
import fs from 'node:fs'
|
|
20
|
-
import
|
|
21
|
+
import crypto from 'node:crypto'
|
|
21
22
|
import { stripTypeScriptTypes } from 'node:module'
|
|
22
23
|
import path from 'node:path'
|
|
23
24
|
import type { Project } from './config.ts'
|
|
24
|
-
import { appendEvent, readEvents, matches, pickedUp,
|
|
25
|
-
import { html, raw
|
|
25
|
+
import { appendEvent, isEventId, readEvents, matches, pickedUp, forAgent } from './events.ts'
|
|
26
|
+
import { html, raw } from './html.ts'
|
|
26
27
|
import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
|
|
27
|
-
import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage
|
|
28
|
-
import { createAuth } from './auth.ts'
|
|
28
|
+
import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage } from './plugins.ts'
|
|
29
|
+
import { createAuth, sameSite } from './auth.ts'
|
|
30
|
+
import { accept, refuse } from './ws.ts'
|
|
29
31
|
import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
|
|
30
|
-
import {
|
|
32
|
+
import { SCROLL, awaiting, projectStatus, type ProjectStatus } from './status.ts'
|
|
31
33
|
import { titleOf } from './pages/render.ts'
|
|
34
|
+
import { createRegistry, holdStream, listenerOf } from './listeners.ts'
|
|
32
35
|
import { inPublic } from './public.ts'
|
|
36
|
+
import { build, type BuildResult } from './build.ts'
|
|
37
|
+
import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts, type Render, type SetUp } from './document.ts'
|
|
38
|
+
import { SKIP_DIRS, isRepoId, pageSource, servedSite, within } from './site.ts'
|
|
33
39
|
import type {
|
|
34
40
|
Listener,
|
|
35
41
|
PageSource,
|
|
36
42
|
PageStatus,
|
|
37
|
-
Plugin,
|
|
38
|
-
PluginHooks,
|
|
39
43
|
Rendered,
|
|
40
44
|
StoredPage,
|
|
41
45
|
PagesSource,
|
|
42
46
|
BuildConfig,
|
|
47
|
+
WbEvent,
|
|
43
48
|
} from './define.ts'
|
|
44
49
|
|
|
45
50
|
const ENGINE_DIR = PACKAGE_DIR
|
|
46
|
-
// the browser runtime, built by build.ts
|
|
47
|
-
const RUNTIME = path.join(ENGINE_DIR, 'dist', 'client', 'runtime.js')
|
|
48
|
-
// the page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts
|
|
49
|
-
const PAGE_CLIENT = path.join(ENGINE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
|
|
50
51
|
const MIME: Record<string, string> = {
|
|
51
52
|
'.css': 'text/css',
|
|
52
53
|
'.js': 'text/javascript',
|
|
@@ -71,14 +72,15 @@ const MIME: Record<string, string> = {
|
|
|
71
72
|
}
|
|
72
73
|
// files in .whiteboard/ that are the server's own bookkeeping, not content
|
|
73
74
|
const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
|
|
75
|
+
|
|
76
|
+
export type { BuildResult }
|
|
77
77
|
|
|
78
78
|
/** A project's server: its request handler, and what it knows. */
|
|
79
79
|
export interface WhiteboardServer {
|
|
80
80
|
/** answer one request */
|
|
81
81
|
handle(req: IncomingMessage, res: ServerResponse): Promise<void>
|
|
82
|
+
/** answer one upgrade request (the HTTP server's 'upgrade' event): the page's live channel */
|
|
83
|
+
upgrade(req: IncomingMessage, conn: Duplex, head: Buffer): void
|
|
82
84
|
/** what is open on each page (or on `page` and below), as /api/status gives it */
|
|
83
85
|
status(page?: string | null): Promise<PageStatus[]>
|
|
84
86
|
/** the project's config, loaded */
|
|
@@ -88,28 +90,23 @@ export interface WhiteboardServer {
|
|
|
88
90
|
/**
|
|
89
91
|
* Hold a listener that is not a connection to this server: the shared server's fallback for a
|
|
90
92
|
* whole entry, which covers every page of each of its projects. Pages are told, as for any
|
|
91
|
-
* listener. @returns what removes it
|
|
93
|
+
* listener. @returns what removes it; null when refused (the project has a fallback already)
|
|
92
94
|
*/
|
|
93
|
-
addListener(l: Listener): () => void
|
|
95
|
+
addListener(l: Listener): (() => void) | null
|
|
96
|
+
/** call `fn` whenever a listener comes or goes; returns what stops it */
|
|
97
|
+
onListeners(fn: () => void): () => void
|
|
94
98
|
/** who listens now: the running waits and watches, and a fallback held for it */
|
|
95
99
|
listeners(): Listener[]
|
|
96
100
|
/** the project's pages as its overview lists them, newest first, with what waits on each; whether it serves its files */
|
|
97
101
|
overview(): Promise<{ pages: PagesSource['pages']; files: boolean }>
|
|
98
102
|
/** tell the open overviews (`/`) that what they list changed */
|
|
99
103
|
touch(): void
|
|
104
|
+
/** tell the open pages that what waits in another project of the shared server changed */
|
|
105
|
+
elsewhere(): void
|
|
100
106
|
/** stop watching and end the live connections; the server answers nothing after */
|
|
101
107
|
close(): void
|
|
102
108
|
}
|
|
103
109
|
|
|
104
|
-
export interface BuildResult {
|
|
105
|
-
/** the folder the site is in */
|
|
106
|
-
out: string
|
|
107
|
-
/** each page, and the file it became */
|
|
108
|
-
pages: { file: string; to: string }[]
|
|
109
|
-
/** what didn't fit: a link to a page outside the build, no index.html */
|
|
110
|
-
warnings: string[]
|
|
111
|
-
}
|
|
112
|
-
|
|
113
110
|
/** How a server is mounted: on a port of its own (the default), or under a path of a shared server. */
|
|
114
111
|
export interface ServerOptions {
|
|
115
112
|
/** the path every URL it makes starts with, without a trailing slash: '' (its own port) or `/rg/develop` */
|
|
@@ -153,14 +150,6 @@ export function createServer(
|
|
|
153
150
|
// ---- plugins --------------------------------------------------------------------------------
|
|
154
151
|
// Behaviour on every page: each one's setup runs once per loaded config.
|
|
155
152
|
|
|
156
|
-
/** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
|
|
157
|
-
interface SetUp extends PluginHooks {
|
|
158
|
-
name: string
|
|
159
|
-
table: MountedRoute[]
|
|
160
|
-
plugin: Plugin
|
|
161
|
-
error?: Error
|
|
162
|
-
}
|
|
163
|
-
|
|
164
153
|
const setups = new WeakMap<LoadedConfig, Promise<SetUp[]>>()
|
|
165
154
|
// the plugins' own folders in .whiteboard/: changes in them reload nothing
|
|
166
155
|
const pluginDirs = new Set<string>()
|
|
@@ -176,15 +165,13 @@ export function createServer(
|
|
|
176
165
|
try {
|
|
177
166
|
pluginDirs.add(e.name)
|
|
178
167
|
const dataDir = pluginDir(project.wb, e.name)
|
|
179
|
-
// what it serves is in its public folder: its client,
|
|
168
|
+
// what it serves is in its public folder: its client, named in its hooks
|
|
180
169
|
const dir = c.publicDirs.get(e.name)!
|
|
181
|
-
const own = (ref: URL | string) => asset(inPublic(dir, ref, `plugin ${e.name}`))
|
|
182
170
|
const hooks =
|
|
183
171
|
(await e.setup?.({
|
|
184
172
|
project: { name: project.name, dir: project.dir, wb: project.wb },
|
|
185
173
|
dataDir,
|
|
186
174
|
authorized: auth.authorized,
|
|
187
|
-
asset: own,
|
|
188
175
|
})) ?? {}
|
|
189
176
|
const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : undefined
|
|
190
177
|
return { name: e.name, ...hooks, client, table: mountRoutes(e.name, hooks.routes), plugin: e }
|
|
@@ -199,51 +186,25 @@ export function createServer(
|
|
|
199
186
|
return setups.get(c)!
|
|
200
187
|
}
|
|
201
188
|
|
|
202
|
-
/**
|
|
203
|
-
* What the plugins add to the page shell for this request, and the notices of those that failed:
|
|
204
|
-
* a failing plugin shows on the page, as a failing config does, instead of quietly leaving its
|
|
205
|
-
* part out.
|
|
206
|
-
*/
|
|
207
|
-
/** What the plugins add to a page: markup for its head and body, their browser modules, and notices. */
|
|
208
|
-
interface Extras {
|
|
209
|
-
head: Html[]
|
|
210
|
-
body: Html[]
|
|
211
|
-
clients: { name: string; client: string }[]
|
|
212
|
-
/** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
|
|
213
|
-
messages?: string[]
|
|
214
|
-
notices?: string[]
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
async function shellExtras(req: IncomingMessage): Promise<Extras & { notices: string[] }> {
|
|
218
|
-
const hooks = await pluginHooks()
|
|
219
|
-
const notices = hooks.filter(h => h.error).map(h => `plugin "${h.name}" failed to start: ${h.error!.message}`)
|
|
220
|
-
const parts = await Promise.all(
|
|
221
|
-
hooks.map(async h => {
|
|
222
|
-
try {
|
|
223
|
-
return (await h.shell?.(req)) ?? null
|
|
224
|
-
} catch (err) {
|
|
225
|
-
console.error(`plugin ${h.name}:`, err)
|
|
226
|
-
notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
|
|
227
|
-
return null
|
|
228
|
-
}
|
|
229
|
-
}),
|
|
230
|
-
)
|
|
231
|
-
// their browser modules, which the runtime imports after the page's
|
|
232
|
-
const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
|
|
233
|
-
const messages = [...(await config()).forReader]
|
|
234
|
-
return {
|
|
235
|
-
head: parts.map(x => raw(String(x?.head ?? ''))),
|
|
236
|
-
body: parts.map(x => raw(String(x?.body ?? ''))),
|
|
237
|
-
clients,
|
|
238
|
-
messages,
|
|
239
|
-
notices,
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/** A page with what the plugins add, their notices among the page's. */
|
|
189
|
+
/** A page as the server serves it: the render with what the plugins add, their failures among its notices. */
|
|
244
190
|
async function page(req: IncomingMessage, stored: StoredPage, rendered: Render): Promise<string> {
|
|
245
|
-
const
|
|
246
|
-
|
|
191
|
+
const notices = [...rendered.notices]
|
|
192
|
+
const parts = await pluginParts(await pluginHooks(), req, {
|
|
193
|
+
asset,
|
|
194
|
+
messages: [...(await config()).forReader],
|
|
195
|
+
failed: message => {
|
|
196
|
+
console.error(message)
|
|
197
|
+
notices.push(message)
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
return pageDocument(stored, { ...rendered, notices }, parts, {
|
|
201
|
+
live: true,
|
|
202
|
+
base,
|
|
203
|
+
asset,
|
|
204
|
+
runtime: `${base}/_/runtime.js`,
|
|
205
|
+
title: projectName(),
|
|
206
|
+
stamps: stamps(),
|
|
207
|
+
})
|
|
247
208
|
}
|
|
248
209
|
|
|
249
210
|
/** The loaded config. Also applies its `files` setting to what is served and watched. */
|
|
@@ -286,140 +247,11 @@ export function createServer(
|
|
|
286
247
|
return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
|
|
287
248
|
}
|
|
288
249
|
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
function inside(base: string, rel: string): string | null {
|
|
295
|
-
const p = path.resolve(base, '.' + path.posix.normalize('/' + rel))
|
|
296
|
-
return within(p, base) ? p : null
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
|
|
300
|
-
|
|
301
|
-
/** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
|
|
302
|
-
function frontmatter(source: string): { data: Record<string, unknown>; error: string | null } {
|
|
303
|
-
const m = FRONTMATTER.exec(source)
|
|
304
|
-
if (!m) return { data: {}, error: null }
|
|
305
|
-
let data: unknown
|
|
306
|
-
try {
|
|
307
|
-
data = parseYaml(m[1]!)
|
|
308
|
-
} catch (err) {
|
|
309
|
-
return { data: {}, error: (err as Error).message }
|
|
310
|
-
}
|
|
311
|
-
if (data == null) return { data: {}, error: null }
|
|
312
|
-
if (typeof data !== 'object' || Array.isArray(data))
|
|
313
|
-
return { data: {}, error: 'it must be fields (`key: value` lines), not a single value or a list' }
|
|
314
|
-
return { data: data as Record<string, unknown>, error: null }
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
function pageSource(id: string, file: string): PageSource {
|
|
318
|
-
const source = fs.readFileSync(file, 'utf8')
|
|
319
|
-
return {
|
|
320
|
-
kind: 'page',
|
|
321
|
-
id,
|
|
322
|
-
file,
|
|
323
|
-
mtime: fs.statSync(file).mtimeMs,
|
|
324
|
-
source,
|
|
325
|
-
body: source.replace(FRONTMATTER, ''),
|
|
326
|
-
...(({ data, error }) => ({ frontmatter: data, frontmatterError: error }))(frontmatter(source)),
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
/** The pages in a folder of the pages folder, newest first, with when each was last answered. */
|
|
331
|
-
function pagesIn(dir: string): PagesSource['pages'] {
|
|
332
|
-
const last = new Map<string, string>()
|
|
333
|
-
// the last time the reader sent something: what the agent appended doesn't count
|
|
334
|
-
for (const e of readEvents(project.eventsFile)) if (fromReader(e)) last.set(e.page, e.ts)
|
|
335
|
-
const out: PagesSource['pages'] = []
|
|
336
|
-
const walk = (d: string) => {
|
|
337
|
-
if (!fs.existsSync(d)) return
|
|
338
|
-
for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
|
|
339
|
-
if (ent.name.startsWith('.') || ent.name === 'node_modules') continue
|
|
340
|
-
const full = path.join(d, ent.name)
|
|
341
|
-
if (ent.isDirectory()) walk(full)
|
|
342
|
-
else if (ent.name.endsWith('.md')) {
|
|
343
|
-
const id = path.relative(project.pagesDir, full).split(path.sep).join('/').replace(/\.md$/, '')
|
|
344
|
-
out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: last.get(id) ?? null, awaiting: 0 })
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
walk(dir)
|
|
349
|
-
return out.sort((a, b) => b.mtime - a.mtime)
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
/** Text files show as files; anything with a NUL byte near the start is binary. */
|
|
353
|
-
function isText(file: string): boolean {
|
|
354
|
-
const fd = fs.openSync(file, 'r')
|
|
355
|
-
const buf = Buffer.alloc(8192)
|
|
356
|
-
const n = fs.readSync(fd, buf, 0, buf.length, 0)
|
|
357
|
-
fs.closeSync(fd)
|
|
358
|
-
return !buf.subarray(0, n).includes(0)
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
/**
|
|
362
|
-
* A page id → the stored page, or one of: { redirect } (a folder asked for without its slash),
|
|
363
|
-
* { raw: file } (serve the bytes), null (nothing there).
|
|
364
|
-
*/
|
|
365
|
-
function stored(id: string): StoredPage | { raw: string } | null {
|
|
366
|
-
if (!id) return { kind: 'pages', id: '', file: project.pagesDir, mtime: null, pages: pagesIn(project.pagesDir) }
|
|
367
|
-
if (isRepoId(id)) {
|
|
368
|
-
const rel = id.slice(2)
|
|
369
|
-
const target = inside(project.dir, rel)
|
|
370
|
-
if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target))
|
|
371
|
-
return null
|
|
372
|
-
const stat = fs.statSync(target)
|
|
373
|
-
if (stat.isDirectory()) {
|
|
374
|
-
const entries = fs
|
|
375
|
-
.readdirSync(target, { withFileTypes: true })
|
|
376
|
-
.filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
|
|
377
|
-
.map(e => ({ name: e.name, dir: e.isDirectory() }))
|
|
378
|
-
.sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name))
|
|
379
|
-
return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
|
|
380
|
-
}
|
|
381
|
-
if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
|
|
382
|
-
if (stat.size > 1e6 || !isText(target)) return { raw: target }
|
|
383
|
-
return { kind: 'file', id, file: target, mtime: stat.mtimeMs, source: fs.readFileSync(target, 'utf8') }
|
|
384
|
-
}
|
|
385
|
-
const target = inside(project.pagesDir, id)
|
|
386
|
-
if (!target) return null
|
|
387
|
-
if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target }
|
|
388
|
-
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
|
|
389
|
-
const index = path.join(target, 'index.md')
|
|
390
|
-
if (fs.existsSync(index)) return pageSource(id, index)
|
|
391
|
-
return { kind: 'pages', id, file: target, mtime: null, pages: pagesIn(target) }
|
|
392
|
-
}
|
|
393
|
-
const file = target + '.md'
|
|
394
|
-
return fs.existsSync(file) ? pageSource(id, file) : null
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
/** The URL that serves a file or folder on disk, or null when nothing here serves it. */
|
|
398
|
-
function urlOf(abs: string): string | null {
|
|
399
|
-
const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
|
|
400
|
-
if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, '')}`
|
|
401
|
-
if (FILES && within(abs, project.dir)) {
|
|
402
|
-
if (
|
|
403
|
-
rel(project.dir)
|
|
404
|
-
.split('/')
|
|
405
|
-
.some(part => SKIP_DIRS.has(part))
|
|
406
|
-
)
|
|
407
|
-
return null
|
|
408
|
-
return `${base}/-/${rel(project.dir)}`
|
|
409
|
-
}
|
|
410
|
-
return null
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
/** For links: the target if it exists (also with .md added), mapped to its URL. */
|
|
414
|
-
function urlFor(abs: string): string | null {
|
|
415
|
-
for (const candidate of [abs, abs + '.md']) {
|
|
416
|
-
if (fs.existsSync(candidate)) {
|
|
417
|
-
const url = urlOf(candidate)
|
|
418
|
-
if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith('/') ? '/' : '')
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
return null
|
|
422
|
-
}
|
|
250
|
+
// ---- stored pages: the site (site.ts) --------------------------------------------------------------
|
|
251
|
+
const site = servedSite(project, { base, files: () => !!FILES })
|
|
252
|
+
const stored = site.page
|
|
253
|
+
const pagesIn = site.pagesIn
|
|
254
|
+
const urlFor = site.urlFor
|
|
423
255
|
|
|
424
256
|
// ---- rendering ---------------------------------------------------------------------------------
|
|
425
257
|
|
|
@@ -450,16 +282,6 @@ export function createServer(
|
|
|
450
282
|
...(entry && { entry: { name: entry, label } }),
|
|
451
283
|
})
|
|
452
284
|
|
|
453
|
-
/** A render as the shell takes it. `page`: whether the page's browser part runs (not on raw text). */
|
|
454
|
-
interface Render {
|
|
455
|
-
page: boolean
|
|
456
|
-
out: Rendered
|
|
457
|
-
notices: string[]
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
|
|
461
|
-
const frontmatterOf = (page: StoredPage): Record<string, unknown> => (page.kind === 'page' ? page.frontmatter : {})
|
|
462
|
-
|
|
463
285
|
/** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
|
|
464
286
|
async function render(page: StoredPage): Promise<Render> {
|
|
465
287
|
const { pages, errors } = await config()
|
|
@@ -481,52 +303,67 @@ export function createServer(
|
|
|
481
303
|
}
|
|
482
304
|
|
|
483
305
|
/**
|
|
484
|
-
*
|
|
485
|
-
*
|
|
486
|
-
*
|
|
306
|
+
* The project's status (status.ts): the pages, below `only` when given, with their questions, the
|
|
307
|
+
* log read once, and who listens. What `whiteboard status`, the hooks, the page lists and the log's
|
|
308
|
+
* picked-up marks take.
|
|
487
309
|
*/
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
let asks: string[] = []
|
|
501
|
-
try {
|
|
502
|
-
asks = pages?.questions(page) ?? []
|
|
503
|
-
} catch (err) {
|
|
504
|
-
console.error('questions:', err)
|
|
505
|
-
}
|
|
506
|
-
const events = all.filter(e => e.page === p.id)
|
|
507
|
-
const listening = listenersFor(p.id)
|
|
508
|
-
// where each question stands, as the page shows it (see status.ts)
|
|
509
|
-
const questions = asks.map(name => ({
|
|
510
|
-
name,
|
|
511
|
-
state: questionState(name, events, listening, id => picked.has(id)).state,
|
|
512
|
-
}))
|
|
513
|
-
const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
|
|
514
|
-
out.push({
|
|
515
|
-
page: p.id,
|
|
516
|
-
title: titleOf(p.file, path.basename(p.id)),
|
|
517
|
-
file: p.file,
|
|
518
|
-
owner: owner.get(p.id) ?? null,
|
|
519
|
-
asks,
|
|
520
|
-
questions,
|
|
521
|
-
open: named('open'),
|
|
522
|
-
unheard: named('open').filter(name => !heard(name, listening)),
|
|
523
|
-
unread: unreadMessages(events, type => forReader.has(type)),
|
|
524
|
-
// the reader's events for an agent: a form's answers, and plugin events declared handOut
|
|
525
|
-
unpicked: events.filter(e => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
|
|
526
|
-
listeners: listening,
|
|
527
|
-
})
|
|
310
|
+
// Each page's questions and title, kept while its file and the config stay as they are: parsing
|
|
311
|
+
// every page's markdown on each ask was most of what a status cost.
|
|
312
|
+
const asked = new Map<
|
|
313
|
+
string,
|
|
314
|
+
{ file: string; mtime: number; size: number; renderer: unknown; title: string; asks: string[] }
|
|
315
|
+
>()
|
|
316
|
+
function questionsOf(renderer: LoadedConfig['pages'], id: string, file: string): { title: string; asks: string[] } {
|
|
317
|
+
let stat: fs.Stats
|
|
318
|
+
try {
|
|
319
|
+
stat = fs.statSync(file)
|
|
320
|
+
} catch {
|
|
321
|
+
return { title: path.basename(id), asks: [] }
|
|
528
322
|
}
|
|
529
|
-
|
|
323
|
+
const kept = asked.get(id)
|
|
324
|
+
if (
|
|
325
|
+
kept &&
|
|
326
|
+
kept.file === file &&
|
|
327
|
+
kept.mtime === stat.mtimeMs &&
|
|
328
|
+
kept.size === stat.size &&
|
|
329
|
+
kept.renderer === renderer
|
|
330
|
+
)
|
|
331
|
+
return kept
|
|
332
|
+
let asks: string[] = []
|
|
333
|
+
try {
|
|
334
|
+
asks = renderer?.questions(pageSource(id, file)) ?? []
|
|
335
|
+
} catch (err) {
|
|
336
|
+
console.error('questions:', err)
|
|
337
|
+
}
|
|
338
|
+
const now = { file, mtime: stat.mtimeMs, size: stat.size, renderer, title: titleOf(file, path.basename(id)), asks }
|
|
339
|
+
asked.set(id, now)
|
|
340
|
+
return now
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function snapshot(listed: PagesSource['pages']): Promise<ProjectStatus> {
|
|
344
|
+
const { pages: renderer, handedOut, forReader } = await config()
|
|
345
|
+
const pages = listed.map(p => ({ id: p.id, file: p.file, ...questionsOf(renderer, p.id, p.file) }))
|
|
346
|
+
return projectStatus({
|
|
347
|
+
pages,
|
|
348
|
+
events: readEvents(project.eventsFile),
|
|
349
|
+
listeners: listenersFor,
|
|
350
|
+
forAgent: forAgent(handedOut),
|
|
351
|
+
forReader: type => forReader.has(type),
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Per page, below `only` when given: what `whiteboard status` and the hooks report (see snapshot). */
|
|
356
|
+
const status = async (only: string | null): Promise<PageStatus[]> =>
|
|
357
|
+
(await snapshot(pagesIn(project.pagesDir).filter(p => !only || p.id === only || p.id.startsWith(only + '/')))).pages
|
|
358
|
+
|
|
359
|
+
/** A list of pages, with when each was last answered and how much waits on it, from one status. */
|
|
360
|
+
async function withStatus(pages: PagesSource['pages']): Promise<PagesSource['pages']> {
|
|
361
|
+
const s = await snapshot(pages)
|
|
362
|
+
pages.forEach((p, i) => {
|
|
363
|
+
p.awaiting = awaiting(s.pages[i]!)
|
|
364
|
+
p.lastEvent = s.lastAnswered(p.id)
|
|
365
|
+
})
|
|
366
|
+
return pages
|
|
530
367
|
}
|
|
531
368
|
|
|
532
369
|
/** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
|
|
@@ -554,101 +391,78 @@ export function createServer(
|
|
|
554
391
|
return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
|
|
555
392
|
}
|
|
556
393
|
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
): string {
|
|
581
|
-
const handoff = {
|
|
582
|
-
id: page.id,
|
|
583
|
-
kind: page.kind,
|
|
584
|
-
live: !built,
|
|
585
|
-
// what the page's own requests start with (see ServerOptions.base)
|
|
586
|
-
base: built ? '' : base,
|
|
587
|
-
client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
|
|
588
|
-
data: out.data ?? null,
|
|
589
|
-
frontmatter: frontmatterOf(page),
|
|
590
|
-
plugins: extras.clients,
|
|
591
|
-
messages: extras.messages ?? [],
|
|
394
|
+
/**
|
|
395
|
+
* What the browser runs and how it looks, as two stamps: one over its code (the runtime, the page's
|
|
396
|
+
* module, the plugins' scripts), one over its stylesheets (the engine's, the plugins', the
|
|
397
|
+
* project's in .whiteboard/). A page gets them with its HTML and asks again when its live channel
|
|
398
|
+
* is back: what changed while it was away (a restart, a background tab whose browser held its
|
|
399
|
+
* timers), it would otherwise never hear of. Made from the files themselves, not from what was
|
|
400
|
+
* served since the server started, so a fresh server gives the same stamps for the same files.
|
|
401
|
+
*/
|
|
402
|
+
function stamps(): { code: string; style: string } {
|
|
403
|
+
const files: string[] = [RUNTIME]
|
|
404
|
+
const add = (dir: string, deep: boolean) => {
|
|
405
|
+
let entries: fs.Dirent[]
|
|
406
|
+
try {
|
|
407
|
+
entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
408
|
+
} catch {
|
|
409
|
+
return
|
|
410
|
+
}
|
|
411
|
+
for (const e of entries) {
|
|
412
|
+
const full = path.join(dir, e.name)
|
|
413
|
+
if (e.isDirectory()) {
|
|
414
|
+
if (deep) add(full, deep)
|
|
415
|
+
} else files.push(full)
|
|
416
|
+
}
|
|
592
417
|
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
<div id="wb-dock"></div>
|
|
610
|
-
<script type="application/json" id="wb-page">
|
|
611
|
-
${raw(json(handoff))}
|
|
612
|
-
</script>
|
|
613
|
-
<script type="module" src="${built ? built.asset(RUNTIME) : `${base}/_/runtime.js`}"></script>
|
|
614
|
-
${extras.body}
|
|
615
|
-
</body>
|
|
616
|
-
</html>`,
|
|
617
|
-
)
|
|
418
|
+
add(path.dirname(PAGE_CLIENT), false)
|
|
419
|
+
for (const dir of publicDirs) add(dir, true)
|
|
420
|
+
for (const f of fs.readdirSync(project.wb).filter(f => f.endsWith('.css'))) files.push(path.join(project.wb, f))
|
|
421
|
+
const of = (list: string[]) => {
|
|
422
|
+
const hash = crypto.createHash('sha1')
|
|
423
|
+
for (const f of [...new Set(list)].toSorted()) {
|
|
424
|
+
try {
|
|
425
|
+
const st = fs.statSync(f)
|
|
426
|
+
hash.update(`${f}\0${st.mtimeMs}\0${st.size}\n`)
|
|
427
|
+
} catch {
|
|
428
|
+
/* gone */
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return hash.digest('hex').slice(0, 16)
|
|
432
|
+
}
|
|
433
|
+
return { code: of(files.filter(f => !f.endsWith('.css'))), style: of(files.filter(f => f.endsWith('.css'))) }
|
|
618
434
|
}
|
|
619
435
|
|
|
620
436
|
// ---- listeners ---------------------------------------------------------------------------------
|
|
621
|
-
// An agent waiting for answers
|
|
622
|
-
// as long as it runs: that connection is the listener, gone when the command is. Pages show what an
|
|
437
|
+
// An agent waiting for answers holds a connection to /api/listen (listeners.ts). Pages show what an
|
|
623
438
|
// agent is waiting for from these, so nothing depends on the agent marking it.
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
const listeners = new Set<Listener>()
|
|
627
|
-
|
|
628
|
-
const listenersFor = (page: string | null): Listener[] =>
|
|
629
|
-
[...listeners]
|
|
630
|
-
.filter(l => page == null || covers(l, page))
|
|
631
|
-
.map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
|
|
439
|
+
const registry = createRegistry()
|
|
440
|
+
const listenersFor = (page: string | null): Listener[] => registry.list(page)
|
|
632
441
|
|
|
633
442
|
// ---- live changes ------------------------------------------------------------------------------
|
|
634
|
-
// The browser listens at /api/
|
|
635
|
-
// `listeners`: an agent started or stopped waiting; `style`:
|
|
636
|
-
// browser code changed; `scroll`: an agent shows the reader a place
|
|
637
|
-
|
|
638
|
-
|
|
443
|
+
// The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
|
|
444
|
+
// page changed; `events`: the log grew; `listeners`: an agent started or stopped waiting; `style`:
|
|
445
|
+
// a stylesheet changed; `reload`: browser code changed; `scroll`: an agent shows the reader a place
|
|
446
|
+
// on the page ({ to }); `elsewhere`: under a shared server, what waits in another project changed.
|
|
447
|
+
// /api/watch says the same as server-sent events, for a tab opened before
|
|
448
|
+
// /api/live: it tells it to reload first, so it moves to the WebSocket (see ws.ts for why).
|
|
449
|
+
|
|
450
|
+
/** A browser following its page; `pending`: what it will be told in a moment. */
|
|
639
451
|
interface WatchClient {
|
|
640
|
-
|
|
452
|
+
send(event: string, data?: unknown): void
|
|
641
453
|
page: string
|
|
642
454
|
isDir: boolean
|
|
643
455
|
pending?: Set<string>
|
|
644
456
|
}
|
|
645
457
|
|
|
646
458
|
const clients = new Set<WatchClient>()
|
|
459
|
+
/** what the browser appended lately, by id: a send it retries is answered with what it got */
|
|
460
|
+
const appended = new Map<string, WbEvent>()
|
|
647
461
|
function notify(client: WatchClient, kind: string) {
|
|
648
462
|
client.pending ??= new Set()
|
|
649
463
|
if (client.pending.size === 0)
|
|
650
464
|
setTimeout(() => {
|
|
651
|
-
for (const k of client.pending!) client.
|
|
465
|
+
for (const k of client.pending!) client.send(k)
|
|
652
466
|
client.pending!.clear()
|
|
653
467
|
}, 60)
|
|
654
468
|
client.pending.add(kind)
|
|
@@ -656,6 +470,11 @@ export function createServer(
|
|
|
656
470
|
const notifyAll = (kind: string) => {
|
|
657
471
|
for (const c of clients) notify(c, kind)
|
|
658
472
|
}
|
|
473
|
+
// who listens shows on this project's pages, and, under a shared server, on the others' (onChange)
|
|
474
|
+
registry.onChange(() => {
|
|
475
|
+
notifyAll('listeners')
|
|
476
|
+
onChange?.()
|
|
477
|
+
})
|
|
659
478
|
|
|
660
479
|
function pageChanged(id: string) {
|
|
661
480
|
onChange?.()
|
|
@@ -799,8 +618,7 @@ export function createServer(
|
|
|
799
618
|
return { redirect: `${base}/${id}/` }
|
|
800
619
|
// a list of pages says which await the reader: where their questions stand takes the config
|
|
801
620
|
if (found.kind === 'pages') {
|
|
802
|
-
|
|
803
|
-
for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0
|
|
621
|
+
await withStatus(found.pages)
|
|
804
622
|
if (!found.id && overview) Object.assign(found, await overview())
|
|
805
623
|
}
|
|
806
624
|
return { page: found }
|
|
@@ -854,7 +672,13 @@ export function createServer(
|
|
|
854
672
|
if (p === '/api/events' && req.method === 'POST') {
|
|
855
673
|
const body = JSON.parse(await readBody(req))
|
|
856
674
|
if (!body.type) return sendJson(res, 400, { error: 'event type required' })
|
|
857
|
-
|
|
675
|
+
// the browser sends it again when it heard nothing back: appended once, the same answer twice
|
|
676
|
+
const again = isEventId(body.id) ? appended.get(body.id) : undefined
|
|
677
|
+
if (again) return sendJson(res, 200, again)
|
|
678
|
+
const event = appendEvent(project.eventsFile, body)
|
|
679
|
+
appended.set(event.id, event)
|
|
680
|
+
if (appended.size > 1000) appended.delete(appended.keys().next().value!)
|
|
681
|
+
return sendJson(res, 200, event)
|
|
858
682
|
}
|
|
859
683
|
// an agent shows the reader a place on a page: every tab with it open scrolls there
|
|
860
684
|
// ({ page, to }: a heading's text, a form's name or any text) → { tabs }
|
|
@@ -862,12 +686,12 @@ export function createServer(
|
|
|
862
686
|
const { page: id, to } = JSON.parse(await readBody(req)) as { page?: unknown; to?: unknown }
|
|
863
687
|
if (typeof id !== 'string' || typeof to !== 'string' || !to.trim())
|
|
864
688
|
return sendJson(res, 400, { error: 'page and to required' })
|
|
689
|
+
// in the log, so a tab that isn't connected now (a server restarting, a background tab
|
|
690
|
+
// whose browser holds its timers) still scrolls there once it is back; a page loaded later
|
|
691
|
+
// doesn't (see the runtime)
|
|
692
|
+
appendEvent(project.eventsFile, { page: id, type: SCROLL, data: { to } }, 'cli')
|
|
865
693
|
let tabs = 0
|
|
866
|
-
for (const c of clients)
|
|
867
|
-
if (c.isDir || (c.page !== id && c.page + '/index' !== id)) continue
|
|
868
|
-
c.res.write(`event: scroll\ndata: ${JSON.stringify({ to })}\n\n`)
|
|
869
|
-
tabs++
|
|
870
|
-
}
|
|
694
|
+
for (const c of clients) if (!c.isDir && (c.page === id || c.page + '/index' === id)) tabs++
|
|
871
695
|
return sendJson(res, 200, { tabs })
|
|
872
696
|
}
|
|
873
697
|
// messages (comments, chat) written in markdown, as HTML: { texts } → { html, styles }
|
|
@@ -896,39 +720,21 @@ export function createServer(
|
|
|
896
720
|
if (p === '/api/docs') return sendJson(res, 200, await docs())
|
|
897
721
|
if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
|
|
898
722
|
if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
|
|
723
|
+
if (p === '/api/stamps') return sendJson(res, 200, stamps())
|
|
899
724
|
if (p === '/api/listen') {
|
|
900
|
-
const
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
})
|
|
909
|
-
res.write(': listening\n\n')
|
|
910
|
-
const l: Listener = {
|
|
911
|
-
page: q.page || '',
|
|
912
|
-
type: q.type || null,
|
|
913
|
-
command: q.command === 'wait' ? 'wait' : 'watch',
|
|
914
|
-
...(fallback && { fallback }),
|
|
915
|
-
}
|
|
916
|
-
listeners.add(l)
|
|
917
|
-
notifyAll('listeners')
|
|
918
|
-
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
919
|
-
const end = () => {
|
|
920
|
-
clearInterval(ping)
|
|
921
|
-
listeners.delete(l)
|
|
922
|
-
streams.delete(end)
|
|
923
|
-
}
|
|
924
|
-
streams.add(() => {
|
|
925
|
-
end()
|
|
926
|
-
res.end()
|
|
927
|
-
})
|
|
928
|
-
req.on('close', () => {
|
|
929
|
-
end()
|
|
930
|
-
notifyAll('listeners')
|
|
725
|
+
const remove = registry.add(listenerOf(url.searchParams))
|
|
726
|
+
if (!remove) return sendJson(res, 409, { error: 'another agent is the fallback already' })
|
|
727
|
+
// a fallback is told who else listens, at once and on every change
|
|
728
|
+
const off = 'fallback' in q ? registry.onChange(() => tell()) : () => {}
|
|
729
|
+
const stream = holdStream(req, res, () => {
|
|
730
|
+
off()
|
|
731
|
+
remove()
|
|
732
|
+
streams.delete(stream.end)
|
|
931
733
|
})
|
|
734
|
+
const tell = () =>
|
|
735
|
+
stream.send('listeners', { projects: [{ dir: project.dir, base, listeners: registry.list() }] })
|
|
736
|
+
if ('fallback' in q) tell()
|
|
737
|
+
streams.add(stream.end)
|
|
932
738
|
return
|
|
933
739
|
}
|
|
934
740
|
if (p === '/api/page' || p === '/api/render') {
|
|
@@ -945,8 +751,14 @@ export function createServer(
|
|
|
945
751
|
connection: 'keep-alive',
|
|
946
752
|
})
|
|
947
753
|
res.write(': connected\n\n')
|
|
948
|
-
const client = {
|
|
754
|
+
const client: WatchClient = {
|
|
755
|
+
send: (event, data = {}) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
|
|
756
|
+
page: q.page || '',
|
|
757
|
+
isDir: 'dir' in q,
|
|
758
|
+
}
|
|
949
759
|
clients.add(client)
|
|
760
|
+
// a tab from before /api/live: onto the WebSocket, which leaves its connection free
|
|
761
|
+
client.send('reload')
|
|
950
762
|
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
951
763
|
const end = () => {
|
|
952
764
|
clearInterval(ping)
|
|
@@ -987,246 +799,46 @@ export function createServer(
|
|
|
987
799
|
}
|
|
988
800
|
}
|
|
989
801
|
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
if (!cfg.pages) throw new Error('the config has no pages renderer')
|
|
1003
|
-
const pages = cfg.pages
|
|
1004
|
-
const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
|
|
1005
|
-
const patterns = defined(options.pages, cfg.build.pages) ?? []
|
|
1006
|
-
const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
|
|
1007
|
-
const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
|
|
1008
|
-
if (!patterns.length)
|
|
1009
|
-
throw new Error(
|
|
1010
|
-
"nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
|
|
1011
|
-
)
|
|
1012
|
-
const warnings: string[] = []
|
|
1013
|
-
|
|
1014
|
-
// the pages: markdown files the globs match, but those a `!` glob leaves out
|
|
1015
|
-
const include = patterns.filter(p => !p.startsWith('!'))
|
|
1016
|
-
const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
|
|
1017
|
-
const files = [
|
|
1018
|
-
...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
|
|
1019
|
-
]
|
|
1020
|
-
.filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
|
|
1021
|
-
.filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
|
|
1022
|
-
.sort()
|
|
1023
|
-
if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
|
|
1024
|
-
// each at its place below the folder they share; a README or index is its folder's index.html
|
|
1025
|
-
const base = files.map(path.dirname).reduce((a, b) => {
|
|
1026
|
-
while (!within(b, a)) a = path.dirname(a)
|
|
1027
|
-
return a
|
|
1028
|
-
})
|
|
1029
|
-
const outOf = (file: string) => {
|
|
1030
|
-
const rel = path.relative(base, file)
|
|
1031
|
-
return path.join(
|
|
1032
|
-
outDir,
|
|
1033
|
-
/^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
|
|
1034
|
-
? path.join(path.dirname(rel), 'index.html')
|
|
1035
|
-
: rel.replace(/\.(md|markdown)$/i, '.html'),
|
|
1036
|
-
)
|
|
802
|
+
/** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
|
|
803
|
+
function upgrade(req: IncomingMessage, conn: Duplex, _head: Buffer) {
|
|
804
|
+
const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
|
|
805
|
+
if (decodeURIComponent(url.pathname) !== '/api/live') return refuse(conn, 404, 'Not Found')
|
|
806
|
+
// no CORS for a WebSocket: any site could open one to localhost, so the origin is checked here
|
|
807
|
+
if (!sameSite(req)) return refuse(conn, 403, 'Forbidden')
|
|
808
|
+
const socket = accept(req, conn)
|
|
809
|
+
if (!socket) return
|
|
810
|
+
const client: WatchClient = {
|
|
811
|
+
send: (event, data = {}) => socket.send(JSON.stringify({ event, data })),
|
|
812
|
+
page: url.searchParams.get('page') ?? '',
|
|
813
|
+
isDir: url.searchParams.has('dir'),
|
|
1037
814
|
}
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
}
|
|
1046
|
-
fs.mkdirSync(outDir, { recursive: true })
|
|
1047
|
-
fs.writeFileSync(
|
|
1048
|
-
path.join(outDir, BUILD_MARK),
|
|
1049
|
-
'written by whiteboard build; the next build replaces this folder\n',
|
|
1050
|
-
)
|
|
1051
|
-
|
|
1052
|
-
// what a page loads, copied once: the package's files under _/whiteboard/, the project's under
|
|
1053
|
-
// _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
|
|
1054
|
-
const copied = new Map<string, string>()
|
|
1055
|
-
function copyAsset(file: string): string {
|
|
1056
|
-
const known = copied.get(file)
|
|
1057
|
-
if (known) return known
|
|
1058
|
-
const rel = within(file, ENGINE_DIR)
|
|
1059
|
-
? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
|
|
1060
|
-
: within(file, project.dir)
|
|
1061
|
-
? path.join('_', 'project', path.relative(project.dir, file))
|
|
1062
|
-
: path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
|
|
1063
|
-
const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
|
|
1064
|
-
copied.set(file, dest)
|
|
1065
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
1066
|
-
if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
|
|
1067
|
-
else fs.copyFileSync(file, dest)
|
|
1068
|
-
// a stylesheet's own files (fonts, images), at the same places beside it
|
|
1069
|
-
if (/\.css$/i.test(file)) {
|
|
1070
|
-
for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
|
|
1071
|
-
const ref = m[1]!
|
|
1072
|
-
if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
|
|
1073
|
-
const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
|
|
1074
|
-
if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
return dest
|
|
1078
|
-
}
|
|
1079
|
-
/** a file beside the pages (an image), copied to its place below the site */
|
|
1080
|
-
function copyBeside(file: string): string | null {
|
|
1081
|
-
if (!within(file, base)) return null
|
|
1082
|
-
const dest = path.join(outDir, path.relative(base, file))
|
|
1083
|
-
if (!fs.existsSync(dest)) {
|
|
1084
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
1085
|
-
fs.copyFileSync(file, dest)
|
|
1086
|
-
}
|
|
1087
|
-
return dest
|
|
1088
|
-
}
|
|
1089
|
-
|
|
1090
|
-
const hooks = await pluginHooks()
|
|
1091
|
-
const result: BuildResult = { out: outDir, pages: [], warnings }
|
|
1092
|
-
for (const [file, dest] of built) {
|
|
1093
|
-
const here = path.dirname(dest)
|
|
1094
|
-
const relTo = (target: string) =>
|
|
1095
|
-
path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
|
|
1096
|
-
const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
|
|
1097
|
-
const urlFor = (abs: string): string | null => {
|
|
1098
|
-
for (const candidate of [abs, abs + '.md']) {
|
|
1099
|
-
if (!fs.existsSync(candidate)) continue
|
|
1100
|
-
if (fs.statSync(candidate).isDirectory()) {
|
|
1101
|
-
const index = [...built.keys()].find(
|
|
1102
|
-
f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
|
|
1103
|
-
)
|
|
1104
|
-
if (index) return relTo(built.get(index)!)
|
|
1105
|
-
continue
|
|
1106
|
-
}
|
|
1107
|
-
if (built.has(candidate)) return relTo(built.get(candidate)!)
|
|
1108
|
-
if (/\.(md|markdown)$/i.test(candidate)) {
|
|
1109
|
-
warnings.push(
|
|
1110
|
-
`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
|
|
1111
|
-
)
|
|
1112
|
-
return null
|
|
1113
|
-
}
|
|
1114
|
-
const copy = copyBeside(candidate)
|
|
1115
|
-
if (copy) return relTo(copy)
|
|
1116
|
-
warnings.push(
|
|
1117
|
-
`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
|
|
1118
|
-
)
|
|
1119
|
-
return null
|
|
1120
|
-
}
|
|
1121
|
-
return null
|
|
1122
|
-
}
|
|
1123
|
-
const id = within(file, project.pagesDir)
|
|
1124
|
-
? path
|
|
1125
|
-
.relative(project.pagesDir, file)
|
|
1126
|
-
.split(path.sep)
|
|
1127
|
-
.join('/')
|
|
1128
|
-
.replace(/\.(md|markdown)$/i, '')
|
|
1129
|
-
: '-/' + path.relative(project.dir, file).split(path.sep).join('/')
|
|
1130
|
-
const stored = pageSource(id, file)
|
|
1131
|
-
if (stored.frontmatterError)
|
|
1132
|
-
warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
|
|
1133
|
-
const context = {
|
|
1134
|
-
project: { name: project.name, dir: project.dir, files: !!FILES },
|
|
1135
|
-
asset: assetHere,
|
|
1136
|
-
urlFor,
|
|
1137
|
-
live: false,
|
|
1138
|
-
skip,
|
|
1139
|
-
}
|
|
1140
|
-
const rendered = await pages.render(stored, context)
|
|
1141
|
-
// a page without a heading of its own is named by its file (a README by its folder), not by
|
|
1142
|
-
// the id the server knows it by
|
|
1143
|
-
const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
|
|
1144
|
-
? path.basename(path.dirname(file))
|
|
1145
|
-
: path.basename(file).replace(/\.(md|markdown)$/i, '')
|
|
1146
|
-
const title = !rendered.title || rendered.title === id ? named : rendered.title
|
|
1147
|
-
const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
|
|
1148
|
-
// the plugins' browser modules, but those the build leaves out; not what they add to a live
|
|
1149
|
-
// page's shell (the terminal's drawer): that is the server's
|
|
1150
|
-
const included = hooks.filter(h => !h.error && !skip.has(h.name))
|
|
1151
|
-
const clients = included.filter(h => h.client).map(h => ({ name: h.name, client: assetHere(h.client!) }))
|
|
1152
|
-
// what the plugins add to the shell, asked with no request: no browser asked for this page
|
|
1153
|
-
const parts = await Promise.all(
|
|
1154
|
-
included.map(async h => {
|
|
1155
|
-
try {
|
|
1156
|
-
return (await h.shell?.(null)) ?? null
|
|
1157
|
-
} catch (err) {
|
|
1158
|
-
warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${(err as Error).message}`)
|
|
1159
|
-
return null
|
|
1160
|
-
}
|
|
1161
|
-
}),
|
|
1162
|
-
)
|
|
1163
|
-
const extras = {
|
|
1164
|
-
head: parts.map(x => raw(String(x?.head ?? ''))),
|
|
1165
|
-
body: parts.map(x => raw(String(x?.body ?? ''))),
|
|
1166
|
-
clients,
|
|
1167
|
-
}
|
|
1168
|
-
let doc = shell(stored, { page: true, out, notices: [] }, extras, { asset: assetHere })
|
|
1169
|
-
// a file a plugin named the server's way (its asset URL, /_/file/<path>): its copy
|
|
1170
|
-
doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served: string) => {
|
|
1171
|
-
let file: string
|
|
1172
|
-
try {
|
|
1173
|
-
file = path.resolve(served.split('/').map(decodeURIComponent).join(path.sep))
|
|
1174
|
-
} catch {
|
|
1175
|
-
return all
|
|
1176
|
-
}
|
|
1177
|
-
return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all
|
|
1178
|
-
})
|
|
1179
|
-
// what the blocks name relative to the page (an ::image's src, an iframe's page): copied too
|
|
1180
|
-
doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref: string) => {
|
|
1181
|
-
if (ref.startsWith('/') || ref.startsWith('_/') || ref.startsWith('../')) return all
|
|
1182
|
-
let decoded = ref
|
|
1183
|
-
try {
|
|
1184
|
-
decoded = decodeURIComponent(ref)
|
|
1185
|
-
} catch {
|
|
1186
|
-
/* as written */
|
|
1187
|
-
}
|
|
1188
|
-
const source = path.resolve(path.dirname(file), decoded)
|
|
1189
|
-
if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
|
|
1190
|
-
const target = path.resolve(here, decoded)
|
|
1191
|
-
if (within(target, outDir) && !fs.existsSync(target)) {
|
|
1192
|
-
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
1193
|
-
fs.copyFileSync(source, target)
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
return all
|
|
1197
|
-
})
|
|
1198
|
-
fs.mkdirSync(here, { recursive: true })
|
|
1199
|
-
fs.writeFileSync(dest, doc)
|
|
1200
|
-
result.pages.push({ file, to: dest })
|
|
1201
|
-
}
|
|
1202
|
-
if (![...built.values()].includes(path.join(outDir, 'index.html')))
|
|
1203
|
-
warnings.push('no README.md or index.md in the top folder: the site has no index.html')
|
|
1204
|
-
return result
|
|
815
|
+
clients.add(client)
|
|
816
|
+
const stop = () => socket.close()
|
|
817
|
+
streams.add(stop)
|
|
818
|
+
socket.onClose(() => {
|
|
819
|
+
clients.delete(client)
|
|
820
|
+
streams.delete(stop)
|
|
821
|
+
})
|
|
1205
822
|
}
|
|
1206
823
|
|
|
1207
824
|
return {
|
|
1208
825
|
handle,
|
|
826
|
+
upgrade,
|
|
1209
827
|
listeners: () => listenersFor(null),
|
|
1210
828
|
async overview() {
|
|
1211
829
|
await config()
|
|
1212
|
-
const pages = pagesIn(project.pagesDir)
|
|
1213
|
-
const counts = new Map((await status(null)).map(s => [s.page, awaiting(s)]))
|
|
1214
|
-
for (const p of pages) p.awaiting = counts.get(p.id) ?? 0
|
|
830
|
+
const pages = await withStatus(pagesIn(project.pagesDir))
|
|
1215
831
|
return { pages, files: !!FILES }
|
|
1216
832
|
},
|
|
1217
833
|
touch() {
|
|
1218
834
|
for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
|
|
1219
835
|
},
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
return () => {
|
|
1224
|
-
if (listeners.delete(l)) notifyAll('listeners')
|
|
1225
|
-
}
|
|
1226
|
-
},
|
|
836
|
+
elsewhere: () => notifyAll('elsewhere'),
|
|
837
|
+
addListener: l => registry.add(l),
|
|
838
|
+
onListeners: fn => registry.onChange(fn),
|
|
1227
839
|
status: (page = null) => status(page),
|
|
1228
840
|
config,
|
|
1229
|
-
build,
|
|
841
|
+
build: options => build({ project, config, hooks: pluginHooks, files: () => !!FILES }, options),
|
|
1230
842
|
close() {
|
|
1231
843
|
for (const w of watchers) w.close()
|
|
1232
844
|
watchers.clear()
|