@bigmistqke/whiteboard 0.4.0 → 0.6.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 (128) hide show
  1. package/README.md +177 -26
  2. package/bin/whiteboard.ts +331 -16
  3. package/dist/bin/whiteboard.js +268 -17
  4. package/dist/client/runtime.js +66 -23
  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/draft/README.md +14 -0
  15. package/dist/plugins/draft/index.js +21 -0
  16. package/dist/plugins/draft/public/style.css +21 -0
  17. package/dist/plugins/grid/README.md +12 -12
  18. package/dist/plugins/grid/index.js +7 -19
  19. package/dist/plugins/grid/public/style.css +4 -33
  20. package/dist/plugins/iframe/README.md +7 -7
  21. package/dist/plugins/iframe/index.js +11 -11
  22. package/dist/plugins/iframe/public/style.css +15 -0
  23. package/dist/plugins/index.js +11 -3
  24. package/dist/plugins/lightbox/README.md +22 -0
  25. package/dist/plugins/lightbox/index.js +20 -0
  26. package/dist/plugins/lightbox/public/client.js +4 -0
  27. package/dist/plugins/lightbox/public/style.css +66 -0
  28. package/dist/plugins/steps/README.md +42 -0
  29. package/dist/plugins/steps/index.js +60 -0
  30. package/dist/plugins/steps/public/client.js +1 -0
  31. package/dist/plugins/steps/public/style.css +77 -0
  32. package/dist/plugins/terminal/host.js +9 -3
  33. package/dist/plugins/terminal/public/client.js +1 -1
  34. package/dist/plugins/terminal/sizes.js +2 -1
  35. package/dist/plugins/toc/README.md +21 -3
  36. package/dist/plugins/toc/index.js +8 -2
  37. package/dist/plugins/toc/public/client.js +1 -1
  38. package/dist/plugins/toc/public/style.css +10 -4
  39. package/dist/plugins/window/README.md +34 -14
  40. package/dist/plugins/window/index.js +21 -13
  41. package/dist/src/auth.js +6 -4
  42. package/dist/src/client/page/base.css +61 -1
  43. package/dist/src/client/page/main.js +74 -20
  44. package/dist/src/entries.js +211 -0
  45. package/dist/src/events.js +1 -1
  46. package/dist/src/hub.js +272 -0
  47. package/dist/src/loader.js +12 -3
  48. package/dist/src/package.js +23 -1
  49. package/dist/src/pages/blocks.js +1 -0
  50. package/dist/src/pages/index.js +1 -1
  51. package/dist/src/pages/markdown.js +87 -33
  52. package/dist/src/pages/render.js +157 -28
  53. package/dist/src/pages/window.js +17 -18
  54. package/dist/src/running.js +37 -2
  55. package/dist/src/serve.js +111 -2
  56. package/dist/src/server.js +264 -23
  57. package/package.json +3 -2
  58. package/plugins/ansi/README.md +36 -0
  59. package/plugins/ansi/index.ts +95 -0
  60. package/plugins/ansi/public/style.css +28 -0
  61. package/plugins/badge/README.md +28 -0
  62. package/plugins/badge/index.ts +35 -0
  63. package/plugins/badge/public/style.css +30 -0
  64. package/plugins/chat/public/style.css +7 -2
  65. package/plugins/code/README.md +4 -2
  66. package/plugins/code/diff.ts +14 -2
  67. package/plugins/code/index.ts +3 -1
  68. package/plugins/draft/README.md +14 -0
  69. package/plugins/draft/index.ts +23 -0
  70. package/plugins/draft/public/style.css +21 -0
  71. package/plugins/grid/README.md +12 -12
  72. package/plugins/grid/index.ts +11 -26
  73. package/plugins/grid/public/style.css +4 -33
  74. package/plugins/iframe/README.md +7 -7
  75. package/plugins/iframe/index.ts +15 -15
  76. package/plugins/iframe/public/style.css +15 -0
  77. package/plugins/index.ts +10 -2
  78. package/plugins/lightbox/README.md +22 -0
  79. package/plugins/lightbox/client.ts +99 -0
  80. package/plugins/lightbox/index.ts +25 -0
  81. package/plugins/lightbox/public/style.css +66 -0
  82. package/plugins/mermaid/index.ts +4 -2
  83. package/plugins/steps/README.md +42 -0
  84. package/plugins/steps/client.ts +75 -0
  85. package/plugins/steps/index.ts +84 -0
  86. package/plugins/steps/public/style.css +77 -0
  87. package/plugins/terminal/client.ts +16 -7
  88. package/plugins/terminal/host.ts +12 -6
  89. package/plugins/terminal/sizes.ts +3 -1
  90. package/plugins/toc/README.md +21 -3
  91. package/plugins/toc/client.ts +47 -6
  92. package/plugins/toc/index.ts +19 -6
  93. package/plugins/toc/public/style.css +10 -4
  94. package/plugins/window/README.md +34 -14
  95. package/plugins/window/index.ts +20 -13
  96. package/skills/whiteboard/SKILL.md +18 -10
  97. package/src/auth.ts +8 -5
  98. package/src/client/base.ts +19 -0
  99. package/src/client/forms.ts +2 -1
  100. package/src/client/markdown.ts +2 -1
  101. package/src/client/page/base.css +61 -1
  102. package/src/client/page/elsewhere.ts +72 -16
  103. package/src/client/page/fresh.ts +2 -1
  104. package/src/client/page/main.ts +18 -6
  105. package/src/client/page/sort.ts +2 -1
  106. package/src/client/runtime.ts +62 -25
  107. package/src/define.ts +126 -19
  108. package/src/entries.ts +258 -0
  109. package/src/events.ts +2 -1
  110. package/src/hub.ts +355 -0
  111. package/src/loader.ts +14 -3
  112. package/src/package.ts +22 -0
  113. package/src/pages/blocks.ts +3 -0
  114. package/src/pages/index.ts +6 -4
  115. package/src/pages/markdown.ts +89 -32
  116. package/src/pages/render.ts +181 -28
  117. package/src/pages/window.ts +23 -25
  118. package/src/running.ts +47 -1
  119. package/src/serve.ts +114 -1
  120. package/src/server.ts +332 -26
  121. package/dist/plugins/gallery/README.md +0 -30
  122. package/dist/plugins/gallery/index.js +0 -75
  123. package/dist/plugins/gallery/public/client.js +0 -1
  124. package/dist/plugins/gallery/public/style.css +0 -90
  125. package/plugins/gallery/README.md +0 -30
  126. package/plugins/gallery/client.tsx +0 -70
  127. package/plugins/gallery/index.ts +0 -89
  128. package/plugins/gallery/public/style.css +0 -90
@@ -2,6 +2,7 @@ import { renderMarkdown } from "./markdown.js";
2
2
  import { html, raw } from "../html.js";
3
3
  import { awaitingLabel } from "../icons.js";
4
4
  import fs from "node:fs";
5
+ import os from "node:os";
5
6
  import path from "node:path";
6
7
  import { execFileSync } from "node:child_process";
7
8
  import { fileURLToPath } from "node:url";
@@ -38,18 +39,19 @@ function titleOf(file, fallback) {
38
39
  return fallback;
39
40
  }
40
41
  }
41
- function crumbs(id, name) {
42
+ function crumbs(id, name, base, entry) {
42
43
  const parts = id ? id.split("/") : [];
43
- return html`<a href="/">${name}</a
44
- >${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join("/")}">${p}</a>`)}`;
44
+ const above = entry ? html`<a href="/">whiteboard</a> / ` : "";
45
+ return html`${above}<a href="${base}/">${name}</a
46
+ >${parts.map((p, i) => html` / <a href="${base}/${parts.slice(0, i + 1).join("/")}">${p}</a>`)}`;
45
47
  }
46
48
  const time = (ts) => html`<time data-ts="${ts}"></time>`;
47
- function pageList(pages) {
49
+ function pageList(pages, base) {
48
50
  return html`<ul class="wb-index">
49
51
  ${pages.map((p) => html`<li>
50
- <a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${p.awaiting > 0 && html` <a
52
+ <a href="${base}/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${p.awaiting > 0 && html` <a
51
53
  class="wb-awaiting"
52
- href="/${p.id}#wb-waiting"
54
+ href="${base}/${p.id}#wb-waiting"
53
55
  title="${awaitingLabel(p.awaiting)}"
54
56
  aria-label="${awaitingLabel(p.awaiting)}"
55
57
  >${raw("<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/></svg>")}${p.awaiting}</a
@@ -133,7 +135,7 @@ function documentsIn(dir) {
133
135
  walk("");
134
136
  }
135
137
  const depth = (f) => f.split("/").length;
136
- return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b));
138
+ return [...new Set(files)].toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b));
137
139
  }
138
140
  /**
139
141
  * The overview's list of the project's documents: each by its title, linked to its rendered page,
@@ -141,8 +143,79 @@ function documentsIn(dir) {
141
143
  * written here), by when last updated, or by title; each row carries what it is sorted by.
142
144
  */
143
145
  function documentList(ctx) {
144
- const files = documentsIn(ctx.project.dir);
146
+ return documentsOf(ctx.project.dir, ctx.base ?? "", ctx.urlFor);
147
+ }
148
+ /**
149
+ * A project's documents by the folder they are in, each folder a fold with how many it holds, the
150
+ * top folder's own documents first: the shared server's overview, where a repository's many
151
+ * documents would otherwise be one long list. A folder holding only one folder is shown as one
152
+ * (`docs/adr/`), so the tree is no deeper than what tells folders apart.
153
+ */
154
+ function documentTree(files, dir, base, urlFor) {
155
+ const root = {
156
+ files: [],
157
+ folders: /* @__PURE__ */ new Map(),
158
+ count: 0
159
+ };
160
+ for (const f of files) {
161
+ let at = root;
162
+ at.count++;
163
+ const parts = f.split("/");
164
+ for (const part of parts.slice(0, -1)) {
165
+ if (!at.folders.has(part)) at.folders.set(part, {
166
+ files: [],
167
+ folders: /* @__PURE__ */ new Map(),
168
+ count: 0
169
+ });
170
+ at = at.folders.get(part);
171
+ at.count++;
172
+ }
173
+ at.files.push(f);
174
+ }
175
+ const row = (f) => {
176
+ const abs = path.join(dir, f);
177
+ const name = path.posix.basename(f);
178
+ const title = titleOf(abs, name);
179
+ let mtime = 0;
180
+ try {
181
+ mtime = fs.statSync(abs).mtimeMs;
182
+ } catch {}
183
+ return html`<li>
184
+ <a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
185
+ <span class="wb-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
186
+ </li>`;
187
+ };
188
+ const folder = (name, f) => {
189
+ while (!f.files.length && f.folders.size === 1) {
190
+ const [inner, next] = [...f.folders][0];
191
+ name = `${name}/${inner}`;
192
+ f = next;
193
+ }
194
+ return html`<details class="wb-folder">
195
+ <summary>${name}/ <span class="wb-meta">${f.count}</span></summary>
196
+ ${contents(f)}
197
+ </details>`;
198
+ };
199
+ const contents = (f) => html`${f.files.length > 0 && html`<ul class="wb-index">
200
+ ${f.files.map(row)}
201
+ </ul>`}${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`;
202
+ return html`<details class="wb-documents wb-folded-documents">
203
+ <summary>Files <span class="wb-meta">${files.length}</span></summary>
204
+ ${contents(root)}
205
+ </details>`;
206
+ }
207
+ /**
208
+ * A project's documents, as its overview lists them: from its folder, linked where it serves them.
209
+ * `folded`: in a fold that says how many (the shared server's overview, where each project has them).
210
+ */
211
+ function documentsOf(dir, base, urlFor, folded = false) {
212
+ const files = documentsIn(dir);
145
213
  if (!files.length) return "";
214
+ const ctx = {
215
+ project: { dir },
216
+ base,
217
+ urlFor
218
+ };
146
219
  const rows = files.map((f, i) => {
147
220
  const abs = path.join(ctx.project.dir, f);
148
221
  const name = path.posix.basename(f);
@@ -153,12 +226,13 @@ function documentList(ctx) {
153
226
  mtime = fs.statSync(abs).mtimeMs;
154
227
  } catch {}
155
228
  return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
156
- <a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a>
229
+ <a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ""}/-/${f}`}">${title}</a>
157
230
  <span class="wb-meta"
158
231
  >${where !== "." && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span
159
232
  >
160
233
  </li>`;
161
234
  });
235
+ if (folded) return documentTree(files, dir, base, urlFor);
162
236
  return html`<section class="wb-documents">
163
237
  <div class="wb-list-head">
164
238
  <h2>Documents</h2>
@@ -216,19 +290,40 @@ function createMessageRender(blocks, links = []) {
216
290
  };
217
291
  };
218
292
  }
219
- function createRender(blocks, style, pluginStyles = [], links = []) {
293
+ /** What a block left out of a build (RenderContext.skip) is: nothing, for its directives and fences alike. */
294
+ const skipped = (name) => ({
295
+ name,
296
+ code: false,
297
+ fences: true,
298
+ props: null,
299
+ html: () => "",
300
+ open: null,
301
+ client: null,
302
+ style: null,
303
+ source: "build"
304
+ });
305
+ function createRender(blocks, style, pluginStyles = [], links = [], composers = /* @__PURE__ */ new Map()) {
220
306
  const textLinks = textLinksOf(links);
221
307
  const STYLE = stylePath(style);
222
- const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f) => !!f);
308
+ const PLUGIN_STYLES = pluginStyles.map((s) => ({
309
+ plugin: s.plugin,
310
+ file: stylePath(s.file)
311
+ })).filter((s) => !!s.file);
223
312
  async function markdown(source, page, file, ctx) {
224
313
  const { blocks: set, code } = blocks();
314
+ const skip = ctx.skip;
225
315
  return renderMarkdown(body(source), {
226
316
  page,
227
317
  file,
228
- resolve: (name) => set.get(name) ?? null,
318
+ resolve: (name) => {
319
+ const block = set.get(name) ?? null;
320
+ if (skip && (skip.has(name) || block && skip.has(block.source))) return skipped(name);
321
+ return block;
322
+ },
229
323
  code,
230
324
  linkFor: ctx.urlFor,
231
- textLinks: textLinks(ctx.project.dir)
325
+ textLinks: textLinks(ctx.project.dir),
326
+ composers: skip ? new Map([...composers].map(([name, compose]) => skip.has(name) ? [name, ({ children }) => String(children)] : [name, compose])) : composers
232
327
  });
233
328
  }
234
329
  async function content(page, ctx) {
@@ -236,15 +331,41 @@ function createRender(blocks, style, pluginStyles = [], links = []) {
236
331
  switch (page.kind) {
237
332
  case "page": return markdown(page.source, page.id, page.file, ctx);
238
333
  case "pages": {
239
- const list = page.pages.length ? pageList(page.pages) : html`<p class="wb-meta">No pages yet.</p>`;
334
+ if (page.groups) {
335
+ const waiting = (ps) => ps.reduce((n, p) => n + p.awaiting, 0);
336
+ const first = (ps) => ps.toSorted((a, b) => Number(b.awaiting > 0) - Number(a.awaiting > 0));
337
+ const groups = page.groups.toSorted((a, b) => Number(waiting(b.pages) > 0) - Number(waiting(a.pages) > 0));
338
+ return {
339
+ html: html`<h1>${project.name}</h1>
340
+ ${groups.map((g) => html`<section class="wb-project">
341
+ <h2>${g.title}</h2>
342
+ <p class="wb-meta">
343
+ <code>${g.dir.replace(os.homedir(), "~")}</code>
344
+ </p>
345
+ ${pageList(first(g.pages), g.base)} ${g.files && documentsOf(g.dir, g.base, () => null, true)}
346
+ </section>`)}
347
+ ${!groups.length && html`<p class="wb-meta">No pages yet.</p>`}
348
+ ${page.empty?.length ? html`<details class="wb-empty-projects">
349
+ <summary>${page.empty.length} without pages</summary>
350
+ <ul>
351
+ ${page.empty.map((e) => html`<li><a href="${e.base}/">${e.title}</a></li>`)}
352
+ </ul>
353
+ </details>` : ""}
354
+ ${page.note && html`<p class="wb-meta">${page.note}</p>`}`,
355
+ title: project.name,
356
+ islands: {},
357
+ styles: []
358
+ };
359
+ }
360
+ const list = page.pages.length ? pageList(page.pages, ctx.base ?? "") : html`<p class="wb-meta">No pages yet.</p>`;
240
361
  return {
241
362
  html: page.id ? html`<h1>${page.id}</h1>
242
363
  ${list}
243
364
  <p class="wb-meta">${page.file}</p>` : html`<h1>${project.name}</h1>
244
365
  ${list}${project.files && documentList(ctx)}
245
366
  <p class="wb-meta">
246
- <code>${project.dir}</code>${project.files && html` · <a href="/-/">files</a>`} ·
247
- <a href="/_/docs">how to write pages</a>
367
+ <code>${project.dir}</code>${project.files && html` · <a href="${ctx.base ?? ""}/-/">files</a>`} ·
368
+ <a href="${ctx.base ?? ""}/_/docs">how to write pages</a>
248
369
  </p>`,
249
370
  title: page.id || project.name,
250
371
  islands: {},
@@ -321,19 +442,27 @@ function createRender(blocks, style, pluginStyles = [], links = []) {
321
442
  client: ctx.asset(island.client)
322
443
  }]));
323
444
  const styles = out.styles.map((s) => ctx.asset(s));
324
- const nav = html`<nav class="wb-nav">
325
- <span>${crumbs(page.id, ctx.project.name)}</span
326
- >${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button
327
- type="button"
328
- class="wb-theme"
329
- title="Theme: follow the system, light or dark"
330
- aria-label="Theme"
331
- ></button
332
- ><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span>
333
- </nav>`;
445
+ const nav = ctx.live === false ? html`<nav class="wb-nav">
446
+ <span>${ctx.project.name}</span
447
+ ><button
448
+ type="button"
449
+ class="wb-theme"
450
+ title="Theme: follow the system, light or dark"
451
+ aria-label="Theme"
452
+ ></button>
453
+ </nav>` : html`<nav class="wb-nav">
454
+ <span>${crumbs(page.id, ctx.entry?.label || ctx.project.name, ctx.base ?? "", ctx.entry)}</span
455
+ >${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button
456
+ type="button"
457
+ class="wb-theme"
458
+ title="Theme: follow the system, light or dark"
459
+ aria-label="Theme"
460
+ ></button
461
+ ><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span>
462
+ </nav>`;
334
463
  const links = [
335
464
  ctx.asset(BASE_CSS),
336
- ...PLUGIN_STYLES.map((f) => ctx.asset(f)),
465
+ ...PLUGIN_STYLES.filter((s) => !ctx.skip?.has(s.plugin)).map((s) => ctx.asset(s.file)),
337
466
  ...styles,
338
467
  ...STYLE ? [ctx.asset(STYLE)] : []
339
468
  ];
@@ -364,7 +493,7 @@ A page is markdown: GFM tables, \`<details>\`, raw HTML and a hand-written \`<fo
364
493
 
365
494
  The blocks here, by the plugin that brings them (each plugin's section below says how to write them):
366
495
 
367
- ${[...byPlugin].sort(([a], [b]) => a.localeCompare(b)).map(([plugin, blocks]) => `- **${plugin}**: ${blocks.map((b) => `\`${b}\``).join(", ")}`).join("\n")}
496
+ ${[...byPlugin].toSorted(([a], [b]) => a.localeCompare(b)).map(([plugin, blocks]) => `- **${plugin}**: ${blocks.map((b) => `\`${b}\``).join(", ")}`).join("\n")}
368
497
  `;
369
498
  };
370
499
  }
@@ -5,26 +5,25 @@ const OPEN = svg("<path d=\"M9 2.5h4.5V7M13.5 2.5 7.5 8.5M11.5 9.5v3a1 1 0 0 1-1
5
5
  const MAXIMIZE = svg("<path d=\"M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10\"/>");
6
6
  const RESTORE = svg("<path d=\"M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5\"/>");
7
7
  /** A window around a block's HTML: see the top of this file. */
8
- function windowFrame({ body, label = null, open = null, wide = false, bare = false, bodyClass = "", height }) {
8
+ function windowFrame({ body, label = null, open = null, wide = false, height, className = "", controls = "" }) {
9
9
  const name = label != null && String(label) !== "" ? html`<span class="wb-window-title">${raw(String(label))}</span>` : open ? html`<span class="wb-window-address">${open}</span>` : html``;
10
- const header = !bare && html`<div class="wb-window-bar">
11
- <span class="wb-window-name" ${open ? html` title="${open}"` : ""}>${name}</span>
12
- ${open && html`<a class="wb-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
13
- <button
14
- type="button"
15
- class="wb-window-button"
16
- data-wb-maximize
17
- title="Fill the window"
18
- aria-label="Fill the window"
19
- >
20
- <span class="wb-window-max">${MAXIMIZE}</span><span class="wb-window-restore">${RESTORE}</span>
21
- </button>
22
- </div>`;
23
- return html`<div class="wb-window${wide && raw(" wb-wide")}">
10
+ const header = html`<div class="wb-window-bar">
11
+ <span class="wb-window-name" ${open ? html` title="${open}"` : ""}>${name}</span>
12
+ ${raw(String(controls))}
13
+ ${open && html`<a class="wb-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
14
+ <button
15
+ type="button"
16
+ class="wb-window-button"
17
+ data-wb-maximize
18
+ title="Fill the window"
19
+ aria-label="Fill the window"
20
+ >
21
+ <span class="wb-window-max">${MAXIMIZE}</span><span class="wb-window-restore">${RESTORE}</span>
22
+ </button>
23
+ </div>`;
24
+ return html`<div class="wb-window${wide && raw(" wb-wide")}${className && raw(" " + className)}">
24
25
  ${header}
25
- <div class="wb-window-body${bodyClass && raw(" " + bodyClass)}" ${height ? html` style="height: ${height}"` : ""}>
26
- ${raw(String(body))}
27
- </div>
26
+ <div class="wb-window-body" ${height ? html` style="height: ${height}"` : ""}>${raw(String(body))}</div>
28
27
  </div>`;
29
28
  }
30
29
  export { windowFrame };
@@ -1,5 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  // src/running.ts
3
+ /**
4
+ * How long a server may take to say it is there: a loaded machine (many agents, builds) can take
5
+ * seconds, and a server taken for gone is one a command starts again or does without.
6
+ */
7
+ const HEALTH_TIMEOUT = 5e3;
3
8
  /** The port the last server of this project recorded, or null. */
4
9
  function recordedPort(project) {
5
10
  try {
@@ -14,11 +19,41 @@ async function runningServer(project, { except } = {}) {
14
19
  if (!port) return null;
15
20
  const base = `http://localhost:${port}`;
16
21
  try {
17
- const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(800) });
22
+ const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT) });
18
23
  const health = res.ok ? await res.json() : null;
19
24
  return health?.dir === project.dir && health.pid !== except ? base : null;
20
25
  } catch {
21
26
  return null;
22
27
  }
23
28
  }
24
- export { recordedPort, runningServer };
29
+ /** The port the shared server recorded in the machine folder, or null. */
30
+ function recordedSharedPort(file) {
31
+ try {
32
+ return Number(JSON.parse(fs.readFileSync(file, "utf8")).port) || null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ /**
38
+ * The machine's running shared server, or null: the port in its record, checked by asking it.
39
+ * `rescan`: have it look for projects first (one just made, say). `except`: a process not to count.
40
+ */
41
+ async function sharedServer(file, { rescan = false, except } = {}) {
42
+ const port = recordedSharedPort(file);
43
+ if (!port) return null;
44
+ const origin = `http://localhost:${port}`;
45
+ try {
46
+ const res = await fetch(`${origin}/api/health${rescan ? "?rescan" : ""}`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT) });
47
+ const health = res.ok ? await res.json() : null;
48
+ if (!health?.hub || health.pid === except) return null;
49
+ return {
50
+ origin,
51
+ pid: health.pid,
52
+ version: String(health.version ?? "0.0.0"),
53
+ projects: health.projects ?? []
54
+ };
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ export { recordedPort, recordedSharedPort, runningServer, sharedServer };
package/dist/src/serve.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { DEFAULT_PORT } from "./config.js";
2
2
  import { createServer } from "./server.js";
3
- import { recordedPort, runningServer } from "./running.js";
3
+ import { recordedPort, recordedSharedPort, runningServer, sharedServer } from "./running.js";
4
+ import { machineConfigFile, machineDir, machineServerFile, readMachineConfig, stateDir } from "./entries.js";
5
+ import { createHub } from "./hub.js";
6
+ import { VERSION, compareVersions } from "./package.js";
4
7
  import fs from "node:fs";
5
8
  import path from "node:path";
6
9
  import http from "node:http";
@@ -68,4 +71,110 @@ async function start(project) {
68
71
  }
69
72
  throw new Error(`no free port from ${DEFAULT_PORT} to ${DEFAULT_PORT + 50}`);
70
73
  }
71
- export { start };
74
+ /** Run the shared server. Exits (0) when one as new or newer runs already. */
75
+ async function startShared(dir = machineDir(), state = stateDir()) {
76
+ const file = machineServerFile(state);
77
+ const other = await sharedServer(file, { except: process.pid });
78
+ if (other) {
79
+ if (compareVersions(VERSION, other.version) <= 0) {
80
+ console.log(`whiteboard: the shared server ${other.version} runs at ${other.origin}`);
81
+ process.exit(0);
82
+ }
83
+ await takeOver(other);
84
+ }
85
+ const config = readMachineConfig(dir);
86
+ if (!config) throw new Error(`no machine config: ${machineConfigFile(dir)}`);
87
+ fs.mkdirSync(state, { recursive: true });
88
+ const hub = createHub({
89
+ dir,
90
+ state,
91
+ onShutdown: () => process.exit(0)
92
+ });
93
+ const server = http.createServer((req, res) => {
94
+ hub.handle(req, res);
95
+ });
96
+ const first = config.port ?? DEFAULT_PORT;
97
+ const candidates = [...new Set([
98
+ other ? Number(new URL(other.origin).port) : null,
99
+ recordedSharedPort(file),
100
+ first,
101
+ ...Array.from({ length: 50 }, (_, i) => first + 1 + i)
102
+ ].filter((p) => !!p))];
103
+ for (const port of candidates) {
104
+ if (!await listenOn(server, port)) continue;
105
+ fs.writeFileSync(file, JSON.stringify({
106
+ port,
107
+ pid: process.pid,
108
+ version: VERSION
109
+ }, null, 2) + "\n");
110
+ try {
111
+ fs.unlinkSync(path.join(state, "server.lock"));
112
+ } catch {}
113
+ process.on("exit", () => {
114
+ try {
115
+ if (JSON.parse(fs.readFileSync(file, "utf8")).pid === process.pid) fs.unlinkSync(file);
116
+ } catch {}
117
+ });
118
+ const yieldToOther = async () => {
119
+ if (await sharedServer(file, { except: process.pid })) {
120
+ console.log("whiteboard: another shared server took over");
121
+ process.exit(0);
122
+ }
123
+ };
124
+ setTimeout(yieldToOther, 1500).unref();
125
+ setInterval(yieldToOther, 3e4).unref();
126
+ for (const signal of [
127
+ "SIGINT",
128
+ "SIGTERM",
129
+ "SIGHUP"
130
+ ]) process.on(signal, () => process.exit(0));
131
+ console.log(`whiteboard ${VERSION}: the shared server at http://localhost:${port}`);
132
+ for (const p of hub.projects()) console.log(` http://localhost:${port}${p.base}/ ${p.dir}`);
133
+ return port;
134
+ }
135
+ throw new Error(`no free port from ${first} to ${first + 50}`);
136
+ }
137
+ /** Ask an older shared server to make way, and wait until it has (else end its process). */
138
+ async function takeOver(other) {
139
+ console.log(`whiteboard ${VERSION}: taking over from the shared server ${other.version} at ${other.origin}`);
140
+ try {
141
+ await fetch(`${other.origin}/api/shutdown`, {
142
+ method: "POST",
143
+ headers: { "content-type": "application/json" },
144
+ body: JSON.stringify({ version: VERSION }),
145
+ signal: AbortSignal.timeout(2e3)
146
+ });
147
+ } catch {}
148
+ const gone = async () => {
149
+ try {
150
+ await fetch(`${other.origin}/api/health`, { signal: AbortSignal.timeout(300) });
151
+ return false;
152
+ } catch {
153
+ return true;
154
+ }
155
+ };
156
+ for (let i = 0; i < 25; i++) {
157
+ if (await gone()) return;
158
+ await new Promise((r) => setTimeout(r, 200));
159
+ }
160
+ try {
161
+ process.kill(other.pid, "SIGTERM");
162
+ } catch {}
163
+ for (let i = 0; i < 25 && !await gone(); i++) await new Promise((r) => setTimeout(r, 200));
164
+ }
165
+ function listenOn(server, port) {
166
+ return new Promise((resolve, reject) => {
167
+ const onError = (err) => {
168
+ server.off("listening", onListening);
169
+ err.code === "EADDRINUSE" ? resolve(false) : reject(err);
170
+ };
171
+ const onListening = () => {
172
+ server.off("error", onError);
173
+ resolve(true);
174
+ };
175
+ server.once("error", onError);
176
+ server.once("listening", onListening);
177
+ server.listen(port, "127.0.0.1");
178
+ });
179
+ }
180
+ export { start, startShared };