@bigmistqke/workpad 0.0.0-stage → 0.18.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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1509 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1190 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2098 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +211 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +341 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +665 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +588 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +133 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +137 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +238 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +426 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +748 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
@@ -0,0 +1,191 @@
1
+ // A page as the browser gets it: the page's render, the plugins' parts (markup for <head> and
2
+ // <body>, their browser modules, notices of those that failed), and the handoff the browser runtime
3
+ // starts from. Put together here once, for a page the server serves and for one `workpad build`
4
+ // writes; what differs is told: how a file is addressed, whether the page is live, which plugins
5
+ // are left out, where a failing plugin is said.
6
+ import path from 'node:path'
7
+ import type { IncomingMessage } from 'node:http'
8
+ import { html, raw, type Html } from './html.ts'
9
+ import { PACKAGE_DIR } from './package.ts'
10
+ import type { MountedRoute } from './plugins.ts'
11
+ import type { Plugin, PluginHooks, Rendered, SlotName, StoredPage } from './define.ts'
12
+
13
+ /** The browser runtime, built by build.ts. */
14
+ export const RUNTIME = path.join(PACKAGE_DIR, 'dist', 'client', 'runtime.js')
15
+ /** The page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts. */
16
+ export const PAGE_CLIENT = path.join(PACKAGE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
17
+
18
+ /** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
19
+ export interface SetUp extends PluginHooks {
20
+ name: string
21
+ table: MountedRoute[]
22
+ plugin: Plugin
23
+ error?: Error
24
+ }
25
+
26
+ /** A render as the document takes it. `page`: whether the page's browser part runs (not on raw text). */
27
+ export interface Render {
28
+ page: boolean
29
+ out: Rendered
30
+ notices: string[]
31
+ }
32
+
33
+ /** The slots at the end of <body>, in the order they are there; `corner` is the page's dock. */
34
+ const BODY_SLOTS = ['aside', 'bottom', 'overlay'] as const
35
+
36
+ /** A plugin's markup in a slot. */
37
+ type Slotted = { name: string; html: Html }
38
+
39
+ /** What the plugins add to a page. */
40
+ export interface PageParts {
41
+ head: Html[]
42
+ /** each plugin's markup in each slot, in plugin order */
43
+ slots: { [K in Exclude<SlotName, 'header'>]: Slotted[] }
44
+ /** their browser modules, which the runtime imports after the page's */
45
+ clients: { name: string; client: string }[]
46
+ /** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
47
+ messages: string[]
48
+ }
49
+
50
+ /**
51
+ * What the plugins add to a page: each one's markup for the slots (`slots`, asked with the browser's request, or
52
+ * null for a page no browser asked for), and its browser module. One that failed to start or fails
53
+ * here is left out and told to `failed`; so are those in `leaveOut` (a build's skip), silently.
54
+ */
55
+ export async function pluginParts(
56
+ hooks: SetUp[],
57
+ req: IncomingMessage | null,
58
+ {
59
+ asset,
60
+ messages,
61
+ leaveOut = new Set(),
62
+ failed,
63
+ }: {
64
+ asset(ref: string | URL): string
65
+ messages: string[]
66
+ leaveOut?: ReadonlySet<string>
67
+ failed(message: string): void
68
+ },
69
+ ): Promise<PageParts> {
70
+ const included = hooks.filter(h => !leaveOut.has(h.name))
71
+ for (const h of included) if (h.error) failed(`plugin "${h.name}" failed to start: ${h.error.message}`)
72
+ const working = included.filter(h => !h.error)
73
+ const parts = await Promise.all(
74
+ working.map(async h => {
75
+ try {
76
+ return (await h.slots?.(req)) ?? null
77
+ } catch (err) {
78
+ failed(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
79
+ return null
80
+ }
81
+ }),
82
+ )
83
+ const slotted = (slot: Exclude<SlotName, 'header'>): Slotted[] =>
84
+ working.flatMap((h, i) => {
85
+ const markup = parts[i]?.[slot]
86
+ return markup == null ? [] : [{ name: h.name, html: raw(String(markup)) }]
87
+ })
88
+ return {
89
+ head: parts.map(x => raw(String(x?.head ?? ''))),
90
+ slots: {
91
+ aside: slotted('aside'),
92
+ bottom: slotted('bottom'),
93
+ overlay: slotted('overlay'),
94
+ corner: slotted('corner'),
95
+ },
96
+ clients: working.filter(h => h.client).map(h => ({ name: h.name, client: asset(h.client!) })),
97
+ messages,
98
+ }
99
+ }
100
+
101
+ /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
102
+ export const frontmatterOf = (page: StoredPage): Record<string, unknown> =>
103
+ page.kind === 'page' ? page.frontmatter : {}
104
+
105
+ /** JSON made safe inside a <script>. */
106
+ const json = (s: unknown) => JSON.stringify(s).replace(/</g, '\\u003c')
107
+
108
+ // the page's corner (the corner slot): the one thing the core puts on every page, empty, for the
109
+ // page's and the plugins' floating buttons and toasts; above what covers the bottom of the window.
110
+ // Above the page and what floats on it (comment threads: 20), under what fills the window (a
111
+ // maximized frame: 40, a lightbox or the terminal drawer: 50)
112
+ const DOCK_STYLE =
113
+ '#wp-dock{position:fixed;right:16px;bottom:calc(16px + var(--wp-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wp-dock:not(:has(> :not(:empty))){display:none}' +
114
+ // the slots (SlotName) and each plugin's element in one: laid out as what is in them says, as if
115
+ // that were where the slot is (a fixed drawer, a panel, a button in the header bar)
116
+ '[data-wp-slot]:not(#wp-dock),[data-wp-slot]>[data-plugin]{display:contents}' +
117
+ // toasts (api.toast): labels in the corner, in the page's theme colours where it has them
118
+ '.wp-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wp-toasts:empty{display:none}' +
119
+ '.wp-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}' +
120
+ '.wp-toast[hidden]{display:none}.wp-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wp-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}' +
121
+ // where an agent scrolled the page to, lit up a moment
122
+ '@keyframes wp-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wp-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wp-flash 2s ease-out}' +
123
+ '.wp-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wp-toast-dismiss:hover{opacity:1}' +
124
+ // a toast's details (ToastOptions.details): a ▸ on its line, unfolding them under it
125
+ '.wp-toast{max-width:min(24rem,calc(100vw - 32px));text-align:left}.wp-toast-more{margin:0 -4px 0 -2px;padding:0 4px;opacity:.75}.wp-toast-more:hover{opacity:1}' +
126
+ '.wp-toast[data-open]{flex-wrap:wrap;border-radius:12px}.wp-toast-details{flex-basis:100%;padding:2px 0 3px;font-weight:400;cursor:text}.wp-toast-details[hidden]{display:none}'
127
+
128
+ /** How a page is put out: by the server (live) or by a build (a file with no server behind it). */
129
+ export interface Output {
130
+ /** a page the server serves: events, listeners and updates; false for a built page */
131
+ live: boolean
132
+ /** what the page's own requests start with (ServerOptions.base); '' for a built page */
133
+ base: string
134
+ /** the address of a file the page loads */
135
+ asset(ref: string | URL): string
136
+ /** the address of the browser runtime */
137
+ runtime: string
138
+ /** the title when the render has none and the page no id: the project's name */
139
+ title: string
140
+ /** what the browser runs and how it looks, compared again when the live channel is back */
141
+ stamps?: { code: string; style: string }
142
+ }
143
+
144
+ /** Each plugin's own element in a slot, with what it rendered there. */
145
+ const slotted = (list: Slotted[]) => list.map(x => html`<div data-plugin="${x.name}">${x.html}</div>`)
146
+
147
+ /** A page as a document: the render, the plugins' parts, and the handoff for the browser runtime. */
148
+ export function pageDocument(
149
+ page: StoredPage,
150
+ { page: rendered, out, notices }: Render,
151
+ parts: PageParts,
152
+ o: Output,
153
+ ): string {
154
+ const handoff = {
155
+ id: page.id,
156
+ kind: page.kind,
157
+ live: o.live,
158
+ base: o.base,
159
+ client: rendered ? o.asset(PAGE_CLIENT) : null,
160
+ data: out.data ?? null,
161
+ frontmatter: frontmatterOf(page),
162
+ plugins: parts.clients,
163
+ messages: parts.messages,
164
+ ...(o.stamps && { stamps: o.stamps }),
165
+ }
166
+ // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
167
+ return String(
168
+ html`<!doctype html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8" />
172
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
173
+ <title>${out.title || page.id || o.title}</title>
174
+ <style>
175
+ ${DOCK_STYLE}
176
+ </style>
177
+ ${raw(String(out.head ?? ''))}${parts.head}
178
+ </head>
179
+ <body data-page="${page.id}" data-kind="${page.kind}">
180
+ ${notices.map(n => html`<pre class="wp-error" role="alert">${n}</pre>`)}
181
+ <div id="wp-root">${raw(String(out.html))}</div>
182
+ <div id="wp-dock" data-wp-slot="corner">${slotted(parts.slots.corner)}</div>
183
+ <script type="application/json" id="wp-page">
184
+ ${raw(json(handoff))}
185
+ </script>
186
+ <script type="module" src="${o.runtime}"></script>
187
+ ${BODY_SLOTS.map(name => html`<div data-wp-slot="${name}">${slotted(parts.slots[name])}</div>`)}
188
+ </body>
189
+ </html>`,
190
+ )
191
+ }
package/src/entries.ts ADDED
@@ -0,0 +1,352 @@
1
+ // The machine's entries: the projects one shared server serves, found from include and exclude globs
2
+ // in the machine config (`config.json` in the machine folder, see machineDir).
3
+ //
4
+ // { "port": 4777,
5
+ // "entries": { "rg": {
6
+ // "include": ["~/rg/develop", "~/rg/develop/.claude/worktrees/*", "~/rg/worksite/jobs/*"],
7
+ // "exclude": ["~/rg/worksite/archive/**"] } } }
8
+ //
9
+ // Every folder an include matches, that no exclude matches and that has a `.workpad/` folder, is
10
+ // a project of that entry. It is served at /<entry>/<path>/: <path> is the include's last literal
11
+ // folder and what its wildcards matched (`develop`, `worktrees/cmux`, `jobs/2026-11-19-x`), with
12
+ // `-2`, `-3` on a collision. Discovery is a pure function of the config and the disk, so the server
13
+ // runs it again to see projects come and go.
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+
18
+ /** One entry of the machine config: which folders are its projects. */
19
+ export interface EntryConfig {
20
+ include: string[]
21
+ exclude?: string[]
22
+ /**
23
+ * whether its projects serve and watch their own files, when a project's config doesn't say:
24
+ * false watches only `.workpad/` (default: true, as a project's config has it)
25
+ */
26
+ files?: boolean
27
+ }
28
+
29
+ /** The machine config: the shared server's port and its entries. */
30
+ export interface MachineConfig {
31
+ port?: number
32
+ /** the address the servers listen on (see listenHost) */
33
+ host?: string
34
+ /** the origins besides localhost a page may be at, to open its live channel and use its token */
35
+ origins?: string[]
36
+ /** where the shared server is reached, when not at http://localhost:<port> (see serverUrl) */
37
+ url?: string
38
+ entries: Record<string, EntryConfig>
39
+ }
40
+
41
+ /** A project found for an entry: its folder, and the path it is served under (`/rg/develop`). */
42
+ export interface EntryProject {
43
+ entry: string
44
+ /** the include's last plain folder: what kind of checkout it is (`develop`, `worktrees`, `jobs`) */
45
+ group: string
46
+ /** what its wildcards matched (`cmux`); '' for an include without any */
47
+ name: string
48
+ dir: string
49
+ /** the URL path it is served under, without a trailing slash: /<entry>/<path> */
50
+ base: string
51
+ /** its entry's `files`, when the entry sets it */
52
+ files?: boolean
53
+ }
54
+
55
+ /**
56
+ * The machine folder: the machine config, `config.json`. `$WORKPAD_HOME`, else
57
+ * `$XDG_CONFIG_HOME/workpad`, else `~/.config/workpad`. The shared server only reads it: what
58
+ * runs in the server (any project's plugins) must not change which folders it serves, nor how it is
59
+ * started (see Entries in DESIGN.md).
60
+ */
61
+ export function machineDir(env: NodeJS.ProcessEnv = process.env): string {
62
+ if (env.WORKPAD_HOME) return path.resolve(env.WORKPAD_HOME)
63
+ const xdg = env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
64
+ return path.join(xdg, 'workpad')
65
+ }
66
+
67
+ /**
68
+ * The shared server's own folder, which it writes: its record (`server.json`), its log, the lock of
69
+ * a start, and the overview's project. `$WORKPAD_STATE`, else `state/` in `$WORKPAD_HOME`
70
+ * when that is set (a throwaway machine, in tests), else `$XDG_STATE_HOME/workpad`, else
71
+ * `~/.local/state/workpad`.
72
+ */
73
+ export function stateDir(env: NodeJS.ProcessEnv = process.env): string {
74
+ if (env.WORKPAD_STATE) return path.resolve(env.WORKPAD_STATE)
75
+ if (env.WORKPAD_HOME) return path.join(path.resolve(env.WORKPAD_HOME), 'state')
76
+ const xdg = env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state')
77
+ return path.join(xdg, 'workpad')
78
+ }
79
+
80
+ export const machineConfigFile = (dir = machineDir()) => path.join(dir, 'config.json')
81
+ export const machineServerFile = (dir = stateDir()) => path.join(dir, 'server.json')
82
+ export const machineLogFile = (dir = stateDir()) => path.join(dir, 'server.log')
83
+
84
+ const NAME = /^[a-z0-9][a-z0-9._-]*$/i
85
+
86
+ /** An origin as a browser sends it (a scheme, a host, a port: no path), or null. A trailing / is let pass. */
87
+ function asOrigin(value: unknown): string | null {
88
+ if (typeof value !== 'string' || !URL.canParse(value)) return null
89
+ const { origin, protocol } = new URL(value)
90
+ return origin !== 'null' && /^https?:$/.test(protocol) && value.replace(/\/$/, '') === origin ? origin : null
91
+ }
92
+
93
+ // a served path's first part is an entry's name: these are the server's own
94
+ const RESERVED = new Set(['api', '_', '-'])
95
+
96
+ /**
97
+ * The machine config, checked; null when there is none. Throws on one that is malformed, and on one
98
+ * that is there but can't be read (a sandbox without a grant for it), rather than taking it for none.
99
+ */
100
+ export function readMachineConfig(dir = machineDir()): MachineConfig | null {
101
+ const file = machineConfigFile(dir)
102
+ let text: string
103
+ try {
104
+ text = fs.readFileSync(file, 'utf8')
105
+ } catch (err) {
106
+ const code = (err as NodeJS.ErrnoException).code
107
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null
108
+ // there, but not to be read: most likely a sandbox without a grant for it. Taken for absent, a
109
+ // command would start a server of the project's own beside the shared one that serves it
110
+ if (code === 'EPERM' || code === 'EACCES')
111
+ throw new Error(
112
+ `cannot read ${file} (${code}): if this runs in a sandbox, it needs a read grant for ${dir}. Without it, workpad can't tell which server serves this project`,
113
+ )
114
+ throw err
115
+ }
116
+ let raw: any
117
+ try {
118
+ raw = JSON.parse(text)
119
+ } catch (err) {
120
+ throw new Error(`${file}: ${(err as Error).message}`)
121
+ }
122
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${file}: must be an object`)
123
+ const entries: Record<string, EntryConfig> = {}
124
+ for (const [name, e] of Object.entries((raw.entries ?? {}) as Record<string, any>)) {
125
+ if (!NAME.test(name) || RESERVED.has(name))
126
+ throw new Error(`${file}: entry name ${JSON.stringify(name)}: letters, digits, . _ - only, and not api, _ or -`)
127
+ const list = (v: unknown, what: string): string[] => {
128
+ if (v == null) return []
129
+ if (!Array.isArray(v) || v.some(x => typeof x !== 'string'))
130
+ throw new Error(`${file}: entries.${name}.${what} must be a list of globs`)
131
+ return v
132
+ }
133
+ if (e?.files != null && typeof e.files !== 'boolean')
134
+ throw new Error(`${file}: entries.${name}.files must be true or false`)
135
+ entries[name] = {
136
+ include: list(e?.include, 'include'),
137
+ exclude: list(e?.exclude, 'exclude'),
138
+ ...(e?.files != null && { files: e.files as boolean }),
139
+ }
140
+ }
141
+ const port = raw.port == null ? undefined : Number(raw.port)
142
+ if (port !== undefined && !(Number.isInteger(port) && port > 0 && port < 65536))
143
+ throw new Error(`${file}: port must be a port number`)
144
+ if (raw.host != null && (typeof raw.host !== 'string' || !raw.host))
145
+ throw new Error(`${file}: host must be an address to listen on, such as 0.0.0.0`)
146
+ let origins: string[] | undefined
147
+ if (raw.origins != null) {
148
+ const bad = () => new Error(`${file}: origins must be a list of origins, such as ["https://workpad.local"]`)
149
+ if (!Array.isArray(raw.origins)) throw bad()
150
+ origins = []
151
+ for (const o of raw.origins as unknown[]) {
152
+ const origin = asOrigin(o)
153
+ if (!origin) throw bad()
154
+ origins.push(origin)
155
+ }
156
+ }
157
+ const url = raw.url == null ? undefined : asOrigin(raw.url)
158
+ if (url === null)
159
+ throw new Error(`${file}: url must be an http or https address without a path, such as https://workpad.local`)
160
+ return {
161
+ ...(port !== undefined && { port }),
162
+ ...(raw.host != null && { host: raw.host as string }),
163
+ ...(origins && { origins }),
164
+ ...(url && { url }),
165
+ entries,
166
+ }
167
+ }
168
+
169
+ /**
170
+ * The address a server listens on, the shared one and a project's own: `$WORKPAD_HOST`, else the
171
+ * machine config's `host`, else 127.0.0.1, this machine alone. A server in a container listens on
172
+ * 0.0.0.0, for the container's own network to reach it.
173
+ */
174
+ export const listenHost = (config: MachineConfig | null, env: NodeJS.ProcessEnv = process.env): string =>
175
+ env.WORKPAD_HOST || config?.host || '127.0.0.1'
176
+
177
+ /**
178
+ * Where a server is reached, when not at http://localhost:<port>: `$WORKPAD_URL`, else the
179
+ * machine config's `url` (pass the config for the shared server alone: a project's own server has a
180
+ * port of its own, so one URL for all of them can't be). A server in a container, with no port on
181
+ * this machine, is at an address of its own (`https://workpad.local`). The server records it,
182
+ * and the command line reaches it there. Null: at localhost, the default.
183
+ */
184
+ export function serverUrl(config: MachineConfig | null, env: NodeJS.ProcessEnv = process.env): string | null {
185
+ if (env.WORKPAD_URL) {
186
+ const url = asOrigin(env.WORKPAD_URL)
187
+ if (!url)
188
+ throw new Error(
189
+ `$WORKPAD_URL must be an http or https address without a path, such as https://workpad.local`,
190
+ )
191
+ return url
192
+ }
193
+ return config?.url ?? null
194
+ }
195
+
196
+ /** `~` and `~/…` as the home folder; the rest resolved, with / separators. */
197
+ export const expandHome = (p: string, home = os.homedir()): string =>
198
+ path
199
+ .resolve(p.replace(/^~(?=$|[\\/])/, home))
200
+ .split(path.sep)
201
+ .join('/')
202
+
203
+ const isGlobPart = (part: string) => /[*?[\]{}!]/.test(part)
204
+
205
+ const hasWorkpad = (dir: string) => {
206
+ try {
207
+ return fs.statSync(path.join(dir, '.workpad')).isDirectory()
208
+ } catch {
209
+ return false
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Where a folder an include matched goes in its entry: its group, the include's last plain folder
215
+ * before the first wildcard (`worktrees`), and its name, what the wildcards matched (`cmux`). An
216
+ * include without wildcards is a group of one, named by the folder (`develop`).
217
+ */
218
+ function placeOf(include: string, dir: string): { group: string; name: string } {
219
+ const parts = include.split('/')
220
+ const wild = parts.findIndex(isGlobPart)
221
+ if (wild < 0) return { group: path.basename(dir), name: '' }
222
+ const literal = parts.slice(0, wild).join('/')
223
+ return { group: parts[wild - 1] ?? '', name: path.relative(literal, dir).split(path.sep).join('/') }
224
+ }
225
+
226
+ /** Is this folder one an exclude glob leaves out (the folder itself, or one it is inside)? */
227
+ const excluded = (dir: string, excludes: string[]) =>
228
+ excludes.some(g => {
229
+ for (let d = dir; ; d = path.posix.dirname(d)) {
230
+ if (path.posix.matchesGlob(d, g)) return true
231
+ if (path.posix.dirname(d) === d) return false
232
+ }
233
+ })
234
+
235
+ /**
236
+ * Every project of the machine config's entries, in config order: the folders an include matches,
237
+ * no exclude matches, with a `.workpad/` folder. A folder two includes match is one project, the
238
+ * first include's. `home`: what `~` means (for tests).
239
+ */
240
+ export function discover(config: MachineConfig, { home = os.homedir() }: { home?: string } = {}): EntryProject[] {
241
+ const out: EntryProject[] = []
242
+ const seen = new Set<string>()
243
+ const taken = new Set<string>()
244
+ for (const [entry, { include, exclude = [], files }] of Object.entries(config.entries)) {
245
+ const excludes = exclude.map(g => expandHome(g, home))
246
+ for (const glob of include.map(g => expandHome(g, home))) {
247
+ const dirs = glob.split('/').some(isGlobPart)
248
+ ? fs
249
+ .globSync(glob)
250
+ .map(d => path.resolve(d))
251
+ .toSorted()
252
+ : [glob]
253
+ for (const dir of dirs) {
254
+ const posix = dir.split(path.sep).join('/')
255
+ if (seen.has(dir) || excluded(posix, excludes) || !hasWorkpad(dir)) continue
256
+ seen.add(dir)
257
+ const place = placeOf(glob, posix)
258
+ const wanted = `/${entry}/${[place.group, place.name].filter(Boolean).join('/')}`
259
+ let base = wanted
260
+ let n = 1
261
+ while (taken.has(base)) base = `${wanted}-${++n}`
262
+ taken.add(base)
263
+ // a second one wanting the same path is named apart the same way
264
+ const name = n > 1 ? (place.name ? `${place.name}-${n}` : '') : place.name
265
+ out.push({
266
+ entry,
267
+ group: n > 1 && !place.name ? `${place.group}-${n}` : place.group,
268
+ name,
269
+ dir,
270
+ base,
271
+ ...(files !== undefined && { files }),
272
+ })
273
+ }
274
+ }
275
+ }
276
+ return out
277
+ }
278
+
279
+ /** Does any include of the machine config match this folder, no exclude leaving it out? Cheap: no globbing of the disk. */
280
+ export function matchesEntries(config: MachineConfig, dir: string, { home = os.homedir() } = {}): string | null {
281
+ const posix = path.resolve(dir).split(path.sep).join('/')
282
+ for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
283
+ const excludes = exclude.map(g => expandHome(g, home))
284
+ if (include.some(g => path.posix.matchesGlob(posix, expandHome(g, home))) && !excluded(posix, excludes))
285
+ return entry
286
+ }
287
+ return null
288
+ }
289
+
290
+ /**
291
+ * Follow the entries' projects: `onChange` gets the projects each time the set changes. Watching
292
+ * globs over the disk in general would mean watching every folder they could match, so it looks
293
+ * again every `interval` ms (cheap: a few folder listings), and at once when told (`rescan`).
294
+ */
295
+ export function followEntries(
296
+ read: () => MachineConfig | null,
297
+ onChange: (projects: EntryProject[]) => void,
298
+ { interval = 1500, home }: { interval?: number; home?: string } = {},
299
+ ) {
300
+ let last = ''
301
+ let current: EntryProject[] = []
302
+ const rescan = () => {
303
+ let projects: EntryProject[] = []
304
+ try {
305
+ const config = read()
306
+ projects = config ? discover(config, { home }) : []
307
+ } catch (err) {
308
+ console.error(`workpad: entries: ${(err as Error).message}`)
309
+ return current
310
+ }
311
+ const key = JSON.stringify(projects)
312
+ if (key !== last) {
313
+ last = key
314
+ current = projects
315
+ onChange(projects)
316
+ }
317
+ return current
318
+ }
319
+ rescan()
320
+ const timer = setInterval(rescan, interval)
321
+ timer.unref()
322
+ return { rescan, projects: () => current, stop: () => clearInterval(timer) }
323
+ }
324
+
325
+ /**
326
+ * The folders the entries' projects can be in: each include up to its first wildcard (all of it
327
+ * when it has none), without those inside another. What the shared server must be able to write,
328
+ * whatever folders appear below them later.
329
+ */
330
+ export function entryFolders(config: MachineConfig, { home = os.homedir() }: { home?: string } = {}): string[] {
331
+ const roots = Object.values(config.entries).flatMap(e =>
332
+ e.include.map(g => {
333
+ const parts = expandHome(g, home).split('/')
334
+ const wild = parts.findIndex(isGlobPart)
335
+ return wild < 0 ? parts.join('/') : parts.slice(0, wild).join('/') || '/'
336
+ }),
337
+ )
338
+ const unique = [...new Set(roots)].toSorted()
339
+ return unique.filter(r => !unique.some(o => o !== r && (r.startsWith(o + '/') || o === '/')))
340
+ }
341
+
342
+ /**
343
+ * What the shared server needs of the disk, for whatever boxes it in (a sandbox wrapper, see
344
+ * `workpad paths`): `write`, the entries' folders and its own state folder; `read`, the machine
345
+ * config and workpad itself.
346
+ */
347
+ export function serverPaths(
348
+ config: MachineConfig,
349
+ { home, packageDir, env = process.env }: { home?: string; packageDir: string; env?: NodeJS.ProcessEnv },
350
+ ): { write: string[]; read: string[] } {
351
+ return { write: [...entryFolders(config, { home }), stateDir(env)], read: [machineDir(env), packageDir] }
352
+ }