@bigmistqke/whiteboard 0.3.1 → 0.5.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 (174) hide show
  1. package/README.md +119 -18
  2. package/bin/whiteboard.ts +300 -71
  3. package/dist/bin/whiteboard.js +21 -0
  4. package/dist/client/runtime.js +132 -54
  5. package/dist/define.js +21 -2
  6. package/dist/plugins/callout/index.js +3 -1
  7. package/dist/plugins/callout/public/style.css +30 -0
  8. package/dist/plugins/chat/index.js +7 -4
  9. package/dist/plugins/chat/{client.js → public/client.js} +1 -1
  10. package/dist/plugins/chat/public/style.css +98 -0
  11. package/dist/plugins/code/index.js +3 -1
  12. package/dist/plugins/code/public/style.css +68 -0
  13. package/dist/plugins/comments/index.js +4 -5
  14. package/dist/plugins/comments/public/client.js +19 -0
  15. package/dist/plugins/comments/public/style.css +185 -0
  16. package/dist/plugins/details/index.js +7 -2
  17. package/dist/plugins/details/public/style.css +7 -0
  18. package/dist/plugins/draft/README.md +14 -0
  19. package/dist/plugins/draft/index.js +21 -0
  20. package/dist/plugins/draft/public/style.css +21 -0
  21. package/dist/plugins/form/index.js +37 -8
  22. package/dist/plugins/form/public/style.css +126 -0
  23. package/dist/plugins/gallery/index.js +4 -3
  24. package/dist/plugins/gallery/public/client.js +1 -0
  25. package/dist/plugins/gallery/public/style.css +90 -0
  26. package/dist/plugins/grid/index.js +9 -3
  27. package/dist/plugins/grid/public/style.css +71 -0
  28. package/dist/plugins/iframe/index.js +13 -14
  29. package/dist/plugins/iframe/public/style.css +13 -0
  30. package/dist/plugins/index.js +7 -1
  31. package/dist/plugins/mermaid/index.js +3 -1
  32. package/dist/plugins/mermaid/{style.css → public/style.css} +7 -2
  33. package/dist/plugins/steps/README.md +42 -0
  34. package/dist/plugins/steps/index.js +99 -0
  35. package/dist/plugins/steps/public/client.js +1 -0
  36. package/dist/plugins/steps/public/style.css +77 -0
  37. package/dist/plugins/terminal/host.js +9 -3
  38. package/dist/plugins/terminal/index.js +10 -9
  39. package/dist/plugins/terminal/{style.css → public/style.css} +199 -45
  40. package/dist/plugins/terminal/sizes.js +2 -1
  41. package/dist/plugins/toc/README.md +21 -3
  42. package/dist/plugins/toc/index.js +12 -5
  43. package/dist/plugins/toc/public/client.js +1 -0
  44. package/dist/plugins/toc/public/style.css +99 -0
  45. package/dist/plugins/window/README.md +29 -0
  46. package/dist/plugins/window/index.js +64 -0
  47. package/dist/solid/index.js +14 -11
  48. package/dist/src/auth.js +2 -1
  49. package/dist/src/client/page/base.css +1078 -199
  50. package/dist/src/client/page/main.js +188 -39
  51. package/dist/src/loader.js +14 -3
  52. package/dist/src/package.js +3 -6
  53. package/dist/src/pages/blocks.js +8 -13
  54. package/dist/src/pages/markdown.js +1 -1
  55. package/dist/src/pages/render.js +106 -20
  56. package/dist/src/pages/window.js +31 -0
  57. package/dist/src/public.js +24 -0
  58. package/dist/src/server.js +251 -23
  59. package/package.json +5 -2
  60. package/plugins/callout/index.ts +3 -1
  61. package/plugins/callout/public/style.css +30 -0
  62. package/plugins/chat/autosize.ts +43 -9
  63. package/plugins/chat/client.tsx +22 -5
  64. package/plugins/chat/index.ts +22 -8
  65. package/plugins/chat/public/style.css +98 -0
  66. package/plugins/claude-code/index.ts +49 -14
  67. package/plugins/code/diff.ts +28 -8
  68. package/plugins/code/index.ts +33 -21
  69. package/plugins/code/public/style.css +68 -0
  70. package/plugins/comments/client.ts +139 -71
  71. package/plugins/comments/index.ts +9 -7
  72. package/plugins/comments/public/style.css +185 -0
  73. package/plugins/details/index.ts +7 -2
  74. package/plugins/details/public/style.css +7 -0
  75. package/plugins/draft/README.md +14 -0
  76. package/plugins/draft/index.ts +23 -0
  77. package/plugins/draft/public/style.css +21 -0
  78. package/plugins/forge/index.ts +16 -3
  79. package/plugins/form/index.ts +75 -27
  80. package/plugins/form/public/style.css +126 -0
  81. package/plugins/gallery/client.tsx +9 -3
  82. package/plugins/gallery/index.ts +31 -9
  83. package/plugins/gallery/public/style.css +90 -0
  84. package/plugins/grid/index.ts +19 -5
  85. package/plugins/grid/public/style.css +71 -0
  86. package/plugins/iframe/index.ts +20 -23
  87. package/plugins/iframe/public/style.css +13 -0
  88. package/plugins/index.ts +20 -1
  89. package/plugins/mermaid/index.ts +7 -3
  90. package/plugins/mermaid/{style.css → public/style.css} +7 -2
  91. package/plugins/steps/README.md +42 -0
  92. package/plugins/steps/client.ts +66 -0
  93. package/plugins/steps/index.ts +127 -0
  94. package/plugins/steps/public/style.css +77 -0
  95. package/plugins/terminal/client.ts +105 -48
  96. package/plugins/terminal/host.ts +143 -35
  97. package/plugins/terminal/index.ts +84 -25
  98. package/plugins/terminal/public/style.css +225 -0
  99. package/plugins/terminal/server.ts +64 -13
  100. package/plugins/terminal/sizes.ts +16 -4
  101. package/plugins/toc/README.md +21 -3
  102. package/plugins/toc/client.ts +90 -30
  103. package/plugins/toc/index.ts +26 -10
  104. package/plugins/toc/public/style.css +99 -0
  105. package/plugins/window/README.md +29 -0
  106. package/plugins/window/index.ts +85 -0
  107. package/skills/whiteboard/SKILL.md +3 -1
  108. package/solid/index.tsx +24 -9
  109. package/src/auth.ts +28 -9
  110. package/src/client/forms.ts +74 -28
  111. package/src/client/markdown.ts +15 -4
  112. package/src/client/page/base.css +1078 -199
  113. package/src/client/page/elsewhere.ts +32 -15
  114. package/src/client/page/fresh.ts +91 -23
  115. package/src/client/page/hold.ts +11 -2
  116. package/src/client/page/live.ts +10 -6
  117. package/src/client/page/main.ts +124 -42
  118. package/src/client/page/orphans.ts +25 -10
  119. package/src/client/page/sort.ts +14 -4
  120. package/src/client/page/sticky.ts +11 -3
  121. package/src/client/page/theme.ts +11 -7
  122. package/src/client/page/waiting.ts +141 -34
  123. package/src/client/page/window.ts +40 -0
  124. package/src/client/reactive.ts +19 -0
  125. package/src/client/read.ts +17 -10
  126. package/src/client/runtime.ts +170 -40
  127. package/src/client/scroll.ts +14 -4
  128. package/src/client/toast.ts +19 -5
  129. package/src/config.ts +20 -5
  130. package/src/define.ts +119 -31
  131. package/src/events.ts +111 -24
  132. package/src/html.ts +6 -2
  133. package/src/icons.ts +4 -2
  134. package/src/load.ts +10 -2
  135. package/src/loader.ts +81 -12
  136. package/src/package.ts +9 -8
  137. package/src/pages/blocks.ts +20 -14
  138. package/src/pages/index.ts +2 -2
  139. package/src/pages/markdown.ts +113 -34
  140. package/src/pages/render.ts +233 -41
  141. package/src/pages/window.ts +78 -0
  142. package/src/plugins.ts +90 -24
  143. package/src/public.ts +39 -0
  144. package/src/running.ts +8 -2
  145. package/src/serve.ts +29 -7
  146. package/src/server.ts +591 -110
  147. package/src/status.ts +15 -9
  148. package/dist/plugins/callout/style.css +0 -12
  149. package/dist/plugins/chat/style.css +0 -24
  150. package/dist/plugins/code/style.css +0 -29
  151. package/dist/plugins/comments/client.js +0 -10
  152. package/dist/plugins/comments/style.css +0 -40
  153. package/dist/plugins/details/style.css +0 -3
  154. package/dist/plugins/form/style.css +0 -44
  155. package/dist/plugins/gallery/client.js +0 -1
  156. package/dist/plugins/gallery/style.css +0 -27
  157. package/dist/plugins/grid/style.css +0 -25
  158. package/dist/plugins/iframe/client.js +0 -1
  159. package/dist/plugins/iframe/style.css +0 -29
  160. package/dist/plugins/toc/client.js +0 -1
  161. package/dist/plugins/toc/style.css +0 -19
  162. package/plugins/callout/style.css +0 -12
  163. package/plugins/chat/style.css +0 -24
  164. package/plugins/code/style.css +0 -29
  165. package/plugins/comments/style.css +0 -40
  166. package/plugins/details/style.css +0 -3
  167. package/plugins/form/style.css +0 -44
  168. package/plugins/gallery/style.css +0 -27
  169. package/plugins/grid/style.css +0 -25
  170. package/plugins/iframe/client.ts +0 -46
  171. package/plugins/iframe/style.css +0 -29
  172. package/plugins/terminal/style.css +0 -71
  173. package/plugins/toc/style.css +0 -19
  174. /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
@@ -10,11 +10,28 @@ import { Terminal } from '@xterm/xterm'
10
10
  import { FitAddon } from '@xterm/addon-fit'
11
11
 
12
12
  const store = {
13
- get: (k: string) => { try { return sessionStorage.getItem(k) } catch { return null } },
14
- set: (k: string, v: string) => { try { sessionStorage.setItem(k, v) } catch { /* storage unavailable */ } },
13
+ get: (k: string) => {
14
+ try {
15
+ return sessionStorage.getItem(k)
16
+ } catch {
17
+ return null
18
+ }
19
+ },
20
+ set: (k: string, v: string) => {
21
+ try {
22
+ sessionStorage.setItem(k, v)
23
+ } catch {
24
+ /* storage unavailable */
25
+ }
26
+ },
15
27
  }
16
28
 
17
- interface Session { id: string; label: string; running: boolean; exited: number | null }
29
+ interface Session {
30
+ id: string
31
+ label: string
32
+ running: boolean
33
+ exited: number | null
34
+ }
18
35
 
19
36
  function init(drawer: HTMLElement) {
20
37
  const screen = drawer.querySelector<HTMLElement>('.wb-term-screen')!
@@ -25,7 +42,12 @@ function init(drawer: HTMLElement) {
25
42
  const grip = drawer.querySelector<HTMLElement>('.wb-term-grip')!
26
43
  // the sessions as the server wrote them into the page, and the tab this browser tab shows
27
44
  let sessions: Session[] = []
28
- try { ({ sessions } = JSON.parse(drawer.dataset.sessions ?? '{}')); sessions ??= [] } catch { /* none */ }
45
+ try {
46
+ ;({ sessions } = JSON.parse(drawer.dataset.sessions ?? '{}'))
47
+ sessions ??= []
48
+ } catch {
49
+ /* none */
50
+ }
29
51
  let current: string | null = drawer.dataset.tab ?? sessions[0]?.id ?? null
30
52
 
31
53
  const term = new Terminal({
@@ -77,7 +99,10 @@ function init(drawer: HTMLElement) {
77
99
  sent = key
78
100
  post('/api/terminal/resize', { id: current, viewer, cols: dims.cols, rows: dims.rows, active: claim })
79
101
  // it is ours from now on; the host confirms with a `size`
80
- if (claim) { active = viewer; claim = false }
102
+ if (claim) {
103
+ active = viewer
104
+ claim = false
105
+ }
81
106
  }
82
107
  show()
83
108
  }
@@ -86,7 +111,8 @@ function init(drawer: HTMLElement) {
86
111
  function show() {
87
112
  const dims = fit.proposeDimensions()
88
113
  const size = mine() || !session ? dims : session
89
- if (size?.cols && size?.rows && (size.cols !== term.cols || size.rows !== term.rows)) term.resize(size.cols, size.rows)
114
+ if (size?.cols && size?.rows && (size.cols !== term.cols || size.rows !== term.rows))
115
+ term.resize(size.cols, size.rows)
90
116
  }
91
117
 
92
118
  /** The reader uses this drawer: the session takes its size. */
@@ -109,11 +135,18 @@ function init(drawer: HTMLElement) {
109
135
  const vt = (document as any).startViewTransition
110
136
  if (vt && !matchMedia('(prefers-reduced-motion: reduce)').matches) vt.call(document, apply)
111
137
  else apply()
112
- requestAnimationFrame(() => { if (open) use(); refit(); if (open) term.focus() })
138
+ requestAnimationFrame(() => {
139
+ if (open) use()
140
+ refit()
141
+ if (open) term.focus()
142
+ })
113
143
  }
114
144
  toggle.addEventListener('click', () => setOpen(!isOpen()))
115
145
  addEventListener('keydown', e => {
116
- if (e.ctrlKey && e.key === '`') { e.preventDefault(); setOpen(!isOpen()) }
146
+ if (e.ctrlKey && e.key === '`') {
147
+ e.preventDefault()
148
+ setOpen(!isOpen())
149
+ }
117
150
  })
118
151
 
119
152
  // ---- height --------------------------------------------------------------------------------
@@ -145,50 +178,60 @@ function init(drawer: HTMLElement) {
145
178
  if (!current) return
146
179
  use()
147
180
  const id = current
148
- if (!pending) queueMicrotask(() => {
149
- const data = pending
150
- pending = ''
151
- chain = chain.then(() => post('/api/terminal/input', { id, data })).then(() => {}, () => {})
152
- })
181
+ if (!pending)
182
+ queueMicrotask(() => {
183
+ const data = pending
184
+ pending = ''
185
+ chain = chain
186
+ .then(() => post('/api/terminal/input', { id, data }))
187
+ .then(
188
+ () => {},
189
+ () => {},
190
+ )
191
+ })
153
192
  pending += d
154
193
  })
155
194
 
156
195
  // ---- the session ---------------------------------------------------------------------------
157
196
  function setStatus(text: string, buttons: [string, () => void][] = []) {
158
197
  status.textContent = text
159
- actions.replaceChildren(...buttons.map(([label, run]) => {
160
- const b = document.createElement('button')
161
- b.type = 'button'
162
- b.textContent = label
163
- b.addEventListener('click', run)
164
- return b
165
- }))
198
+ actions.replaceChildren(
199
+ ...buttons.map(([label, run]) => {
200
+ const b = document.createElement('button')
201
+ b.type = 'button'
202
+ b.textContent = label
203
+ b.addEventListener('click', run)
204
+ return b
205
+ }),
206
+ )
166
207
  }
167
208
 
168
209
  // ---- tabs ----------------------------------------------------------------------------------
169
210
  function drawTabs() {
170
- tabs.replaceChildren(...sessions.map(x => {
171
- const tab = document.createElement('span')
172
- tab.className = 'wb-term-tab'
173
- tab.dataset.id = x.id
174
- tab.classList.toggle('wb-current', x.id === current)
175
- tab.toggleAttribute('data-exited', !x.running)
176
- const name = document.createElement('button')
177
- name.type = 'button'
178
- name.className = 'wb-term-tab-name'
179
- name.textContent = x.label
180
- name.title = x.running ? x.label : `${x.label}: exited (${x.exited})`
181
- name.addEventListener('click', () => select(x.id))
182
- tab.append(name)
183
- const close = document.createElement('button')
184
- close.type = 'button'
185
- close.className = 'wb-term-tab-close'
186
- close.title = 'Close this tab (ends its program)'
187
- close.textContent = '×'
188
- close.addEventListener('click', () => closeTab(x.id))
189
- tab.append(close)
190
- return tab
191
- }))
211
+ tabs.replaceChildren(
212
+ ...sessions.map(x => {
213
+ const tab = document.createElement('span')
214
+ tab.className = 'wb-term-tab'
215
+ tab.dataset.id = x.id
216
+ tab.classList.toggle('wb-current', x.id === current)
217
+ tab.toggleAttribute('data-exited', !x.running)
218
+ const name = document.createElement('button')
219
+ name.type = 'button'
220
+ name.className = 'wb-term-tab-name'
221
+ name.textContent = x.label
222
+ name.title = x.running ? x.label : `${x.label}: exited (${x.exited})`
223
+ name.addEventListener('click', () => select(x.id))
224
+ tab.append(name)
225
+ const close = document.createElement('button')
226
+ close.type = 'button'
227
+ close.className = 'wb-term-tab-close'
228
+ close.title = 'Close this tab (ends its program)'
229
+ close.textContent = '×'
230
+ close.addEventListener('click', () => closeTab(x.id))
231
+ tab.append(close)
232
+ return tab
233
+ }),
234
+ )
192
235
  showStatus()
193
236
  }
194
237
 
@@ -206,12 +249,17 @@ function init(drawer: HTMLElement) {
206
249
  // no tab yet: "+" opens one
207
250
  if (!x) return setStatus('', [])
208
251
  if (x.running) return setStatus('', [])
209
- setStatus(x.exited == null ? 'stopped' : `exited (${x.exited})`, [['Start again', () => start({ id: x.id, restart: true })]])
252
+ setStatus(x.exited == null ? 'stopped' : `exited (${x.exited})`, [
253
+ ['Start again', () => start({ id: x.id, restart: true })],
254
+ ])
210
255
  }
211
256
 
212
257
  function select(id: string | null) {
213
258
  // the tab that shows already: just give it the keyboard back
214
- if (id === current && stream) { if (isOpen()) term.focus(); return }
259
+ if (id === current && stream) {
260
+ if (isOpen()) term.focus()
261
+ return
262
+ }
215
263
  current = id
216
264
  if (id) store.set('wb-terminal-tab', id)
217
265
  drawTabs()
@@ -242,7 +290,9 @@ function init(drawer: HTMLElement) {
242
290
  try {
243
291
  const res = await fetch('/api/terminal/sessions')
244
292
  if (res.ok) ({ sessions } = await res.json())
245
- } catch { /* the server is away: the stream reconnects */ }
293
+ } catch {
294
+ /* the server is away: the stream reconnects */
295
+ }
246
296
  drawTabs()
247
297
  }
248
298
 
@@ -253,7 +303,9 @@ function init(drawer: HTMLElement) {
253
303
  sent = ''
254
304
  if (!current) showStatus()
255
305
  // without a tab too: the host tells it when one appears (started from the command line, say)
256
- stream = new EventSource(`/api/terminal/stream?${current ? `id=${encodeURIComponent(current)}&` : ''}viewer=${viewer}`)
306
+ stream = new EventSource(
307
+ `/api/terminal/stream?${current ? `id=${encodeURIComponent(current)}&` : ''}viewer=${viewer}`,
308
+ )
257
309
  stream.addEventListener('sessions', e => {
258
310
  sessions = JSON.parse((e as MessageEvent).data).sessions
259
311
  // the current tab is gone, or there was none and one appeared: show the last
@@ -297,13 +349,18 @@ function init(drawer: HTMLElement) {
297
349
  stream.addEventListener('exit', e => {
298
350
  const code = JSON.parse((e as MessageEvent).data).code
299
351
  const x = sessions.find(y => y.id === current)
300
- if (x) { x.running = false; x.exited = code }
352
+ if (x) {
353
+ x.running = false
354
+ x.exited = code
355
+ }
301
356
  drawTabs()
302
357
  })
303
358
  }
304
359
 
305
360
  // whether the terminal had the keyboard, for the next page
306
- addEventListener('pagehide', () => store.set('wb-terminal-focus', drawer.contains(document.activeElement) ? '1' : '0'))
361
+ addEventListener('pagehide', () =>
362
+ store.set('wb-terminal-focus', drawer.contains(document.activeElement) ? '1' : '0'),
363
+ )
307
364
 
308
365
  drawTabs()
309
366
  connect()
@@ -40,26 +40,42 @@ import fs from 'node:fs'
40
40
  import net from 'node:net'
41
41
  import path from 'node:path'
42
42
  import { createRequire } from 'node:module'
43
+ import type * as NodePty from 'node-pty'
43
44
  import type { IPty } from 'node-pty'
44
- import type { Terminal as HeadlessTerminal } from '@xterm/headless'
45
- import type { SerializeAddon as Serializer } from '@xterm/addon-serialize'
45
+ import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless'
46
+ import xtermSerialize, { type SerializeAddon as Serializer } from '@xterm/addon-serialize'
46
47
  import { followMouseEncoding } from './modes.ts'
47
48
  import { handOver, lastUsed, leave, report, type Sizes } from './sizes.ts'
48
49
 
49
50
  const require = createRequire(import.meta.url)
50
51
  const [dir, socket] = process.argv.slice(2)
51
- if (!dir || !socket) { console.error('usage: host <project dir> <socket path>'); process.exit(2) }
52
+ if (!dir || !socket) {
53
+ console.error('usage: host <project dir> <socket path>')
54
+ process.exit(2)
55
+ }
52
56
 
53
- /** node-pty. Its prebuilt helper ships without execute permission (1.1.0): add it. */
54
- function loadPty(): typeof import('node-pty') {
57
+ /**
58
+ * node-pty, loaded when a session starts rather than imported: a native module that may not load on
59
+ * this machine, which then is an error to report, not a host that fails to start. Its prebuilt
60
+ * helper ships without execute permission (1.1.0): add it.
61
+ */
62
+ function loadPty(): typeof NodePty {
55
63
  const pty = require('node-pty')
56
- const helper = path.join(path.dirname(require.resolve('node-pty/package.json')), 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper')
57
- try { if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 0o111)) fs.chmodSync(helper, 0o755) } catch {}
64
+ const helper = path.join(
65
+ path.dirname(require.resolve('node-pty/package.json')),
66
+ 'prebuilds',
67
+ `${process.platform}-${process.arch}`,
68
+ 'spawn-helper',
69
+ )
70
+ try {
71
+ if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 0o111)) fs.chmodSync(helper, 0o755)
72
+ } catch {}
58
73
  return pty
59
74
  }
60
75
 
61
- const { Terminal } = (await import('@xterm/headless')).default
62
- const { SerializeAddon } = (await import('@xterm/addon-serialize')).default
76
+ // CommonJS packages: their exports are the default's
77
+ const { Terminal } = xtermHeadless
78
+ const { SerializeAddon } = xtermSerialize
63
79
 
64
80
  /** A program in a pseudo-terminal, and the headless terminal that keeps its screen. */
65
81
  interface Session extends Sizes {
@@ -99,16 +115,27 @@ const watchers = new Set<Conn>()
99
115
  let idle: ReturnType<typeof setTimeout> | undefined
100
116
  function checkIdle() {
101
117
  clearTimeout(idle)
102
- if (![...sessions.values()].some(s => s.exited == null)) idle = setTimeout(() => quit('no program ran for ten minutes'), 10 * 60 * 1000)
118
+ if (![...sessions.values()].some(s => s.exited == null))
119
+ idle = setTimeout(() => quit('no program ran for ten minutes'), 10 * 60 * 1000)
103
120
  }
104
121
 
105
- const list = () => [...sessions.values()].map(s => ({ id: s.id, label: s.label, running: s.exited == null, exited: s.exited, started: s.started }))
106
- function announce() { for (const c of watchers) send(c, { t: 'sessions', sessions: list() }) }
122
+ const list = () =>
123
+ [...sessions.values()].map(s => ({
124
+ id: s.id,
125
+ label: s.label,
126
+ running: s.exited == null,
127
+ exited: s.exited,
128
+ started: s.started,
129
+ }))
130
+ function announce() {
131
+ for (const c of watchers) send(c, { t: 'sessions', sessions: list() })
132
+ }
107
133
 
108
134
  function start(id: string, command: string, args: string[], label: string): Session {
109
135
  const pty = loadPty()
110
136
  const before = sessions.get(id)
111
- const cols = before?.cols ?? 100, rows = before?.rows ?? 30
137
+ const cols = before?.cols ?? 100,
138
+ rows = before?.rows ?? 30
112
139
  const attached = before?.attached ?? new Set<Conn>()
113
140
  const viewers = before?.viewers ?? new Map()
114
141
  const active = before?.active ?? null
@@ -118,11 +145,30 @@ function start(id: string, command: string, args: string[], label: string): Sess
118
145
  screen.loadAddon(serializer)
119
146
  const mouseEncoding = followMouseEncoding(screen)
120
147
  const proc = pty.spawn(command, args, {
121
- name: 'xterm-256color', cols, rows, cwd: dir,
148
+ name: 'xterm-256color',
149
+ cols,
150
+ rows,
151
+ cwd: dir,
122
152
  // WHITEBOARD_TERMINAL: which tab a program runs in, so it can show a page where its drawer is (`open`)
123
153
  env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor', WHITEBOARD_TERMINAL: id },
124
154
  })
125
- const s: Session = { id, label, command, args, proc, screen, serializer, mouseEncoding, cols, rows, attached, viewers, active, exited: null, started: new Date().toISOString() }
155
+ const s: Session = {
156
+ id,
157
+ label,
158
+ command,
159
+ args,
160
+ proc,
161
+ screen,
162
+ serializer,
163
+ mouseEncoding,
164
+ cols,
165
+ rows,
166
+ attached,
167
+ viewers,
168
+ active,
169
+ exited: null,
170
+ started: new Date().toISOString(),
171
+ }
126
172
  proc.onData(d => {
127
173
  screen.write(d)
128
174
  for (const c of s.attached) send(c, { t: 'data', d })
@@ -143,7 +189,9 @@ function start(id: string, command: string, args: string[], label: string): Sess
143
189
  }
144
190
 
145
191
  function endProcess(s: Session) {
146
- try { if (s.exited == null) s.proc.kill() } catch {}
192
+ try {
193
+ if (s.exited == null) s.proc.kill()
194
+ } catch {}
147
195
  s.screen.dispose()
148
196
  }
149
197
 
@@ -167,7 +215,9 @@ function quit(reason: string) {
167
215
  const running = [...sessions.values()].filter(s => s.exited == null).length
168
216
  log(`leaves: ${reason}${running ? `, ending ${running} running tab${running > 1 ? 's' : ''}` : ''}`)
169
217
  for (const id of [...sessions.keys()]) close(id)
170
- try { fs.unlinkSync(socket) } catch {}
218
+ try {
219
+ fs.unlinkSync(socket)
220
+ } catch {}
171
221
  process.exit(0)
172
222
  }
173
223
 
@@ -176,7 +226,8 @@ function quit(reason: string) {
176
226
  /** Give a session a size, and tell the drawers showing it. */
177
227
  function resize(s: Session, cols: number, rows: number) {
178
228
  if (cols !== s.cols || rows !== s.rows) {
179
- s.cols = cols; s.rows = rows
229
+ s.cols = cols
230
+ s.rows = rows
180
231
  s.screen.resize(cols, rows)
181
232
  if (s.exited == null) s.proc.resize(cols, rows)
182
233
  }
@@ -209,7 +260,16 @@ function send(conn: Conn, msg: unknown) {
209
260
  function sendScreen(conn: Conn, s: Session) {
210
261
  conn.queue = []
211
262
  s.screen.write('', () => {
212
- conn.socket.write(JSON.stringify({ t: 'screen', d: s.serializer.serialize() + s.mouseEncoding(), cols: s.cols, rows: s.rows, active: s.active, exited: s.exited }) + '\n')
263
+ conn.socket.write(
264
+ JSON.stringify({
265
+ t: 'screen',
266
+ d: s.serializer.serialize() + s.mouseEncoding(),
267
+ cols: s.cols,
268
+ rows: s.rows,
269
+ active: s.active,
270
+ exited: s.exited,
271
+ }) + '\n',
272
+ )
213
273
  const queued = conn.queue ?? []
214
274
  conn.queue = null
215
275
  for (const msg of queued) send(conn, msg)
@@ -222,14 +282,19 @@ function html(s: Session | undefined): string {
222
282
  // the rows, without the wrapper that sets the serializer's own colors and font; text is escaped
223
283
  const m = /<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(s.serializer.serializeAsHTML())
224
284
  return m ? m[1] : ''
225
- } catch { return '' }
285
+ } catch {
286
+ return ''
287
+ }
226
288
  }
227
289
 
228
290
  function handle(conn: Conn, req: Record<string, any>) {
229
- const reply = (msg: unknown) => { conn.socket.end(JSON.stringify(msg) + '\n') }
291
+ const reply = (msg: unknown) => {
292
+ conn.socket.end(JSON.stringify(msg) + '\n')
293
+ }
230
294
  const s = req.id != null ? sessions.get(String(req.id)) : undefined
231
295
  switch (req.t) {
232
- case 'list': return reply({ sessions: list() })
296
+ case 'list':
297
+ return reply({ sessions: list() })
233
298
  case 'start': {
234
299
  const id = req.id != null ? String(req.id) : String(nextId)
235
300
  const running = sessions.get(id)
@@ -237,9 +302,18 @@ function handle(conn: Conn, req: Record<string, any>) {
237
302
  // without a command: start it again as it was (restarting a tab)
238
303
  const command = typeof req.command === 'string' && req.command ? req.command : running?.command
239
304
  if (!command) return reply({ error: 'start needs a command' })
240
- const args = typeof req.command === 'string' && req.command ? (Array.isArray(req.args) ? req.args.map(String) : []) : running!.args
305
+ const args =
306
+ typeof req.command === 'string' && req.command
307
+ ? Array.isArray(req.args)
308
+ ? req.args.map(String)
309
+ : []
310
+ : running!.args
241
311
  const label = String(req.label ?? (req.command ? path.basename(req.command) : running!.label))
242
- try { start(id, command, args, label) } catch (e) { return reply({ error: (e as Error).message }) }
312
+ try {
313
+ start(id, command, args, label)
314
+ } catch (e) {
315
+ return reply({ error: (e as Error).message })
316
+ }
243
317
  log(`tab ${id} (${label}) ${running ? 'restarted' : 'started'}`)
244
318
  // ids are never reused while the host runs, so a closed tab's id can't come back as another
245
319
  if (Number(id) >= nextId) nextId = Number(id) + 1
@@ -251,19 +325,36 @@ function handle(conn: Conn, req: Record<string, any>) {
251
325
  case 'resize': {
252
326
  const { cols, rows } = req
253
327
  const viewer = String(req.viewer ?? '')
254
- if (s && viewer && Number.isInteger(cols) && Number.isInteger(rows) && cols > 1 && rows > 1 && cols < 1000 && rows < 500) {
328
+ if (
329
+ s &&
330
+ viewer &&
331
+ Number.isInteger(cols) &&
332
+ Number.isInteger(rows) &&
333
+ cols > 1 &&
334
+ rows > 1 &&
335
+ cols < 1000 &&
336
+ rows < 500
337
+ ) {
255
338
  const size = report(s, viewer, cols, rows, !!req.active)
256
339
  resize(s, size.cols, size.rows)
257
340
  }
258
341
  return reply({ ok: true })
259
342
  }
260
- case 'html': return reply({ html: html(s ?? sessions.values().next().value) })
261
- case 'close': close(String(req.id)); return reply({ ok: true })
343
+ case 'html':
344
+ return reply({ html: html(s ?? sessions.values().next().value) })
345
+ case 'close':
346
+ close(String(req.id))
347
+ return reply({ ok: true })
262
348
  case 'open': {
263
349
  // show a page in the browser tab whose drawer the reader used last: for session `id`, or
264
350
  // without one, across all of them (where the reader is). With none active, in every drawer
265
351
  // that shows the session.
266
- const target = s ?? (req.id == null ? lastUsed([...sessions.values()].filter(x => x.attached.size)) ?? [...sessions.values()].find(x => x.attached.size) : undefined)
352
+ const target =
353
+ s ??
354
+ (req.id == null
355
+ ? (lastUsed([...sessions.values()].filter(x => x.attached.size)) ??
356
+ [...sessions.values()].find(x => x.attached.size))
357
+ : undefined)
267
358
  if (!target || typeof req.path !== 'string') return reply({ shown: 0 })
268
359
  const mine = [...target.attached].filter(c => c.viewer && c.viewer === target.active)
269
360
  const to = mine.length ? mine : [...target.attached]
@@ -271,7 +362,9 @@ function handle(conn: Conn, req: Record<string, any>) {
271
362
  for (const c of to) send(c, { t: 'navigate', path: req.path })
272
363
  return reply({ shown: to.length })
273
364
  }
274
- case 'stop': reply({ ok: true }); return void setTimeout(() => quit('asked to stop (whiteboard terminal stop)'), 50)
365
+ case 'stop':
366
+ reply({ ok: true })
367
+ return void setTimeout(() => quit('asked to stop (whiteboard terminal stop)'), 50)
275
368
  case 'attach': {
276
369
  watchers.add(conn)
277
370
  if (req.viewer) conn.viewer = String(req.viewer)
@@ -285,7 +378,8 @@ function handle(conn: Conn, req: Record<string, any>) {
285
378
  sendScreen(conn, s)
286
379
  return
287
380
  }
288
- default: return reply({ error: `unknown request ${req.t}` })
381
+ default:
382
+ return reply({ error: `unknown request ${req.t}` })
289
383
  }
290
384
  }
291
385
 
@@ -302,7 +396,11 @@ const server = net.createServer(socketConn => {
302
396
  buf = ''
303
397
  socketConn.removeAllListeners('data')
304
398
  let req
305
- try { req = JSON.parse(line) } catch { return socketConn.end(JSON.stringify({ error: 'not JSON' }) + '\n') }
399
+ try {
400
+ req = JSON.parse(line)
401
+ } catch {
402
+ return socketConn.end(JSON.stringify({ error: 'not JSON' }) + '\n')
403
+ }
306
404
  handle(conn, req)
307
405
  })
308
406
  })
@@ -311,15 +409,25 @@ const server = net.createServer(socketConn => {
311
409
  try {
312
410
  await new Promise<void>((resolve, reject) => {
313
411
  const probe = net.connect(socket)
314
- probe.on('connect', () => { probe.destroy(); reject(new Error('running')) })
412
+ probe.on('connect', () => {
413
+ probe.destroy()
414
+ reject(new Error('running'))
415
+ })
315
416
  probe.on('error', () => resolve())
316
417
  })
317
- try { fs.unlinkSync(socket) } catch {}
318
- } catch { console.error('terminal host: another host answers on', socket); process.exit(0) }
418
+ try {
419
+ fs.unlinkSync(socket)
420
+ } catch {}
421
+ } catch {
422
+ console.error('terminal host: another host answers on', socket)
423
+ process.exit(0)
424
+ }
319
425
 
320
426
  server.listen(socket, () => {
321
427
  // only its owner may talk to it: the socket runs code
322
- try { fs.chmodSync(socket, 0o600) } catch {}
428
+ try {
429
+ fs.chmodSync(socket, 0o600)
430
+ } catch {}
323
431
  log(`listening on ${socket}`)
324
432
  checkIdle()
325
433
  })