@bigmistqke/whiteboard 0.6.1 → 0.7.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.
- package/README.md +13 -7
- package/dist/bin/whiteboard.js +0 -0
- package/dist/client/runtime.js +235 -58
- package/dist/plugins/badge/README.md +3 -1
- package/dist/plugins/badge/public/style.css +17 -0
- package/dist/plugins/chat/public/client.js +2 -2
- package/dist/plugins/chat/public/style.css +9 -0
- package/dist/plugins/comments/public/client.js +7 -2
- package/dist/plugins/comments/public/style.css +4 -0
- package/dist/plugins/grid/public/style.css +0 -5
- package/dist/plugins/index.js +5 -1
- package/dist/plugins/timeline/README.md +40 -0
- package/dist/plugins/timeline/index.js +82 -0
- package/dist/plugins/timeline/public/style.css +118 -0
- package/dist/plugins/toc/README.md +13 -13
- package/dist/plugins/toc/index.js +5 -3
- package/dist/plugins/toc/public/client.js +1 -1
- package/dist/plugins/toc/public/style.css +19 -2
- package/dist/solid/index.js +2 -1
- package/dist/src/auth.js +7 -3
- package/dist/src/client/page/base.css +74 -35
- package/dist/src/client/page/main.js +15 -4
- package/dist/src/events.js +4 -2
- package/dist/src/hub.js +43 -18
- package/dist/src/serve.js +2 -0
- package/dist/src/server.js +49 -11
- package/dist/src/ws.js +128 -0
- package/package.json +1 -1
- package/plugins/badge/README.md +3 -1
- package/plugins/badge/public/style.css +17 -0
- package/plugins/chat/client.tsx +34 -6
- package/plugins/chat/public/style.css +9 -0
- package/plugins/comments/client.ts +48 -5
- package/plugins/comments/public/style.css +4 -0
- package/plugins/grid/public/style.css +0 -5
- package/plugins/index.ts +6 -1
- package/plugins/timeline/README.md +40 -0
- package/plugins/timeline/index.ts +92 -0
- package/plugins/timeline/public/style.css +118 -0
- package/plugins/toc/README.md +13 -13
- package/plugins/toc/client.ts +49 -30
- package/plugins/toc/index.ts +12 -12
- package/plugins/toc/public/style.css +19 -2
- package/solid/index.tsx +3 -0
- package/src/auth.ts +7 -2
- package/src/client/forms.ts +102 -5
- package/src/client/page/base.css +74 -35
- package/src/client/page/elsewhere.ts +12 -3
- package/src/client/page/waiting.ts +10 -5
- package/src/client/read.ts +16 -3
- package/src/client/runtime.ts +134 -45
- package/src/client/toast.ts +35 -5
- package/src/define.ts +10 -0
- package/src/events.ts +7 -1
- package/src/hub.ts +54 -22
- package/src/serve.ts +2 -0
- package/src/server.ts +73 -17
- package/src/ws.ts +155 -0
package/src/client/runtime.ts
CHANGED
|
@@ -55,27 +55,77 @@ function setEvents(next: WbEvent[]) {
|
|
|
55
55
|
async function loadEvents() {
|
|
56
56
|
if (!live) return
|
|
57
57
|
const res = await fetch(url(`/api/events?page=${encodeURIComponent(page)}`))
|
|
58
|
-
const all: WbEvent[] = await res.json()
|
|
59
|
-
|
|
58
|
+
const all: WbEvent[] = (await res.json()).filter((e: WbEvent) => e.page === page)
|
|
59
|
+
// what is still on its way stays: the log doesn't have it yet
|
|
60
|
+
const known = new Set(all.map(e => e.id))
|
|
61
|
+
for (const [id, e] of sending) if (known.has(id)) sending.delete(id)
|
|
62
|
+
setEvents([...all, ...[...sending.values()]])
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
// Appending is optimistic: the event is in the page's events at once, marked `sending`, so the page
|
|
66
|
+
// shows it without waiting; the server's copy replaces it once it is in the log. Its id is made
|
|
67
|
+
// here and the server keeps it, so a send that heard nothing back can be sent again without
|
|
68
|
+
// appending it twice: it is retried, and only when none goes through is it taken out again and the
|
|
69
|
+
// append fails.
|
|
70
|
+
|
|
71
|
+
/** How long one send may take before it is tried again, in ms; and how many tries in all. */
|
|
72
|
+
const SEND_TIMEOUT = 8_000
|
|
73
|
+
const TRIES = 4
|
|
74
|
+
|
|
75
|
+
/** Events appended here that the server hasn't confirmed: kept in the events when they are loaded. */
|
|
76
|
+
const sending = new Map<string, WbEvent>()
|
|
77
|
+
|
|
78
|
+
/** An id as the server makes them (isEventId): the time in base 36, a dash, random hex. */
|
|
79
|
+
const newId = () =>
|
|
80
|
+
`${Date.now().toString(36)}-${[...crypto.getRandomValues(new Uint8Array(6))].map(b => b.toString(16).padStart(2, '0')).join('')}`
|
|
81
|
+
|
|
62
82
|
async function append(
|
|
63
83
|
type: string,
|
|
64
84
|
data: Record<string, unknown> = {},
|
|
65
85
|
action: string | null = null,
|
|
66
86
|
): Promise<WbEvent> {
|
|
67
87
|
if (!live) throw new Error('a built page is a file: there is no log to append to')
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
})
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
88
|
+
const id = newId()
|
|
89
|
+
const shown: WbEvent = { id, ts: new Date().toISOString(), page, type, action, data, sending: true }
|
|
90
|
+
sending.set(id, shown)
|
|
91
|
+
setEvents([...events, shown])
|
|
92
|
+
const body = JSON.stringify({ id, page, type, action, data })
|
|
93
|
+
let failure: unknown
|
|
94
|
+
for (let attempt = 0; attempt < TRIES; attempt++) {
|
|
95
|
+
if (attempt) await new Promise(r => setTimeout(r, 500 * 2 ** attempt))
|
|
96
|
+
try {
|
|
97
|
+
const res = await fetch(url('/api/events'), {
|
|
98
|
+
method: 'POST',
|
|
99
|
+
headers: { 'content-type': 'application/json' },
|
|
100
|
+
body,
|
|
101
|
+
// never left hanging: a browser holds a request while it has no connection to send it on
|
|
102
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT),
|
|
103
|
+
})
|
|
104
|
+
// refused: sending it again changes nothing
|
|
105
|
+
if (res.status >= 400 && res.status < 500) {
|
|
106
|
+
failure = new Error(await res.text())
|
|
107
|
+
break
|
|
108
|
+
}
|
|
109
|
+
if (!res.ok) throw new Error(await res.text())
|
|
110
|
+
const saved: WbEvent = await res.json()
|
|
111
|
+
sending.delete(id)
|
|
112
|
+
// the server's copy in its place (a load may have brought it already)
|
|
113
|
+
setEvents([...events.filter(e => e.id !== id && e.id !== saved.id), saved].toSorted(byTime))
|
|
114
|
+
return saved
|
|
115
|
+
} catch (err) {
|
|
116
|
+
failure = err
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// the log has it already (a load brought it), though no answer to a send came back
|
|
120
|
+
const arrived = !sending.has(id) && events.find(e => e.id === id && !e.sending)
|
|
121
|
+
if (arrived) return arrived
|
|
122
|
+
sending.delete(id)
|
|
123
|
+
setEvents(events.filter(e => e.id !== id))
|
|
124
|
+
throw failure
|
|
77
125
|
}
|
|
78
126
|
|
|
127
|
+
const byTime = (a: WbEvent, b: WbEvent) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)
|
|
128
|
+
|
|
79
129
|
let listeners: Listener[] = []
|
|
80
130
|
const listenersValue = reactive(() => listeners)
|
|
81
131
|
|
|
@@ -205,54 +255,93 @@ if (!handoff.client)
|
|
|
205
255
|
|
|
206
256
|
// ---- live channel ------------------------------------------------------------------------------
|
|
207
257
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
// nothing still redraws, sorts and scrolls, under the reader's hands
|
|
218
|
-
caughtUp()
|
|
219
|
-
}
|
|
220
|
-
es.onerror = () => {
|
|
221
|
-
delete document.documentElement.dataset.wbLive
|
|
258
|
+
// A WebSocket, not server-sent events: a browser keeps six HTTP/1.1 connections to an origin, and
|
|
259
|
+
// every whiteboard tab is on the same one; one stream per tab left none for a form's answer (see
|
|
260
|
+
// src/ws.ts). A WebSocket doesn't reconnect by itself: this does, sooner at first, then every few
|
|
261
|
+
// seconds, and at once when the tab is shown or the network comes back.
|
|
262
|
+
const reloadWhenUp = async () => {
|
|
263
|
+
try {
|
|
264
|
+
if ((await fetch(url('/api/health'), { cache: 'no-store' })).ok) return location.reload()
|
|
265
|
+
} catch {
|
|
266
|
+
/* not up yet */
|
|
222
267
|
}
|
|
223
|
-
|
|
268
|
+
setTimeout(reloadWhenUp, 500)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** What the server says on the live channel, by its name. */
|
|
272
|
+
const onLive: Record<string, (data: unknown) => void> = {
|
|
273
|
+
change: () => {
|
|
224
274
|
for (const fn of changeListeners) fn()
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
|
|
275
|
+
},
|
|
276
|
+
events: () => loadEvents(),
|
|
277
|
+
listeners: () => loadListeners(),
|
|
278
|
+
// under a shared server: what waits in another project changed (the page's menu of it listens)
|
|
279
|
+
elsewhere: () => document.dispatchEvent(new Event('wb-elsewhere')),
|
|
228
280
|
// browser code changed; the page keeps what matters across a reload itself. Reload only once
|
|
229
281
|
// the server answers: reloading while it restarts would leave the browser's error page, which
|
|
230
282
|
// has nothing left in it to recover with.
|
|
231
|
-
|
|
232
|
-
const go = async () => {
|
|
233
|
-
try {
|
|
234
|
-
if ((await fetch(url('/api/health'), { cache: 'no-store' })).ok) return location.reload()
|
|
235
|
-
} catch {
|
|
236
|
-
/* not up yet */
|
|
237
|
-
}
|
|
238
|
-
setTimeout(go, 500)
|
|
239
|
-
}
|
|
240
|
-
go()
|
|
241
|
-
})
|
|
283
|
+
reload: () => reloadWhenUp(),
|
|
242
284
|
// an agent shows the reader a place on the page
|
|
243
|
-
|
|
244
|
-
const { to } =
|
|
285
|
+
scroll: data => {
|
|
286
|
+
const { to } = data as { to: string }
|
|
245
287
|
if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`)
|
|
246
|
-
}
|
|
247
|
-
|
|
288
|
+
},
|
|
289
|
+
style: () => {
|
|
248
290
|
for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {
|
|
249
291
|
const url = new URL(link.href)
|
|
250
292
|
if (url.origin !== location.origin) continue
|
|
251
293
|
url.searchParams.set('t', String(Date.now()))
|
|
252
294
|
link.href = url.pathname + url.search
|
|
253
295
|
}
|
|
254
|
-
}
|
|
296
|
+
},
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
let socket: WebSocket | null = null
|
|
300
|
+
let retries = 0
|
|
301
|
+
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
|
302
|
+
|
|
303
|
+
function connect() {
|
|
304
|
+
clearTimeout(retryTimer)
|
|
305
|
+
if (socket && socket.readyState <= WebSocket.OPEN) return
|
|
306
|
+
const at = new URL(url(`/api/live?page=${encodeURIComponent(page)}${isDir ? '&dir' : ''}`), location.href)
|
|
307
|
+
at.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
308
|
+
const ws = (socket = new WebSocket(at))
|
|
309
|
+
ws.onopen = () => {
|
|
310
|
+
retries = 0
|
|
311
|
+
document.documentElement.dataset.wbLive = ''
|
|
312
|
+
// after a server restart: who is listening now, and what was answered meanwhile, here and
|
|
313
|
+
// elsewhere
|
|
314
|
+
loadListeners()
|
|
315
|
+
loadEvents()
|
|
316
|
+
document.dispatchEvent(new Event('wb-elsewhere'))
|
|
317
|
+
// and the page, if it changed while the channel wasn't open yet (just after loading, or while
|
|
318
|
+
// the server restarted): that change was never announced. Only then: an update that changes
|
|
319
|
+
// nothing still redraws, sorts and scrolls, under the reader's hands
|
|
320
|
+
caughtUp()
|
|
321
|
+
}
|
|
322
|
+
ws.onmessage = e => {
|
|
323
|
+
let message: { event?: string; data?: unknown }
|
|
324
|
+
try {
|
|
325
|
+
message = JSON.parse(String(e.data))
|
|
326
|
+
} catch {
|
|
327
|
+
return
|
|
328
|
+
}
|
|
329
|
+
if (message.event) onLive[message.event]?.(message.data)
|
|
330
|
+
}
|
|
331
|
+
ws.onclose = () => {
|
|
332
|
+
if (socket !== ws) return
|
|
333
|
+
socket = null
|
|
334
|
+
delete document.documentElement.dataset.wbLive
|
|
335
|
+
retryTimer = setTimeout(connect, Math.min(250 * 2 ** retries++, 5000))
|
|
336
|
+
}
|
|
255
337
|
}
|
|
338
|
+
// back at once: a tab shown again (a browser may have let its connection go), the network back
|
|
339
|
+
document.addEventListener('visibilitychange', () => {
|
|
340
|
+
if (document.visibilityState === 'visible' && !socket) connect()
|
|
341
|
+
})
|
|
342
|
+
addEventListener('online', () => {
|
|
343
|
+
if (!socket) connect()
|
|
344
|
+
})
|
|
256
345
|
|
|
257
346
|
await Promise.all([loadEvents(), loadListeners()])
|
|
258
347
|
if (handoff.client) {
|
package/src/client/toast.ts
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// "↓ new (3)", "Sent, but no agent is listening". One goes after a few seconds, or on a click; one
|
|
4
4
|
// with `ms: 0` stays until closed, and changes its text, or hides and shows again, through what
|
|
5
5
|
// toast() returns. A click runs `onClick` (and closes a toast that goes by itself); `onDismiss`
|
|
6
|
-
// adds a ✕ that runs it and closes the toast.
|
|
6
|
+
// adds a ✕ that runs it and closes the toast. A toast stays short: what more there is to say goes in
|
|
7
|
+
// `details`, which a ▸ unfolds under it; unfolded, it doesn't go by itself until folded again. Their look is the core's (server.ts), in the page's
|
|
7
8
|
// theme colours.
|
|
8
9
|
import type { Toast, ToastOptions } from '../define.ts'
|
|
9
10
|
|
|
@@ -21,9 +22,14 @@ function place(corner: HTMLElement) {
|
|
|
21
22
|
export function createToast(corner: () => HTMLElement) {
|
|
22
23
|
return function toast(
|
|
23
24
|
text: string,
|
|
24
|
-
{ kind = 'info', ms = 7000, onClick, onDismiss, name, order = 0 }: ToastOptions = {},
|
|
25
|
+
{ kind = 'info', ms = 7000, onClick, onDismiss, name, order = 0, details }: ToastOptions = {},
|
|
25
26
|
): Toast {
|
|
26
27
|
const el = document.createElement('button')
|
|
28
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
29
|
+
const close = () => {
|
|
30
|
+
clearTimeout(timer)
|
|
31
|
+
el.remove()
|
|
32
|
+
}
|
|
27
33
|
el.type = 'button'
|
|
28
34
|
el.className = 'wb-toast'
|
|
29
35
|
el.dataset.kind = kind
|
|
@@ -33,6 +39,28 @@ export function createToast(corner: () => HTMLElement) {
|
|
|
33
39
|
label.className = 'wb-toast-text'
|
|
34
40
|
label.textContent = text
|
|
35
41
|
el.append(label)
|
|
42
|
+
let more: HTMLElement | null = null
|
|
43
|
+
let detail: HTMLElement | null = null
|
|
44
|
+
if (details) {
|
|
45
|
+
more = document.createElement('span')
|
|
46
|
+
more.className = 'wb-toast-more'
|
|
47
|
+
detail = document.createElement('span')
|
|
48
|
+
detail.className = 'wb-toast-details'
|
|
49
|
+
detail.textContent = details
|
|
50
|
+
// read out with the toast, folded or not
|
|
51
|
+
el.setAttribute('aria-description', details)
|
|
52
|
+
el.append(more, detail)
|
|
53
|
+
fold(false)
|
|
54
|
+
}
|
|
55
|
+
function fold(open: boolean) {
|
|
56
|
+
el.toggleAttribute('data-open', open)
|
|
57
|
+
detail!.hidden = !open
|
|
58
|
+
more!.textContent = open ? '▾' : '▸'
|
|
59
|
+
more!.title = open ? 'Less' : 'More'
|
|
60
|
+
// being read: it stays; folded again, it goes as it would have
|
|
61
|
+
clearTimeout(timer)
|
|
62
|
+
if (!open && ms) timer = setTimeout(close, ms)
|
|
63
|
+
}
|
|
36
64
|
if (onDismiss) {
|
|
37
65
|
const x = document.createElement('span')
|
|
38
66
|
x.className = 'wb-toast-dismiss'
|
|
@@ -40,17 +68,19 @@ export function createToast(corner: () => HTMLElement) {
|
|
|
40
68
|
x.title = x.ariaLabel = 'Dismiss'
|
|
41
69
|
el.append(x)
|
|
42
70
|
}
|
|
43
|
-
const close = () => el.remove()
|
|
44
71
|
el.addEventListener('click', e => {
|
|
45
|
-
|
|
72
|
+
const target = e.target as HTMLElement
|
|
73
|
+
if (onDismiss && target.closest('.wb-toast-dismiss')) {
|
|
46
74
|
close()
|
|
47
75
|
onDismiss()
|
|
48
76
|
return
|
|
49
77
|
}
|
|
78
|
+
// the ▸, or the details themselves: fold or unfold, nothing else
|
|
79
|
+
if (details && target.closest('.wb-toast-more, .wb-toast-details')) return fold(!el.hasAttribute('data-open'))
|
|
50
80
|
if (ms) close()
|
|
51
81
|
onClick?.()
|
|
52
82
|
})
|
|
53
|
-
if (ms) setTimeout(close, ms)
|
|
83
|
+
if (ms && !details) timer = setTimeout(close, ms)
|
|
54
84
|
place(corner()).append(el)
|
|
55
85
|
return {
|
|
56
86
|
close,
|
package/src/define.ts
CHANGED
|
@@ -479,6 +479,11 @@ export interface WbEvent {
|
|
|
479
479
|
from?: 'cli'
|
|
480
480
|
/** in the browser: an agent has picked this event up (`whiteboard wait` or `watch` handed it out) */
|
|
481
481
|
pickedUp?: true
|
|
482
|
+
/**
|
|
483
|
+
* in the browser: appended here and shown at once, but the server hasn't confirmed it yet. Show
|
|
484
|
+
* it as on its way ("sending…"), not as done. Should it fail, it leaves the events again.
|
|
485
|
+
*/
|
|
486
|
+
sending?: true
|
|
482
487
|
}
|
|
483
488
|
|
|
484
489
|
/**
|
|
@@ -511,6 +516,11 @@ export interface ToastOptions {
|
|
|
511
516
|
name?: string
|
|
512
517
|
/** where it is among the corner's toasts: lower first (default 0) */
|
|
513
518
|
order?: number
|
|
519
|
+
/**
|
|
520
|
+
* more about it, for whoever wants to know: the toast stays a short line, with a ▸ that unfolds
|
|
521
|
+
* this under it (and keeps it open while it is read). Keep `text` a few words, and put the why here.
|
|
522
|
+
*/
|
|
523
|
+
details?: string
|
|
514
524
|
}
|
|
515
525
|
|
|
516
526
|
/** A toast on the screen: change what it says (a count), hide it and show it again, or close it. */
|
package/src/events.ts
CHANGED
|
@@ -15,6 +15,8 @@ export { fromReader }
|
|
|
15
15
|
|
|
16
16
|
/** What is appended: the id and time are added. */
|
|
17
17
|
export interface EventInput {
|
|
18
|
+
/** the id the browser gave it, so a send it retries is appended once (see isEventId); else a new one */
|
|
19
|
+
id?: unknown
|
|
18
20
|
page?: unknown
|
|
19
21
|
type?: unknown
|
|
20
22
|
action?: string | null
|
|
@@ -37,6 +39,10 @@ export const CLAIM = 'whiteboard:claim'
|
|
|
37
39
|
|
|
38
40
|
// ---- primitives ----------------------------------------------------------------------------------
|
|
39
41
|
|
|
42
|
+
/** An event id as the log has them: the time in base 36, a dash, random hex. */
|
|
43
|
+
export const isEventId = (id: unknown): id is string =>
|
|
44
|
+
typeof id === 'string' && /^[0-9a-z]{6,12}-[0-9a-f]{6,32}$/.test(id)
|
|
45
|
+
|
|
40
46
|
/**
|
|
41
47
|
* Append one event; `action` is the button that submitted a form, null for anything else. `from`
|
|
42
48
|
* is set only for events the command line writes ('cli'), so that waits skip them and pages can
|
|
@@ -44,7 +50,7 @@ export const CLAIM = 'whiteboard:claim'
|
|
|
44
50
|
*/
|
|
45
51
|
export function appendEvent(file: string, input: EventInput, from: 'cli' | null = null): WbEvent {
|
|
46
52
|
const event: WbEvent = {
|
|
47
|
-
id: `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
|
|
53
|
+
id: isEventId(input.id) ? input.id : `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
|
|
48
54
|
ts: new Date().toISOString(),
|
|
49
55
|
page: String(input.page ?? ''),
|
|
50
56
|
type: String(input.type ?? ''),
|
package/src/hub.ts
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import fs from 'node:fs'
|
|
21
21
|
import path from 'node:path'
|
|
22
22
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
23
|
+
import type { Duplex } from 'node:stream'
|
|
23
24
|
import { project as projectAt, type Project } from './config.ts'
|
|
24
25
|
import { followEntries, machineDir, readMachineConfig, stateDir, type EntryProject } from './entries.ts'
|
|
25
26
|
import { compareVersions, VERSION } from './package.ts'
|
|
@@ -82,6 +83,8 @@ export interface IndexProject {
|
|
|
82
83
|
|
|
83
84
|
export interface Hub {
|
|
84
85
|
handle(req: IncomingMessage, res: ServerResponse): Promise<void>
|
|
86
|
+
/** an upgrade request (the HTTP server's 'upgrade' event): a page's live channel */
|
|
87
|
+
upgrade(req: IncomingMessage, conn: Duplex, head: Buffer): void
|
|
85
88
|
/** the projects it serves now */
|
|
86
89
|
projects(): EntryProject[]
|
|
87
90
|
/** look for projects coming and going now */
|
|
@@ -119,7 +122,7 @@ export function createHub({
|
|
|
119
122
|
base: p.base,
|
|
120
123
|
entry: p.entry,
|
|
121
124
|
label: [p.group, p.name].filter(Boolean).join(' › '),
|
|
122
|
-
onChange: () =>
|
|
125
|
+
onChange: () => changed(p.base),
|
|
123
126
|
})
|
|
124
127
|
const fallback = fallbacks.get(p.entry)
|
|
125
128
|
served.set(key, { ...p, project, server, ...(fallback && { fallback: server.addListener(fallback) }) })
|
|
@@ -153,9 +156,21 @@ export function createHub({
|
|
|
153
156
|
})
|
|
154
157
|
// what the overview lists changed: told a moment later, once for several changes
|
|
155
158
|
let touching: ReturnType<typeof setTimeout> | undefined
|
|
159
|
+
// the projects that changed since: each other project's open pages are told, for their menu of
|
|
160
|
+
// what waits elsewhere (pushed, so no page has to ask every project now and then)
|
|
161
|
+
const changes = new Set<string>()
|
|
156
162
|
const touch = () => {
|
|
157
163
|
clearTimeout(touching)
|
|
158
|
-
touching = setTimeout(() =>
|
|
164
|
+
touching = setTimeout(() => {
|
|
165
|
+
root.touch()
|
|
166
|
+
const from = [...changes]
|
|
167
|
+
changes.clear()
|
|
168
|
+
for (const s of served.values()) if (from.some(b => b !== s.base)) s.server.elsewhere()
|
|
169
|
+
}, 150)
|
|
170
|
+
}
|
|
171
|
+
const changed = (base: string) => {
|
|
172
|
+
changes.add(base)
|
|
173
|
+
touch()
|
|
159
174
|
}
|
|
160
175
|
|
|
161
176
|
const entries = followEntries(() => readMachineConfig(dir), sync, { interval, home })
|
|
@@ -258,33 +273,49 @@ export function createHub({
|
|
|
258
273
|
res.writeHead(204)
|
|
259
274
|
return void res.end()
|
|
260
275
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
if (s) {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
res.writeHead(302, { location: `${s.base}/${url.search}` })
|
|
267
|
-
return void res.end()
|
|
268
|
-
}
|
|
269
|
-
// the path less the project's part, encoded again for the project's server to decode
|
|
270
|
-
rest = p.slice(s.base.length).split('/').map(encodeURIComponent).join('/') + url.search
|
|
271
|
-
} else {
|
|
272
|
-
// A plugin's browser module that writes `/api/<name>/…` itself, from before api.url: the page
|
|
273
|
-
// that asked is in the Referer, and the request is that project's.
|
|
274
|
-
const from = req.headers.referer ? new URL(req.headers.referer).pathname : null
|
|
275
|
-
s = /^\/(api|_)\//.test(p) && from ? owner(decodeURIComponent(from)) : null
|
|
276
|
-
// anything else outside the projects is the overview's: /, its page, its files and live channel
|
|
277
|
-
if (!s) return root.handle(req, res)
|
|
278
|
-
rest = (req.url ?? '/').replace(/^\/+/, '/')
|
|
276
|
+
// the project's overview is at its folder: /rg/develop/
|
|
277
|
+
const s = owner(p)
|
|
278
|
+
if (s && p === s.base) {
|
|
279
|
+
res.writeHead(302, { location: `${s.base}/${url.search}` })
|
|
280
|
+
return void res.end()
|
|
279
281
|
}
|
|
280
|
-
req.
|
|
281
|
-
return s.server.handle(req, res)
|
|
282
|
+
return route(req, p, url).handle(req, res)
|
|
282
283
|
} catch (err) {
|
|
283
284
|
console.error(err)
|
|
284
285
|
send(res, 500, String((err as Error)?.stack || err), 'text/plain')
|
|
285
286
|
}
|
|
286
287
|
}
|
|
287
288
|
|
|
289
|
+
/**
|
|
290
|
+
* Whose request this is: a project's (`req.url` made the path within it), or else the overview's.
|
|
291
|
+
*/
|
|
292
|
+
function route(req: IncomingMessage, p: string, url: URL): WhiteboardServer {
|
|
293
|
+
let s = owner(p)
|
|
294
|
+
if (s) {
|
|
295
|
+
// the path less the project's part, encoded again for the project's server to decode
|
|
296
|
+
req.url = p.slice(s.base.length).split('/').map(encodeURIComponent).join('/') + url.search
|
|
297
|
+
return s.server
|
|
298
|
+
}
|
|
299
|
+
// A plugin's browser module that writes `/api/<name>/…` itself, from before api.url: the page
|
|
300
|
+
// that asked is in the Referer, and the request is that project's.
|
|
301
|
+
const from = req.headers.referer ? new URL(req.headers.referer).pathname : null
|
|
302
|
+
s = /^\/(api|_)\//.test(p) && from ? owner(decodeURIComponent(from)) : null
|
|
303
|
+
req.url = s ? (req.url ?? '/').replace(/^\/+/, '/') : req.url
|
|
304
|
+
// anything else outside the projects is the overview's: /, its page, its files and live channel
|
|
305
|
+
return s ? s.server : root
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** An upgrade (a page's live channel), routed as a request is. */
|
|
309
|
+
function upgrade(req: IncomingMessage, conn: Duplex, head: Buffer) {
|
|
310
|
+
try {
|
|
311
|
+
const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
|
|
312
|
+
route(req, decodeURIComponent(url.pathname), url).upgrade(req, conn, head)
|
|
313
|
+
} catch (err) {
|
|
314
|
+
console.error(err)
|
|
315
|
+
conn.destroy()
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
288
319
|
/**
|
|
289
320
|
* The fallback of a whole entry (a `wait` or `watch` without --page in one of its projects): one
|
|
290
321
|
* per entry, refused (409) while another runs, or while a project of it has a fallback of its own
|
|
@@ -330,6 +361,7 @@ export function createHub({
|
|
|
330
361
|
|
|
331
362
|
return {
|
|
332
363
|
handle,
|
|
364
|
+
upgrade,
|
|
333
365
|
projects: list,
|
|
334
366
|
rescan() {
|
|
335
367
|
entries.rescan()
|
package/src/serve.ts
CHANGED
|
@@ -25,6 +25,7 @@ export async function start(project: Project): Promise<number> {
|
|
|
25
25
|
const server = http.createServer((req, res) => {
|
|
26
26
|
void wb.handle(req, res)
|
|
27
27
|
})
|
|
28
|
+
server.on('upgrade', (req, conn, head) => wb.upgrade(req, conn, head))
|
|
28
29
|
const candidates = [
|
|
29
30
|
...new Set(
|
|
30
31
|
[recordedPort(project), DEFAULT_PORT, ...Array.from({ length: 50 }, (_, i) => DEFAULT_PORT + 1 + i)].filter(
|
|
@@ -100,6 +101,7 @@ export async function startShared(dir = machineDir(), state = stateDir()): Promi
|
|
|
100
101
|
const server = http.createServer((req, res) => {
|
|
101
102
|
void hub.handle(req, res)
|
|
102
103
|
})
|
|
104
|
+
server.on('upgrade', (req, conn, head) => hub.upgrade(req, conn, head))
|
|
103
105
|
const first = config.port ?? DEFAULT_PORT
|
|
104
106
|
const candidates = [
|
|
105
107
|
...new Set(
|