@bigmistqke/whiteboard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +125 -25
  2. package/bin/whiteboard.ts +299 -16
  3. package/dist/bin/whiteboard.js +247 -17
  4. package/dist/client/runtime.js +22 -10
  5. package/dist/plugins/ansi/README.md +36 -0
  6. package/dist/plugins/ansi/index.js +64 -0
  7. package/dist/plugins/ansi/public/style.css +28 -0
  8. package/dist/plugins/badge/README.md +28 -0
  9. package/dist/plugins/badge/index.js +24 -0
  10. package/dist/plugins/badge/public/style.css +30 -0
  11. package/dist/plugins/chat/public/style.css +7 -2
  12. package/dist/plugins/code/README.md +4 -2
  13. package/dist/plugins/code/diff.js +12 -2
  14. package/dist/plugins/grid/README.md +12 -12
  15. package/dist/plugins/grid/index.js +7 -19
  16. package/dist/plugins/grid/public/style.css +4 -33
  17. package/dist/plugins/iframe/README.md +7 -7
  18. package/dist/plugins/iframe/index.js +11 -11
  19. package/dist/plugins/iframe/public/style.css +15 -0
  20. package/dist/plugins/index.js +7 -3
  21. package/dist/plugins/lightbox/README.md +22 -0
  22. package/dist/plugins/lightbox/index.js +20 -0
  23. package/dist/plugins/lightbox/public/client.js +4 -0
  24. package/dist/plugins/lightbox/public/style.css +66 -0
  25. package/dist/plugins/steps/README.md +3 -3
  26. package/dist/plugins/steps/index.js +3 -42
  27. package/dist/plugins/steps/public/client.js +1 -1
  28. package/dist/plugins/terminal/host.js +1 -1
  29. package/dist/plugins/terminal/public/client.js +1 -1
  30. package/dist/plugins/window/README.md +34 -14
  31. package/dist/plugins/window/index.js +21 -13
  32. package/dist/src/auth.js +4 -3
  33. package/dist/src/client/page/base.css +61 -1
  34. package/dist/src/client/page/main.js +60 -14
  35. package/dist/src/entries.js +217 -0
  36. package/dist/src/events.js +1 -1
  37. package/dist/src/hub.js +272 -0
  38. package/dist/src/loader.js +4 -1
  39. package/dist/src/package.js +23 -1
  40. package/dist/src/pages/blocks.js +1 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +87 -33
  43. package/dist/src/pages/render.js +116 -14
  44. package/dist/src/pages/window.js +16 -18
  45. package/dist/src/running.js +37 -2
  46. package/dist/src/serve.js +111 -2
  47. package/dist/src/server.js +49 -14
  48. package/package.json +1 -1
  49. package/plugins/ansi/README.md +36 -0
  50. package/plugins/ansi/index.ts +95 -0
  51. package/plugins/ansi/public/style.css +28 -0
  52. package/plugins/badge/README.md +28 -0
  53. package/plugins/badge/index.ts +35 -0
  54. package/plugins/badge/public/style.css +30 -0
  55. package/plugins/chat/public/style.css +7 -2
  56. package/plugins/code/README.md +4 -2
  57. package/plugins/code/diff.ts +14 -2
  58. package/plugins/grid/README.md +12 -12
  59. package/plugins/grid/index.ts +11 -26
  60. package/plugins/grid/public/style.css +4 -33
  61. package/plugins/iframe/README.md +7 -7
  62. package/plugins/iframe/index.ts +15 -15
  63. package/plugins/iframe/public/style.css +15 -0
  64. package/plugins/index.ts +6 -2
  65. package/plugins/lightbox/README.md +22 -0
  66. package/plugins/lightbox/client.ts +99 -0
  67. package/plugins/lightbox/index.ts +25 -0
  68. package/plugins/lightbox/public/style.css +66 -0
  69. package/plugins/steps/README.md +3 -3
  70. package/plugins/steps/client.ts +15 -6
  71. package/plugins/steps/index.ts +3 -46
  72. package/plugins/terminal/client.ts +16 -7
  73. package/plugins/window/README.md +34 -14
  74. package/plugins/window/index.ts +20 -13
  75. package/skills/whiteboard/SKILL.md +17 -10
  76. package/src/auth.ts +5 -3
  77. package/src/client/base.ts +19 -0
  78. package/src/client/forms.ts +2 -1
  79. package/src/client/markdown.ts +2 -1
  80. package/src/client/page/base.css +61 -1
  81. package/src/client/page/elsewhere.ts +72 -16
  82. package/src/client/page/fresh.ts +2 -1
  83. package/src/client/page/sort.ts +2 -1
  84. package/src/client/runtime.ts +11 -9
  85. package/src/define.ts +66 -7
  86. package/src/entries.ts +269 -0
  87. package/src/events.ts +2 -1
  88. package/src/hub.ts +355 -0
  89. package/src/loader.ts +7 -1
  90. package/src/package.ts +22 -0
  91. package/src/pages/blocks.ts +3 -0
  92. package/src/pages/index.ts +4 -2
  93. package/src/pages/markdown.ts +89 -32
  94. package/src/pages/render.ts +134 -13
  95. package/src/pages/window.ts +16 -25
  96. package/src/running.ts +47 -1
  97. package/src/serve.ts +114 -1
  98. package/src/server.ts +80 -14
  99. package/dist/plugins/gallery/README.md +0 -30
  100. package/dist/plugins/gallery/index.js +0 -75
  101. package/dist/plugins/gallery/public/client.js +0 -1
  102. package/dist/plugins/gallery/public/style.css +0 -90
  103. package/plugins/gallery/README.md +0 -30
  104. package/plugins/gallery/client.tsx +0 -70
  105. package/plugins/gallery/index.ts +0 -89
  106. package/plugins/gallery/public/style.css +0 -90
@@ -4,8 +4,9 @@ import { CLAIM, appendEvent, editEvent, follow, forAgent, handOut, matches, pick
4
4
  import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from "../src/loader.js";
5
5
  import { parseCommandArgs, pluginCommands, usage } from "../src/plugins.js";
6
6
  import { projectToken } from "../src/auth.js";
7
- import { packagePath } from "../src/package.js";
8
- import { runningServer } from "../src/running.js";
7
+ import { PACKAGE_DIR, VERSION, compareVersions, packagePath } from "../src/package.js";
8
+ import { recordedSharedPort, runningServer, sharedServer } from "../src/running.js";
9
+ import { machineDir, machineServerFile, matchesEntries, readMachineConfig, serverPaths, stateDir } from "../src/entries.js";
9
10
  import { statusLines, takenByOther, whose } from "../src/status.js";
10
11
  import fs from "node:fs";
11
12
  import os from "node:os";
@@ -43,18 +44,27 @@ const HELP = `whiteboard — markdown pages in the browser, what the reader does
43
44
  whiteboard append --page <p> --type <t> [--data <json>] add an event to a page's log (e.g. a reply)
44
45
  whiteboard pick <event id> record an event as picked up, as wait does when it hands one out
45
46
  whiteboard status [--page <p>] per page: questions without an answer, answers no agent picked up, who listens
46
- whiteboard serve run this project's server in the foreground
47
+ whiteboard serve run this project's server in the foreground; for a project of the
48
+ machine's entries, or outside any project, the shared server
47
49
  whiteboard skill [dir] print where the agent skill is, or link it into a skills folder
50
+ whiteboard paths [--write|--read] the folders the shared server needs, ':' between them, for a sandbox
51
+ wrapper to grant: --write the entries' folders and its state, --read
52
+ the machine config and whiteboard itself
48
53
 
49
54
  filters: --page <page|file> (includes pages below it) --type <type>
50
55
  wait: --timeout <seconds> (exit 2 on timeout) --count <n> (default 1)
51
56
  wait, watch without --page: the fallback, taking only what no other wait or watch would, on any
52
- page, also once they stop; one per project (a second exits 1)
57
+ page, also once they stop; one per project (a second exits 1), or, in a project of the
58
+ machine's entries, one for the whole entry, each event with its project and url
53
59
  events: --since <iso time or event id> --last <n>
54
60
 
55
61
  Every command works on the project of the current folder: the nearest folder upward with a
56
62
  .whiteboard/ folder. A project needs no config: .whiteboard/config.ts only says what differs from
57
63
  the defaults (markdown with the built-in plugins). Each project runs its own server; its port is in .whiteboard/server.json.
64
+ A project the machine config's entries include (${machineDir()}/config.json) is served by the one shared
65
+ server instead, under its path (/<entry>/<folder>), with an index of every entry at /. It is started
66
+ outside the agents' sandboxes (\`whiteboard serve\` outside any project, or a login service), and
67
+ \`serve\` takes an older one over; commands never start it. A wait without a server waits for one.
58
68
  A page appends events {id, ts, page, type, action, data} to .whiteboard/events.ndjson;
59
69
  which types it sends is up to its plugins (\`whiteboard docs\` says). The project's plugins
60
70
  can add commands of their own; \`whiteboard help\` in a project lists them.`;
@@ -81,7 +91,9 @@ const { values: opts, positionals } = cmd && !BUILTIN_COMMANDS.has(cmd) ? {
81
91
  help: {
82
92
  type: "boolean",
83
93
  short: "h"
84
- }
94
+ },
95
+ write: { type: "boolean" },
96
+ read: { type: "boolean" }
85
97
  }
86
98
  });
87
99
  const project = project$1(findProjectDir());
@@ -96,12 +108,45 @@ const filter = () => ({
96
108
  page: opts.page ? pageId(needProject(), opts.page) : void 0,
97
109
  type: opts.type
98
110
  });
99
- /** The running server of this project: its base URL, or null. */
100
- const running = (proj) => runningServer(proj);
101
- /** This project's server, started in the background when it is not running. @returns its base URL */
111
+ /**
112
+ * Is this project one of the machine's entries (see src/entries.ts)? Then the shared server serves
113
+ * it, under its path, and no server of its own runs. A project outside every include runs its own.
114
+ */
115
+ function isShared(proj) {
116
+ const config = readMachineConfig();
117
+ return !!config && !!matchesEntries(config, proj.dir);
118
+ }
119
+ /**
120
+ * The running server of this project: the URL it is served at (`http://localhost:4777`, or
121
+ * `http://localhost:4777/rg/develop` under the shared server), or null.
122
+ */
123
+ async function running(proj) {
124
+ if (!isShared(proj)) return runningServer(proj);
125
+ const file = machineServerFile();
126
+ const shared = await sharedServer(file);
127
+ if (!shared) return null;
128
+ const mine = shared.projects.find((p) => p.dir === proj.dir) ?? (await sharedServer(file, { rescan: true }))?.projects.find((p) => p.dir === proj.dir);
129
+ return mine ? `${shared.origin}${mine.base}` : null;
130
+ }
131
+ /**
132
+ * This project's server, started in the background when it is not running. Under the shared server
133
+ * nothing is started: it is started outside every agent's sandbox (a login service, or `whiteboard
134
+ * serve` in a terminal), since it serves every project of the entries and runs their plugins; a
135
+ * command inside one sandbox would start it boxed in there. Only `show` and a plugin's command that
136
+ * asks for the server get here. @returns the URL it serves the project at
137
+ */
102
138
  async function ensureServer() {
103
139
  const proj = needProject();
140
+ const shared = isShared(proj);
104
141
  const base = await running(proj);
142
+ if (shared) {
143
+ const server = await sharedServer(machineServerFile());
144
+ if (base) {
145
+ if (server && compareVersions(VERSION, server.version) > 0) console.error(`whiteboard: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`whiteboard serve\` takes it over)`);
146
+ return base;
147
+ }
148
+ throw new Error(server ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?` : `the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with \`whiteboard serve\` in a terminal, outside any project`);
149
+ }
105
150
  if (base) return base;
106
151
  const lock = path.join(proj.wb, "server.lock");
107
152
  const claim = () => {
@@ -151,12 +196,59 @@ async function ensureServer() {
151
196
  }
152
197
  throw new Error(`server did not start; see ${proj.logFile}`);
153
198
  }
199
+ /** This project's running server, or an error saying how to start one. */
200
+ async function needServer() {
201
+ const proj = needProject();
202
+ const base = await running(proj);
203
+ if (base) return base;
204
+ if (isShared(proj)) {
205
+ const port = recordedSharedPort(machineServerFile());
206
+ throw new Error(port ? `the shared server recorded on port ${port} did not answer, or does not serve ${proj.dir}` : "the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with `whiteboard serve` in a terminal, outside any project");
207
+ }
208
+ throw new Error("no server runs for this project; `whiteboard show <page>` starts it");
209
+ }
210
+ /** Is there a page (a markdown file) in this folder or below it? */
211
+ function hasPages(dir) {
212
+ let entries;
213
+ try {
214
+ entries = fs.readdirSync(dir, { withFileTypes: true });
215
+ } catch {
216
+ return false;
217
+ }
218
+ return entries.some((e) => e.isDirectory() ? !e.name.startsWith(".") && hasPages(path.join(dir, e.name)) : e.name.endsWith(".md"));
219
+ }
220
+ /**
221
+ * Ask the project's server. Without one running, a server made for this one question answers it,
222
+ * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
223
+ * never starts one. It has no listeners, as no server runs to hold them.
224
+ */
154
225
  async function api(route) {
155
- const res = await fetch(`${await ensureServer()}${route}`);
226
+ const base = await running(needProject());
227
+ const res = base ? await fetch(`${base}${route}`) : await askInProcess(route);
156
228
  const body = await res.json();
157
229
  if (!res.ok) throw new Error(body.error ?? res.statusText);
158
230
  return body;
159
231
  }
232
+ async function askInProcess(route) {
233
+ if (route.startsWith("/api/status") && !hasPages(needProject().pagesDir)) return Response.json([]);
234
+ const { createServer } = await import("../src/server.js");
235
+ const server = createServer(needProject());
236
+ const listener = http.createServer((req, res) => void server.handle(req, res));
237
+ await new Promise((r) => listener.listen(0, "127.0.0.1", r));
238
+ try {
239
+ const { port } = listener.address();
240
+ const res = await fetch(`http://127.0.0.1:${port}${route}`);
241
+ const text = await res.text();
242
+ return new Response(text, {
243
+ status: res.status,
244
+ headers: res.headers
245
+ });
246
+ } finally {
247
+ server.close();
248
+ listener.closeAllConnections();
249
+ listener.close();
250
+ }
251
+ }
160
252
  /**
161
253
  * Tell the project's server that an agent is waiting, for as long as this command runs: pages show
162
254
  * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
@@ -171,7 +263,7 @@ function listen(f, command, fallback = false) {
171
263
  const connect = async () => {
172
264
  let base;
173
265
  try {
174
- base = await ensureServer();
266
+ base = await needServer();
175
267
  } catch {
176
268
  return setTimeout(connect, 2e3).unref();
177
269
  }
@@ -207,11 +299,11 @@ function listen(f, command, fallback = false) {
207
299
  * Who else listens, kept current: the fallback leaves to them what they would take. Calls
208
300
  * `changed` after each change (the server's live channel says when).
209
301
  */
210
- async function otherListeners(changed) {
302
+ async function otherListeners(changed, server = needServer) {
211
303
  let list = [];
212
304
  const load = async () => {
213
305
  try {
214
- list = await (await fetch(`${await ensureServer()}/api/listeners`)).json();
306
+ list = await (await fetch(`${await server()}/api/listeners`)).json();
215
307
  } catch {}
216
308
  changed();
217
309
  };
@@ -225,7 +317,7 @@ async function otherListeners(changed) {
225
317
  };
226
318
  let base;
227
319
  try {
228
- base = await ensureServer();
320
+ base = await server();
229
321
  } catch {
230
322
  return retry();
231
323
  }
@@ -284,8 +376,11 @@ const relFile = (file) => path.relative(process.cwd(), file) || file;
284
376
  * The project's config, as the command line needs it: for its plugins (their commands, the
285
377
  * session, which events reach an agent), so without the pages. Loaded once per command.
286
378
  */
287
- let loaded = null;
288
- const projectConfig = (proj) => loaded ??= createConfigLoader(proj, { pages: false }).config();
379
+ const loaded = /* @__PURE__ */ new Map();
380
+ const projectConfig = (proj) => {
381
+ if (!loaded.has(proj.dir)) loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config());
382
+ return loaded.get(proj.dir);
383
+ };
289
384
  /**
290
385
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
291
386
  * plugin reads it from the environment): the first one that names one. Null without any.
@@ -317,7 +412,17 @@ async function status() {
317
412
  }
318
413
  switch (cmd) {
319
414
  case "serve": {
415
+ if (!project && readMachineConfig()) {
416
+ const { startShared } = await import("../src/serve.js");
417
+ await startShared();
418
+ break;
419
+ }
320
420
  const proj = needProject();
421
+ if (isShared(proj)) {
422
+ const { startShared } = await import("../src/serve.js");
423
+ await startShared();
424
+ break;
425
+ }
321
426
  const base = await running(proj);
322
427
  if (base) {
323
428
  console.error(`whiteboard: ${proj.name} is already served at ${base}`);
@@ -382,7 +487,7 @@ switch (cmd) {
382
487
  case "show":
383
488
  case "url": {
384
489
  if (cmd === "show" && !positionals[0]) throw new Error("usage: whiteboard show <page|file>");
385
- const base = await ensureServer();
490
+ const base = cmd === "show" ? await ensureServer() : await needServer();
386
491
  console.log(`${base}/${pageId(project, positionals[0] ?? "")}`);
387
492
  break;
388
493
  }
@@ -438,7 +543,7 @@ switch (cmd) {
438
543
  if (!target || !to) throw new Error("usage: whiteboard scroll <page|file> <heading, form name or text>");
439
544
  const proj = needProject();
440
545
  const id = pageId(proj, target);
441
- const base = await ensureServer();
546
+ const base = await needServer();
442
547
  const rendered = await (await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)).json().catch(() => null);
443
548
  const text = (rendered?.html ?? "").replace(/<[^>]+>/g, " ").replace(/&[a-z#0-9]+;/gi, " ").replace(/\s+/g, " ").toLowerCase();
444
549
  const named = new RegExp(`<form[^>]*\\bname="${to.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"`).test(rendered?.html ?? "");
@@ -527,6 +632,11 @@ switch (cmd) {
527
632
  case "watch": {
528
633
  const proj = needProject();
529
634
  const f = filter();
635
+ const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig(), proj.dir) : null;
636
+ if (entry) {
637
+ await entryFallback(entry, f, cmd);
638
+ break;
639
+ }
530
640
  const { handedOut } = await projectConfig(proj);
531
641
  const fallback = !f.page;
532
642
  let recheck = () => {};
@@ -582,6 +692,20 @@ switch (cmd) {
582
692
  case "status":
583
693
  await status();
584
694
  break;
695
+ case "paths": {
696
+ const config = readMachineConfig();
697
+ if (!config) throw new Error(`no machine config: ${machineDir()}/config.json`);
698
+ const paths = serverPaths(config, { packageDir: PACKAGE_DIR });
699
+ try {
700
+ fs.mkdirSync(stateDir(), { recursive: true });
701
+ } catch {}
702
+ const write = paths.write.filter((d) => fs.existsSync(d));
703
+ const read = paths.read.filter((d) => fs.existsSync(d));
704
+ if (opts.write) console.log(write.join(":"));
705
+ else if (opts.read) console.log(read.join(":"));
706
+ else console.log(`write: ${write.join(":")}\nread: ${read.join(":")}`);
707
+ break;
708
+ }
585
709
  case "skill": {
586
710
  const source = packagePath("skills", "whiteboard");
587
711
  if (!positionals[0]) {
@@ -650,6 +774,112 @@ switch (cmd) {
650
774
  if (!asked) process.exit(1);
651
775
  }
652
776
  }
777
+ /**
778
+ * The fallback of a whole entry: what no other wait or watch in any of its projects would take, on
779
+ * any page, also once they stop, from each project's own log, each event with the project it is
780
+ * from (`project`, its folder) and its page's `url`. One per entry: the shared server holds it, and
781
+ * refuses a second (exit 1). Without a shared server running it waits for one, as any wait does: who
782
+ * else listens is the server's to say. Projects that appear meanwhile are followed too.
783
+ */
784
+ async function entryFallback(entry, f, command) {
785
+ const file = machineServerFile();
786
+ const count = command === "wait" ? Number(opts.count ?? 1) : Infinity;
787
+ const done = new AbortController();
788
+ let total = 0;
789
+ done.signal.addEventListener("abort", () => setImmediate(() => process.exit(0)));
790
+ if (opts.timeout && command === "wait") setTimeout(() => {
791
+ console.error("timeout");
792
+ process.exit(2);
793
+ }, Number(opts.timeout) * 1e3);
794
+ await new Promise((registered) => {
795
+ const connect = async () => {
796
+ const shared = await sharedServer(file);
797
+ if (!shared) return setTimeout(connect, 2e3).unref();
798
+ const q = new URLSearchParams({
799
+ entry,
800
+ command,
801
+ ...f.type ? { type: f.type } : {}
802
+ });
803
+ let again = false;
804
+ const retry = (ms) => {
805
+ if (!again) {
806
+ again = true;
807
+ setTimeout(connect, ms).unref();
808
+ }
809
+ };
810
+ const req = http.get(`${shared.origin}/api/listen?${q}`, (res) => {
811
+ if (res.statusCode === 409) {
812
+ let body = "";
813
+ res.on("data", (d) => body += d);
814
+ res.on("end", () => {
815
+ console.error(`whiteboard: ${JSON.parse(body || "{}").error ?? "another agent is the fallback"}. Add --page to wait on a page of your own.`);
816
+ process.exit(1);
817
+ });
818
+ return;
819
+ }
820
+ res.resume();
821
+ registered();
822
+ res.on("close", () => retry(1e3));
823
+ });
824
+ req.on("error", () => retry(2e3));
825
+ req.on("socket", (socket) => socket.unref());
826
+ };
827
+ connect();
828
+ });
829
+ const following = /* @__PURE__ */ new Map();
830
+ async function start(p, origin) {
831
+ const proj = project$1(p.dir);
832
+ if (!proj) return;
833
+ const stop = new AbortController();
834
+ following.set(p.dir, stop);
835
+ const { handedOut } = await projectConfig(proj);
836
+ let recheck = () => {};
837
+ const at = async () => {
838
+ const shared = await sharedServer(file);
839
+ const now = shared?.projects.find((x) => x.dir === p.dir);
840
+ if (!shared || !now) throw new Error("not served");
841
+ return `${shared.origin}${now.base}`;
842
+ };
843
+ const others = await otherListeners(() => recheck(), at);
844
+ const held = /* @__PURE__ */ new Set();
845
+ const skip = (e) => {
846
+ if (!held.has(e.id)) {
847
+ held.add(e.id);
848
+ setTimeout(() => recheck(), 500).unref();
849
+ return true;
850
+ }
851
+ return takenByOther(others(), e);
852
+ };
853
+ const page = (id) => id.split("/").map(encodeURIComponent).join("/");
854
+ await handOut(proj.eventsFile, { type: f.type }, (e) => {
855
+ console.log(JSON.stringify({
856
+ ...e,
857
+ project: p.dir,
858
+ url: `${origin}${p.base}/${page(e.page)}`
859
+ }));
860
+ if (++total >= count) done.abort();
861
+ }, {
862
+ forAgent: forAgent(handedOut),
863
+ signal: AbortSignal.any([stop.signal, done.signal]),
864
+ skip,
865
+ recheck: (again) => {
866
+ recheck = again;
867
+ }
868
+ });
869
+ }
870
+ const sync = async () => {
871
+ const shared = await sharedServer(file);
872
+ if (!shared) return;
873
+ const mine = shared.projects.filter((p) => p.entry === entry);
874
+ for (const p of mine) if (!following.has(p.dir)) start(p, shared.origin);
875
+ for (const [dir, stop] of following) if (!mine.some((p) => p.dir === dir)) {
876
+ stop.abort();
877
+ following.delete(dir);
878
+ }
879
+ };
880
+ await sync();
881
+ setInterval(sync, 2e3);
882
+ }
653
883
  /** The commands the project's plugins add: `whiteboard <plugin> [sub]`. */
654
884
  async function projectCommands(proj) {
655
885
  const { plugins, errors } = await projectConfig(proj);
@@ -93,6 +93,17 @@ function reactive(get) {
93
93
  };
94
94
  return value;
95
95
  }
96
+ const base = (() => {
97
+ try {
98
+ return JSON.parse(document.getElementById("wb-page")?.textContent ?? "{}");
99
+ } catch {
100
+ return {};
101
+ }
102
+ })().base ?? "";
103
+ /** A path of the project's server (`/api/events`) as this page requests it. */
104
+ const url = (path) => base + path;
105
+ /** A localStorage key, kept apart from other projects' on the same origin. */
106
+ const storageKey = (key) => base ? `${base}|${key}` : key;
96
107
  // src/client/forms.ts
97
108
  let root$1;
98
109
  let api$1;
@@ -157,7 +168,7 @@ function onOtherInput(e) {
157
168
  if (text.value.trim()) option.checked = true;
158
169
  else if (option.type === "checkbox") option.checked = false;
159
170
  }
160
- const draftKey = (form) => `wb-draft:${page$1}:${form.getAttribute("name")}`;
171
+ const draftKey = (form) => storageKey(`wb-draft:${page$1}:${form.getAttribute("name")}`);
161
172
  function saveDraft(e) {
162
173
  const form = e.target?.closest?.("form");
163
174
  if (!form || !managed(form) || !root$1.contains(form) || keepsOwnFields(form)) return;
@@ -415,7 +426,7 @@ async function flush() {
415
426
  const batch = queue;
416
427
  queue = [];
417
428
  try {
418
- const res = await fetch("/api/markdown", {
429
+ const res = await fetch(url("/api/markdown"), {
419
430
  method: "POST",
420
431
  headers: { "content-type": "application/json" },
421
432
  body: JSON.stringify({ texts: batch.map((b) => b.text) })
@@ -501,11 +512,11 @@ function setEvents(next) {
501
512
  }
502
513
  async function loadEvents() {
503
514
  if (!live) return;
504
- setEvents((await (await fetch(`/api/events?page=${encodeURIComponent(page)}`)).json()).filter((e) => e.page === page));
515
+ setEvents((await (await fetch(url(`/api/events?page=${encodeURIComponent(page)}`))).json()).filter((e) => e.page === page));
505
516
  }
506
517
  async function append(type, data = {}, action = null) {
507
518
  if (!live) throw new Error("a built page is a file: there is no log to append to");
508
- const res = await fetch("/api/events", {
519
+ const res = await fetch(url("/api/events"), {
509
520
  method: "POST",
510
521
  headers: { "content-type": "application/json" },
511
522
  body: JSON.stringify({
@@ -524,7 +535,7 @@ let listeners = [];
524
535
  const listenersValue = reactive(() => listeners);
525
536
  async function loadListeners() {
526
537
  if (!live) return;
527
- listeners = await (await fetch(`/api/listeners?page=${encodeURIComponent(page)}`)).json();
538
+ listeners = await (await fetch(url(`/api/listeners?page=${encodeURIComponent(page)}`))).json();
528
539
  listenersValue.notify();
529
540
  }
530
541
  const renderedListeners = /* @__PURE__ */ new Set();
@@ -538,6 +549,7 @@ function writeTitle() {
538
549
  }
539
550
  const api = {
540
551
  page,
552
+ url,
541
553
  events: eventsValue,
542
554
  last: (type) => events.findLast((e) => e.type === type),
543
555
  pickedUp: (id) => !!events.find((e) => e.id === id)?.pickedUp,
@@ -602,18 +614,18 @@ const handle = {
602
614
  return () => changeListeners.delete(fn);
603
615
  },
604
616
  render: async () => {
605
- const next = await getJson(`/api/render?page=${encodeURIComponent(page)}`);
617
+ const next = await getJson(url(`/api/render?page=${encodeURIComponent(page)}`));
606
618
  nextData = next.data ?? null;
607
619
  nextFrontmatter = next.frontmatter ?? {};
608
620
  return next;
609
621
  },
610
- stored: () => getJson(`/api/page?page=${encodeURIComponent(page)}`)
622
+ stored: () => getJson(url(`/api/page?page=${encodeURIComponent(page)}`))
611
623
  };
612
624
  /** Did the page change since it was rendered here (its file's time, or it came to be)? Then say so. */
613
625
  async function caughtUp() {
614
626
  let now;
615
627
  try {
616
- now = (await getJson(`/api/render?page=${encodeURIComponent(page)}`)).mtime ?? null;
628
+ now = (await getJson(url(`/api/render?page=${encodeURIComponent(page)}`))).mtime ?? null;
617
629
  } catch {
618
630
  now = null;
619
631
  }
@@ -625,7 +637,7 @@ if (!handoff.client) handle.onChange(async () => {
625
637
  api.rendered();
626
638
  });
627
639
  function connect() {
628
- const es = new EventSource(`/api/watch?page=${encodeURIComponent(page)}${isDir ? "&dir" : ""}`);
640
+ const es = new EventSource(url(`/api/watch?page=${encodeURIComponent(page)}${isDir ? "&dir" : ""}`));
629
641
  es.onopen = () => {
630
642
  document.documentElement.dataset.wbLive = "";
631
643
  loadListeners();
@@ -643,7 +655,7 @@ function connect() {
643
655
  es.addEventListener("reload", () => {
644
656
  const go = async () => {
645
657
  try {
646
- if ((await fetch("/api/health", { cache: "no-store" })).ok) return location.reload();
658
+ if ((await fetch(url("/api/health"), { cache: "no-store" })).ok) return location.reload();
647
659
  } catch {}
648
660
  setTimeout(go, 500);
649
661
  };
@@ -0,0 +1,36 @@
1
+ What a program printed, as its terminal showed it: an `ansi` fence holds the
2
+ output with its escape codes, and the page draws it dark, in its colours, as a
3
+ terminal does. It goes through a terminal emulator on the server, so colours
4
+ (16, 256 and true colour, foreground and background), bold, dim and underline
5
+ show, and a progress line that a carriage return writes over shows as it
6
+ ended. It is plain HTML: nothing runs on the page, and `whiteboard build` keeps
7
+ it. Wide output scrolls sideways (a line wraps at 240 columns, as a terminal
8
+ that wide would).
9
+
10
+ ````markdown
11
+ ```ansi
12
+ \e[32m✔\e[0m parses a page
13
+ \e[31m✖\e[0m renders a diff \e[2m(12ms)\e[0m
14
+ ```
15
+ ````
16
+
17
+ ```ansi
18
+ \e[32m✔\e[0m parses a page
19
+ \e[31m✖\e[0m renders a diff \e[2m(12ms)\e[0m
20
+ ```
21
+
22
+ The escape byte itself works, and so does any way of writing it out: `\e`,
23
+ `\x1b`, `\033`, `\u001b` or `^[`. A carriage return has to be the byte itself,
24
+ as a program prints it: `\r` written out stays as written, since it is as
25
+ likely a path (`C:\repo`). To capture a command's colours, have it colour
26
+ output that isn't a terminal (`--color=always`, `FORCE_COLOR=1`) and paste
27
+ what it printed.
28
+
29
+ `title` puts it in a window with that label, whose button fills the browser
30
+ window with it:
31
+
32
+ ````markdown
33
+ ```ansi {title="npm test"}
34
+ …
35
+ ```
36
+ ````
@@ -0,0 +1,64 @@
1
+ import { builtinPublic } from "../../src/package.js";
2
+ import fs from "node:fs";
3
+ import { definePlugin, html, raw, windowFrame } from "@bigmistqke/whiteboard";
4
+ import xtermHeadless from "@xterm/headless";
5
+ import xtermSerialize from "@xterm/addon-serialize";
6
+ // plugins/ansi/index.ts
7
+ const { Terminal } = xtermHeadless;
8
+ const { SerializeAddon } = xtermSerialize;
9
+ /** The widest a line is laid out before it wraps, as a terminal would. */
10
+ const MAX_COLS = 240;
11
+ const ESC = "\x1B";
12
+ /**
13
+ * Escapes written out as text count as escapes: an agent writing a page often can't put the ESC
14
+ * byte itself in a file, so `\e[31m`, `\x1b[31m`, `\033[31m`, `\u001b[31m` and `^[[31m` are one.
15
+ */
16
+ const unescape = (text) => text.replace(/\\e(?=\[)|\\x1b|\\033|\\u001b|\^\[(?=\[)/gi, ESC);
17
+ /** How wide a line shows: its characters, without its escape sequences. */
18
+ const shown = (line) => [...line.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, "").split("\r").at(-1)].length;
19
+ /**
20
+ * What the text shows in a terminal as wide as its widest line (up to MAX_COLS), as HTML rows: the
21
+ * serializer's spans, colours inline, text escaped; trailing blank space and blank rows left out.
22
+ */
23
+ async function toHtml(text) {
24
+ const input = unescape(text).replace(/\r?\n$/, "");
25
+ const lines = input.split(/\r?\n/);
26
+ const cols = Math.min(MAX_COLS, Math.max(20, ...lines.map(shown)));
27
+ const term = new Terminal({
28
+ cols,
29
+ rows: Math.max(1, lines.length),
30
+ scrollback: 1e5,
31
+ allowProposedApi: true,
32
+ convertEol: true
33
+ });
34
+ const serializer = new SerializeAddon();
35
+ term.loadAddon(serializer);
36
+ await new Promise((resolve) => term.write(input, resolve));
37
+ const out = serializer.serializeAsHTML({ includeGlobalBackground: false });
38
+ term.dispose();
39
+ const rows = [...(/<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(out)?.[1] ?? "").matchAll(/<div>([\s\S]*?)<\/div>/g)].map((m) => m[1].replace(/<span><\/span>/g, "").replace(/<span> +<\/span>$/, "").replace(/(<span>[^<]*?) +(<\/span>)$/, "$1$2"));
40
+ while (rows.length && !rows.at(-1).replace(/<[^>]+>/g, "").trim()) rows.pop();
41
+ return rows.map((r) => `<span class="wb-ansi-row">${r}</span>`).join("\n");
42
+ }
43
+ async function render(ctx) {
44
+ const body = html`<pre class="wb-ansi"><code>${raw(await toHtml(ctx.text))}</code></pre>`;
45
+ const title = ctx.attrs.title;
46
+ return title ? windowFrame({
47
+ body,
48
+ label: String(html`${title}`),
49
+ className: "wb-ansi-window"
50
+ }) : body;
51
+ }
52
+ function ansi() {
53
+ return definePlugin({
54
+ name: "ansi",
55
+ public: builtinPublic("ansi"),
56
+ blocks: { ansi: {
57
+ fence: true,
58
+ html: render,
59
+ style: "style.css"
60
+ } },
61
+ docs: () => fs.readFileSync(new URL("./README.md", import.meta.url), "utf8")
62
+ });
63
+ }
64
+ export { ansi as default, render, toHtml, unescape };
@@ -0,0 +1,28 @@
1
+ /* Terminal output: dark as a terminal in either theme, since the colours in it are a terminal's
2
+ palette, written inline. Wide output scrolls sideways rather than wrapping. */
3
+ .wb-ansi {
4
+ margin: 1.6em 0;
5
+ padding: 12px 16px;
6
+ overflow-x: auto;
7
+ background: #0f1115;
8
+ color: #d7dae0;
9
+ border-radius: var(--radius, 6px);
10
+ font: 0.82rem/1.45 var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
11
+ white-space: pre;
12
+ tab-size: 8;
13
+ }
14
+ .wb-ansi code {
15
+ font: inherit;
16
+ background: none;
17
+ padding: 0;
18
+ color: inherit;
19
+ }
20
+ /* in a window (title=, or compose=window) the terminal fills it, the frame its edge */
21
+ .wb-window-body:has(> .wb-ansi:only-child) {
22
+ padding: 0;
23
+ background: #0f1115;
24
+ }
25
+ .wb-window-body > .wb-ansi {
26
+ margin: 0;
27
+ border-radius: 0;
28
+ }
@@ -0,0 +1,28 @@
1
+ A status as a coloured dot and a word, inline wherever text goes: in a
2
+ heading, a table cell, a list item, a sentence. `done ok yes good` are
3
+ green, `active new info` blue, `open todo maybe warning` amber,
4
+ `blocked no bad error` red; any other word is grey.
5
+
6
+ ```markdown
7
+ ### Parser :badge[done]
8
+
9
+ | step | state |
10
+ | --- | --- |
11
+ | parse | :badge[done] |
12
+ | render | :badge[active] |
13
+ | docs | :badge[todo] |
14
+
15
+ The release is :badge[blocked] on review.
16
+ ```
17
+
18
+ A grid card whose heading ends in a badge shows it at the card's right edge.
19
+
20
+ ### Parser :badge[done]
21
+
22
+ | step | state |
23
+ | --- | --- |
24
+ | parse | :badge[done] |
25
+ | render | :badge[active] |
26
+ | docs | :badge[todo] |
27
+
28
+ The release is :badge[blocked] on review.
@@ -0,0 +1,24 @@
1
+ import { builtinPublic } from "../../src/package.js";
2
+ import fs from "node:fs";
3
+ import { definePlugin, html, raw } from "@bigmistqke/whiteboard";
4
+ // plugins/badge/index.ts
5
+ /** The word a badge's colour is chosen by: its text, lowercased, runs of other characters a `-`. */
6
+ const tone = (s) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
7
+ /** `:badge[done]`: a coloured dot and a word, inline wherever text goes. */
8
+ function render(ctx) {
9
+ const text = ctx.labelText?.trim();
10
+ if (!text) return html``;
11
+ return html`<span class="wb-badge" data-badge="${tone(text)}">${raw(ctx.label ?? "")}</span>`;
12
+ }
13
+ function badge() {
14
+ return definePlugin({
15
+ name: "badge",
16
+ public: builtinPublic("badge"),
17
+ blocks: { badge: {
18
+ html: render,
19
+ style: "style.css"
20
+ } },
21
+ docs: () => fs.readFileSync(new URL("./README.md", import.meta.url), "utf8")
22
+ });
23
+ }
24
+ export { badge as default, render, tone };