@bigmistqke/whiteboard 0.4.0 → 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 (50) hide show
  1. package/README.md +55 -4
  2. package/bin/whiteboard.ts +32 -0
  3. package/dist/bin/whiteboard.js +21 -0
  4. package/dist/client/runtime.js +44 -13
  5. package/dist/plugins/draft/README.md +14 -0
  6. package/dist/plugins/draft/index.js +21 -0
  7. package/dist/plugins/draft/public/style.css +21 -0
  8. package/dist/plugins/index.js +5 -1
  9. package/dist/plugins/steps/README.md +42 -0
  10. package/dist/plugins/steps/index.js +99 -0
  11. package/dist/plugins/steps/public/client.js +1 -0
  12. package/dist/plugins/steps/public/style.css +77 -0
  13. package/dist/plugins/terminal/host.js +9 -3
  14. package/dist/plugins/terminal/sizes.js +2 -1
  15. package/dist/plugins/toc/README.md +21 -3
  16. package/dist/plugins/toc/index.js +8 -2
  17. package/dist/plugins/toc/public/client.js +1 -1
  18. package/dist/plugins/toc/public/style.css +10 -4
  19. package/dist/src/auth.js +2 -1
  20. package/dist/src/client/page/main.js +14 -6
  21. package/dist/src/loader.js +8 -2
  22. package/dist/src/pages/render.js +42 -15
  23. package/dist/src/pages/window.js +3 -2
  24. package/dist/src/server.js +216 -10
  25. package/package.json +3 -2
  26. package/plugins/code/index.ts +3 -1
  27. package/plugins/draft/README.md +14 -0
  28. package/plugins/draft/index.ts +23 -0
  29. package/plugins/draft/public/style.css +21 -0
  30. package/plugins/index.ts +4 -0
  31. package/plugins/mermaid/index.ts +4 -2
  32. package/plugins/steps/README.md +42 -0
  33. package/plugins/steps/client.ts +66 -0
  34. package/plugins/steps/index.ts +127 -0
  35. package/plugins/steps/public/style.css +77 -0
  36. package/plugins/terminal/host.ts +12 -6
  37. package/plugins/terminal/sizes.ts +3 -1
  38. package/plugins/toc/README.md +21 -3
  39. package/plugins/toc/client.ts +47 -6
  40. package/plugins/toc/index.ts +19 -6
  41. package/plugins/toc/public/style.css +10 -4
  42. package/src/auth.ts +3 -2
  43. package/src/client/page/main.ts +18 -6
  44. package/src/client/runtime.ts +51 -16
  45. package/src/define.ts +60 -12
  46. package/src/loader.ts +7 -2
  47. package/src/pages/index.ts +2 -2
  48. package/src/pages/render.ts +48 -16
  49. package/src/pages/window.ts +8 -1
  50. package/src/server.ts +253 -13
package/src/server.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  // text.
18
18
  import type { IncomingMessage, ServerResponse } from 'node:http'
19
19
  import fs from 'node:fs'
20
+ import { parse as parseYaml } from 'yaml'
20
21
  import { stripTypeScriptTypes } from 'node:module'
21
22
  import path from 'node:path'
22
23
  import type { Project } from './config.ts'
@@ -38,6 +39,7 @@ import type {
38
39
  Rendered,
39
40
  StoredPage,
40
41
  PagesSource,
42
+ BuildConfig,
41
43
  } from './define.ts'
42
44
 
43
45
  const ENGINE_DIR = PACKAGE_DIR
@@ -70,7 +72,7 @@ const MIME: Record<string, string> = {
70
72
  // files in .whiteboard/ that are the server's own bookkeeping, not content
71
73
  const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
72
74
  const SKIP_DIRS = new Set(['node_modules', '.git'])
73
- // a page's frontmatter: `---` lines around `key: value` lines, at the very start
75
+ // a page's frontmatter: YAML between `---` lines, at the very start
74
76
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
75
77
 
76
78
  /** A project's server: its request handler, and what it knows. */
@@ -81,10 +83,21 @@ export interface WhiteboardServer {
81
83
  status(page?: string | null): Promise<PageStatus[]>
82
84
  /** the project's config, loaded */
83
85
  config(): Promise<LoadedConfig>
86
+ /** a static site of some pages (`whiteboard build`); options over the config's `build` */
87
+ build(options?: BuildConfig): Promise<BuildResult>
84
88
  /** stop watching and end the live connections; the server answers nothing after */
85
89
  close(): void
86
90
  }
87
91
 
92
+ export interface BuildResult {
93
+ /** the folder the site is in */
94
+ out: string
95
+ /** each page, and the file it became */
96
+ pages: { file: string; to: string }[]
97
+ /** what didn't fit: a link to a page outside the build, no index.html */
98
+ warnings: string[]
99
+ }
100
+
88
101
  export function createServer(project: Project): WhiteboardServer {
89
102
  const loader = createConfigLoader(project)
90
103
  const auth = createAuth(project.wb)
@@ -251,15 +264,20 @@ export function createServer(project: Project): WhiteboardServer {
251
264
 
252
265
  const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
253
266
 
254
- function frontmatter(source: string): Record<string, string> {
267
+ /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
268
+ function frontmatter(source: string): { data: Record<string, unknown>; error: string | null } {
255
269
  const m = FRONTMATTER.exec(source)
256
- const out: Record<string, string> = {}
257
- if (m)
258
- for (const line of m[1]!.split(/\r?\n/)) {
259
- const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line)
260
- if (kv) out[kv[1]!] = kv[2]!.trim().replace(/^["']|["']$/g, '')
261
- }
262
- return out
270
+ if (!m) return { data: {}, error: null }
271
+ let data: unknown
272
+ try {
273
+ data = parseYaml(m[1]!)
274
+ } catch (err) {
275
+ return { data: {}, error: (err as Error).message }
276
+ }
277
+ if (data == null) return { data: {}, error: null }
278
+ if (typeof data !== 'object' || Array.isArray(data))
279
+ return { data: {}, error: 'it must be fields (`key: value` lines), not a single value or a list' }
280
+ return { data: data as Record<string, unknown>, error: null }
263
281
  }
264
282
 
265
283
  function pageSource(id: string, file: string): PageSource {
@@ -271,7 +289,7 @@ export function createServer(project: Project): WhiteboardServer {
271
289
  mtime: fs.statSync(file).mtimeMs,
272
290
  source,
273
291
  body: source.replace(FRONTMATTER, ''),
274
- frontmatter: frontmatter(source),
292
+ ...(({ data, error }) => ({ frontmatter: data, frontmatterError: error }))(frontmatter(source)),
275
293
  }
276
294
  }
277
295
 
@@ -400,12 +418,13 @@ export function createServer(project: Project): WhiteboardServer {
400
418
  }
401
419
 
402
420
  /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
403
- const frontmatterOf = (page: StoredPage): Record<string, string> => (page.kind === 'page' ? page.frontmatter : {})
421
+ const frontmatterOf = (page: StoredPage): Record<string, unknown> => (page.kind === 'page' ? page.frontmatter : {})
404
422
 
405
423
  /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
406
424
  async function render(page: StoredPage): Promise<Render> {
407
425
  const { pages, errors } = await config()
408
426
  const notices = errors.map(e => `config: ${(e as Error).message}`)
427
+ if (page.kind === 'page' && page.frontmatterError) notices.push(`frontmatter: ${page.frontmatterError}`)
409
428
  let out: Rendered
410
429
  let rendered = !!pages
411
430
  try {
@@ -516,11 +535,14 @@ export function createServer(project: Project): WhiteboardServer {
516
535
  page: StoredPage,
517
536
  { page: rendered, out, notices }: Render,
518
537
  extras: Extras = { head: [], body: [], clients: [] },
538
+ /** a built page (`whiteboard build`): its files as the build names them, and no server behind it */
539
+ built?: { asset(ref: string | URL): string },
519
540
  ): string {
520
541
  const handoff = {
521
542
  id: page.id,
522
543
  kind: page.kind,
523
- client: rendered ? asset(PAGE_CLIENT) : null,
544
+ live: !built,
545
+ client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
524
546
  data: out.data ?? null,
525
547
  frontmatter: frontmatterOf(page),
526
548
  plugins: extras.clients,
@@ -546,7 +568,7 @@ export function createServer(project: Project): WhiteboardServer {
546
568
  <script type="application/json" id="wb-page">
547
569
  ${raw(json(handoff))}
548
570
  </script>
549
- <script type="module" src="/_/runtime.js"></script>
571
+ <script type="module" src="${built ? built.asset(RUNTIME) : '/_/runtime.js'}"></script>
550
572
  ${extras.body}
551
573
  </body>
552
574
  </html>`,
@@ -917,10 +939,228 @@ export function createServer(project: Project): WhiteboardServer {
917
939
  }
918
940
  }
919
941
 
942
+ // ---- build: a static site ---------------------------------------------------------------------
943
+ // Pages rendered once (`whiteboard build`), as files: each page's HTML with its links relative, and
944
+ // what it loads copied beside it. See BuildConfig.
945
+
946
+ /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
947
+ const BUILD_SKIP = ['form', 'chat', 'comments', 'draft']
948
+ /** In the folder a build writes, so that a next build knows it may replace it. */
949
+ const BUILD_MARK = '.whiteboard-build'
950
+
951
+ async function build(options: BuildConfig = {}): Promise<BuildResult> {
952
+ const cfg = await config()
953
+ if (cfg.errors.length) throw new Error(`the config failed to load: ${(cfg.errors[0] as Error).message}`)
954
+ if (!cfg.pages) throw new Error('the config has no pages renderer')
955
+ const pages = cfg.pages
956
+ const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
957
+ const patterns = defined(options.pages, cfg.build.pages) ?? []
958
+ const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
959
+ const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
960
+ if (!patterns.length)
961
+ throw new Error(
962
+ "nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
963
+ )
964
+ const warnings: string[] = []
965
+
966
+ // the pages: markdown files the globs match, but those a `!` glob leaves out
967
+ const include = patterns.filter(p => !p.startsWith('!'))
968
+ const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
969
+ const files = [
970
+ ...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
971
+ ]
972
+ .filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
973
+ .filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
974
+ .sort()
975
+ if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
976
+ // each at its place below the folder they share; a README or index is its folder's index.html
977
+ const base = files.map(path.dirname).reduce((a, b) => {
978
+ while (!within(b, a)) a = path.dirname(a)
979
+ return a
980
+ })
981
+ const outOf = (file: string) => {
982
+ const rel = path.relative(base, file)
983
+ return path.join(
984
+ outDir,
985
+ /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
986
+ ? path.join(path.dirname(rel), 'index.html')
987
+ : rel.replace(/\.(md|markdown)$/i, '.html'),
988
+ )
989
+ }
990
+ const built = new Map(files.map(f => [f, outOf(f)]))
991
+
992
+ // the folder it writes: new, empty, or what an earlier build wrote
993
+ if (fs.existsSync(outDir)) {
994
+ if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK)))
995
+ throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`)
996
+ fs.rmSync(outDir, { recursive: true })
997
+ }
998
+ fs.mkdirSync(outDir, { recursive: true })
999
+ fs.writeFileSync(
1000
+ path.join(outDir, BUILD_MARK),
1001
+ 'written by whiteboard build; the next build replaces this folder\n',
1002
+ )
1003
+
1004
+ // what a page loads, copied once: the package's files under _/whiteboard/, the project's under
1005
+ // _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
1006
+ const copied = new Map<string, string>()
1007
+ function copyAsset(file: string): string {
1008
+ const known = copied.get(file)
1009
+ if (known) return known
1010
+ const rel = within(file, ENGINE_DIR)
1011
+ ? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
1012
+ : within(file, project.dir)
1013
+ ? path.join('_', 'project', path.relative(project.dir, file))
1014
+ : path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
1015
+ const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
1016
+ copied.set(file, dest)
1017
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
1018
+ if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
1019
+ else fs.copyFileSync(file, dest)
1020
+ // a stylesheet's own files (fonts, images), at the same places beside it
1021
+ if (/\.css$/i.test(file)) {
1022
+ for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
1023
+ const ref = m[1]!
1024
+ if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
1025
+ const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
1026
+ if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
1027
+ }
1028
+ }
1029
+ return dest
1030
+ }
1031
+ /** a file beside the pages (an image), copied to its place below the site */
1032
+ function copyBeside(file: string): string | null {
1033
+ if (!within(file, base)) return null
1034
+ const dest = path.join(outDir, path.relative(base, file))
1035
+ if (!fs.existsSync(dest)) {
1036
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
1037
+ fs.copyFileSync(file, dest)
1038
+ }
1039
+ return dest
1040
+ }
1041
+
1042
+ const hooks = await pluginHooks()
1043
+ const result: BuildResult = { out: outDir, pages: [], warnings }
1044
+ for (const [file, dest] of built) {
1045
+ const here = path.dirname(dest)
1046
+ const relTo = (target: string) =>
1047
+ path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
1048
+ const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
1049
+ const urlFor = (abs: string): string | null => {
1050
+ for (const candidate of [abs, abs + '.md']) {
1051
+ if (!fs.existsSync(candidate)) continue
1052
+ if (fs.statSync(candidate).isDirectory()) {
1053
+ const index = [...built.keys()].find(
1054
+ f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
1055
+ )
1056
+ if (index) return relTo(built.get(index)!)
1057
+ continue
1058
+ }
1059
+ if (built.has(candidate)) return relTo(built.get(candidate)!)
1060
+ if (/\.(md|markdown)$/i.test(candidate)) {
1061
+ warnings.push(
1062
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
1063
+ )
1064
+ return null
1065
+ }
1066
+ const copy = copyBeside(candidate)
1067
+ if (copy) return relTo(copy)
1068
+ warnings.push(
1069
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
1070
+ )
1071
+ return null
1072
+ }
1073
+ return null
1074
+ }
1075
+ const id = within(file, project.pagesDir)
1076
+ ? path
1077
+ .relative(project.pagesDir, file)
1078
+ .split(path.sep)
1079
+ .join('/')
1080
+ .replace(/\.(md|markdown)$/i, '')
1081
+ : '-/' + path.relative(project.dir, file).split(path.sep).join('/')
1082
+ const stored = pageSource(id, file)
1083
+ if (stored.frontmatterError)
1084
+ warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
1085
+ const context = {
1086
+ project: { name: project.name, dir: project.dir, files: !!FILES },
1087
+ asset: assetHere,
1088
+ urlFor,
1089
+ live: false,
1090
+ skip,
1091
+ }
1092
+ const rendered = await pages.render(stored, context)
1093
+ // a page without a heading of its own is named by its file (a README by its folder), not by
1094
+ // the id the server knows it by
1095
+ const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
1096
+ ? path.basename(path.dirname(file))
1097
+ : path.basename(file).replace(/\.(md|markdown)$/i, '')
1098
+ const title = !rendered.title || rendered.title === id ? named : rendered.title
1099
+ const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
1100
+ // the plugins' browser modules, but those the build leaves out; not what they add to a live
1101
+ // page's shell (the terminal's drawer): that is the server's
1102
+ const included = hooks.filter(h => !h.error && !skip.has(h.name))
1103
+ const clients = included.filter(h => h.client).map(h => ({ name: h.name, client: assetHere(h.client!) }))
1104
+ // what the plugins add to the shell, asked with no request: no browser asked for this page
1105
+ const parts = await Promise.all(
1106
+ included.map(async h => {
1107
+ try {
1108
+ return (await h.shell?.(null)) ?? null
1109
+ } catch (err) {
1110
+ warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${(err as Error).message}`)
1111
+ return null
1112
+ }
1113
+ }),
1114
+ )
1115
+ const extras = {
1116
+ head: parts.map(x => raw(String(x?.head ?? ''))),
1117
+ body: parts.map(x => raw(String(x?.body ?? ''))),
1118
+ clients,
1119
+ }
1120
+ let doc = shell(stored, { page: true, out, notices: [] }, extras, { asset: assetHere })
1121
+ // a file a plugin named the server's way (its asset URL, /_/file/<path>): its copy
1122
+ doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served: string) => {
1123
+ let file: string
1124
+ try {
1125
+ file = path.resolve(served.split('/').map(decodeURIComponent).join(path.sep))
1126
+ } catch {
1127
+ return all
1128
+ }
1129
+ return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all
1130
+ })
1131
+ // what the blocks name relative to the page (an ::image's src, an iframe's page): copied too
1132
+ doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref: string) => {
1133
+ if (ref.startsWith('/') || ref.startsWith('_/') || ref.startsWith('../')) return all
1134
+ let decoded = ref
1135
+ try {
1136
+ decoded = decodeURIComponent(ref)
1137
+ } catch {
1138
+ /* as written */
1139
+ }
1140
+ const source = path.resolve(path.dirname(file), decoded)
1141
+ if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
1142
+ const target = path.resolve(here, decoded)
1143
+ if (within(target, outDir) && !fs.existsSync(target)) {
1144
+ fs.mkdirSync(path.dirname(target), { recursive: true })
1145
+ fs.copyFileSync(source, target)
1146
+ }
1147
+ }
1148
+ return all
1149
+ })
1150
+ fs.mkdirSync(here, { recursive: true })
1151
+ fs.writeFileSync(dest, doc)
1152
+ result.pages.push({ file, to: dest })
1153
+ }
1154
+ if (![...built.values()].includes(path.join(outDir, 'index.html')))
1155
+ warnings.push('no README.md or index.md in the top folder: the site has no index.html')
1156
+ return result
1157
+ }
1158
+
920
1159
  return {
921
1160
  handle,
922
1161
  status: (page = null) => status(page),
923
1162
  config,
1163
+ build,
924
1164
  close() {
925
1165
  for (const w of watchers) w.close()
926
1166
  watchers.clear()