@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,76 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ // src/config.ts
4
+ const CONFIG_NAMES = [
5
+ "config.ts",
6
+ "config.mts",
7
+ "config.js",
8
+ "config.mjs"
9
+ ];
10
+ /** the port a project's server tries first; it takes the next free one when that is taken */
11
+ const DEFAULT_PORT = Number(process.env.WHITEBOARD_PORT || 4777);
12
+ /** The config file in a `.whiteboard` folder, or null. */
13
+ function configFileIn(whiteboardDir) {
14
+ for (const name of CONFIG_NAMES) {
15
+ const f = path.join(whiteboardDir, name);
16
+ if (fs.existsSync(f)) return f;
17
+ }
18
+ return null;
19
+ }
20
+ const isDir = (p) => {
21
+ try {
22
+ return fs.statSync(p).isDirectory();
23
+ } catch {
24
+ return false;
25
+ }
26
+ };
27
+ /** The project folder a path is in: the nearest folder upward with a `.whiteboard/` folder. */
28
+ function findProjectDir(from = process.cwd()) {
29
+ let dir = path.resolve(from);
30
+ for (;;) {
31
+ if (isDir(path.join(dir, ".whiteboard"))) return dir;
32
+ const up = path.dirname(dir);
33
+ if (up === dir) return null;
34
+ dir = up;
35
+ }
36
+ }
37
+ /** Everything about the project in `dir`, or null when `dir` is not one. */
38
+ function project(dir) {
39
+ if (!dir) return null;
40
+ const wb = path.join(dir, ".whiteboard");
41
+ if (!isDir(wb)) return null;
42
+ return {
43
+ dir,
44
+ wb,
45
+ /** the config file, or null: looked up each time, since one can be added or removed while a server runs */
46
+ get configFile() {
47
+ return configFileIn(wb);
48
+ },
49
+ pagesDir: path.join(wb, "pages"),
50
+ eventsFile: path.join(wb, "events.ndjson"),
51
+ serverFile: path.join(wb, "server.json"),
52
+ logFile: path.join(wb, "server.log"),
53
+ /** shown in titles and the overview: `name` in the config if it is a plain literal, else the folder name */
54
+ get name() {
55
+ const file = configFileIn(wb);
56
+ return file && (/\bname\s*:\s*['"]([^'"]+)['"]/.exec(fs.readFileSync(file, "utf8")) ?? [])[1] || path.basename(dir);
57
+ }
58
+ };
59
+ }
60
+ const strip = (p) => p.replace(/\\/g, "/").replace(/\.md$/, "").replace(/^\/+|\/+$/g, "");
61
+ /**
62
+ * A file path or page name → the page id used in URLs and events.
63
+ * - a file inside the pages folder → "<path>" without .md
64
+ * - any other file inside the project folder → "-/<path>" (shown from the repository)
65
+ * - anything else → the name as given, without .md
66
+ */
67
+ function pageId(proj, input, cwd = process.cwd()) {
68
+ if (!input) return "";
69
+ const s = String(input);
70
+ if (!(path.isAbsolute(s) || s.startsWith(".") || /\.\w+$/.test(s)) || !proj) return strip(s);
71
+ const abs = path.resolve(cwd, s);
72
+ if (abs.startsWith(proj.pagesDir + path.sep)) return strip(path.relative(proj.pagesDir, abs));
73
+ if (abs === proj.dir || abs.startsWith(proj.dir + path.sep)) return `-/${path.relative(proj.dir, abs).replace(/\\/g, "/")}`.replace(/\/$/, "");
74
+ return strip(s);
75
+ }
76
+ export { CONFIG_NAMES, DEFAULT_PORT, configFileIn, findProjectDir, pageId, project };
@@ -0,0 +1,183 @@
1
+ import { fromReader } from "./status.js";
2
+ import fs from "node:fs";
3
+ import crypto from "node:crypto";
4
+ // src/events.ts
5
+ /**
6
+ * The type of the event `whiteboard new` appends when an agent session creates a page:
7
+ * `{ session }`. The colon keeps it apart from form names, which are event types too.
8
+ */
9
+ const CLAIM = "whiteboard:claim";
10
+ /**
11
+ * Append one event; `action` is the button that submitted a form, null for anything else. `from`
12
+ * is set only for events the command line writes ('cli'), so that waits skip them and pages can
13
+ * tell them apart; what the browser appends has none.
14
+ */
15
+ function appendEvent(file, input, from = null) {
16
+ const event = {
17
+ id: `${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`,
18
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
19
+ page: String(input.page ?? ""),
20
+ type: String(input.type ?? ""),
21
+ action: input.action ?? null,
22
+ data: input.data ?? {},
23
+ ...from ? { from } : {}
24
+ };
25
+ fs.appendFileSync(file, JSON.stringify(event) + "\n");
26
+ return event;
27
+ }
28
+ function parseLines(text) {
29
+ const out = [];
30
+ for (const line of text.split("\n")) {
31
+ if (!line.trim()) continue;
32
+ let event;
33
+ try {
34
+ event = JSON.parse(line);
35
+ } catch {
36
+ continue;
37
+ }
38
+ out.push(event);
39
+ }
40
+ return out;
41
+ }
42
+ function readEvents(file) {
43
+ return read(file).events;
44
+ }
45
+ /**
46
+ * The events in the log, and the byte offset they end at: after its last whole line. A line still
47
+ * being written is left out, and following from `end` gets it whole, so reading and then following
48
+ * from `end` never loses or splits an event.
49
+ */
50
+ function read(file) {
51
+ let buf;
52
+ try {
53
+ buf = fs.readFileSync(file);
54
+ } catch {
55
+ return {
56
+ events: [],
57
+ end: 0
58
+ };
59
+ }
60
+ const end = buf.lastIndexOf(10) + 1;
61
+ return {
62
+ events: parseLines(buf.subarray(0, end).toString("utf8")),
63
+ end
64
+ };
65
+ }
66
+ /**
67
+ * Call `onEvent` for each event appended to the log from byte `from` on (a line boundary, such as
68
+ * `read`'s `end`), in order, as whole lines arrive. Checks every `interval` ms (default 200).
69
+ * Returns a function that stops it.
70
+ */
71
+ function follow(file, from, onEvent, { interval = 200 } = {}) {
72
+ let offset = from;
73
+ let partial = "";
74
+ const poll = () => {
75
+ let size;
76
+ try {
77
+ size = fs.statSync(file).size;
78
+ } catch {
79
+ return;
80
+ }
81
+ if (size < offset) {
82
+ offset = 0;
83
+ partial = "";
84
+ }
85
+ if (size === offset) return;
86
+ const fd = fs.openSync(file, "r");
87
+ const buf = Buffer.alloc(size - offset);
88
+ fs.readSync(fd, buf, 0, buf.length, offset);
89
+ fs.closeSync(fd);
90
+ offset = size;
91
+ const text = partial + buf.toString("utf8");
92
+ const cut = text.lastIndexOf("\n");
93
+ partial = text.slice(cut + 1);
94
+ for (const e of parseLines(text.slice(0, cut + 1))) onEvent(e);
95
+ };
96
+ const timer = setInterval(poll, interval);
97
+ return () => clearInterval(timer);
98
+ }
99
+ /** `page` matches the page itself and every page below it, unless `exact`. */
100
+ function matches(event, { page, type, exact } = {}) {
101
+ if (page && event.page !== page && (exact || !event.page.startsWith(page + "/"))) return false;
102
+ if (type && event.type !== type) return false;
103
+ return true;
104
+ }
105
+ /** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
106
+ const PICKED = "whiteboard:picked";
107
+ /** The ids of the events that were picked up. Only the command line's picks count. */
108
+ function pickedUp(events) {
109
+ return new Set(events.filter((e) => e.type === "whiteboard:picked" && !fromReader(e)).map((e) => String(e.data?.event)));
110
+ }
111
+ /** Record that `event` was handed to an agent: from then on it counts as picked up. */
112
+ function pick(file, event) {
113
+ return appendEvent(file, {
114
+ page: event.page,
115
+ type: PICKED,
116
+ data: { event: event.id }
117
+ }, "cli");
118
+ }
119
+ /**
120
+ * Which event types reach an agent unasked: a form's answers (types without a colon) always, and of
121
+ * the plugins' events (`<plugin>:<what>`) those declared `handOut: true`, given in `handedOut`.
122
+ */
123
+ const forAgent = (handedOut = /* @__PURE__ */ new Set()) => (type) => !type.includes(":") || handedOut.has(type);
124
+ /**
125
+ * Hand the reader's events that match `filter` to `onEvent`, each marked as picked up once it is
126
+ * handed out. First the backlog: those nobody picked up yet, also from before this started,
127
+ * whatever filter picked up the others. Then, with `follow`, every new one as it comes, also when
128
+ * another running hand-out gets it too. The backlog and the following split the log at one line
129
+ * boundary, so no event falls between them. Events an agent wrote are never handed out, and of the
130
+ * plugins' events only those for an agent (`forAgent`), unless the filter asks for a type by name.
131
+ *
132
+ * Resolves with how many were handed out: once `count` is reached, after the backlog without
133
+ * `follow`, or when `signal` aborts.
134
+ */
135
+ function handOut(file, filter, onEvent, options = {}) {
136
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck } = options;
137
+ return new Promise((resolve) => {
138
+ let got = 0;
139
+ let stop = () => {};
140
+ const finish = () => {
141
+ stop();
142
+ signal?.removeEventListener("abort", finish);
143
+ resolve(got);
144
+ };
145
+ const wanted = (e) => fromReader(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type));
146
+ const hand = (e) => {
147
+ onEvent(e);
148
+ pick(file, e);
149
+ return ++got < count;
150
+ };
151
+ const left = /* @__PURE__ */ new Map();
152
+ const offer = (e) => {
153
+ if (skip?.(e)) {
154
+ left.set(e.id, e);
155
+ return true;
156
+ }
157
+ return hand(e);
158
+ };
159
+ if (count <= 0 || signal?.aborted) return finish();
160
+ const { events, end } = read(file);
161
+ const picked = pickedUp(events);
162
+ for (const e of events) if (wanted(e) && !picked.has(e.id) && !offer(e)) return finish();
163
+ if (!following) return finish();
164
+ signal?.addEventListener("abort", finish);
165
+ recheck?.(() => {
166
+ if (!left.size || got >= count) return;
167
+ const picked = pickedUp(read(file).events);
168
+ for (const [id, e] of left) {
169
+ if (picked.has(id)) {
170
+ left.delete(id);
171
+ continue;
172
+ }
173
+ if (skip?.(e)) continue;
174
+ left.delete(id);
175
+ if (!hand(e)) return finish();
176
+ }
177
+ });
178
+ stop = follow(file, end, (e) => {
179
+ if (got < count && wanted(e) && !offer(e)) finish();
180
+ }, { interval });
181
+ });
182
+ }
183
+ export { CLAIM, PICKED, appendEvent, follow, forAgent, fromReader, handOut, matches, parseLines, pick, pickedUp, read, readEvents };
@@ -0,0 +1,34 @@
1
+ // src/html.ts
2
+ /** A piece of HTML that is not escaped again. `String(piece)` is its markup. */
3
+ var Html = class {
4
+ value;
5
+ constructor(value) {
6
+ this.value = value;
7
+ }
8
+ toString() {
9
+ return this.value;
10
+ }
11
+ };
12
+ const ESCAPE = {
13
+ "&": "&amp;",
14
+ "<": "&lt;",
15
+ ">": "&gt;",
16
+ "\"": "&quot;",
17
+ "'": "&#39;"
18
+ };
19
+ /** Text → HTML that shows it as text. */
20
+ const escape = (value) => String(value).replace(/[&<>"']/g, (c) => ESCAPE[c]);
21
+ /** Markup to use as it is: only for HTML that is safe already, never for text from outside. */
22
+ const raw = (value) => new Html(String(value ?? ""));
23
+ function part(value) {
24
+ if (value == null || value === false) return "";
25
+ if (value instanceof Html) return value.value;
26
+ if (Array.isArray(value)) return value.map(part).join("");
27
+ return escape(value);
28
+ }
29
+ function html(strings, ...values) {
30
+ let out = strings[0];
31
+ for (let i = 0; i < values.length; i++) out += part(values[i]) + strings[i + 1];
32
+ return new Html(out);
33
+ }
34
+ export { Html, escape, html, raw };
@@ -0,0 +1,6 @@
1
+ // src/icons.ts
2
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
3
+ const INBOX_ICON = "<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>";
4
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
5
+ const awaitingLabel = (n, where = "") => `Awaiting you: ${n === 1 ? "1 question or message" : `${n} questions and messages`}${where}`;
6
+ export { INBOX_ICON, awaitingLabel };
@@ -0,0 +1,77 @@
1
+ import { FROM_SOURCE, PACKAGE_DIR } from "./package.js";
2
+ import { registerHooks } from "node:module";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ // src/load.ts
7
+ const ENGINE_DIR = PACKAGE_DIR;
8
+ const PACKAGE = "@bigmistqke/whiteboard";
9
+ /** The file `@bigmistqke/whiteboard` or one of its parts is, by the package's `exports`; null for none. */
10
+ function ownFile(specifier) {
11
+ if (specifier !== PACKAGE && !specifier.startsWith(PACKAGE + "/")) return null;
12
+ let exports;
13
+ try {
14
+ exports = JSON.parse(fs.readFileSync(path.join(ENGINE_DIR, "package.json"), "utf8")).exports;
15
+ } catch {
16
+ return null;
17
+ }
18
+ const target = exports?.[specifier === PACKAGE ? "." : `./${specifier.slice(23)}`];
19
+ const file = typeof target === "string" ? target : FROM_SOURCE && target?.source || target?.default;
20
+ return file ? path.join(ENGINE_DIR, file) : null;
21
+ }
22
+ const versionOf = (url) => new URL(url).searchParams.get("wb-v");
23
+ /**
24
+ * Install the hooks, once: the first time something loads a config or the package's own parts, not
25
+ * on import, so a command that loads nothing leaves the process's module loading alone.
26
+ */
27
+ let installed = false;
28
+ function installHooks() {
29
+ if (installed) return;
30
+ installed = true;
31
+ registerHooks({ resolve(specifier, context, next) {
32
+ const own = ownFile(specifier);
33
+ if (own) {
34
+ const url = pathToFileURL(own).href;
35
+ const v = context.parentURL && versionOf(context.parentURL);
36
+ return {
37
+ url: v ? `${url}?wb-v=${v}` : url,
38
+ shortCircuit: true,
39
+ format: moduleFormat(own) ?? "module"
40
+ };
41
+ }
42
+ const resolved = next(specifier, context);
43
+ if (!resolved.url.startsWith("file:") || resolved.url.includes("/node_modules/")) return resolved;
44
+ const v = versionOf(resolved.url) ?? (context.parentURL?.startsWith("file:") && versionOf(context.parentURL));
45
+ if (!v) return resolved;
46
+ const url = new URL(resolved.url);
47
+ url.searchParams.set("wb-v", v);
48
+ const inProject = url.pathname.split("/").includes(".whiteboard");
49
+ return {
50
+ ...resolved,
51
+ url: url.href,
52
+ format: inProject ? moduleFormat(url.pathname) : resolved.format ?? moduleFormat(url.pathname)
53
+ };
54
+ } });
55
+ }
56
+ function moduleFormat(file) {
57
+ if (/\.[mc]?ts$/.test(file)) return file.endsWith(".cts") ? "commonjs-typescript" : "module-typescript";
58
+ if (/\.c?js$/.test(file)) return file.endsWith(".cjs") ? "commonjs" : "module";
59
+ }
60
+ let version = 0;
61
+ /**
62
+ * Import one of the package's own parts (`plugins`) afresh, with everything it imports, the way
63
+ * `importFresh` does a config: for what the core loads itself on a config's behalf, such as the
64
+ * built-in plugins, which must reload along with the config.
65
+ */
66
+ function importOwn(part) {
67
+ installHooks();
68
+ const file = ownFile(`${PACKAGE}/${part}`);
69
+ if (!file) throw new Error(`the package has no part "${part}"`);
70
+ return import(`${pathToFileURL(file).href}?wb-v=${++version}`);
71
+ }
72
+ /** Import `file` and everything local it imports afresh. */
73
+ function importFresh(file) {
74
+ installHooks();
75
+ return import(`${pathToFileURL(file).href}?wb-v=${++version}`);
76
+ }
77
+ export { importFresh, importOwn, installHooks };
@@ -0,0 +1,126 @@
1
+ import { importFresh, importOwn } from "./load.js";
2
+ import { createPages } from "./pages/index.js";
3
+ import { pluginCommands } from "./plugins.js";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ // src/loader.ts
8
+ const NAME = /^[\w-]+$/;
9
+ /** The command line's own commands: a plugin can't be named like one, since its commands are `whiteboard <name>`. */
10
+ const BUILTIN_COMMANDS = /* @__PURE__ */ new Set([
11
+ "serve",
12
+ "init",
13
+ "root",
14
+ "new",
15
+ "show",
16
+ "url",
17
+ "docs",
18
+ "events",
19
+ "wait",
20
+ "watch",
21
+ "append",
22
+ "pick",
23
+ "status",
24
+ "skill",
25
+ "help"
26
+ ]);
27
+ const RESERVED = /* @__PURE__ */ new Set([
28
+ "pages",
29
+ "plugins",
30
+ ...BUILTIN_COMMANDS
31
+ ]);
32
+ /** A plugin's own folder, `.whiteboard/<name>/`, made with a .gitignore that ignores all of it. */
33
+ function pluginDir(wb, name) {
34
+ const dir = path.join(wb, name);
35
+ fs.mkdirSync(dir, { recursive: true });
36
+ const ignore = path.join(dir, ".gitignore");
37
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, `# what the ${name} plugin keeps; not for git\n*\n`);
38
+ return dir;
39
+ }
40
+ /** A file reference (URL, file: URL string, or absolute path) → absolute path. */
41
+ function toPath(ref) {
42
+ if (ref instanceof URL || typeof ref === "string" && ref.startsWith("file:")) return fileURLToPath(ref);
43
+ return String(ref);
44
+ }
45
+ /** The built-in plugins, afresh with every load of the config, like what a config imports itself. */
46
+ async function builtinPlugins() {
47
+ const { builtins } = await importOwn("plugins");
48
+ return builtins();
49
+ }
50
+ /** Check a plugin, as the config gives it. */
51
+ function checkPlugin(e, where) {
52
+ if (typeof e !== "object" || !NAME.test(e?.name ?? "")) throw new Error(`a plugin in ${where} needs a name: letters, digits, - and _`);
53
+ if (RESERVED.has(e.name)) throw new Error(`plugin name "${e.name}" in ${where} is taken by the core (a folder in .whiteboard/ or a command)`);
54
+ pluginCommands(e);
55
+ for (const type of Object.keys(e.events ?? {})) if (!type.startsWith(`${e.name}:`) || type.length <= e.name.length + 1) throw new Error(`plugin ${e.name}: event type "${type}" must be named after it: ${e.name}:<what>`);
56
+ }
57
+ /**
58
+ * The config, cached until invalidate() (which loads it afresh). Errors are returned, not thrown:
59
+ * a config that fails to load leaves the project without its plugins, so pages show as raw text,
60
+ * and serves no repository files.
61
+ *
62
+ * The project's plugins are the built-in ones, then the config's: one with a built-in's name
63
+ * replaces it. Their blocks make the pages. `pages: false` leaves the pages out, for the command
64
+ * line, which only needs the plugins (their commands, the session, their events).
65
+ */
66
+ function createConfigLoader(proj, { pages: withPages = true } = {}) {
67
+ let cached = null;
68
+ async function load() {
69
+ const configFile = proj.configFile;
70
+ const exported = (configFile ? await importFresh(configFile) : { default: {} }).default;
71
+ const config = typeof exported === "function" ? await exported() : exported;
72
+ const plugins = await builtinPlugins();
73
+ const builtin = new Set(plugins.map((p) => p.name));
74
+ const added = /* @__PURE__ */ new Set();
75
+ for (const e of [config?.plugins ?? []].flat(Infinity)) {
76
+ if (!e) continue;
77
+ checkPlugin(e, configFile);
78
+ if (added.has(e.name)) throw new Error(`two plugins are named "${e.name}" in ${configFile}`);
79
+ added.add(e.name);
80
+ if (builtin.has(e.name)) plugins[plugins.findIndex((p) => p.name === e.name)] = e;
81
+ else plugins.push(e);
82
+ }
83
+ const blocks = plugins.flatMap((p) => Object.entries(p.blocks ?? {}).map(([name, block]) => ({
84
+ name,
85
+ block,
86
+ plugin: p.name
87
+ })));
88
+ const styles = plugins.map((p) => p.style).filter((s) => !!s);
89
+ const links = plugins.flatMap((p) => p.links ? [p.links.bind(p)] : []);
90
+ const pages = withPages ? createPages({
91
+ blocks,
92
+ style: config?.style,
93
+ styles,
94
+ links
95
+ }) : null;
96
+ const declared = (flag) => new Set(plugins.flatMap((p) => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.[flag]).map(([type]) => type)));
97
+ return {
98
+ pages,
99
+ plugins,
100
+ handedOut: declared("handOut"),
101
+ forReader: declared("forReader"),
102
+ files: config?.files !== false
103
+ };
104
+ }
105
+ function config() {
106
+ cached ??= load().then((value) => ({
107
+ ...value,
108
+ errors: []
109
+ }), (error) => ({
110
+ pages: null,
111
+ plugins: [],
112
+ handedOut: /* @__PURE__ */ new Set(),
113
+ forReader: /* @__PURE__ */ new Set(),
114
+ files: false,
115
+ errors: [error]
116
+ }));
117
+ return cached;
118
+ }
119
+ return {
120
+ config,
121
+ invalidate: () => {
122
+ cached = null;
123
+ }
124
+ };
125
+ }
126
+ export { BUILTIN_COMMANDS, createConfigLoader, pluginDir, toPath };
@@ -0,0 +1,33 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // src/package.ts
5
+ function findRoot(from) {
6
+ for (let dir = from;; dir = path.dirname(dir)) {
7
+ try {
8
+ if (JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).name === "@bigmistqke/whiteboard") return dir;
9
+ } catch {}
10
+ if (path.dirname(dir) === dir) throw new Error(`whiteboard: no package.json of @bigmistqke/whiteboard above ${from}`);
11
+ }
12
+ }
13
+ /** The package's folder: where its package.json is. */
14
+ const PACKAGE_DIR = findRoot(path.dirname(fileURLToPath(import.meta.url)));
15
+ /** A path inside the package. */
16
+ const packagePath = (...parts) => path.join(PACKAGE_DIR, ...parts);
17
+ /**
18
+ * Is the engine running from its TypeScript source (`bin/whiteboard.ts`), rather than from its build
19
+ * (`dist/bin/whiteboard.js`, what an installed package runs)? Then what a config imports from the
20
+ * package comes from source too (the `source` export conditions), so the two never mix.
21
+ */
22
+ const FROM_SOURCE = fileURLToPath(import.meta.url).endsWith(".ts");
23
+ /**
24
+ * A browser file built from the module at `moduleUrl`'s folder: `name` in that folder's place in
25
+ * dist/. The same whether the module runs from source (plugins/form/index.ts gives
26
+ * dist/plugins/form/client.js) or from dist/ itself.
27
+ */
28
+ function builtFile(moduleUrl, name) {
29
+ const rel = path.relative(PACKAGE_DIR, path.dirname(fileURLToPath(moduleUrl)));
30
+ const inDist = rel === "dist" || rel.startsWith("dist" + path.sep);
31
+ return path.join(PACKAGE_DIR, inDist ? "" : "dist", rel, name);
32
+ }
33
+ export { FROM_SOURCE, PACKAGE_DIR, builtFile, packagePath };
@@ -0,0 +1,50 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // src/pages/blocks.ts
5
+ const NAME = /^[\w-]+$/;
6
+ /** A block's file reference (URL, file: URL string, or absolute path) → absolute path. */
7
+ function toPath(ref, field, block) {
8
+ if (ref == null) return null;
9
+ if (ref instanceof URL || typeof ref === "string" && ref.startsWith("file:")) return fileURLToPath(ref);
10
+ if (typeof ref === "string" && path.isAbsolute(ref)) return ref;
11
+ throw new Error(`block "${block}": ${field} must be a URL, e.g. new URL('./${field}.js', import.meta.url)`);
12
+ }
13
+ /** Check and resolve one block into what the engine uses. */
14
+ function normalize({ name, block: b, plugin }) {
15
+ if (typeof b !== "object" || !b) throw new Error(`plugin ${plugin}: block "${name}" is not an object`);
16
+ if (!NAME.test(name)) throw new Error(`plugin ${plugin}: block name ${JSON.stringify(name)}: use letters, digits, - and _`);
17
+ const files = {
18
+ client: toPath(b.client, "client", name),
19
+ style: toPath(b.style, "style", name)
20
+ };
21
+ for (const [field, file] of Object.entries(files)) if (file && !fs.existsSync(file)) throw new Error(`plugin ${plugin}, block "${name}": ${field} file not found: ${file}`);
22
+ return {
23
+ name,
24
+ code: b.fence === "any",
25
+ fences: b.fence === true || b.fence === "any",
26
+ props: typeof b.props === "function" ? b.props.bind(b) : null,
27
+ html: typeof b.html === "function" ? b.html.bind(b) : null,
28
+ ...files,
29
+ source: plugin
30
+ };
31
+ }
32
+ /**
33
+ * Resolve the plugins' blocks. A block name is one plugin's: two plugins bringing the same block is
34
+ * an error. `code` is the block for code fences no block claims by name: the last one with
35
+ * `fence: 'any'`.
36
+ */
37
+ function resolveBlocks(entries) {
38
+ const blocks = /* @__PURE__ */ new Map();
39
+ for (const entry of entries) {
40
+ const n = normalize(entry);
41
+ const other = blocks.get(n.name);
42
+ if (other) throw new Error(`block "${n.name}" comes from two plugins: ${other.source} and ${n.source}`);
43
+ blocks.set(n.name, n);
44
+ }
45
+ return {
46
+ blocks,
47
+ code: [...blocks.values()].findLast((t) => t.code) ?? null
48
+ };
49
+ }
50
+ export { resolveBlocks };
@@ -0,0 +1,15 @@
1
+ import { resolveBlocks } from "./blocks.js";
2
+ import { createDocs, createMessageRender, createRender } from "./render.js";
3
+ import { formNames } from "./markdown.js";
4
+ // src/pages/index.ts
5
+ function createPages(options) {
6
+ const resolved = resolveBlocks(options.blocks);
7
+ const blocks = () => resolved;
8
+ return {
9
+ render: createRender(blocks, options.style, options.styles ?? [], options.links ?? []),
10
+ message: createMessageRender(blocks, options.links ?? []),
11
+ docs: createDocs(blocks),
12
+ questions: (page) => formNames(page.source)
13
+ };
14
+ }
15
+ export { createPages };