@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
@@ -1,23 +1,23 @@
1
- import { appendEvent, forAgent, isEventId, matches, pickedUp, readEvents } from "./events.js";
2
- import { html, raw } from "./html.js";
1
+ import { appendEvent, forAgent, isEventId, matches, readEvents } from "./events.js";
2
+ import { html } from "./html.js";
3
3
  import { createConfigLoader, pluginDir, toPath } from "./loader.js";
4
4
  import { describeRoutes, dispatch, mountRoutes, pluginCommands, usage } from "./plugins.js";
5
5
  import { createAuth, sameSite } from "./auth.js";
6
6
  import { accept, refuse } from "./ws.js";
7
7
  import { FROM_SOURCE, PACKAGE_DIR, VERSION } from "./package.js";
8
- import { awaiting, covers, fromReader, heard, questionState, unreadMessages } from "./status.js";
8
+ import { SCROLL, awaiting, pickedUp, projectStatus } from "./status.js";
9
9
  import { titleOf } from "./pages/render.js";
10
+ import { createRegistry, holdStream, listenerOf } from "./listeners.js";
10
11
  import { inPublic } from "./public.js";
11
- import _taggedTemplateLiteral from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js";
12
+ import { build } from "./build.js";
13
+ import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts } from "./document.js";
14
+ import { SKIP_DIRS, isRepoId, pageSource, servedSite, within } from "./site.js";
12
15
  import { stripTypeScriptTypes } from "node:module";
13
16
  import fs from "node:fs";
14
17
  import path from "node:path";
15
- import { parse } from "yaml";
18
+ import crypto from "node:crypto";
16
19
  // src/server.ts
17
- var _templateObject;
18
20
  const ENGINE_DIR = PACKAGE_DIR;
19
- const RUNTIME = path.join(ENGINE_DIR, "dist", "client", "runtime.js");
20
- const PAGE_CLIENT = path.join(ENGINE_DIR, "dist", "src", "client", "page", "main.js");
21
21
  const MIME = {
22
22
  ".css": "text/css",
23
23
  ".js": "text/javascript",
@@ -47,8 +47,6 @@ const OWN_FILES = /* @__PURE__ */ new Set([
47
47
  "server.lock",
48
48
  "token"
49
49
  ]);
50
- const SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
51
- const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
52
50
  function createServer(project, { base = "", entry, label, name, files: filesOption, overview, onChange } = {}) {
53
51
  const projectName = () => name ?? project.name;
54
52
  const loader = createConfigLoader(project);
@@ -72,7 +70,6 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
72
70
  pluginDirs.add(e.name);
73
71
  const dataDir = pluginDir(project.wb, e.name);
74
72
  const dir = c.publicDirs.get(e.name);
75
- const own = (ref) => asset(inPublic(dir, ref, `plugin ${e.name}`));
76
73
  const hooks = await e.setup?.({
77
74
  project: {
78
75
  name: project.name,
@@ -80,8 +77,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
80
77
  wb: project.wb
81
78
  },
82
79
  dataDir,
83
- authorized: auth.authorized,
84
- asset: own
80
+ authorized: auth.authorized
85
81
  }) ?? {};
86
82
  const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : void 0;
87
83
  return {
@@ -103,38 +99,28 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
103
99
  })));
104
100
  return setups.get(c);
105
101
  }
106
- async function shellExtras(req) {
107
- const hooks = await pluginHooks();
108
- const notices = hooks.filter((h) => h.error).map((h) => `plugin "${h.name}" failed to start: ${h.error.message}`);
109
- const parts = await Promise.all(hooks.map(async (h) => {
110
- try {
111
- return await h.shell?.(req) ?? null;
112
- } catch (err) {
113
- console.error(`plugin ${h.name}:`, err);
114
- notices.push(`plugin "${h.name}" failed on this page: ${err.message}`);
115
- return null;
116
- }
117
- }));
118
- const clients = hooks.filter((h) => h.client && !h.error).map((h) => ({
119
- name: h.name,
120
- client: asset(h.client)
121
- }));
122
- const messages = [...(await config()).forReader];
123
- return {
124
- head: parts.map((x) => raw(String(x?.head ?? ""))),
125
- body: parts.map((x) => raw(String(x?.body ?? ""))),
126
- clients,
127
- messages,
128
- notices
129
- };
130
- }
131
- /** A page with what the plugins add, their notices among the page's. */
102
+ /** A page as the server serves it: the render with what the plugins add, their failures among its notices. */
132
103
  async function page(req, stored, rendered) {
133
- const extras = await shellExtras(req);
134
- return shell(stored, {
104
+ const notices = [...rendered.notices];
105
+ const parts = await pluginParts(await pluginHooks(), req, {
106
+ asset,
107
+ messages: [...(await config()).forReader],
108
+ failed: (message) => {
109
+ console.error(message);
110
+ notices.push(message);
111
+ }
112
+ });
113
+ return pageDocument(stored, {
135
114
  ...rendered,
136
- notices: [...rendered.notices, ...extras.notices]
137
- }, extras);
115
+ notices
116
+ }, parts, {
117
+ live: true,
118
+ base,
119
+ asset,
120
+ runtime: `${base}/_/runtime.js`,
121
+ title: projectName(),
122
+ stamps: stamps()
123
+ });
138
124
  }
139
125
  /** The loaded config. Also applies its `files` setting to what is served and watched. */
140
126
  async function config() {
@@ -161,166 +147,13 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
161
147
  }
162
148
  return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
163
149
  }
164
- const within = (file, dir) => file === dir || file.startsWith(dir + path.sep);
165
- /** Resolve a path inside a base folder, refusing anything that escapes it. */
166
- function inside(base, rel) {
167
- const p = path.resolve(base, "." + path.posix.normalize("/" + rel));
168
- return within(p, base) ? p : null;
169
- }
170
- const isRepoId = (id) => id === "-" || id.startsWith("-/");
171
- /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
172
- function frontmatter(source) {
173
- const m = FRONTMATTER.exec(source);
174
- if (!m) return {
175
- data: {},
176
- error: null
177
- };
178
- let data;
179
- try {
180
- data = parse(m[1]);
181
- } catch (err) {
182
- return {
183
- data: {},
184
- error: err.message
185
- };
186
- }
187
- if (data == null) return {
188
- data: {},
189
- error: null
190
- };
191
- if (typeof data !== "object" || Array.isArray(data)) return {
192
- data: {},
193
- error: "it must be fields (`key: value` lines), not a single value or a list"
194
- };
195
- return {
196
- data,
197
- error: null
198
- };
199
- }
200
- function pageSource(id, file) {
201
- const source = fs.readFileSync(file, "utf8");
202
- return {
203
- kind: "page",
204
- id,
205
- file,
206
- mtime: fs.statSync(file).mtimeMs,
207
- source,
208
- body: source.replace(FRONTMATTER, ""),
209
- ...(({ data, error }) => ({
210
- frontmatter: data,
211
- frontmatterError: error
212
- }))(frontmatter(source))
213
- };
214
- }
215
- /** The pages in a folder of the pages folder, newest first, with when each was last answered. */
216
- function pagesIn(dir) {
217
- const last = /* @__PURE__ */ new Map();
218
- for (const e of readEvents(project.eventsFile)) if (fromReader(e)) last.set(e.page, e.ts);
219
- const out = [];
220
- const walk = (d) => {
221
- if (!fs.existsSync(d)) return;
222
- for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
223
- if (ent.name.startsWith(".") || ent.name === "node_modules") continue;
224
- const full = path.join(d, ent.name);
225
- if (ent.isDirectory()) walk(full);
226
- else if (ent.name.endsWith(".md")) {
227
- const id = path.relative(project.pagesDir, full).split(path.sep).join("/").replace(/\.md$/, "");
228
- out.push({
229
- id,
230
- file: full,
231
- mtime: fs.statSync(full).mtimeMs,
232
- lastEvent: last.get(id) ?? null,
233
- awaiting: 0
234
- });
235
- }
236
- }
237
- };
238
- walk(dir);
239
- return out.sort((a, b) => b.mtime - a.mtime);
240
- }
241
- /** Text files show as files; anything with a NUL byte near the start is binary. */
242
- function isText(file) {
243
- const fd = fs.openSync(file, "r");
244
- const buf = Buffer.alloc(8192);
245
- const n = fs.readSync(fd, buf, 0, buf.length, 0);
246
- fs.closeSync(fd);
247
- return !buf.subarray(0, n).includes(0);
248
- }
249
- /**
250
- * A page id → the stored page, or one of: { redirect } (a folder asked for without its slash),
251
- * { raw: file } (serve the bytes), null (nothing there).
252
- */
253
- function stored(id) {
254
- if (!id) return {
255
- kind: "pages",
256
- id: "",
257
- file: project.pagesDir,
258
- mtime: null,
259
- pages: pagesIn(project.pagesDir)
260
- };
261
- if (isRepoId(id)) {
262
- const rel = id.slice(2);
263
- const target = inside(project.dir, rel);
264
- if (!target || path.relative(project.dir, target).split(path.sep).includes(".git") || !fs.existsSync(target)) return null;
265
- const stat = fs.statSync(target);
266
- if (stat.isDirectory()) {
267
- const entries = fs.readdirSync(target, { withFileTypes: true }).filter((e) => !SKIP_DIRS.has(e.name) && e.name !== ".DS_Store").map((e) => ({
268
- name: e.name,
269
- dir: e.isDirectory()
270
- })).sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name));
271
- return {
272
- kind: "folder",
273
- id,
274
- file: target,
275
- mtime: stat.mtimeMs,
276
- entries
277
- };
278
- }
279
- if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target);
280
- if (stat.size > 1e6 || !isText(target)) return { raw: target };
281
- return {
282
- kind: "file",
283
- id,
284
- file: target,
285
- mtime: stat.mtimeMs,
286
- source: fs.readFileSync(target, "utf8")
287
- };
288
- }
289
- const target = inside(project.pagesDir, id);
290
- if (!target) return null;
291
- if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target };
292
- if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
293
- const index = path.join(target, "index.md");
294
- if (fs.existsSync(index)) return pageSource(id, index);
295
- return {
296
- kind: "pages",
297
- id,
298
- file: target,
299
- mtime: null,
300
- pages: pagesIn(target)
301
- };
302
- }
303
- const file = target + ".md";
304
- return fs.existsSync(file) ? pageSource(id, file) : null;
305
- }
306
- /** The URL that serves a file or folder on disk, or null when nothing here serves it. */
307
- function urlOf(abs) {
308
- const rel = (dir) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join("/");
309
- if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, "")}`;
310
- if (FILES && within(abs, project.dir)) {
311
- if (rel(project.dir).split("/").some((part) => SKIP_DIRS.has(part))) return null;
312
- return `${base}/-/${rel(project.dir)}`;
313
- }
314
- return null;
315
- }
316
- /** For links: the target if it exists (also with .md added), mapped to its URL. */
317
- function urlFor(abs) {
318
- for (const candidate of [abs, abs + ".md"]) if (fs.existsSync(candidate)) {
319
- const url = urlOf(candidate);
320
- if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith("/") ? "/" : "");
321
- }
322
- return null;
323
- }
150
+ const site = servedSite(project, {
151
+ base,
152
+ files: () => !!FILES
153
+ });
154
+ const stored = site.page;
155
+ const pagesIn = site.pagesIn;
156
+ const urlFor = site.urlFor;
324
157
  /** A config that failed to load: the page as stored, as text, under the error. */
325
158
  function rawRender(page) {
326
159
  const list = (items) => html`<ul>
@@ -344,8 +177,6 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
344
177
  label
345
178
  } }
346
179
  });
347
- /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
348
- const frontmatterOf = (page) => page.kind === "page" ? page.frontmatter : {};
349
180
  /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
350
181
  async function render(page) {
351
182
  const { pages, errors } = await config();
@@ -373,49 +204,65 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
373
204
  };
374
205
  }
375
206
  /**
376
- * Per page: the questions it asks that have no answer yet, the reader's events no wait or watch
377
- * picked up, who is listening, and the session that claimed it. What `whiteboard status` and the
378
- * hooks report. The questions are a page's named forms.
207
+ * The project's status (status.ts): the pages, below `only` when given, with their questions, the
208
+ * log read once, and who listens. What `whiteboard status`, the hooks, the page lists and the log's
209
+ * picked-up marks take.
379
210
  */
380
- async function status(only) {
381
- const { pages, handedOut, forReader } = await config();
382
- const isForAgent = forAgent(handedOut);
383
- const all = readEvents(project.eventsFile);
384
- const picked = pickedUp(all);
385
- const owner = /* @__PURE__ */ new Map();
386
- for (const e of all) if (e.type === "whiteboard:claim" && !fromReader(e)) owner.set(e.page, e.data?.session ?? null);
387
- const out = [];
388
- for (const p of pagesIn(project.pagesDir)) {
389
- if (only && p.id !== only && !p.id.startsWith(only + "/")) continue;
390
- const page = pageSource(p.id, p.file);
391
- let asks = [];
392
- try {
393
- asks = pages?.questions(page) ?? [];
394
- } catch (err) {
395
- console.error("questions:", err);
396
- }
397
- const events = all.filter((e) => e.page === p.id);
398
- const listening = listenersFor(p.id);
399
- const questions = asks.map((name) => ({
400
- name,
401
- state: questionState(name, events, listening, (id) => picked.has(id)).state
402
- }));
403
- const named = (...states) => questions.filter((q) => states.includes(q.state)).map((q) => q.name);
404
- out.push({
405
- page: p.id,
406
- title: titleOf(p.file, path.basename(p.id)),
407
- file: p.file,
408
- owner: owner.get(p.id) ?? null,
409
- asks,
410
- questions,
411
- open: named("open"),
412
- unheard: named("open").filter((name) => !heard(name, listening)),
413
- unread: unreadMessages(events, (type) => forReader.has(type)),
414
- unpicked: events.filter((e) => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
415
- listeners: listening
416
- });
211
+ const asked = /* @__PURE__ */ new Map();
212
+ function questionsOf(renderer, id, file) {
213
+ let stat;
214
+ try {
215
+ stat = fs.statSync(file);
216
+ } catch {
217
+ return {
218
+ title: path.basename(id),
219
+ asks: []
220
+ };
417
221
  }
418
- return out;
222
+ const kept = asked.get(id);
223
+ if (kept && kept.file === file && kept.mtime === stat.mtimeMs && kept.size === stat.size && kept.renderer === renderer) return kept;
224
+ let asks = [];
225
+ try {
226
+ asks = renderer?.questions(pageSource(id, file)) ?? [];
227
+ } catch (err) {
228
+ console.error("questions:", err);
229
+ }
230
+ const now = {
231
+ file,
232
+ mtime: stat.mtimeMs,
233
+ size: stat.size,
234
+ renderer,
235
+ title: titleOf(file, path.basename(id)),
236
+ asks
237
+ };
238
+ asked.set(id, now);
239
+ return now;
240
+ }
241
+ async function snapshot(listed) {
242
+ const { pages: renderer, handedOut, forReader } = await config();
243
+ const pages = listed.map((p) => ({
244
+ id: p.id,
245
+ file: p.file,
246
+ ...questionsOf(renderer, p.id, p.file)
247
+ }));
248
+ return projectStatus({
249
+ pages,
250
+ events: readEvents(project.eventsFile),
251
+ listeners: listenersFor,
252
+ forAgent: forAgent(handedOut),
253
+ forReader: (type) => forReader.has(type)
254
+ });
255
+ }
256
+ /** Per page, below `only` when given: what `whiteboard status` and the hooks report (see snapshot). */
257
+ const status = async (only) => (await snapshot(pagesIn(project.pagesDir).filter((p) => !only || p.id === only || p.id.startsWith(only + "/")))).pages;
258
+ /** A list of pages, with when each was last answered and how much waits on it, from one status. */
259
+ async function withStatus(pages) {
260
+ const s = await snapshot(pages);
261
+ pages.forEach((p, i) => {
262
+ p.awaiting = awaiting(s.pages[i]);
263
+ p.lastEvent = s.lastAnswered(p.id);
264
+ });
265
+ return pages;
419
266
  }
420
267
  /** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
421
268
  async function docs() {
@@ -442,48 +289,48 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
442
289
  plugins
443
290
  };
444
291
  }
445
- const json = (s) => JSON.stringify(s).replace(/</g, "\\u003c");
446
- const DOCK_STYLE = "#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}.wb-toast{max-width:min(24rem,calc(100vw - 32px));text-align:left}.wb-toast-more{margin:0 -4px 0 -2px;padding:0 4px;opacity:.75}.wb-toast-more:hover{opacity:1}.wb-toast[data-open]{flex-wrap:wrap;border-radius:12px}.wb-toast-details{flex-basis:100%;padding:2px 0 3px;font-weight:400;cursor:text}.wb-toast-details[hidden]{display:none}";
447
- /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
448
- function shell(page, { page: rendered, out, notices }, extras = {
449
- head: [],
450
- body: [],
451
- clients: []
452
- }, built) {
453
- const handoff = {
454
- id: page.id,
455
- kind: page.kind,
456
- live: !built,
457
- base: built ? "" : base,
458
- client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
459
- data: out.data ?? null,
460
- frontmatter: frontmatterOf(page),
461
- plugins: extras.clients,
462
- messages: extras.messages ?? []
292
+ /**
293
+ * What the browser runs and how it looks, as two stamps: one over its code (the runtime, the page's
294
+ * module, the plugins' scripts), one over its stylesheets (the engine's, the plugins', the
295
+ * project's in .whiteboard/). A page gets them with its HTML and asks again when its live channel
296
+ * is back: what changed while it was away (a restart, a background tab whose browser held its
297
+ * timers), it would otherwise never hear of. Made from the files themselves, not from what was
298
+ * served since the server started, so a fresh server gives the same stamps for the same files.
299
+ */
300
+ function stamps() {
301
+ const files = [RUNTIME];
302
+ const add = (dir, deep) => {
303
+ let entries;
304
+ try {
305
+ entries = fs.readdirSync(dir, { withFileTypes: true });
306
+ } catch {
307
+ return;
308
+ }
309
+ for (const e of entries) {
310
+ const full = path.join(dir, e.name);
311
+ if (e.isDirectory()) {
312
+ if (deep) add(full, deep);
313
+ } else files.push(full);
314
+ }
315
+ };
316
+ add(path.dirname(PAGE_CLIENT), false);
317
+ for (const dir of publicDirs) add(dir, true);
318
+ for (const f of fs.readdirSync(project.wb).filter((f) => f.endsWith(".css"))) files.push(path.join(project.wb, f));
319
+ const of = (list) => {
320
+ const hash = crypto.createHash("sha1");
321
+ for (const f of [...new Set(list)].toSorted()) try {
322
+ const st = fs.statSync(f);
323
+ hash.update(`${f}\0${st.mtimeMs}\0${st.size}\n`);
324
+ } catch {}
325
+ return hash.digest("hex").slice(0, 16);
326
+ };
327
+ return {
328
+ code: of(files.filter((f) => !f.endsWith(".css"))),
329
+ style: of(files.filter((f) => f.endsWith(".css")))
463
330
  };
464
- return String(html(_templateObject || (_templateObject = _taggedTemplateLiteral([
465
- "<!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <title>",
466
- "</title>\n <style>\n ",
467
- "\n </style>\n ",
468
- "",
469
- "\n </head>\n <body data-page=\"",
470
- "\" data-kind=\"",
471
- "\">\n ",
472
- "\n <div id=\"wb-root\">",
473
- "</div>\n <div id=\"wb-dock\"></div>\n <script type=\"application/json\" id=\"wb-page\">\n ",
474
- "\n <\/script>\n <script type=\"module\" src=\"",
475
- "\"><\/script>\n ",
476
- "\n </body>\n </html>"
477
- ])), out.title || page.id || projectName(), DOCK_STYLE, raw(out.head ?? ""), extras.head, page.id, page.kind, notices.map((n) => html`<pre class="wb-error" role="alert">${n}</pre>`), raw(String(out.html)), raw(json(handoff)), built ? built.asset(RUNTIME) : `${base}/_/runtime.js`, extras.body));
478
331
  }
479
- /** A listener as the server holds it. */
480
- const listeners = /* @__PURE__ */ new Set();
481
- const listenersFor = (page) => [...listeners].filter((l) => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({
482
- page,
483
- type,
484
- command,
485
- ...fallback && { fallback }
486
- }));
332
+ const registry = createRegistry();
333
+ const listenersFor = (page) => registry.list(page);
487
334
  const clients = /* @__PURE__ */ new Set();
488
335
  /** what the browser appended lately, by id: a send it retries is answered with what it got */
489
336
  const appended = /* @__PURE__ */ new Map();
@@ -498,10 +345,10 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
498
345
  const notifyAll = (kind) => {
499
346
  for (const c of clients) notify(c, kind);
500
347
  };
501
- const listenersChanged = () => {
348
+ registry.onChange(() => {
502
349
  notifyAll("listeners");
503
350
  onChange?.();
504
- };
351
+ });
505
352
  function pageChanged(id) {
506
353
  onChange?.();
507
354
  for (const c of clients) if (c.isDir ? !c.page || id.startsWith(c.page + "/") : c.page === id || c.page + "/index" === id) notify(c, "change");
@@ -606,8 +453,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
606
453
  if ("raw" in found) return found;
607
454
  if ((found.kind === "folder" || found.kind === "pages" && id) && !requested.endsWith("/")) return { redirect: `${base}/${id}/` };
608
455
  if (found.kind === "pages") {
609
- const counts = new Map((await status(found.id || null)).map((s) => [s.page, awaiting(s)]));
610
- for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0;
456
+ await withStatus(found.pages);
611
457
  if (!found.id && overview) Object.assign(found, await overview());
612
458
  }
613
459
  return { page: found };
@@ -662,12 +508,13 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
662
508
  if (p === "/api/scroll" && req.method === "POST") {
663
509
  const { page: id, to } = JSON.parse(await readBody(req));
664
510
  if (typeof id !== "string" || typeof to !== "string" || !to.trim()) return sendJson(res, 400, { error: "page and to required" });
511
+ appendEvent(project.eventsFile, {
512
+ page: id,
513
+ type: SCROLL,
514
+ data: { to }
515
+ }, "cli");
665
516
  let tabs = 0;
666
- for (const c of clients) {
667
- if (c.isDir || c.page !== id && c.page + "/index" !== id) continue;
668
- c.send("scroll", { to });
669
- tabs++;
670
- }
517
+ for (const c of clients) if (!c.isDir && (c.page === id || c.page + "/index" === id)) tabs++;
671
518
  return sendJson(res, 200, { tabs });
672
519
  }
673
520
  if (p === "/api/markdown" && req.method === "POST") {
@@ -694,37 +541,23 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
694
541
  if (p === "/api/docs") return sendJson(res, 200, await docs());
695
542
  if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
696
543
  if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
544
+ if (p === "/api/stamps") return sendJson(res, 200, stamps());
697
545
  if (p === "/api/listen") {
698
- const fallback = "fallback" in q;
699
- if (fallback && [...listeners].some((l) => l.fallback)) return sendJson(res, 409, { error: "another agent is the fallback already" });
700
- res.writeHead(200, {
701
- "content-type": "text/event-stream",
702
- "cache-control": "no-store",
703
- connection: "keep-alive"
704
- });
705
- res.write(": listening\n\n");
706
- const l = {
707
- page: q.page || "",
708
- type: q.type || null,
709
- command: q.command === "wait" ? "wait" : "watch",
710
- ...fallback && { fallback }
711
- };
712
- listeners.add(l);
713
- listenersChanged();
714
- const ping = setInterval(() => res.write(": ping\n\n"), 25e3);
715
- const end = () => {
716
- clearInterval(ping);
717
- listeners.delete(l);
718
- streams.delete(end);
719
- };
720
- streams.add(() => {
721
- end();
722
- res.end();
723
- });
724
- req.on("close", () => {
725
- end();
726
- listenersChanged();
546
+ const remove = registry.add(listenerOf(url.searchParams));
547
+ if (!remove) return sendJson(res, 409, { error: "another agent is the fallback already" });
548
+ const off = "fallback" in q ? registry.onChange(() => tell()) : () => {};
549
+ const stream = holdStream(req, res, () => {
550
+ off();
551
+ remove();
552
+ streams.delete(stream.end);
727
553
  });
554
+ const tell = () => stream.send("listeners", { projects: [{
555
+ dir: project.dir,
556
+ base,
557
+ listeners: registry.list()
558
+ }] });
559
+ if ("fallback" in q) tell();
560
+ streams.add(stream.end);
728
561
  return;
729
562
  }
730
563
  if (p === "/api/page" || p === "/api/render") {
@@ -794,184 +627,6 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
794
627
  send(res, 500, String(err?.stack || err), "text/plain");
795
628
  }
796
629
  }
797
- /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
798
- const BUILD_SKIP = [
799
- "form",
800
- "chat",
801
- "comments",
802
- "draft"
803
- ];
804
- /** In the folder a build writes, so that a next build knows it may replace it. */
805
- const BUILD_MARK = ".whiteboard-build";
806
- async function build(options = {}) {
807
- const cfg = await config();
808
- if (cfg.errors.length) throw new Error(`the config failed to load: ${cfg.errors[0].message}`);
809
- if (!cfg.pages) throw new Error("the config has no pages renderer");
810
- const pages = cfg.pages;
811
- const defined = (...xs) => xs.find((x) => x !== void 0);
812
- const patterns = defined(options.pages, cfg.build.pages) ?? [];
813
- const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP);
814
- const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? "site");
815
- if (!patterns.length) throw new Error("nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config");
816
- const warnings = [];
817
- const include = patterns.filter((p) => !p.startsWith("!"));
818
- const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
819
- const files = [...new Set(include.flatMap((p) => fs.globSync(p, { cwd: project.dir }).map((f) => path.resolve(project.dir, f))))].filter((f) => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile()).filter((f) => !exclude.some((g) => path.matchesGlob(path.relative(project.dir, f), g))).sort();
820
- if (!files.length) throw new Error(`no markdown files match ${patterns.join(" ")}`);
821
- const base = files.map(path.dirname).reduce((a, b) => {
822
- while (!within(b, a)) a = path.dirname(a);
823
- return a;
824
- });
825
- const outOf = (file) => {
826
- const rel = path.relative(base, file);
827
- return path.join(outDir, /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel)) ? path.join(path.dirname(rel), "index.html") : rel.replace(/\.(md|markdown)$/i, ".html"));
828
- };
829
- const built = new Map(files.map((f) => [f, outOf(f)]));
830
- if (fs.existsSync(outDir)) {
831
- if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK))) throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`);
832
- fs.rmSync(outDir, { recursive: true });
833
- }
834
- fs.mkdirSync(outDir, { recursive: true });
835
- fs.writeFileSync(path.join(outDir, BUILD_MARK), "written by whiteboard build; the next build replaces this folder\n");
836
- const copied = /* @__PURE__ */ new Map();
837
- function copyAsset(file) {
838
- const known = copied.get(file);
839
- if (known) return known;
840
- const rel = within(file, ENGINE_DIR) ? path.join("_", "whiteboard", path.relative(ENGINE_DIR, file)) : within(file, project.dir) ? path.join("_", "project", path.relative(project.dir, file)) : path.join("_", "files", path.basename(path.dirname(file)), path.basename(file));
841
- const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, ".js") : rel);
842
- copied.set(file, dest);
843
- fs.mkdirSync(path.dirname(dest), { recursive: true });
844
- if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file));
845
- else fs.copyFileSync(file, dest);
846
- if (/\.css$/i.test(file)) for (const m of fs.readFileSync(file, "utf8").matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
847
- const ref = m[1];
848
- if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue;
849
- const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ""));
850
- if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target);
851
- }
852
- return dest;
853
- }
854
- /** a file beside the pages (an image), copied to its place below the site */
855
- function copyBeside(file) {
856
- if (!within(file, base)) return null;
857
- const dest = path.join(outDir, path.relative(base, file));
858
- if (!fs.existsSync(dest)) {
859
- fs.mkdirSync(path.dirname(dest), { recursive: true });
860
- fs.copyFileSync(file, dest);
861
- }
862
- return dest;
863
- }
864
- const hooks = await pluginHooks();
865
- const result = {
866
- out: outDir,
867
- pages: [],
868
- warnings
869
- };
870
- for (const [file, dest] of built) {
871
- const here = path.dirname(dest);
872
- const relTo = (target) => path.relative(here, target).split(path.sep).map(encodeURIComponent).join("/") || ".";
873
- const assetHere = (ref) => relTo(copyAsset(toPath(ref)));
874
- const urlFor = (abs) => {
875
- for (const candidate of [abs, abs + ".md"]) {
876
- if (!fs.existsSync(candidate)) continue;
877
- if (fs.statSync(candidate).isDirectory()) {
878
- const index = [...built.keys()].find((f) => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)));
879
- if (index) return relTo(built.get(index));
880
- continue;
881
- }
882
- if (built.has(candidate)) return relTo(built.get(candidate));
883
- if (/\.(md|markdown)$/i.test(candidate)) {
884
- warnings.push(`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`);
885
- return null;
886
- }
887
- const copy = copyBeside(candidate);
888
- if (copy) return relTo(copy);
889
- warnings.push(`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`);
890
- return null;
891
- }
892
- return null;
893
- };
894
- const id = within(file, project.pagesDir) ? path.relative(project.pagesDir, file).split(path.sep).join("/").replace(/\.(md|markdown)$/i, "") : "-/" + path.relative(project.dir, file).split(path.sep).join("/");
895
- const stored = pageSource(id, file);
896
- if (stored.frontmatterError) warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`);
897
- const context = {
898
- project: {
899
- name: project.name,
900
- dir: project.dir,
901
- files: !!FILES
902
- },
903
- asset: assetHere,
904
- urlFor,
905
- live: false,
906
- skip
907
- };
908
- const rendered = await pages.render(stored, context);
909
- const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file)) ? path.basename(path.dirname(file)) : path.basename(file).replace(/\.(md|markdown)$/i, "");
910
- const title = !rendered.title || rendered.title === id ? named : rendered.title;
911
- const out = {
912
- ...rendered,
913
- title,
914
- html: String(rendered.html ?? ""),
915
- head: String(rendered.head ?? "")
916
- };
917
- const included = hooks.filter((h) => !h.error && !skip.has(h.name));
918
- const clients = included.filter((h) => h.client).map((h) => ({
919
- name: h.name,
920
- client: assetHere(h.client)
921
- }));
922
- const parts = await Promise.all(included.map(async (h) => {
923
- try {
924
- return await h.shell?.(null) ?? null;
925
- } catch (err) {
926
- warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${err.message}`);
927
- return null;
928
- }
929
- }));
930
- const extras = {
931
- head: parts.map((x) => raw(String(x?.head ?? ""))),
932
- body: parts.map((x) => raw(String(x?.body ?? ""))),
933
- clients
934
- };
935
- let doc = shell(stored, {
936
- page: true,
937
- out,
938
- notices: []
939
- }, extras, { asset: assetHere });
940
- doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served) => {
941
- let file;
942
- try {
943
- file = path.resolve(served.split("/").map(decodeURIComponent).join(path.sep));
944
- } catch {
945
- return all;
946
- }
947
- return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all;
948
- });
949
- doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref) => {
950
- if (ref.startsWith("/") || ref.startsWith("_/") || ref.startsWith("../")) return all;
951
- let decoded = ref;
952
- try {
953
- decoded = decodeURIComponent(ref);
954
- } catch {}
955
- const source = path.resolve(path.dirname(file), decoded);
956
- if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
957
- const target = path.resolve(here, decoded);
958
- if (within(target, outDir) && !fs.existsSync(target)) {
959
- fs.mkdirSync(path.dirname(target), { recursive: true });
960
- fs.copyFileSync(source, target);
961
- }
962
- }
963
- return all;
964
- });
965
- fs.mkdirSync(here, { recursive: true });
966
- fs.writeFileSync(dest, doc);
967
- result.pages.push({
968
- file,
969
- to: dest
970
- });
971
- }
972
- if (![...built.values()].includes(path.join(outDir, "index.html"))) warnings.push("no README.md or index.md in the top folder: the site has no index.html");
973
- return result;
974
- }
975
630
  /** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
976
631
  function upgrade(req, conn, _head) {
977
632
  const url = new URL((req.url ?? "/").replace(/^\/+/, "/"), "http://localhost");
@@ -1001,11 +656,8 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
1001
656
  listeners: () => listenersFor(null),
1002
657
  async overview() {
1003
658
  await config();
1004
- const pages = pagesIn(project.pagesDir);
1005
- const counts = new Map((await status(null)).map((s) => [s.page, awaiting(s)]));
1006
- for (const p of pages) p.awaiting = counts.get(p.id) ?? 0;
1007
659
  return {
1008
- pages,
660
+ pages: await withStatus(pagesIn(project.pagesDir)),
1009
661
  files: !!FILES
1010
662
  };
1011
663
  },
@@ -1013,16 +665,16 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
1013
665
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
1014
666
  },
1015
667
  elsewhere: () => notifyAll("elsewhere"),
1016
- addListener(l) {
1017
- listeners.add(l);
1018
- listenersChanged();
1019
- return () => {
1020
- if (listeners.delete(l)) listenersChanged();
1021
- };
1022
- },
668
+ addListener: (l) => registry.add(l),
669
+ onListeners: (fn) => registry.onChange(fn),
1023
670
  status: (page = null) => status(page),
1024
671
  config,
1025
- build,
672
+ build: (options) => build({
673
+ project,
674
+ config,
675
+ hooks: pluginHooks,
676
+ files: () => !!FILES
677
+ }, options),
1026
678
  close() {
1027
679
  for (const w of watchers) w.close();
1028
680
  watchers.clear();