@bigmistqke/whiteboard 0.0.0-stage → 0.1.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/bin/whiteboard.ts +431 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +471 -0
  6. package/dist/client/runtime.js +391 -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 +45 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +46 -0
  14. package/dist/plugins/chat/style.css +17 -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 +64 -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 +51 -0
  22. package/dist/plugins/comments/style.css +32 -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/form/README.md +111 -0
  27. package/dist/plugins/form/index.js +102 -0
  28. package/dist/plugins/form/style.css +41 -0
  29. package/dist/plugins/gallery/README.md +30 -0
  30. package/dist/plugins/gallery/client.js +1 -0
  31. package/dist/plugins/gallery/index.js +74 -0
  32. package/dist/plugins/gallery/style.css +27 -0
  33. package/dist/plugins/grid/README.md +33 -0
  34. package/dist/plugins/grid/index.js +33 -0
  35. package/dist/plugins/grid/style.css +25 -0
  36. package/dist/plugins/index.js +26 -0
  37. package/dist/plugins/mermaid/README.md +21 -0
  38. package/dist/plugins/mermaid/index.js +34 -0
  39. package/dist/plugins/mermaid/style.css +16 -0
  40. package/dist/plugins/quiet/README.md +26 -0
  41. package/dist/plugins/quiet/index.js +17 -0
  42. package/dist/plugins/terminal/client.js +41 -0
  43. package/dist/plugins/terminal/host.js +332 -0
  44. package/dist/plugins/terminal/index.js +171 -0
  45. package/dist/plugins/terminal/modes.js +32 -0
  46. package/dist/plugins/terminal/server.js +256 -0
  47. package/dist/plugins/terminal/sizes.js +57 -0
  48. package/dist/plugins/terminal/style.css +357 -0
  49. package/dist/solid/index.js +35 -0
  50. package/dist/src/auth.js +54 -0
  51. package/dist/src/client/page/base.css +274 -0
  52. package/dist/src/client/page/main.js +1004 -0
  53. package/dist/src/config.js +76 -0
  54. package/dist/src/events.js +162 -0
  55. package/dist/src/html.js +34 -0
  56. package/dist/src/load.js +77 -0
  57. package/dist/src/loader.js +120 -0
  58. package/dist/src/package.js +33 -0
  59. package/dist/src/pages/blocks.js +49 -0
  60. package/dist/src/pages/index.js +14 -0
  61. package/dist/src/pages/markdown.js +307 -0
  62. package/dist/src/pages/render.js +257 -0
  63. package/dist/src/plugins.js +238 -0
  64. package/dist/src/running.js +24 -0
  65. package/dist/src/serve.js +71 -0
  66. package/dist/src/server.js +700 -0
  67. package/dist/src/status.js +43 -0
  68. package/package.json +131 -4
  69. package/plugins/callout/README.md +13 -0
  70. package/plugins/callout/index.ts +25 -0
  71. package/plugins/callout/style.css +12 -0
  72. package/plugins/chat/README.md +45 -0
  73. package/plugins/chat/autosize.ts +101 -0
  74. package/plugins/chat/client.tsx +81 -0
  75. package/plugins/chat/index.ts +61 -0
  76. package/plugins/chat/style.css +17 -0
  77. package/plugins/claude-code/index.ts +136 -0
  78. package/plugins/code/README.md +42 -0
  79. package/plugins/code/diff.ts +58 -0
  80. package/plugins/code/index.ts +94 -0
  81. package/plugins/code/style.css +29 -0
  82. package/plugins/comments/client.ts +448 -0
  83. package/plugins/comments/index.ts +52 -0
  84. package/plugins/comments/style.css +32 -0
  85. package/plugins/details/README.md +17 -0
  86. package/plugins/details/index.ts +21 -0
  87. package/plugins/details/style.css +3 -0
  88. package/plugins/form/README.md +111 -0
  89. package/plugins/form/index.ts +104 -0
  90. package/plugins/form/style.css +41 -0
  91. package/plugins/gallery/README.md +30 -0
  92. package/plugins/gallery/client.tsx +64 -0
  93. package/plugins/gallery/index.ts +67 -0
  94. package/plugins/gallery/style.css +27 -0
  95. package/plugins/grid/README.md +33 -0
  96. package/plugins/grid/index.ts +36 -0
  97. package/plugins/grid/style.css +25 -0
  98. package/plugins/index.ts +19 -0
  99. package/plugins/mermaid/README.md +21 -0
  100. package/plugins/mermaid/index.ts +39 -0
  101. package/plugins/mermaid/style.css +16 -0
  102. package/plugins/quiet/README.md +26 -0
  103. package/plugins/quiet/index.ts +27 -0
  104. package/plugins/terminal/client.ts +317 -0
  105. package/plugins/terminal/host.ts +326 -0
  106. package/plugins/terminal/index.ts +138 -0
  107. package/plugins/terminal/modes.ts +30 -0
  108. package/plugins/terminal/server.ts +215 -0
  109. package/plugins/terminal/sizes.ts +60 -0
  110. package/plugins/terminal/style.css +71 -0
  111. package/skills/whiteboard/SKILL.md +292 -0
  112. package/solid/index.tsx +56 -0
  113. package/src/auth.ts +66 -0
  114. package/src/client/forms.ts +186 -0
  115. package/src/client/page/base.css +274 -0
  116. package/src/client/page/fresh.ts +205 -0
  117. package/src/client/page/main.ts +249 -0
  118. package/src/client/page/orphans.ts +46 -0
  119. package/src/client/page/theme.ts +32 -0
  120. package/src/client/page/view.ts +9 -0
  121. package/src/client/page/waiting.ts +109 -0
  122. package/src/client/runtime.ts +170 -0
  123. package/src/config.ts +96 -0
  124. package/src/define.ts +546 -0
  125. package/src/events.ts +194 -0
  126. package/src/html.ts +40 -0
  127. package/src/load.ts +89 -0
  128. package/src/loader.ts +109 -0
  129. package/src/package.ts +39 -0
  130. package/src/pages/blocks.ts +67 -0
  131. package/src/pages/index.ts +36 -0
  132. package/src/pages/markdown.ts +276 -0
  133. package/src/pages/render.ts +196 -0
  134. package/src/plugins.ts +197 -0
  135. package/src/running.ts +22 -0
  136. package/src/serve.ts +52 -0
  137. package/src/server.ts +644 -0
  138. package/src/status.ts +69 -0
@@ -0,0 +1,332 @@
1
+ import { followMouseEncoding } from "./modes.js";
2
+ import { handOver, lastUsed, leave, report } from "./sizes.js";
3
+ import { createRequire } from "node:module";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import net from "node:net";
7
+ // plugins/terminal/host.ts
8
+ const require = createRequire(import.meta.url);
9
+ const [dir, socket] = process.argv.slice(2);
10
+ if (!dir || !socket) {
11
+ console.error("usage: host <project dir> <socket path>");
12
+ process.exit(2);
13
+ }
14
+ /** node-pty. Its prebuilt helper ships without execute permission (1.1.0): add it. */
15
+ function loadPty() {
16
+ const pty = require("node-pty");
17
+ const helper = path.join(path.dirname(require.resolve("node-pty/package.json")), "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
18
+ try {
19
+ if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 73)) fs.chmodSync(helper, 493);
20
+ } catch {}
21
+ return pty;
22
+ }
23
+ const { Terminal } = (await import("@xterm/headless")).default;
24
+ const { SerializeAddon } = (await import("@xterm/addon-serialize")).default;
25
+ /** the sessions by id, in the order they were made */
26
+ const sessions = /* @__PURE__ */ new Map();
27
+ let nextId = 1;
28
+ const watchers = /* @__PURE__ */ new Set();
29
+ let idle;
30
+ function checkIdle() {
31
+ clearTimeout(idle);
32
+ if (![...sessions.values()].some((s) => s.exited == null)) idle = setTimeout(() => quit("no program ran for ten minutes"), 6e5);
33
+ }
34
+ const list = () => [...sessions.values()].map((s) => ({
35
+ id: s.id,
36
+ label: s.label,
37
+ running: s.exited == null,
38
+ exited: s.exited,
39
+ started: s.started
40
+ }));
41
+ function announce() {
42
+ for (const c of watchers) send(c, {
43
+ t: "sessions",
44
+ sessions: list()
45
+ });
46
+ }
47
+ function start(id, command, args, label) {
48
+ const pty = loadPty();
49
+ const before = sessions.get(id);
50
+ const cols = before?.cols ?? 100, rows = before?.rows ?? 30;
51
+ const attached = before?.attached ?? /* @__PURE__ */ new Set();
52
+ const viewers = before?.viewers ?? /* @__PURE__ */ new Map();
53
+ const active = before?.active ?? null;
54
+ if (before) endProcess(before);
55
+ const screen = new Terminal({
56
+ cols,
57
+ rows,
58
+ scrollback: 2e3,
59
+ allowProposedApi: true
60
+ });
61
+ const serializer = new SerializeAddon();
62
+ screen.loadAddon(serializer);
63
+ const mouseEncoding = followMouseEncoding(screen);
64
+ const proc = pty.spawn(command, args, {
65
+ name: "xterm-256color",
66
+ cols,
67
+ rows,
68
+ cwd: dir,
69
+ env: {
70
+ ...process.env,
71
+ TERM: "xterm-256color",
72
+ COLORTERM: "truecolor",
73
+ WHITEBOARD_TERMINAL: id
74
+ }
75
+ });
76
+ const s = {
77
+ id,
78
+ label,
79
+ command,
80
+ args,
81
+ proc,
82
+ screen,
83
+ serializer,
84
+ mouseEncoding,
85
+ cols,
86
+ rows,
87
+ attached,
88
+ viewers,
89
+ active,
90
+ exited: null,
91
+ started: (/* @__PURE__ */ new Date()).toISOString()
92
+ };
93
+ proc.onData((d) => {
94
+ screen.write(d);
95
+ for (const c of s.attached) send(c, {
96
+ t: "data",
97
+ d
98
+ });
99
+ });
100
+ proc.onExit(({ exitCode, signal }) => {
101
+ s.exited = exitCode;
102
+ log(`tab ${id} (${label}) ended: ${signal ? `signal ${signal}` : `exit code ${exitCode}`}`);
103
+ for (const c of s.attached) send(c, {
104
+ t: "exit",
105
+ code: exitCode
106
+ });
107
+ announce();
108
+ checkIdle();
109
+ });
110
+ sessions.set(id, s);
111
+ for (const c of attached) sendScreen(c, s);
112
+ clearTimeout(idle);
113
+ announce();
114
+ return s;
115
+ }
116
+ function endProcess(s) {
117
+ try {
118
+ if (s.exited == null) s.proc.kill();
119
+ } catch {}
120
+ s.screen.dispose();
121
+ }
122
+ function close(id) {
123
+ const s = sessions.get(id);
124
+ if (!s) return;
125
+ endProcess(s);
126
+ sessions.delete(id);
127
+ for (const c of s.attached) send(c, { t: "none" });
128
+ announce();
129
+ checkIdle();
130
+ }
131
+ /** A line in the host's log (.whiteboard/terminal/host.log), with the time: what happened to it and its tabs. */
132
+ function log(line) {
133
+ console.log(`${(/* @__PURE__ */ new Date()).toISOString()} terminal host ${process.pid}: ${line}`);
134
+ }
135
+ /** Leave, saying why: the log is where to look when the tabs are gone. */
136
+ function quit(reason) {
137
+ const running = [...sessions.values()].filter((s) => s.exited == null).length;
138
+ log(`leaves: ${reason}${running ? `, ending ${running} running tab${running > 1 ? "s" : ""}` : ""}`);
139
+ for (const id of [...sessions.keys()]) close(id);
140
+ try {
141
+ fs.unlinkSync(socket);
142
+ } catch {}
143
+ process.exit(0);
144
+ }
145
+ /** Give a session a size, and tell the drawers showing it. */
146
+ function resize(s, cols, rows) {
147
+ if (cols !== s.cols || rows !== s.rows) {
148
+ s.cols = cols;
149
+ s.rows = rows;
150
+ s.screen.resize(cols, rows);
151
+ if (s.exited == null) s.proc.resize(cols, rows);
152
+ }
153
+ sendSize(s);
154
+ }
155
+ function sendSize(s) {
156
+ for (const c of s.attached) send(c, {
157
+ t: "size",
158
+ cols: s.cols,
159
+ rows: s.rows,
160
+ active: s.active
161
+ });
162
+ }
163
+ /** A drawer stopped showing a session. If it was the active one, pass the session on, after a moment. */
164
+ function leaveSession(s, viewer) {
165
+ if ([...s.attached].some((c) => c.viewer === viewer)) return;
166
+ if (!leave(s, viewer)) return;
167
+ setTimeout(() => {
168
+ if (sessions.get(s.id) !== s) return;
169
+ const size = handOver(s, viewer);
170
+ if (size) resize(s, size.cols, size.rows);
171
+ }, 1500);
172
+ }
173
+ /** Write a message to a connection; one that is still waiting for its screen queues it. */
174
+ function send(conn, msg) {
175
+ if (conn.queue) return void conn.queue.push(msg);
176
+ conn.socket.write(JSON.stringify(msg) + "\n");
177
+ }
178
+ /** The screen once the headless terminal has parsed everything written so far; what arrives meanwhile follows it. */
179
+ function sendScreen(conn, s) {
180
+ conn.queue = [];
181
+ s.screen.write("", () => {
182
+ conn.socket.write(JSON.stringify({
183
+ t: "screen",
184
+ d: s.serializer.serialize() + s.mouseEncoding(),
185
+ cols: s.cols,
186
+ rows: s.rows,
187
+ active: s.active,
188
+ exited: s.exited
189
+ }) + "\n");
190
+ const queued = conn.queue ?? [];
191
+ conn.queue = null;
192
+ for (const msg of queued) send(conn, msg);
193
+ });
194
+ }
195
+ function html(s) {
196
+ if (!s) return "";
197
+ try {
198
+ const m = /<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(s.serializer.serializeAsHTML());
199
+ return m ? m[1] : "";
200
+ } catch {
201
+ return "";
202
+ }
203
+ }
204
+ function handle(conn, req) {
205
+ const reply = (msg) => {
206
+ conn.socket.end(JSON.stringify(msg) + "\n");
207
+ };
208
+ const s = req.id != null ? sessions.get(String(req.id)) : void 0;
209
+ switch (req.t) {
210
+ case "list": return reply({ sessions: list() });
211
+ case "start": {
212
+ const id = req.id != null ? String(req.id) : String(nextId);
213
+ const running = sessions.get(id);
214
+ if (running && running.exited == null && !req.restart) return reply({
215
+ session: id,
216
+ already: true
217
+ });
218
+ const command = typeof req.command === "string" && req.command ? req.command : running?.command;
219
+ if (!command) return reply({ error: "start needs a command" });
220
+ const args = typeof req.command === "string" && req.command ? Array.isArray(req.args) ? req.args.map(String) : [] : running.args;
221
+ const label = String(req.label ?? (req.command ? path.basename(req.command) : running.label));
222
+ try {
223
+ start(id, command, args, label);
224
+ } catch (e) {
225
+ return reply({ error: e.message });
226
+ }
227
+ log(`tab ${id} (${label}) ${running ? "restarted" : "started"}`);
228
+ if (Number(id) >= nextId) nextId = Number(id) + 1;
229
+ return reply({ session: id });
230
+ }
231
+ case "input":
232
+ if (s && s.exited == null && typeof req.d === "string") s.proc.write(req.d);
233
+ return reply({ ok: true });
234
+ case "resize": {
235
+ const { cols, rows } = req;
236
+ const viewer = String(req.viewer ?? "");
237
+ if (s && viewer && Number.isInteger(cols) && Number.isInteger(rows) && cols > 1 && rows > 1 && cols < 1e3 && rows < 500) {
238
+ const size = report(s, viewer, cols, rows, !!req.active);
239
+ resize(s, size.cols, size.rows);
240
+ }
241
+ return reply({ ok: true });
242
+ }
243
+ case "html": return reply({ html: html(s ?? sessions.values().next().value) });
244
+ case "close":
245
+ close(String(req.id));
246
+ return reply({ ok: true });
247
+ case "open": {
248
+ const target = s ?? (req.id == null ? lastUsed([...sessions.values()].filter((x) => x.attached.size)) ?? [...sessions.values()].find((x) => x.attached.size) : void 0);
249
+ if (!target || typeof req.path !== "string") return reply({ shown: 0 });
250
+ const mine = [...target.attached].filter((c) => c.viewer && c.viewer === target.active);
251
+ const to = mine.length ? mine : [...target.attached];
252
+ for (const c of to) send(c, {
253
+ t: "navigate",
254
+ path: req.path
255
+ });
256
+ return reply({ shown: to.length });
257
+ }
258
+ case "stop":
259
+ reply({ ok: true });
260
+ setTimeout(() => quit("asked to stop (whiteboard terminal stop)"), 50);
261
+ return;
262
+ case "attach":
263
+ watchers.add(conn);
264
+ if (req.viewer) conn.viewer = String(req.viewer);
265
+ conn.socket.on("close", () => {
266
+ watchers.delete(conn);
267
+ for (const x of sessions.values()) if (x.attached.delete(conn) && conn.viewer) leaveSession(x, conn.viewer);
268
+ });
269
+ send(conn, {
270
+ t: "sessions",
271
+ sessions: list()
272
+ });
273
+ if (!s) return send(conn, { t: "none" });
274
+ s.attached.add(conn);
275
+ sendScreen(conn, s);
276
+ return;
277
+ default: return reply({ error: `unknown request ${req.t}` });
278
+ }
279
+ }
280
+ const server = net.createServer((socketConn) => {
281
+ const conn = {
282
+ socket: socketConn,
283
+ queue: null
284
+ };
285
+ let buf = "";
286
+ socketConn.setEncoding("utf8");
287
+ socketConn.on("error", () => {});
288
+ socketConn.on("data", (chunk) => {
289
+ buf += chunk;
290
+ const nl = buf.indexOf("\n");
291
+ if (nl < 0) return;
292
+ const line = buf.slice(0, nl);
293
+ buf = "";
294
+ socketConn.removeAllListeners("data");
295
+ let req;
296
+ try {
297
+ req = JSON.parse(line);
298
+ } catch {
299
+ return socketConn.end(JSON.stringify({ error: "not JSON" }) + "\n");
300
+ }
301
+ handle(conn, req);
302
+ });
303
+ });
304
+ try {
305
+ await new Promise((resolve, reject) => {
306
+ const probe = net.connect(socket);
307
+ probe.on("connect", () => {
308
+ probe.destroy();
309
+ reject(/* @__PURE__ */ new Error("running"));
310
+ });
311
+ probe.on("error", () => resolve());
312
+ });
313
+ try {
314
+ fs.unlinkSync(socket);
315
+ } catch {}
316
+ } catch {
317
+ console.error("terminal host: another host answers on", socket);
318
+ process.exit(0);
319
+ }
320
+ server.listen(socket, () => {
321
+ try {
322
+ fs.chmodSync(socket, 384);
323
+ } catch {}
324
+ log(`listening on ${socket}`);
325
+ checkIdle();
326
+ });
327
+ for (const signal of [
328
+ "SIGINT",
329
+ "SIGTERM",
330
+ "SIGHUP"
331
+ ]) process.on(signal, () => quit(`got ${signal} from outside`));
332
+ export {};
@@ -0,0 +1,171 @@
1
+ import { html, raw } from "../../src/html.js";
2
+ import { packagePath } from "../../src/package.js";
3
+ import { createTerminal } from "./server.js";
4
+ import _taggedTemplateLiteral from "../../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js";
5
+ // plugins/terminal/index.ts
6
+ var _templateObject;
7
+ const CLIENT = packagePath("dist/plugins/terminal/client.js");
8
+ const STYLE = packagePath("dist/plugins/terminal/style.css");
9
+ /**
10
+ * The drawer's markup, written by the server so that it is there when the page first renders and
11
+ * the browser can morph it from the previous page (a view transition across the page load). Its
12
+ * open state, height and tab come from this browser tab's sessionStorage, set before the first
13
+ * render, and each session's screen is in it as HTML, so a page shows it from its first render on;
14
+ * client.js puts the live terminal in its place.
15
+ */
16
+ const drawer = (state, screens, client) => html(_templateObject || (_templateObject = _taggedTemplateLiteral([
17
+ "<aside id=\"wb-terminal\" aria-label=\"Terminal\" data-sessions=\"",
18
+ "\">\n<div class=\"wb-term-grip\" title=\"drag to resize\"></div>\n<div class=\"wb-term-bar\"><button type=\"button\" class=\"wb-term-toggle\" title=\"Toggle the terminal (Ctrl+`)\"><span class=\"wb-term-chevron\"></span>terminal</button><span class=\"wb-term-status\"></span><span class=\"wb-term-actions\"></span><span class=\"wb-term-tabs\">",
19
+ "</span></div>\n<div class=\"wb-term-screen\">",
20
+ "</div>\n</aside>\n<script>try{const t=document.getElementById('wb-terminal'),s=sessionStorage,o=new URLSearchParams(location.search).get('terminal')==='open'||s.getItem('wb-terminal-open')==='1';t.dataset.state=o?'open':'collapsed';const h=+s.getItem('wb-terminal-height');if(h)document.documentElement.style.setProperty('--wb-term-h',h+'px');const tabs=[...t.querySelectorAll('.wb-term-tab')],k=s.getItem('wb-terminal-tab'),a=tabs.find(b=>b.dataset.id===k)??tabs[0];if(a){t.dataset.tab=a.dataset.id;a.classList.add('wb-current');t.querySelector('.wb-term-placeholder[data-id=\"'+a.dataset.id+'\"]')?.classList.add('wb-current')}}catch{}<\/script>\n<script type=\"module\" src=\"",
21
+ "\"><\/script>"
22
+ ], [
23
+ "<aside id=\"wb-terminal\" aria-label=\"Terminal\" data-sessions=\"",
24
+ "\">\n<div class=\"wb-term-grip\" title=\"drag to resize\"></div>\n<div class=\"wb-term-bar\"><button type=\"button\" class=\"wb-term-toggle\" title=\"Toggle the terminal (Ctrl+\\`)\"><span class=\"wb-term-chevron\"></span>terminal</button><span class=\"wb-term-status\"></span><span class=\"wb-term-actions\"></span><span class=\"wb-term-tabs\">",
25
+ "</span></div>\n<div class=\"wb-term-screen\">",
26
+ "</div>\n</aside>\n<script>try{const t=document.getElementById('wb-terminal'),s=sessionStorage,o=new URLSearchParams(location.search).get('terminal')==='open'||s.getItem('wb-terminal-open')==='1';t.dataset.state=o?'open':'collapsed';const h=+s.getItem('wb-terminal-height');if(h)document.documentElement.style.setProperty('--wb-term-h',h+'px');const tabs=[...t.querySelectorAll('.wb-term-tab')],k=s.getItem('wb-terminal-tab'),a=tabs.find(b=>b.dataset.id===k)??tabs[0];if(a){t.dataset.tab=a.dataset.id;a.classList.add('wb-current');t.querySelector('.wb-term-placeholder[data-id=\"'+a.dataset.id+'\"]')?.classList.add('wb-current')}}catch{}<\/script>\n<script type=\"module\" src=\"",
27
+ "\"><\/script>"
28
+ ])), JSON.stringify(state), state.sessions.map((s) => html`<button type="button" class="wb-term-tab" data-id="${s.id}">${s.label}</button>`), state.sessions.map((s) => screens[s.id] && html`<div class="wb-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`), client);
29
+ function terminal() {
30
+ return {
31
+ name: "terminal",
32
+ style: STYLE,
33
+ setup(ctx) {
34
+ const term = createTerminal({
35
+ dir: ctx.project.dir,
36
+ home: ctx.dataDir
37
+ });
38
+ const client = ctx.asset(CLIENT);
39
+ return {
40
+ routes: {
41
+ "GET /sessions": {
42
+ description: "the sessions (the drawer's tabs): id, label, whether each runs",
43
+ auth: true,
44
+ run: () => term.sessions()
45
+ },
46
+ "POST /start": {
47
+ description: "start a tab: the shell, or program (with its arguments) in it; in session id, a new tab without one; with restart, start it again as it was",
48
+ auth: true,
49
+ body: {
50
+ id: "string?",
51
+ program: "string[]?",
52
+ restart: "boolean?"
53
+ },
54
+ run: ({ body }) => term.start(body)
55
+ },
56
+ "POST /input": {
57
+ description: "keystrokes for a session, as the terminal sends them",
58
+ auth: true,
59
+ body: {
60
+ id: "string",
61
+ data: "string"
62
+ },
63
+ run: ({ body }) => term.input(body.id, body.data)
64
+ },
65
+ "POST /resize": {
66
+ description: "the size that fits the terminal in a page (`viewer`: that drawer); `active`: the reader uses this drawer now, so the session takes its size",
67
+ auth: true,
68
+ body: {
69
+ id: "string",
70
+ viewer: "string",
71
+ cols: "number",
72
+ rows: "number",
73
+ active: "boolean?"
74
+ },
75
+ run: ({ body }) => term.resize(body.id, body.viewer, body.cols, body.rows, !!body.active)
76
+ },
77
+ "GET /stream": {
78
+ description: "the tabs and a session's whole screen, then its output as it comes (events sessions, screen, data, size, navigate, exit; none without that session)",
79
+ auth: true,
80
+ stream: true,
81
+ query: {
82
+ id: "string?",
83
+ viewer: "string?"
84
+ },
85
+ run: ({ req, res, query }) => term.stream(req, res, query.id, query.viewer)
86
+ },
87
+ "POST /close": {
88
+ description: "end a session and drop its tab",
89
+ auth: true,
90
+ body: { id: "string" },
91
+ run: ({ body }) => term.close(body.id)
92
+ },
93
+ "POST /stop": {
94
+ description: "end every session and their host",
95
+ auth: true,
96
+ run: () => term.stop()
97
+ },
98
+ "POST /open": {
99
+ description: "show the page at path in the browser tab whose drawer the reader used last, for session id or, without one, of all; how many were shown",
100
+ auth: true,
101
+ body: {
102
+ id: "string?",
103
+ path: "string"
104
+ },
105
+ run: ({ body }) => term.open(body.id, body.path)
106
+ }
107
+ },
108
+ async shell(req) {
109
+ if (!ctx.authorized(req)) return null;
110
+ const state = await term.sessions();
111
+ return { body: drawer(state, await term.screens(state.sessions), client) };
112
+ }
113
+ };
114
+ },
115
+ commands: {
116
+ "": {
117
+ description: "print a link that opens the terminal drawer in this browser (it gives the browser the project's token); with --new, open a tab with the shell; with a program after --, run it in a new tab",
118
+ args: "[page]",
119
+ options: { new: {
120
+ type: "boolean?",
121
+ description: "open a new tab with the shell"
122
+ } },
123
+ rest: "<program> [arguments]",
124
+ async run(ctx) {
125
+ if (ctx.options.new || ctx.rest.length) {
126
+ const body = await call(ctx, "POST", "/start", { program: ctx.rest });
127
+ console.error(`whiteboard: started in tab ${body.session}`);
128
+ }
129
+ console.log(await ctx.authLink(`${ctx.pagePath(ctx.positionals[0])}?terminal=open`));
130
+ }
131
+ },
132
+ open: {
133
+ description: "show a page in the browser tab whose drawer the reader used last (from a program in a terminal tab: that tab's drawer)",
134
+ args: "<page|file>",
135
+ async run(ctx) {
136
+ if (!ctx.positionals[0]) throw new Error("usage: whiteboard terminal open <page|file>");
137
+ const id = process.env.WHITEBOARD_TERMINAL || void 0;
138
+ const path = ctx.pagePath(ctx.positionals[0]);
139
+ const { shown } = await call(ctx, "POST", "/open", {
140
+ id,
141
+ path
142
+ });
143
+ if (!shown) throw new Error(`no browser shows ${id ? `terminal tab ${id}` : "the terminal drawer"} right now; the page is at ${await ctx.server()}${path}`);
144
+ console.log(`opened ${path} ${id ? `where tab ${id}'s drawer is` : "where the drawer you used last is"}`);
145
+ }
146
+ },
147
+ stop: {
148
+ description: "end every session and their host",
149
+ async run(ctx) {
150
+ const { stopped } = await call(ctx, "POST", "/stop");
151
+ console.log(stopped ? "stopped" : "no session ran");
152
+ }
153
+ }
154
+ }
155
+ };
156
+ }
157
+ /** A request to one of the terminal's routes, from a command. */
158
+ async function call(ctx, method, route, body) {
159
+ const res = await fetch(`${await ctx.server()}/api/terminal${route}`, {
160
+ method,
161
+ headers: {
162
+ "content-type": "application/json",
163
+ "x-whiteboard-token": ctx.token
164
+ },
165
+ body: body ? JSON.stringify(body) : void 0
166
+ });
167
+ const out = await res.json().catch(() => ({}));
168
+ if (!res.ok) throw new Error(out.error ?? res.statusText);
169
+ return out;
170
+ }
171
+ export { terminal as default };
@@ -0,0 +1,32 @@
1
+ // plugins/terminal/modes.ts
2
+ /** The mouse encodings a program can ask for: UTF-8 (1005), SGR (1006), URXVT (1015). */
3
+ const ENCODINGS = [
4
+ 1005,
5
+ 1006,
6
+ 1015
7
+ ];
8
+ /**
9
+ * Follow the mouse encoding the program on `terminal` asks for. Returns what to append to a
10
+ * serialized screen to restore it: the escape sequence, or '' for the default encoding.
11
+ */
12
+ function followMouseEncoding(terminal) {
13
+ let encoding = null;
14
+ const handle = (on) => (params) => {
15
+ for (const p of params.flat()) {
16
+ if (!ENCODINGS.includes(p)) continue;
17
+ if (on) encoding = p;
18
+ else if (encoding === p) encoding = null;
19
+ }
20
+ return false;
21
+ };
22
+ terminal.parser.registerCsiHandler({
23
+ prefix: "?",
24
+ final: "h"
25
+ }, handle(true));
26
+ terminal.parser.registerCsiHandler({
27
+ prefix: "?",
28
+ final: "l"
29
+ }, handle(false));
30
+ return () => encoding ? `\x1b[?${encoding}h` : "";
31
+ }
32
+ export { followMouseEncoding };