@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.
- package/LICENSE +21 -0
- package/README.md +609 -2
- package/bin/whiteboard.ts +431 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/whiteboard.js +471 -0
- package/dist/client/runtime.js +391 -0
- package/dist/define.js +7 -0
- package/dist/plugins/callout/README.md +13 -0
- package/dist/plugins/callout/index.js +27 -0
- package/dist/plugins/callout/style.css +12 -0
- package/dist/plugins/chat/README.md +45 -0
- package/dist/plugins/chat/client.js +3 -0
- package/dist/plugins/chat/index.js +46 -0
- package/dist/plugins/chat/style.css +17 -0
- package/dist/plugins/claude-code/index.js +120 -0
- package/dist/plugins/code/README.md +42 -0
- package/dist/plugins/code/diff.js +64 -0
- package/dist/plugins/code/index.js +77 -0
- package/dist/plugins/code/style.css +29 -0
- package/dist/plugins/comments/client.js +10 -0
- package/dist/plugins/comments/index.js +51 -0
- package/dist/plugins/comments/style.css +32 -0
- package/dist/plugins/details/README.md +17 -0
- package/dist/plugins/details/index.js +17 -0
- package/dist/plugins/details/style.css +3 -0
- package/dist/plugins/form/README.md +111 -0
- package/dist/plugins/form/index.js +102 -0
- package/dist/plugins/form/style.css +41 -0
- package/dist/plugins/gallery/README.md +30 -0
- package/dist/plugins/gallery/client.js +1 -0
- package/dist/plugins/gallery/index.js +74 -0
- package/dist/plugins/gallery/style.css +27 -0
- package/dist/plugins/grid/README.md +33 -0
- package/dist/plugins/grid/index.js +33 -0
- package/dist/plugins/grid/style.css +25 -0
- package/dist/plugins/index.js +26 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +34 -0
- package/dist/plugins/mermaid/style.css +16 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +17 -0
- package/dist/plugins/terminal/client.js +41 -0
- package/dist/plugins/terminal/host.js +332 -0
- package/dist/plugins/terminal/index.js +171 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +57 -0
- package/dist/plugins/terminal/style.css +357 -0
- package/dist/solid/index.js +35 -0
- package/dist/src/auth.js +54 -0
- package/dist/src/client/page/base.css +274 -0
- package/dist/src/client/page/main.js +1004 -0
- package/dist/src/config.js +76 -0
- package/dist/src/events.js +162 -0
- package/dist/src/html.js +34 -0
- package/dist/src/load.js +77 -0
- package/dist/src/loader.js +120 -0
- package/dist/src/package.js +33 -0
- package/dist/src/pages/blocks.js +49 -0
- package/dist/src/pages/index.js +14 -0
- package/dist/src/pages/markdown.js +307 -0
- package/dist/src/pages/render.js +257 -0
- package/dist/src/plugins.js +238 -0
- package/dist/src/running.js +24 -0
- package/dist/src/serve.js +71 -0
- package/dist/src/server.js +700 -0
- package/dist/src/status.js +43 -0
- package/package.json +131 -4
- package/plugins/callout/README.md +13 -0
- package/plugins/callout/index.ts +25 -0
- package/plugins/callout/style.css +12 -0
- package/plugins/chat/README.md +45 -0
- package/plugins/chat/autosize.ts +101 -0
- package/plugins/chat/client.tsx +81 -0
- package/plugins/chat/index.ts +61 -0
- package/plugins/chat/style.css +17 -0
- package/plugins/claude-code/index.ts +136 -0
- package/plugins/code/README.md +42 -0
- package/plugins/code/diff.ts +58 -0
- package/plugins/code/index.ts +94 -0
- package/plugins/code/style.css +29 -0
- package/plugins/comments/client.ts +448 -0
- package/plugins/comments/index.ts +52 -0
- package/plugins/comments/style.css +32 -0
- package/plugins/details/README.md +17 -0
- package/plugins/details/index.ts +21 -0
- package/plugins/details/style.css +3 -0
- package/plugins/form/README.md +111 -0
- package/plugins/form/index.ts +104 -0
- package/plugins/form/style.css +41 -0
- package/plugins/gallery/README.md +30 -0
- package/plugins/gallery/client.tsx +64 -0
- package/plugins/gallery/index.ts +67 -0
- package/plugins/gallery/style.css +27 -0
- package/plugins/grid/README.md +33 -0
- package/plugins/grid/index.ts +36 -0
- package/plugins/grid/style.css +25 -0
- package/plugins/index.ts +19 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +39 -0
- package/plugins/mermaid/style.css +16 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +27 -0
- package/plugins/terminal/client.ts +317 -0
- package/plugins/terminal/host.ts +326 -0
- package/plugins/terminal/index.ts +138 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/server.ts +215 -0
- package/plugins/terminal/sizes.ts +60 -0
- package/plugins/terminal/style.css +71 -0
- package/skills/whiteboard/SKILL.md +292 -0
- package/solid/index.tsx +56 -0
- package/src/auth.ts +66 -0
- package/src/client/forms.ts +186 -0
- package/src/client/page/base.css +274 -0
- package/src/client/page/fresh.ts +205 -0
- package/src/client/page/main.ts +249 -0
- package/src/client/page/orphans.ts +46 -0
- package/src/client/page/theme.ts +32 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +109 -0
- package/src/client/runtime.ts +170 -0
- package/src/config.ts +96 -0
- package/src/define.ts +546 -0
- package/src/events.ts +194 -0
- package/src/html.ts +40 -0
- package/src/load.ts +89 -0
- package/src/loader.ts +109 -0
- package/src/package.ts +39 -0
- package/src/pages/blocks.ts +67 -0
- package/src/pages/index.ts +36 -0
- package/src/pages/markdown.ts +276 -0
- package/src/pages/render.ts +196 -0
- package/src/plugins.ts +197 -0
- package/src/running.ts +22 -0
- package/src/serve.ts +52 -0
- package/src/server.ts +644 -0
- package/src/status.ts +69 -0
package/src/plugins.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// Plugins' routes and commands: declared, so the core mounts them under the plugin's name,
|
|
2
|
+
// checks the token and the arguments before a plugin's code runs, and lists them in the help
|
|
3
|
+
// and the docs. Two plugins can't collide: everything a plugin declares lives under its name,
|
|
4
|
+
// and names are unique (and can't be a built-in command).
|
|
5
|
+
//
|
|
6
|
+
// routes: { 'GET /status': { description, auth, query, run } } → GET /api/<plugin>/status
|
|
7
|
+
// commands: { '': { description, args, options, run }, stop: {…} } → whiteboard <plugin> [stop]
|
|
8
|
+
import { parseArgs, type ParseArgsOptionsConfig } from 'node:util'
|
|
9
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
10
|
+
import type { Command, FieldType, Plugin, Route } from './define.ts'
|
|
11
|
+
|
|
12
|
+
/** A route as mounted: its method and full path, and the plugin it is from. */
|
|
13
|
+
export interface MountedRoute {
|
|
14
|
+
method: string
|
|
15
|
+
path: string
|
|
16
|
+
route: Route
|
|
17
|
+
plugin: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A plugin's command as the command line offers it: `whiteboard <plugin> [sub]`. */
|
|
21
|
+
export interface PluginCommand {
|
|
22
|
+
plugin: string
|
|
23
|
+
sub: string
|
|
24
|
+
command: Command
|
|
25
|
+
/** `<plugin> <sub>`, as typed */
|
|
26
|
+
name: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ---- fields --------------------------------------------------------------------------------------
|
|
30
|
+
// The small vocabulary of a route's body and query and a command's options: a type name, `?` for
|
|
31
|
+
// optional.
|
|
32
|
+
|
|
33
|
+
type BaseType = 'string' | 'number' | 'boolean' | 'string[]'
|
|
34
|
+
|
|
35
|
+
const TYPES: Record<BaseType, (v: unknown) => boolean> = {
|
|
36
|
+
string: v => typeof v === 'string',
|
|
37
|
+
number: v => typeof v === 'number' && Number.isFinite(v),
|
|
38
|
+
boolean: v => typeof v === 'boolean',
|
|
39
|
+
'string[]': v => Array.isArray(v) && v.every(x => typeof x === 'string'),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseType(spec: FieldType | string, where: string): { type: BaseType; optional: boolean } {
|
|
43
|
+
const optional = spec.endsWith('?')
|
|
44
|
+
const type = optional ? spec.slice(0, -1) : spec
|
|
45
|
+
if (!(type in TYPES)) throw new Error(`${where}: unknown type "${spec}" (one of ${Object.keys(TYPES).join(', ')}, with ? when optional)`)
|
|
46
|
+
return { type: type as BaseType, optional }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What is wrong with `value` against `spec` ({ name: 'string?' }), or null. Unknown fields are wrong too. */
|
|
50
|
+
function checkFields(spec: Record<string, FieldType> = {}, input: unknown = {}, where: string): string | null {
|
|
51
|
+
if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${where} must be an object`
|
|
52
|
+
const value = input as Record<string, unknown>
|
|
53
|
+
for (const [name, s] of Object.entries(spec)) {
|
|
54
|
+
const { type, optional } = parseType(s, where)
|
|
55
|
+
if (value[name] === undefined) { if (!optional) return `${where}: ${name} is missing`; continue }
|
|
56
|
+
if (!TYPES[type](value[name])) return `${where}: ${name} must be ${type}`
|
|
57
|
+
}
|
|
58
|
+
for (const name of Object.keys(value)) if (!(name in spec)) return `${where}: unknown field ${name}`
|
|
59
|
+
return null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Query strings are text: a number or boolean in the spec is read from it. */
|
|
63
|
+
function fromQuery(spec: Record<string, FieldType> = {}, params: URLSearchParams): Record<string, unknown> {
|
|
64
|
+
const out: Record<string, unknown> = {}
|
|
65
|
+
for (const [name, value] of params) {
|
|
66
|
+
const field = spec[name]
|
|
67
|
+
const type = field ? parseType(field, 'query').type : 'string'
|
|
68
|
+
out[name] = type === 'number' ? Number(value) : type === 'boolean' ? value === 'true' || value === '' : value
|
|
69
|
+
}
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---- routes ------------------------------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
const ROUTE = /^(GET|POST|PUT|PATCH|DELETE) (\/[\w\-/]*)$/
|
|
76
|
+
|
|
77
|
+
/** A plugin's routes, checked and mounted under /api/<name>/. Throws on a malformed one. */
|
|
78
|
+
export function mountRoutes(name: string, routes: Record<string, Route> = {}): MountedRoute[] {
|
|
79
|
+
const table: MountedRoute[] = []
|
|
80
|
+
for (const [key, route] of Object.entries(routes)) {
|
|
81
|
+
const m = ROUTE.exec(key)
|
|
82
|
+
if (!m) throw new Error(`plugin ${name}: route "${key}" must look like "GET /path"`)
|
|
83
|
+
if (typeof route?.run !== 'function') throw new Error(`plugin ${name}: route "${key}" has no run function`)
|
|
84
|
+
for (const [field, spec] of Object.entries({ ...route.body, ...route.query })) parseType(spec, `plugin ${name}, route "${key}", ${field}`)
|
|
85
|
+
const [, method, at] = m as unknown as [string, string, string]
|
|
86
|
+
const path = `/api/${name}${at === '/' ? '' : at.replace(/\/$/, '')}`
|
|
87
|
+
if (table.some(r => r.method === method && r.path === path)) throw new Error(`plugin ${name}: route "${key}" is declared twice`)
|
|
88
|
+
table.push({ method, path, route, plugin: name })
|
|
89
|
+
}
|
|
90
|
+
return table
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function readJson(req: IncomingMessage): Promise<unknown> {
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
let body = ''
|
|
96
|
+
req.on('data', (c: Buffer) => { body += c; if (body.length > 1e6) { reject(new Error('body too large')); req.destroy() } })
|
|
97
|
+
req.on('end', () => { try { resolve(body ? JSON.parse(body) : {}) } catch { reject(new Error('the body is not JSON')) } })
|
|
98
|
+
req.on('error', reject)
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const json = (res: ServerResponse, status: number, data: unknown) => {
|
|
103
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
|
|
104
|
+
res.end(JSON.stringify(data))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Answer a request with the route it matches: false when none does. The core checks the token
|
|
109
|
+
* (`auth`), the query and the body before the route's code runs. A route returns what is sent as
|
|
110
|
+
* JSON; a stream route (`stream: true`) writes to `res` itself. An error it throws is sent with its
|
|
111
|
+
* `status` (default 500).
|
|
112
|
+
*/
|
|
113
|
+
export async function dispatch(table: MountedRoute[], req: IncomingMessage, res: ServerResponse, url: URL, authorized: (req: IncomingMessage) => boolean): Promise<boolean> {
|
|
114
|
+
const forPath = table.filter(r => r.path === url.pathname)
|
|
115
|
+
if (!forPath.length) return false
|
|
116
|
+
const hit = forPath.find(r => r.method === req.method)
|
|
117
|
+
if (!hit) { res.setHeader('allow', forPath.map(r => r.method).join(', ')); json(res, 405, { error: `use ${forPath.map(r => r.method).join(' or ')}` }); return true }
|
|
118
|
+
const { route } = hit
|
|
119
|
+
if (route.auth && !authorized(req)) { json(res, 403, { error: 'this needs the project\'s token: open a link from the command line, or send x-whiteboard-token' }); return true }
|
|
120
|
+
try {
|
|
121
|
+
const query = fromQuery(route.query, url.searchParams)
|
|
122
|
+
const queryError = route.query ? checkFields(route.query, query, 'query') : null
|
|
123
|
+
if (queryError) { json(res, 400, { error: queryError }); return true }
|
|
124
|
+
let body: Record<string, unknown> = {}
|
|
125
|
+
if (hit.method !== 'GET' && hit.method !== 'DELETE') {
|
|
126
|
+
const input = await readJson(req)
|
|
127
|
+
const bodyError = checkFields(route.body, input, 'body')
|
|
128
|
+
if (bodyError) { json(res, 400, { error: bodyError }); return true }
|
|
129
|
+
body = input as Record<string, unknown>
|
|
130
|
+
}
|
|
131
|
+
if (route.stream) { await route.run({ body, query, req, res }); return true }
|
|
132
|
+
const out = await route.run({ body, query, req })
|
|
133
|
+
json(res, 200, out ?? { ok: true })
|
|
134
|
+
} catch (err) {
|
|
135
|
+
if (res.headersSent) { res.end(); return true }
|
|
136
|
+
const e = err as { status?: number; message?: string } | null
|
|
137
|
+
json(res, e?.status ?? 500, { error: e?.message ?? String(err) })
|
|
138
|
+
}
|
|
139
|
+
return true
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The routes for the docs: method, path, what it does, what it takes. */
|
|
143
|
+
export const describeRoutes = (table: MountedRoute[]) => table.map(({ method, path, route }) => ({
|
|
144
|
+
method, path, description: route.description ?? '', auth: !!route.auth, stream: !!route.stream,
|
|
145
|
+
body: route.body ?? null, query: route.query ?? null,
|
|
146
|
+
}))
|
|
147
|
+
|
|
148
|
+
// ---- commands ----------------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
/** The commands of a plugin as `whiteboard <name> [sub]`, checked. */
|
|
151
|
+
export function pluginCommands(plugin: Plugin): PluginCommand[] {
|
|
152
|
+
return Object.entries(plugin.commands ?? {}).map(([sub, command]) => {
|
|
153
|
+
const where = `plugin ${plugin.name}, command "${sub}"`
|
|
154
|
+
if (sub && !/^[\w-]+$/.test(sub)) throw new Error(`${where}: use letters, digits, - and _`)
|
|
155
|
+
if (typeof command?.run !== 'function') throw new Error(`${where} has no run function`)
|
|
156
|
+
for (const [name, o] of Object.entries(command.options ?? {})) parseType(o.type, `${where}, option ${name}`)
|
|
157
|
+
return { plugin: plugin.name, sub, command, name: [plugin.name, sub].filter(Boolean).join(' ') }
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** `[page] [--restart] [-- <arguments>]` */
|
|
162
|
+
export function usage(command: Command): string {
|
|
163
|
+
const options = Object.entries(command.options ?? {}).map(([name, o]) => {
|
|
164
|
+
const { type } = parseType(o.type, name)
|
|
165
|
+
return `[--${name}${type === 'boolean' ? '' : ` <${o.value ?? type}>`}]`
|
|
166
|
+
})
|
|
167
|
+
return [command.args ?? '', ...options, command.rest ? `[-- ${command.rest}]` : ''].filter(Boolean).join(' ')
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Parse a command's arguments by its declared options; throws with the usage on a wrong one. What
|
|
172
|
+
* follows `--` is passed on untouched, as `rest`, when the command takes it.
|
|
173
|
+
*/
|
|
174
|
+
export function parseCommandArgs(command: Command, all: string[], name: string) {
|
|
175
|
+
const cut = all.indexOf('--')
|
|
176
|
+
const args = cut < 0 ? all : all.slice(0, cut)
|
|
177
|
+
const rest = cut < 0 ? [] : all.slice(cut + 1)
|
|
178
|
+
if (rest.length && !command.rest) throw new Error(`whiteboard ${name} takes nothing after --\nusage: whiteboard ${name} ${usage(command)}`)
|
|
179
|
+
const options: ParseArgsOptionsConfig = Object.fromEntries(Object.entries(command.options ?? {}).map(([key, o]) => {
|
|
180
|
+
const { type } = parseType(o.type, key)
|
|
181
|
+
return [key, { type: type === 'boolean' ? 'boolean' as const : 'string' as const, ...(o.short ? { short: o.short } : {}) }]
|
|
182
|
+
}))
|
|
183
|
+
let parsed
|
|
184
|
+
try { parsed = parseArgs({ args, options, allowPositionals: true, strict: true }) } catch (err) {
|
|
185
|
+
throw new Error(`${(err as Error).message}\nusage: whiteboard ${name} ${usage(command)}`)
|
|
186
|
+
}
|
|
187
|
+
const values: Record<string, unknown> = { ...parsed.values }
|
|
188
|
+
for (const [key, o] of Object.entries(command.options ?? {})) {
|
|
189
|
+
const { type, optional } = parseType(o.type, key)
|
|
190
|
+
if (values[key] === undefined) { if (!optional && type !== 'boolean') throw new Error(`--${key} is missing\nusage: whiteboard ${name} ${usage(command)}`); continue }
|
|
191
|
+
if (type === 'number') {
|
|
192
|
+
values[key] = Number(values[key])
|
|
193
|
+
if (!Number.isFinite(values[key])) throw new Error(`--${key} must be a number`)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { options: values, positionals: parsed.positionals, rest }
|
|
197
|
+
}
|
package/src/running.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Finding a project's running server: the port in .whiteboard/server.json, checked by asking the
|
|
2
|
+
// server which project it serves (the port may since have been taken by another project's). The
|
|
3
|
+
// command line uses it to reach the server, and a starting server to see whether one runs already.
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import type { Project } from './config.ts'
|
|
6
|
+
|
|
7
|
+
/** The port the last server of this project recorded, or null. */
|
|
8
|
+
export function recordedPort(project: Project): number | null {
|
|
9
|
+
try { return Number(JSON.parse(fs.readFileSync(project.serverFile, 'utf8')).port) || null } catch { return null }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** The base URL of this project's running server, or null. `except`: a process to not count (the asking server itself). */
|
|
13
|
+
export async function runningServer(project: Project, { except }: { except?: number } = {}): Promise<string | null> {
|
|
14
|
+
const port = recordedPort(project)
|
|
15
|
+
if (!port) return null
|
|
16
|
+
const base = `http://localhost:${port}`
|
|
17
|
+
try {
|
|
18
|
+
const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(800) })
|
|
19
|
+
const health = res.ok ? await res.json() : null
|
|
20
|
+
return health?.dir === project.dir && health.pid !== except ? base : null
|
|
21
|
+
} catch { return null }
|
|
22
|
+
}
|
package/src/serve.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Running a project's server as a process of its own (`whiteboard serve`, which `whiteboard show`
|
|
2
|
+
// starts in the background): one server per project, on the port it had last time, else the
|
|
3
|
+
// default, else the next free one, recorded in .whiteboard/server.json so the command line finds it.
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import http from 'node:http'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { DEFAULT_PORT, type Project } from './config.ts'
|
|
8
|
+
import { createServer } from './server.ts'
|
|
9
|
+
import { recordedPort, runningServer } from './running.ts'
|
|
10
|
+
|
|
11
|
+
/** Listen on the previous port, else the default, else the next free one; then record it in server.json. */
|
|
12
|
+
export async function start(project: Project): Promise<number> {
|
|
13
|
+
// one server per project: another may have started a moment ago
|
|
14
|
+
const other = await runningServer(project, { except: process.pid })
|
|
15
|
+
if (other) {
|
|
16
|
+
console.log(`whiteboard: ${project.name} is already served at ${other}`)
|
|
17
|
+
process.exit(0)
|
|
18
|
+
}
|
|
19
|
+
fs.mkdirSync(project.pagesDir, { recursive: true })
|
|
20
|
+
const wb = createServer(project)
|
|
21
|
+
await wb.config()
|
|
22
|
+
const server = http.createServer((req, res) => { void wb.handle(req, res) })
|
|
23
|
+
const candidates = [...new Set([recordedPort(project), DEFAULT_PORT, ...Array.from({ length: 50 }, (_, i) => DEFAULT_PORT + 1 + i)].filter((p): p is number => !!p))]
|
|
24
|
+
for (const port of candidates) {
|
|
25
|
+
const ok = await new Promise<boolean>((resolve, reject) => {
|
|
26
|
+
const onError = (err: NodeJS.ErrnoException) => { server.off('listening', onListening); err.code === 'EADDRINUSE' ? resolve(false) : reject(err) }
|
|
27
|
+
const onListening = () => { server.off('error', onError); resolve(true) }
|
|
28
|
+
server.once('error', onError)
|
|
29
|
+
server.once('listening', onListening)
|
|
30
|
+
server.listen(port, '127.0.0.1')
|
|
31
|
+
})
|
|
32
|
+
if (!ok) continue
|
|
33
|
+
fs.writeFileSync(project.serverFile, JSON.stringify({ port, pid: process.pid }, null, 2) + '\n')
|
|
34
|
+
// the command that started this server waits for it; others can now find it
|
|
35
|
+
try { fs.unlinkSync(path.join(project.wb, 'server.lock')) } catch {}
|
|
36
|
+
const cleanup = () => {
|
|
37
|
+
try { if (JSON.parse(fs.readFileSync(project.serverFile, 'utf8')).pid === process.pid) fs.unlinkSync(project.serverFile) } catch {}
|
|
38
|
+
}
|
|
39
|
+
process.on('exit', cleanup)
|
|
40
|
+
// one server per project: should another have started at the same moment, whichever one
|
|
41
|
+
// server.json names last stays, and the others leave (their clients reconnect to it)
|
|
42
|
+
const yieldToOther = async () => {
|
|
43
|
+
if (await runningServer(project, { except: process.pid })) { console.log('whiteboard: another server of this project took over'); process.exit(0) }
|
|
44
|
+
}
|
|
45
|
+
setTimeout(yieldToOther, 1500).unref()
|
|
46
|
+
setInterval(yieldToOther, 30000).unref()
|
|
47
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.on(signal, () => process.exit(0))
|
|
48
|
+
console.log(`whiteboard: ${project.name} (${project.dir}) at http://localhost:${port}`)
|
|
49
|
+
return port
|
|
50
|
+
}
|
|
51
|
+
throw new Error(`no free port from ${DEFAULT_PORT} to ${DEFAULT_PORT + 50}`)
|
|
52
|
+
}
|