@bigmistqke/whiteboard 0.0.0-stage → 0.2.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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +628 -2
  3. package/bin/whiteboard.ts +488 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +542 -0
  6. package/dist/client/runtime.js +544 -0
  7. package/dist/define.js +7 -0
  8. package/dist/plugins/callout/README.md +13 -0
  9. package/dist/plugins/callout/index.js +27 -0
  10. package/dist/plugins/callout/style.css +12 -0
  11. package/dist/plugins/chat/README.md +46 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +47 -0
  14. package/dist/plugins/chat/style.css +24 -0
  15. package/dist/plugins/claude-code/index.js +120 -0
  16. package/dist/plugins/code/README.md +42 -0
  17. package/dist/plugins/code/diff.js +65 -0
  18. package/dist/plugins/code/index.js +77 -0
  19. package/dist/plugins/code/style.css +29 -0
  20. package/dist/plugins/comments/client.js +10 -0
  21. package/dist/plugins/comments/index.js +54 -0
  22. package/dist/plugins/comments/style.css +40 -0
  23. package/dist/plugins/details/README.md +17 -0
  24. package/dist/plugins/details/index.js +17 -0
  25. package/dist/plugins/details/style.css +3 -0
  26. package/dist/plugins/forge/README.md +12 -0
  27. package/dist/plugins/forge/index.js +83 -0
  28. package/dist/plugins/form/README.md +111 -0
  29. package/dist/plugins/form/index.js +102 -0
  30. package/dist/plugins/form/style.css +41 -0
  31. package/dist/plugins/gallery/README.md +30 -0
  32. package/dist/plugins/gallery/client.js +1 -0
  33. package/dist/plugins/gallery/index.js +74 -0
  34. package/dist/plugins/gallery/style.css +27 -0
  35. package/dist/plugins/grid/README.md +33 -0
  36. package/dist/plugins/grid/index.js +33 -0
  37. package/dist/plugins/grid/style.css +25 -0
  38. package/dist/plugins/iframe/README.md +18 -0
  39. package/dist/plugins/iframe/client.js +1 -0
  40. package/dist/plugins/iframe/index.js +40 -0
  41. package/dist/plugins/iframe/style.css +29 -0
  42. package/dist/plugins/index.js +30 -0
  43. package/dist/plugins/mermaid/README.md +21 -0
  44. package/dist/plugins/mermaid/index.js +35 -0
  45. package/dist/plugins/mermaid/style.css +16 -0
  46. package/dist/plugins/quiet/README.md +26 -0
  47. package/dist/plugins/quiet/index.js +17 -0
  48. package/dist/plugins/terminal/client.js +41 -0
  49. package/dist/plugins/terminal/host.js +332 -0
  50. package/dist/plugins/terminal/index.js +171 -0
  51. package/dist/plugins/terminal/modes.js +32 -0
  52. package/dist/plugins/terminal/server.js +256 -0
  53. package/dist/plugins/terminal/sizes.js +57 -0
  54. package/dist/plugins/terminal/style.css +357 -0
  55. package/dist/solid/index.js +36 -0
  56. package/dist/src/auth.js +54 -0
  57. package/dist/src/client/page/base.css +295 -0
  58. package/dist/src/client/page/main.js +1228 -0
  59. package/dist/src/config.js +76 -0
  60. package/dist/src/events.js +183 -0
  61. package/dist/src/html.js +34 -0
  62. package/dist/src/icons.js +6 -0
  63. package/dist/src/load.js +77 -0
  64. package/dist/src/loader.js +126 -0
  65. package/dist/src/package.js +33 -0
  66. package/dist/src/pages/blocks.js +50 -0
  67. package/dist/src/pages/index.js +15 -0
  68. package/dist/src/pages/markdown.js +410 -0
  69. package/dist/src/pages/render.js +311 -0
  70. package/dist/src/plugins.js +238 -0
  71. package/dist/src/running.js +24 -0
  72. package/dist/src/serve.js +71 -0
  73. package/dist/src/server.js +725 -0
  74. package/dist/src/status.js +71 -0
  75. package/package.json +131 -4
  76. package/plugins/callout/README.md +13 -0
  77. package/plugins/callout/index.ts +25 -0
  78. package/plugins/callout/style.css +12 -0
  79. package/plugins/chat/README.md +46 -0
  80. package/plugins/chat/autosize.ts +101 -0
  81. package/plugins/chat/client.tsx +93 -0
  82. package/plugins/chat/index.ts +61 -0
  83. package/plugins/chat/style.css +24 -0
  84. package/plugins/claude-code/index.ts +136 -0
  85. package/plugins/code/README.md +42 -0
  86. package/plugins/code/diff.ts +64 -0
  87. package/plugins/code/index.ts +94 -0
  88. package/plugins/code/style.css +29 -0
  89. package/plugins/comments/client.ts +492 -0
  90. package/plugins/comments/index.ts +54 -0
  91. package/plugins/comments/style.css +40 -0
  92. package/plugins/details/README.md +17 -0
  93. package/plugins/details/index.ts +21 -0
  94. package/plugins/details/style.css +3 -0
  95. package/plugins/forge/README.md +12 -0
  96. package/plugins/forge/index.ts +71 -0
  97. package/plugins/form/README.md +111 -0
  98. package/plugins/form/index.ts +104 -0
  99. package/plugins/form/style.css +41 -0
  100. package/plugins/gallery/README.md +30 -0
  101. package/plugins/gallery/client.tsx +64 -0
  102. package/plugins/gallery/index.ts +67 -0
  103. package/plugins/gallery/style.css +27 -0
  104. package/plugins/grid/README.md +33 -0
  105. package/plugins/grid/index.ts +36 -0
  106. package/plugins/grid/style.css +25 -0
  107. package/plugins/iframe/README.md +18 -0
  108. package/plugins/iframe/client.ts +46 -0
  109. package/plugins/iframe/index.ts +54 -0
  110. package/plugins/iframe/style.css +29 -0
  111. package/plugins/index.ts +21 -0
  112. package/plugins/mermaid/README.md +21 -0
  113. package/plugins/mermaid/index.ts +40 -0
  114. package/plugins/mermaid/style.css +16 -0
  115. package/plugins/quiet/README.md +26 -0
  116. package/plugins/quiet/index.ts +27 -0
  117. package/plugins/terminal/client.ts +317 -0
  118. package/plugins/terminal/host.ts +326 -0
  119. package/plugins/terminal/index.ts +138 -0
  120. package/plugins/terminal/modes.ts +30 -0
  121. package/plugins/terminal/server.ts +215 -0
  122. package/plugins/terminal/sizes.ts +60 -0
  123. package/plugins/terminal/style.css +71 -0
  124. package/skills/whiteboard/SKILL.md +302 -0
  125. package/solid/index.tsx +59 -0
  126. package/src/auth.ts +66 -0
  127. package/src/client/forms.ts +185 -0
  128. package/src/client/markdown.ts +36 -0
  129. package/src/client/page/base.css +295 -0
  130. package/src/client/page/elsewhere.ts +70 -0
  131. package/src/client/page/fresh.ts +205 -0
  132. package/src/client/page/live.ts +30 -0
  133. package/src/client/page/main.ts +272 -0
  134. package/src/client/page/orphans.ts +46 -0
  135. package/src/client/page/sort.ts +38 -0
  136. package/src/client/page/theme.ts +32 -0
  137. package/src/client/page/view.ts +9 -0
  138. package/src/client/page/waiting.ts +182 -0
  139. package/src/client/read.ts +73 -0
  140. package/src/client/runtime.ts +183 -0
  141. package/src/client/toast.ts +25 -0
  142. package/src/config.ts +96 -0
  143. package/src/define.ts +612 -0
  144. package/src/events.ts +218 -0
  145. package/src/html.ts +40 -0
  146. package/src/icons.ts +8 -0
  147. package/src/load.ts +89 -0
  148. package/src/loader.ts +112 -0
  149. package/src/package.ts +39 -0
  150. package/src/pages/blocks.ts +70 -0
  151. package/src/pages/index.ts +42 -0
  152. package/src/pages/markdown.ts +364 -0
  153. package/src/pages/render.ts +233 -0
  154. package/src/plugins.ts +197 -0
  155. package/src/running.ts +22 -0
  156. package/src/serve.ts +52 -0
  157. package/src/server.ts +667 -0
  158. package/src/status.ts +113 -0
@@ -0,0 +1,311 @@
1
+ import { renderMarkdown } from "./markdown.js";
2
+ import { html, raw } from "../html.js";
3
+ import { awaitingLabel } from "../icons.js";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ // src/pages/render.ts
9
+ const BASE_CSS = new URL("../client/page/base.css", import.meta.url);
10
+ const THEME_SCRIPT = raw(`<script>try{const t=localStorage.getItem('wb-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t}catch{}<\/script>`);
11
+ const CODE_LANG = {
12
+ js: "javascript",
13
+ mjs: "javascript",
14
+ cjs: "javascript",
15
+ ts: "typescript",
16
+ tsx: "tsx",
17
+ jsx: "jsx",
18
+ json: "json",
19
+ css: "css",
20
+ html: "html",
21
+ sh: "bash",
22
+ zsh: "bash",
23
+ py: "python",
24
+ rs: "rust",
25
+ go: "go",
26
+ toml: "toml",
27
+ yml: "yaml",
28
+ yaml: "yaml"
29
+ };
30
+ /** Frontmatter is the core's; the page starts after it. */
31
+ const body = (source) => source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "");
32
+ /** A page's title: its first heading, else its name. */
33
+ function titleOf(file, fallback) {
34
+ try {
35
+ const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, "utf8")));
36
+ return h1 ? h1[1].replace(/[*_`]/g, "") : fallback;
37
+ } catch {
38
+ return fallback;
39
+ }
40
+ }
41
+ function crumbs(id, name) {
42
+ const parts = id ? id.split("/") : [];
43
+ return html`<a href="/">${name}</a>${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join("/")}">${p}</a>`)}`;
44
+ }
45
+ const time = (ts) => html`<time data-ts="${ts}"></time>`;
46
+ function pageList(pages) {
47
+ return html`<ul class="wb-index">${pages.map((p) => html`<li><a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${p.awaiting > 0 && html` <a class="wb-awaiting" href="/${p.id}#wb-waiting" title="${awaitingLabel(p.awaiting)}" aria-label="${awaitingLabel(p.awaiting)}">${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>`} <span class="wb-meta"><code>${p.id}</code> · edited ${time(p.mtime)}${p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}</span></li>`)}</ul>`;
48
+ }
49
+ /** The folder's README, when it has one. */
50
+ function readmeOf(page) {
51
+ const name = [
52
+ "README.md",
53
+ "readme.md",
54
+ "Readme.md"
55
+ ].find((n) => page.entries.some((e) => !e.dir && e.name === n));
56
+ if (!name) return null;
57
+ const file = path.join(page.file, name);
58
+ return {
59
+ file,
60
+ source: fs.readFileSync(file, "utf8")
61
+ };
62
+ }
63
+ /** A stylesheet reference (URL, file: URL string, or absolute path) → absolute path. */
64
+ function stylePath(ref) {
65
+ if (ref == null) return null;
66
+ const file = ref instanceof URL || String(ref).startsWith("file:") ? fileURLToPath(ref) : String(ref);
67
+ if (!path.isAbsolute(file)) throw new Error(`style: use a URL, e.g. new URL('./style.css', import.meta.url)`);
68
+ if (!fs.existsSync(file)) throw new Error(`style: file not found: ${file}`);
69
+ return file;
70
+ }
71
+ const SKIP = /* @__PURE__ */ new Set([
72
+ "node_modules",
73
+ ".git",
74
+ ".whiteboard",
75
+ "dist",
76
+ "build"
77
+ ]);
78
+ const MARKDOWN = /\.(md|markdown)$/i;
79
+ /**
80
+ * Every markdown file in the project, which renders as a page: the top folder's first,
81
+ * then by path. In a git repository, the files git knows (tracked, or new and not ignored), so
82
+ * built copies and dependencies stay out; elsewhere a walk that skips the usual build and
83
+ * dependency folders. The project's own pages (.whiteboard/) are listed apart.
84
+ */
85
+ function documentsIn(dir) {
86
+ let files;
87
+ try {
88
+ files = execFileSync("git", [
89
+ "ls-files",
90
+ "--cached",
91
+ "--others",
92
+ "--exclude-standard",
93
+ "--",
94
+ ":(icase)*.md",
95
+ ":(icase)*.markdown"
96
+ ], {
97
+ cwd: dir,
98
+ encoding: "utf8",
99
+ stdio: [
100
+ "ignore",
101
+ "pipe",
102
+ "ignore"
103
+ ]
104
+ }).split("\n").filter((f) => f && !f.startsWith(".whiteboard/") && fs.existsSync(path.join(dir, f)));
105
+ } catch {
106
+ files = [];
107
+ const walk = (rel) => {
108
+ let entries = [];
109
+ try {
110
+ entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true });
111
+ } catch {
112
+ return;
113
+ }
114
+ for (const e of entries) if (e.isDirectory()) {
115
+ if (!SKIP.has(e.name) && !e.name.startsWith(".")) walk(path.posix.join(rel, e.name));
116
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name));
117
+ };
118
+ walk("");
119
+ }
120
+ const depth = (f) => f.split("/").length;
121
+ return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b));
122
+ }
123
+ /**
124
+ * The overview's list of the project's documents: each by its title, linked to its rendered page,
125
+ * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
126
+ * written here), by when last updated, or by title; each row carries what it is sorted by.
127
+ */
128
+ function documentList(ctx) {
129
+ const files = documentsIn(ctx.project.dir);
130
+ if (!files.length) return "";
131
+ const rows = files.map((f, i) => {
132
+ const abs = path.join(ctx.project.dir, f);
133
+ const name = path.posix.basename(f);
134
+ const title = titleOf(abs, name);
135
+ const where = title === name ? path.posix.dirname(f) : f;
136
+ let mtime = 0;
137
+ try {
138
+ mtime = fs.statSync(abs).mtimeMs;
139
+ } catch {}
140
+ return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}"><a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a> <span class="wb-meta">${where !== "." && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span></li>`;
141
+ });
142
+ return html`<section class="wb-documents"><div class="wb-list-head"><h2>Documents</h2><label class="wb-sort">sort <select data-wb-sort="documents" aria-label="Sort the documents"><option value="order">by folder</option><option value="updated">last updated</option><option value="title">by title</option></select></label></div><ul class="wb-index">${rows}</ul></section>`;
143
+ }
144
+ /** The plugins' text links for a project folder, asked once per folder. */
145
+ function textLinksOf(links) {
146
+ const linksFor = /* @__PURE__ */ new Map();
147
+ return (dir) => {
148
+ let got = linksFor.get(dir);
149
+ if (!got) {
150
+ got = links.flatMap((fn) => {
151
+ try {
152
+ return fn({ dir });
153
+ } catch (err) {
154
+ console.error("links:", err);
155
+ return [];
156
+ }
157
+ });
158
+ linksFor.set(dir, got);
159
+ }
160
+ return got;
161
+ };
162
+ }
163
+ /**
164
+ * A message (a comment, a chat message) as HTML: markdown as on a page, but its raw HTML as text and
165
+ * its directives as written. Code fences go to the code block, so `styles` are what it needs linked.
166
+ */
167
+ function createMessageRender(blocks, links = []) {
168
+ const textLinks = textLinksOf(links);
169
+ return async (text, ctx) => {
170
+ const out = await renderMarkdown(String(text ?? ""), {
171
+ page: "",
172
+ file: "",
173
+ resolve: () => null,
174
+ code: blocks().code,
175
+ textLinks: textLinks(ctx.project.dir),
176
+ message: true
177
+ });
178
+ return {
179
+ html: out.html,
180
+ styles: out.styles.map((s) => ctx.asset(s))
181
+ };
182
+ };
183
+ }
184
+ function createRender(blocks, style, pluginStyles = [], links = []) {
185
+ const textLinks = textLinksOf(links);
186
+ const STYLE = stylePath(style);
187
+ const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f) => !!f);
188
+ async function markdown(source, page, file, ctx) {
189
+ const { blocks: set, code } = blocks();
190
+ return renderMarkdown(body(source), {
191
+ page,
192
+ file,
193
+ resolve: (name) => set.get(name) ?? null,
194
+ code,
195
+ linkFor: ctx.urlFor,
196
+ textLinks: textLinks(ctx.project.dir)
197
+ });
198
+ }
199
+ async function content(page, ctx) {
200
+ const { project } = ctx;
201
+ switch (page.kind) {
202
+ case "page": return markdown(page.source, page.id, page.file, ctx);
203
+ case "pages": {
204
+ const list = page.pages.length ? pageList(page.pages) : html`<p class="wb-meta">No pages yet.</p>`;
205
+ return {
206
+ html: page.id ? html`<h1>${page.id}</h1>${list}<p class="wb-meta">${page.file}</p>` : html`<h1>${project.name}</h1>${list}${project.files && documentList(ctx)}<p class="wb-meta"><code>${project.dir}</code>${project.files && html` · <a href="/-/">files</a>`} · <a href="/_/docs">how to write pages</a></p>`,
207
+ title: page.id || project.name,
208
+ islands: {},
209
+ styles: []
210
+ };
211
+ }
212
+ case "folder": {
213
+ const rel = page.id.slice(2);
214
+ const rows = page.entries.map((e) => html`<li><a href="${encodeURIComponent(e.name) + (e.dir ? "/" : "")}">${e.name + (e.dir ? "/" : "")}</a></li>`);
215
+ const listing = html`<h1>${rel || project.name}</h1><ul class="wb-files">${rel && html`<li><a href="../">../</a></li>`}${rows}</ul><p class="wb-meta">${page.file} · <code>${page.id}</code></p>`;
216
+ const readme = readmeOf(page);
217
+ if (!readme) return {
218
+ html: listing,
219
+ title: rel || project.name,
220
+ islands: {},
221
+ styles: []
222
+ };
223
+ const r = await markdown(readme.source, page.id, readme.file, ctx);
224
+ return {
225
+ ...r,
226
+ html: html`${raw(r.html)}<hr>${listing}`
227
+ };
228
+ }
229
+ case "file": {
230
+ const { code } = blocks();
231
+ const ext = path.extname(page.file).slice(1).toLowerCase();
232
+ const tree = {
233
+ type: "root",
234
+ children: [{
235
+ type: "code",
236
+ lang: CODE_LANG[ext] ?? (ext || null),
237
+ meta: null,
238
+ value: page.source
239
+ }]
240
+ };
241
+ const out = await renderMarkdown(tree, {
242
+ page: page.id,
243
+ file: page.file,
244
+ resolve: () => null,
245
+ code,
246
+ linkFor: ctx.urlFor
247
+ });
248
+ return {
249
+ html: html`<h1 class="wb-code-title wb-wide">${page.id.slice(2)}</h1><div class="wb-code wb-wide">${raw(out.html)}</div>`,
250
+ title: path.basename(page.file),
251
+ islands: out.islands,
252
+ styles: out.styles
253
+ };
254
+ }
255
+ }
256
+ }
257
+ return async function render(page, ctx) {
258
+ let out;
259
+ try {
260
+ out = await content(page, ctx);
261
+ } catch (err) {
262
+ out = {
263
+ html: html`<pre class="wb-error">${err.message}</pre>`,
264
+ islands: {},
265
+ styles: []
266
+ };
267
+ }
268
+ const islands = Object.fromEntries(Object.entries(out.islands).map(([id, island]) => [id, {
269
+ ...island,
270
+ client: ctx.asset(island.client)
271
+ }]));
272
+ const styles = out.styles.map((s) => ctx.asset(s));
273
+ const nav = html`<nav class="wb-nav"><span>${crumbs(page.id, ctx.project.name)}</span>${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button type="button" class="wb-theme" title="Theme: follow the system, light or dark" aria-label="Theme"></button><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span></nav>`;
274
+ const links = [
275
+ ctx.asset(BASE_CSS),
276
+ ...PLUGIN_STYLES.map((f) => ctx.asset(f)),
277
+ ...styles,
278
+ ...STYLE ? [ctx.asset(STYLE)] : []
279
+ ];
280
+ return {
281
+ title: out.title || page.id || ctx.project.name,
282
+ head: html`${THEME_SCRIPT}
283
+ ${links.map((href) => html`<link rel="stylesheet" href="${href}">`)}`,
284
+ html: html`${nav}<main id="wb-main">${raw(out.html)}</main>`,
285
+ data: {
286
+ islands,
287
+ styles,
288
+ mtime: page.mtime
289
+ }
290
+ };
291
+ };
292
+ }
293
+ /**
294
+ * What `whiteboard docs` prints first: how pages are written, and which blocks the project's plugins
295
+ * bring. Each plugin's own docs, printed after it, say how to write its blocks.
296
+ */
297
+ function createDocs(blocks) {
298
+ return function docs(_ctx) {
299
+ const byPlugin = /* @__PURE__ */ new Map();
300
+ for (const t of blocks().blocks.values()) byPlugin.set(t.source, [...byPlugin.get(t.source) ?? [], t.code ? `${t.name} (every other code fence)` : t.name]);
301
+ return `# Pages
302
+
303
+ A page is markdown: GFM tables, \`<details>\`, raw HTML and a hand-written \`<form name="…">\` work as they are. Plugins add blocks to it: \`:::name\` around content, \`::name\` on a line, \`:name\` inside a line, and code fences (\`\`\`\` \`\`\`name \`\`\`\`). A block nobody brings renders its content, so a typo never breaks a page.
304
+
305
+ The blocks here, by the plugin that brings them (each plugin's section below says how to write them):
306
+
307
+ ${[...byPlugin].sort(([a], [b]) => a.localeCompare(b)).map(([plugin, blocks]) => `- **${plugin}**: ${blocks.map((b) => `\`${b}\``).join(", ")}`).join("\n")}
308
+ `;
309
+ };
310
+ }
311
+ export { createDocs, createMessageRender, createRender, titleOf };
@@ -0,0 +1,238 @@
1
+ import { parseArgs } from "node:util";
2
+ // src/plugins.ts
3
+ const TYPES = {
4
+ string: (v) => typeof v === "string",
5
+ number: (v) => typeof v === "number" && Number.isFinite(v),
6
+ boolean: (v) => typeof v === "boolean",
7
+ "string[]": (v) => Array.isArray(v) && v.every((x) => typeof x === "string")
8
+ };
9
+ function parseType(spec, where) {
10
+ const optional = spec.endsWith("?");
11
+ const type = optional ? spec.slice(0, -1) : spec;
12
+ if (!(type in TYPES)) throw new Error(`${where}: unknown type "${spec}" (one of ${Object.keys(TYPES).join(", ")}, with ? when optional)`);
13
+ return {
14
+ type,
15
+ optional
16
+ };
17
+ }
18
+ /** What is wrong with `value` against `spec` ({ name: 'string?' }), or null. Unknown fields are wrong too. */
19
+ function checkFields(spec = {}, input = {}, where) {
20
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return `${where} must be an object`;
21
+ const value = input;
22
+ for (const [name, s] of Object.entries(spec)) {
23
+ const { type, optional } = parseType(s, where);
24
+ if (value[name] === void 0) {
25
+ if (!optional) return `${where}: ${name} is missing`;
26
+ continue;
27
+ }
28
+ if (!TYPES[type](value[name])) return `${where}: ${name} must be ${type}`;
29
+ }
30
+ for (const name of Object.keys(value)) if (!(name in spec)) return `${where}: unknown field ${name}`;
31
+ return null;
32
+ }
33
+ /** Query strings are text: a number or boolean in the spec is read from it. */
34
+ function fromQuery(spec = {}, params) {
35
+ const out = {};
36
+ for (const [name, value] of params) {
37
+ const field = spec[name];
38
+ const type = field ? parseType(field, "query").type : "string";
39
+ out[name] = type === "number" ? Number(value) : type === "boolean" ? value === "true" || value === "" : value;
40
+ }
41
+ return out;
42
+ }
43
+ const ROUTE = /^(GET|POST|PUT|PATCH|DELETE) (\/[\w\-/]*)$/;
44
+ /** A plugin's routes, checked and mounted under /api/<name>/. Throws on a malformed one. */
45
+ function mountRoutes(name, routes = {}) {
46
+ const table = [];
47
+ for (const [key, route] of Object.entries(routes)) {
48
+ const m = ROUTE.exec(key);
49
+ if (!m) throw new Error(`plugin ${name}: route "${key}" must look like "GET /path"`);
50
+ if (typeof route?.run !== "function") throw new Error(`plugin ${name}: route "${key}" has no run function`);
51
+ for (const [field, spec] of Object.entries({
52
+ ...route.body,
53
+ ...route.query
54
+ })) parseType(spec, `plugin ${name}, route "${key}", ${field}`);
55
+ const [, method, at] = m;
56
+ const path = `/api/${name}${at === "/" ? "" : at.replace(/\/$/, "")}`;
57
+ if (table.some((r) => r.method === method && r.path === path)) throw new Error(`plugin ${name}: route "${key}" is declared twice`);
58
+ table.push({
59
+ method,
60
+ path,
61
+ route,
62
+ plugin: name
63
+ });
64
+ }
65
+ return table;
66
+ }
67
+ function readJson(req) {
68
+ return new Promise((resolve, reject) => {
69
+ let body = "";
70
+ req.on("data", (c) => {
71
+ body += c;
72
+ if (body.length > 1e6) {
73
+ reject(/* @__PURE__ */ new Error("body too large"));
74
+ req.destroy();
75
+ }
76
+ });
77
+ req.on("end", () => {
78
+ try {
79
+ resolve(body ? JSON.parse(body) : {});
80
+ } catch {
81
+ reject(/* @__PURE__ */ new Error("the body is not JSON"));
82
+ }
83
+ });
84
+ req.on("error", reject);
85
+ });
86
+ }
87
+ const json = (res, status, data) => {
88
+ res.writeHead(status, {
89
+ "content-type": "application/json",
90
+ "cache-control": "no-store"
91
+ });
92
+ res.end(JSON.stringify(data));
93
+ };
94
+ /**
95
+ * Answer a request with the route it matches: false when none does. The core checks the token
96
+ * (`auth`), the query and the body before the route's code runs. A route returns what is sent as
97
+ * JSON; a stream route (`stream: true`) writes to `res` itself. An error it throws is sent with its
98
+ * `status` (default 500).
99
+ */
100
+ async function dispatch(table, req, res, url, authorized) {
101
+ const forPath = table.filter((r) => r.path === url.pathname);
102
+ if (!forPath.length) return false;
103
+ const hit = forPath.find((r) => r.method === req.method);
104
+ if (!hit) {
105
+ res.setHeader("allow", forPath.map((r) => r.method).join(", "));
106
+ json(res, 405, { error: `use ${forPath.map((r) => r.method).join(" or ")}` });
107
+ return true;
108
+ }
109
+ const { route } = hit;
110
+ if (route.auth && !authorized(req)) {
111
+ json(res, 403, { error: "this needs the project's token: open a link from the command line, or send x-whiteboard-token" });
112
+ return true;
113
+ }
114
+ try {
115
+ const query = fromQuery(route.query, url.searchParams);
116
+ const queryError = route.query ? checkFields(route.query, query, "query") : null;
117
+ if (queryError) {
118
+ json(res, 400, { error: queryError });
119
+ return true;
120
+ }
121
+ let body = {};
122
+ if (hit.method !== "GET" && hit.method !== "DELETE") {
123
+ const input = await readJson(req);
124
+ const bodyError = checkFields(route.body, input, "body");
125
+ if (bodyError) {
126
+ json(res, 400, { error: bodyError });
127
+ return true;
128
+ }
129
+ body = input;
130
+ }
131
+ if (route.stream) {
132
+ await route.run({
133
+ body,
134
+ query,
135
+ req,
136
+ res
137
+ });
138
+ return true;
139
+ }
140
+ const out = await route.run({
141
+ body,
142
+ query,
143
+ req
144
+ });
145
+ json(res, 200, out ?? { ok: true });
146
+ } catch (err) {
147
+ if (res.headersSent) {
148
+ res.end();
149
+ return true;
150
+ }
151
+ const e = err;
152
+ json(res, e?.status ?? 500, { error: e?.message ?? String(err) });
153
+ }
154
+ return true;
155
+ }
156
+ /** The routes for the docs: method, path, what it does, what it takes. */
157
+ const describeRoutes = (table) => table.map(({ method, path, route }) => ({
158
+ method,
159
+ path,
160
+ description: route.description ?? "",
161
+ auth: !!route.auth,
162
+ stream: !!route.stream,
163
+ body: route.body ?? null,
164
+ query: route.query ?? null
165
+ }));
166
+ /** The commands of a plugin as `whiteboard <name> [sub]`, checked. */
167
+ function pluginCommands(plugin) {
168
+ return Object.entries(plugin.commands ?? {}).map(([sub, command]) => {
169
+ const where = `plugin ${plugin.name}, command "${sub}"`;
170
+ if (sub && !/^[\w-]+$/.test(sub)) throw new Error(`${where}: use letters, digits, - and _`);
171
+ if (typeof command?.run !== "function") throw new Error(`${where} has no run function`);
172
+ for (const [name, o] of Object.entries(command.options ?? {})) parseType(o.type, `${where}, option ${name}`);
173
+ return {
174
+ plugin: plugin.name,
175
+ sub,
176
+ command,
177
+ name: [plugin.name, sub].filter(Boolean).join(" ")
178
+ };
179
+ });
180
+ }
181
+ /** `[page] [--restart] [-- <arguments>]` */
182
+ function usage(command) {
183
+ const options = Object.entries(command.options ?? {}).map(([name, o]) => {
184
+ const { type } = parseType(o.type, name);
185
+ return `[--${name}${type === "boolean" ? "" : ` <${o.value ?? type}>`}]`;
186
+ });
187
+ return [
188
+ command.args ?? "",
189
+ ...options,
190
+ command.rest ? `[-- ${command.rest}]` : ""
191
+ ].filter(Boolean).join(" ");
192
+ }
193
+ /**
194
+ * Parse a command's arguments by its declared options; throws with the usage on a wrong one. What
195
+ * follows `--` is passed on untouched, as `rest`, when the command takes it.
196
+ */
197
+ function parseCommandArgs(command, all, name) {
198
+ const cut = all.indexOf("--");
199
+ const args = cut < 0 ? all : all.slice(0, cut);
200
+ const rest = cut < 0 ? [] : all.slice(cut + 1);
201
+ if (rest.length && !command.rest) throw new Error(`whiteboard ${name} takes nothing after --\nusage: whiteboard ${name} ${usage(command)}`);
202
+ const options = Object.fromEntries(Object.entries(command.options ?? {}).map(([key, o]) => {
203
+ const { type } = parseType(o.type, key);
204
+ return [key, {
205
+ type: type === "boolean" ? "boolean" : "string",
206
+ ...o.short ? { short: o.short } : {}
207
+ }];
208
+ }));
209
+ let parsed;
210
+ try {
211
+ parsed = parseArgs({
212
+ args,
213
+ options,
214
+ allowPositionals: true,
215
+ strict: true
216
+ });
217
+ } catch (err) {
218
+ throw new Error(`${err.message}\nusage: whiteboard ${name} ${usage(command)}`);
219
+ }
220
+ const values = { ...parsed.values };
221
+ for (const [key, o] of Object.entries(command.options ?? {})) {
222
+ const { type, optional } = parseType(o.type, key);
223
+ if (values[key] === void 0) {
224
+ if (!optional && type !== "boolean") throw new Error(`--${key} is missing\nusage: whiteboard ${name} ${usage(command)}`);
225
+ continue;
226
+ }
227
+ if (type === "number") {
228
+ values[key] = Number(values[key]);
229
+ if (!Number.isFinite(values[key])) throw new Error(`--${key} must be a number`);
230
+ }
231
+ }
232
+ return {
233
+ options: values,
234
+ positionals: parsed.positionals,
235
+ rest
236
+ };
237
+ }
238
+ export { describeRoutes, dispatch, mountRoutes, parseCommandArgs, pluginCommands, usage };
@@ -0,0 +1,24 @@
1
+ import fs from "node:fs";
2
+ // src/running.ts
3
+ /** The port the last server of this project recorded, or null. */
4
+ function recordedPort(project) {
5
+ try {
6
+ return Number(JSON.parse(fs.readFileSync(project.serverFile, "utf8")).port) || null;
7
+ } catch {
8
+ return null;
9
+ }
10
+ }
11
+ /** The base URL of this project's running server, or null. `except`: a process to not count (the asking server itself). */
12
+ async function runningServer(project, { except } = {}) {
13
+ const port = recordedPort(project);
14
+ if (!port) return null;
15
+ const base = `http://localhost:${port}`;
16
+ try {
17
+ const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(800) });
18
+ const health = res.ok ? await res.json() : null;
19
+ return health?.dir === project.dir && health.pid !== except ? base : null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+ export { recordedPort, runningServer };
@@ -0,0 +1,71 @@
1
+ import { DEFAULT_PORT } from "./config.js";
2
+ import { createServer } from "./server.js";
3
+ import { recordedPort, runningServer } from "./running.js";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import http from "node:http";
7
+ // src/serve.ts
8
+ /** Listen on the previous port, else the default, else the next free one; then record it in server.json. */
9
+ async function start(project) {
10
+ const other = await runningServer(project, { except: process.pid });
11
+ if (other) {
12
+ console.log(`whiteboard: ${project.name} is already served at ${other}`);
13
+ process.exit(0);
14
+ }
15
+ fs.mkdirSync(project.pagesDir, { recursive: true });
16
+ const wb = createServer(project);
17
+ await wb.config();
18
+ const server = http.createServer((req, res) => {
19
+ wb.handle(req, res);
20
+ });
21
+ const candidates = [...new Set([
22
+ recordedPort(project),
23
+ DEFAULT_PORT,
24
+ ...Array.from({ length: 50 }, (_, i) => DEFAULT_PORT + 1 + i)
25
+ ].filter((p) => !!p))];
26
+ for (const port of candidates) {
27
+ if (!await new Promise((resolve, reject) => {
28
+ const onError = (err) => {
29
+ server.off("listening", onListening);
30
+ err.code === "EADDRINUSE" ? resolve(false) : reject(err);
31
+ };
32
+ const onListening = () => {
33
+ server.off("error", onError);
34
+ resolve(true);
35
+ };
36
+ server.once("error", onError);
37
+ server.once("listening", onListening);
38
+ server.listen(port, "127.0.0.1");
39
+ })) continue;
40
+ fs.writeFileSync(project.serverFile, JSON.stringify({
41
+ port,
42
+ pid: process.pid
43
+ }, null, 2) + "\n");
44
+ try {
45
+ fs.unlinkSync(path.join(project.wb, "server.lock"));
46
+ } catch {}
47
+ const cleanup = () => {
48
+ try {
49
+ if (JSON.parse(fs.readFileSync(project.serverFile, "utf8")).pid === process.pid) fs.unlinkSync(project.serverFile);
50
+ } catch {}
51
+ };
52
+ process.on("exit", cleanup);
53
+ const yieldToOther = async () => {
54
+ if (await runningServer(project, { except: process.pid })) {
55
+ console.log("whiteboard: another server of this project took over");
56
+ process.exit(0);
57
+ }
58
+ };
59
+ setTimeout(yieldToOther, 1500).unref();
60
+ setInterval(yieldToOther, 3e4).unref();
61
+ for (const signal of [
62
+ "SIGINT",
63
+ "SIGTERM",
64
+ "SIGHUP"
65
+ ]) process.on(signal, () => process.exit(0));
66
+ console.log(`whiteboard: ${project.name} (${project.dir}) at http://localhost:${port}`);
67
+ return port;
68
+ }
69
+ throw new Error(`no free port from ${DEFAULT_PORT} to ${DEFAULT_PORT + 50}`);
70
+ }
71
+ export { start };