@noy4/docserve 0.3.4 → 0.3.5

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 (61) hide show
  1. package/bin.mjs +8 -213
  2. package/dist/gallery/assets/index-CGV64tuk.css +1 -0
  3. package/dist/gallery/assets/index-Cf8Uf0vA.js +10 -0
  4. package/dist/gallery/assets/index-Cf8Uf0vA.js.map +1 -0
  5. package/dist/gallery/index.html +15 -0
  6. package/dist/node/cli.mjs +4095 -0
  7. package/dist/node/cli.mjs.map +7 -0
  8. package/dist/widget/index.js +730 -495
  9. package/package.json +14 -4
  10. package/src/node/cli.mjs +155 -0
  11. package/src/node/{files.mjs → docs/files.mjs} +1 -1
  12. package/src/node/{inject.mjs → docs/inject.mjs} +1 -1
  13. package/src/node/{meta.mjs → docs/meta.mjs} +1 -1
  14. package/src/node/http/app.mjs +20 -0
  15. package/src/node/{assets.mjs → http/assets.mjs} +3 -2
  16. package/src/node/http/gallery.mjs +45 -0
  17. package/src/node/http/response.mjs +31 -0
  18. package/src/node/http/routes.mjs +59 -0
  19. package/src/node/{serve-static.mjs → http/serve-static.mjs} +1 -1
  20. package/src/node/{server.mjs → http/server.mjs} +10 -10
  21. package/src/node/{state.mjs → instances/state.mjs} +9 -5
  22. package/src/node/instances/view.mjs +19 -0
  23. package/src/node/{watch.mjs → live/watch.mjs} +1 -1
  24. package/src/node/paths.mjs +10 -0
  25. package/src/node/rpc/files.mjs +5 -0
  26. package/src/node/rpc/index.mjs +39 -0
  27. package/src/node/rpc/route.mjs +34 -0
  28. package/src/node/rpc/servers.mjs +16 -0
  29. package/src/plugins/servers/client.js +77 -0
  30. package/src/plugins/servers/commands.ts +30 -0
  31. package/src/plugins/servers/model.ts +106 -0
  32. package/src/plugins/servers/servers.css +144 -0
  33. package/src/plugins/servers/ui/ServersPopover.tsx +71 -0
  34. package/src/plugins/sidebar/ui/PageList.tsx +1 -1
  35. package/src/plugins/sidebar/ui/RadioMenu.tsx +1 -1
  36. package/src/plugins/sidebar/ui/Sidebar.tsx +3 -3
  37. package/src/plugins/sidebar/ui/TreeList.tsx +10 -3
  38. package/src/{plugins/sidebar/ui → shared/client}/preview-model.ts +18 -4
  39. package/src/{plugins/sidebar/ui/useModel.ts → shared/client/use-model.ts} +1 -8
  40. package/src/shared/types.d.ts +17 -1
  41. package/src/widget/{pages.js → api/pages.js} +4 -7
  42. package/src/widget/api/rpc-client.js +25 -0
  43. package/src/widget/api/servers.js +46 -0
  44. package/src/widget/host.js +10 -8
  45. package/src/widget/index.js +2 -0
  46. package/src/widget/{docks.js → shell/docks.js} +2 -2
  47. package/src/widget/{palette.js → shell/palette.js} +3 -3
  48. package/src/widget/{placement.js → shell/placement.js} +1 -1
  49. package/src/widget/{ui.js → shell/ui.js} +1 -1
  50. package/index.html +0 -365
  51. package/src/node/adapter.mjs +0 -67
  52. package/src/node/gallery.mjs +0 -33
  53. package/src/node/routes.mjs +0 -105
  54. /package/src/node/{dates.mjs → docs/dates.mjs} +0 -0
  55. /package/src/node/{docs-info.mjs → docs/info.mjs} +0 -0
  56. /package/src/node/{scan.mjs → docs/scan.mjs} +0 -0
  57. /package/src/node/{websocket.mjs → live/websocket.mjs} +0 -0
  58. /package/src/widget/{live.js → api/live.js} +0 -0
  59. /package/src/widget/{rpc.js → api/rpc.js} +0 -0
  60. /package/src/widget/{palette.css → shell/palette.css} +0 -0
  61. /package/src/widget/{styles.js → shell/styles.js} +0 -0
package/package.json CHANGED
@@ -1,14 +1,20 @@
1
1
  {
2
2
  "name": "@noy4/docserve",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "description": "Serves a folder of HTML as a card gallery with live reload.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "docserve": "./bin.mjs"
8
8
  },
9
+ "imports": {
10
+ "#shared/*": "./src/shared/*"
11
+ },
9
12
  "scripts": {
10
13
  "dev": "node scripts/dev.mjs",
11
- "build": "vite build",
14
+ "build": "npm run build:node && npm run build:widget && npm run build:gallery",
15
+ "build:node": "node scripts/build-node.mjs",
16
+ "build:widget": "vite build",
17
+ "build:gallery": "vite build --config app/vite.config.ts",
12
18
  "test": "npm run build && node --test --test-timeout=60000",
13
19
  "typecheck": "tsc --noEmit",
14
20
  "pack:check": "npm pack --dry-run",
@@ -16,9 +22,10 @@
16
22
  },
17
23
  "files": [
18
24
  "bin.mjs",
19
- "index.html",
20
25
  "src/",
21
- "dist/widget/*.js"
26
+ "dist/node/**",
27
+ "dist/widget/*.js",
28
+ "dist/gallery/**"
22
29
  ],
23
30
  "devDependencies": {
24
31
  "@iconify/json": "^2.2.558",
@@ -29,6 +36,9 @@
29
36
  "@types/react": "^19.3.0",
30
37
  "@types/react-dom": "^19.3.0",
31
38
  "@vitejs/plugin-react": "^6.1.1",
39
+ "cac": "^7.1.0",
40
+ "esbuild": "^0.24.2",
41
+ "h3": "^2.0.8",
32
42
  "react": "^19.3.1",
33
43
  "react-dom": "^19.3.1",
34
44
  "typescript": "^5.7.0",
@@ -0,0 +1,155 @@
1
+ import { execFile, spawn } from "node:child_process"
2
+ import fs from "node:fs"
3
+ import path from "node:path"
4
+ import cac from "cac"
5
+ import { runServer } from "./http/server.mjs"
6
+ import { findByDir, listLiveStates, removeState } from "./instances/state.mjs"
7
+ import { PACKAGE_JSON } from "./paths.mjs"
8
+
9
+ const pkg = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8"))
10
+ const VERSION = pkg.version
11
+ const DEFAULT_PORT = 4242
12
+
13
+ export async function main(argv = process.argv) {
14
+ const cli = cac("docserve")
15
+
16
+ cli
17
+ .usage("[dir] [command] [options]")
18
+ .option("--open", "Open the gallery in the browser once the port is bound")
19
+ .option("--port <number>", `Port to bind (default: ${DEFAULT_PORT}); falls back +1 up to 20 tries`, { default: DEFAULT_PORT })
20
+ .option("--background", "Start detached; the bound port and pid land in the state dir")
21
+ .help()
22
+ .version(VERSION)
23
+
24
+ cli
25
+ .command("[dir]", "Serve a folder of HTML files (default: current directory)")
26
+ .usage("[dir] [options]")
27
+ .example("docserve ~/reports --open")
28
+ .action(async (dir, options) => {
29
+ await startServer(dir, options)
30
+ })
31
+
32
+ cli
33
+ .command("stop [dir]", "Stop the server serving [dir], or every server when [dir] is omitted")
34
+ .action((dir) => {
35
+ stopServer(dir)
36
+ })
37
+
38
+ cli
39
+ .command("status", "List the running servers (url + docs); exit 1 if none")
40
+ .action(() => {
41
+ showStatus()
42
+ })
43
+
44
+ cli.parse(argv, { run: false })
45
+ await cli.runMatchedCommand()
46
+ }
47
+
48
+ // --- commands ---
49
+
50
+ async function startServer(dir, options) {
51
+ const docsDir = path.resolve(dir ?? ".")
52
+ if (!isDirectory(docsDir))
53
+ throw new Error(`[docserve] Directory not found: ${docsDir}`)
54
+
55
+ const port = parsePort(options.port)
56
+ const open = options.open ?? false
57
+
58
+ const running = findByDir(docsDir)
59
+ if (running) {
60
+ if (open) openBrowser(running.url)
61
+ console.log(`docserve is already serving this folder: ${running.url}`)
62
+ return
63
+ }
64
+
65
+ if (options.background) {
66
+ await startBackground({ docsDir, port, open })
67
+ return
68
+ }
69
+
70
+ console.log(`docserve v${VERSION}`)
71
+ console.log(`docs : ${docsDir}`)
72
+ await runServer({ docsDir, port, open })
73
+ }
74
+
75
+ function stopServer(dir) {
76
+ const resolved = dir ? path.resolve(dir) : null
77
+ const states = resolved ? [findByDir(resolved)].filter(Boolean) : listLiveStates()
78
+ if (!states.length) {
79
+ if (resolved) throw new Error(`docserve is not serving ${resolved}.`)
80
+ console.log("docserve is not running.")
81
+ return
82
+ }
83
+
84
+ for (const state of states) {
85
+ try {
86
+ process.kill(state.pid, "SIGTERM")
87
+ } catch { }
88
+ removeState(state)
89
+ console.log(`Stopped docserve (${state.url})`)
90
+ console.log(` docs : ${state.docsDir}`)
91
+ }
92
+ }
93
+
94
+ function showStatus() {
95
+ const states = listLiveStates()
96
+ if (!states.length) throw new Error("docserve is not running.")
97
+ for (const [index, state] of states.entries()) {
98
+ if (index > 0) console.log()
99
+ console.log(state.url)
100
+ console.log(`docs : ${state.docsDir}`)
101
+ }
102
+ }
103
+
104
+ async function startBackground({ docsDir, port, open }) {
105
+ const entry = process.argv[1]
106
+ if (!entry) throw new Error("[docserve] Cannot locate the CLI entry for --background.")
107
+
108
+ const childArgs = [entry, docsDir]
109
+ if (open) childArgs.push("--open")
110
+ childArgs.push("--port", String(port))
111
+
112
+ const child = spawn(process.execPath, childArgs, { detached: true, stdio: "ignore" })
113
+ child.unref()
114
+
115
+ const state = await waitForState(child.pid)
116
+ if (!state) throw new Error("[docserve] Server did not report startup (no state file). Try running in the foreground.")
117
+
118
+ console.log("docserve started in the background")
119
+ console.log(` pid : ${state.pid}`)
120
+ console.log(` url : ${state.url}`)
121
+ console.log(` docs : ${state.docsDir}`)
122
+ console.log(" stop : docserve stop")
123
+ }
124
+
125
+ async function waitForState(pid, { timeoutMs = 10000, intervalMs = 200 } = {}) {
126
+ const deadline = Date.now() + timeoutMs
127
+ while (Date.now() < deadline) {
128
+ const state = listLiveStates().find((entry) => entry.pid === pid)
129
+ if (state) return state
130
+ await new Promise((resolve) => setTimeout(resolve, intervalMs))
131
+ }
132
+ return null
133
+ }
134
+
135
+ // --- utils ---
136
+
137
+ function parsePort(value) {
138
+ const port = Number(value ?? DEFAULT_PORT)
139
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
140
+ throw new Error(`[docserve] --port expects an integer between 1 and 65535, got "${value}"`)
141
+ }
142
+ return port
143
+ }
144
+
145
+ function openBrowser(url) {
146
+ if (process.platform === "darwin") execFile("open", [url], () => { })
147
+ }
148
+
149
+ function isDirectory(target) {
150
+ try {
151
+ return fs.statSync(target).isDirectory()
152
+ } catch {
153
+ return false
154
+ }
155
+ }
@@ -1,4 +1,4 @@
1
- // /api/files payload: page metadata composed from scanning, head parsing and
1
+ // docserve:pages:list payload: page metadata composed from scanning, head parsing and
2
2
  // git dates.
3
3
  import { realpathSync } from "node:fs"
4
4
  import { stat } from "node:fs/promises"
@@ -1,7 +1,7 @@
1
1
  // Injection: every HTML response from the docs root gets the widget tags before
2
2
  // the last </body>. The gallery template is served separately and never reaches
3
3
  // this module.
4
- import { docsInfo } from "./docs-info.mjs"
4
+ import { docsInfo } from "./info.mjs"
5
5
 
6
6
  export const WS_PATH = "/__reload"
7
7
 
@@ -1,5 +1,5 @@
1
1
  // Title, created_at and favicon extracted from the head of a document, cached
2
- // by path + mtime so repeated /api/files calls only re-read changed files.
2
+ // by path + mtime so repeated docserve:pages:list calls only re-read changed files.
3
3
  import { open } from "node:fs/promises"
4
4
  import { dirname, join } from "node:path"
5
5
  import { isWithin, normalizedRelative } from "./scan.mjs"
@@ -0,0 +1,20 @@
1
+ import { H3 } from "h3/node"
2
+ import { registerRoutes } from "./routes.mjs"
3
+ import { registerFiles } from "../rpc/files.mjs"
4
+ import { createRpc } from "../rpc/index.mjs"
5
+ import { registerRpcRoute } from "../rpc/route.mjs"
6
+ import { registerServers } from "../rpc/servers.mjs"
7
+
8
+ /**
9
+ * @param {{ docsDir: string }} options
10
+ * @returns {H3}
11
+ */
12
+ export function createApp({ docsDir }) {
13
+ const app = new H3()
14
+ const rpc = createRpc()
15
+ registerFiles(rpc, { docsDir })
16
+ registerServers(rpc, { docsDir })
17
+ registerRpcRoute(app, rpc)
18
+ registerRoutes(app, { docsDir })
19
+ return app
20
+ }
@@ -1,5 +1,6 @@
1
1
  // Widget and plugin assets: the same static handler as the docs tree, rooted
2
2
  // at src/widget and src/plugins and read per request so edits need no restart.
3
+ import { notFound } from "./response.mjs"
3
4
  import { createStaticHandler } from "./serve-static.mjs"
4
5
 
5
6
  export { MIME } from "./serve-static.mjs"
@@ -27,10 +28,10 @@ function handlerFor(root) {
27
28
  * @returns {Promise<Response>}
28
29
  */
29
30
  export async function serveAsset(root, relative) {
30
- if (!relative) return new Response("Not Found", { status: 404 })
31
+ if (!relative) return notFound()
31
32
 
32
33
  // Re-encode segment-wise so the handler's single decode yields the input.
33
34
  const encoded = relative.split("/").map(encodeURIComponent).join("/")
34
35
  const response = await handlerFor(root)(new Request(`http://localhost/${encoded}`))
35
- return response ?? new Response("Not Found", { status: 404 })
36
+ return response ?? notFound()
36
37
  }
@@ -0,0 +1,45 @@
1
+ // The gallery SPA shell served at / and /index.html. Every other HTML file
2
+ // comes from the docs folder and is injected instead.
3
+ import { readFile } from "node:fs/promises"
4
+ import { join } from "node:path"
5
+ import { docsInfo } from "../docs/info.mjs"
6
+ import { text } from "./response.mjs"
7
+ import { GALLERY_DIST_DIR } from "../paths.mjs"
8
+
9
+ const SHELL = join(GALLERY_DIST_DIR, "index.html")
10
+
11
+ /**
12
+ * @param {string} docsDir
13
+ * @returns {Promise<Response>}
14
+ */
15
+ export async function galleryResponse(docsDir) {
16
+ const { name, path, hue } = docsInfo(docsDir)
17
+
18
+ let html
19
+ try {
20
+ html = await readFile(SHELL, "utf8")
21
+ } catch {
22
+ return text("Gallery build missing: run `npm run build`", 503, { "cache-control": "no-store" })
23
+ }
24
+
25
+ html = html
26
+ .replaceAll("__DOCS_NAME__", escapeHtml(name))
27
+ .replaceAll("__DOCS_PATH__", escapeHtml(path))
28
+ .replaceAll("__DOCS_HUE__", String(hue))
29
+
30
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } })
31
+ }
32
+
33
+ /**
34
+ * Escape text for an HTML text node or a double-quoted attribute.
35
+ * @param {string} s
36
+ * @returns {string}
37
+ */
38
+ function escapeHtml(s) {
39
+ return s
40
+ .replaceAll("&", "&amp;")
41
+ .replaceAll("<", "&lt;")
42
+ .replaceAll(">", "&gt;")
43
+ .replaceAll('"', "&quot;")
44
+ .replaceAll("'", "&#39;")
45
+ }
@@ -0,0 +1,31 @@
1
+ const NO_STORE = { "cache-control": "no-store" }
2
+
3
+ /**
4
+ * @param {any} body
5
+ * @param {number} [status]
6
+ * @returns {Response}
7
+ */
8
+ export function json(body, status = 200) {
9
+ return Response.json(body, { status, headers: NO_STORE })
10
+ }
11
+
12
+ /**
13
+ * @param {string} body
14
+ * @param {number} [status]
15
+ * @param {Record<string, string>} [headers]
16
+ * @returns {Response}
17
+ */
18
+ export function text(body, status = 200, headers = {}) {
19
+ return new Response(body, {
20
+ status,
21
+ headers: { "content-type": "text/plain; charset=utf-8", ...headers },
22
+ })
23
+ }
24
+
25
+ /**
26
+ * @param {string} [body]
27
+ * @returns {Response}
28
+ */
29
+ export function notFound(body = "Not Found") {
30
+ return text(body, 404, NO_STORE)
31
+ }
@@ -0,0 +1,59 @@
1
+ // h3 route registration: internal assets, the gallery, and one docs static
2
+ // handler. Nothing here knows about listening, signals or sockets.
3
+ import { serveAsset } from "./assets.mjs"
4
+ import { galleryResponse } from "./gallery.mjs"
5
+ import { notFound, text } from "./response.mjs"
6
+ import { injectIntoHtml } from "../docs/inject.mjs"
7
+ import { PLUGINS_SOURCE_DIR, GALLERY_DIST_DIR, WIDGET_DIST_DIR, WIDGET_SOURCE_DIR } from "../paths.mjs"
8
+ import { createStaticHandler } from "./serve-static.mjs"
9
+
10
+ const INTERNAL_PREFIX = "/__docserve/"
11
+ const WIDGET_PREFIX = `${INTERNAL_PREFIX}widget/`
12
+ const PLUGINS_PREFIX = `${INTERNAL_PREFIX}plugins/`
13
+ const GALLERY_PREFIX = `${INTERNAL_PREFIX}gallery/`
14
+
15
+ /**
16
+ * @param {import("h3/node").H3} app
17
+ * @param {{ docsDir: string }} options
18
+ */
19
+ export function registerRoutes(app, { docsDir }) {
20
+ const docs = createStaticHandler({
21
+ root: docsDir,
22
+ headers: { "cache-control": "no-store" },
23
+ transform: (html, relative) => injectIntoHtml(html, relative, docsDir),
24
+ })
25
+
26
+ app.get(`${WIDGET_PREFIX}**`, (event) => serveWidget(event.url.pathname.slice(WIDGET_PREFIX.length)))
27
+
28
+ app.get(`${PLUGINS_PREFIX}**`, (event) => serveAsset(PLUGINS_SOURCE_DIR, event.url.pathname.slice(PLUGINS_PREFIX.length)))
29
+
30
+ app.get(`${GALLERY_PREFIX}**`, (event) => serveAsset(GALLERY_DIST_DIR, event.url.pathname.slice(GALLERY_PREFIX.length)))
31
+
32
+ app.all(`${INTERNAL_PREFIX}**`, () => notFound())
33
+
34
+ app.get("/", () => galleryResponse(docsDir))
35
+ app.get("/index.html", () => galleryResponse(docsDir))
36
+
37
+ app.all("/**", async (event) => (await docs(event.req)) ?? notFound())
38
+ }
39
+
40
+ /**
41
+ * Built widget first, source files (CSS) as the fallback. A JS request that
42
+ * misses the build is an error: the source entry now has bare imports.
43
+ * @param {string} relative
44
+ * @returns {Promise<Response>}
45
+ */
46
+ async function serveWidget(relative) {
47
+ if (!relative) return notFound()
48
+
49
+ const built = await serveAsset(WIDGET_DIST_DIR, relative)
50
+ if (built.status !== 404) return built
51
+
52
+ if (/\.m?js$/.test(relative)) {
53
+ return text("Widget bundle missing: run `pnpm -C cli build`", 503, {
54
+ "cache-control": "no-store",
55
+ })
56
+ }
57
+
58
+ return serveAsset(WIDGET_SOURCE_DIR, relative)
59
+ }
@@ -7,7 +7,7 @@ import { createReadStream } from "node:fs"
7
7
  import { readFile, realpath, stat } from "node:fs/promises"
8
8
  import { extname, resolve, sep } from "node:path"
9
9
  import { Readable } from "node:stream"
10
- import { isWithin, normalizedRelative } from "./scan.mjs"
10
+ import { isWithin, normalizedRelative } from "../docs/scan.mjs"
11
11
 
12
12
  export const MIME = {
13
13
  ".html": "text/html",
@@ -3,19 +3,19 @@
3
3
  //
4
4
  // ┌──────────────────────────────────────────────────────────┐
5
5
  // │ runServer() │
6
- // │ ├─ createServer ──▶ adapter(createHandler()) │
6
+ // │ ├─ createServer ──▶ toNodeHandler(createApp()) │
7
7
  // │ ├─ WebSocketServer("/__reload") ◀─ FileWatcher │
8
8
  // │ └─ listen ──▶ watcher.start() + writeState() │
9
9
  // └──────────────────────────────────────────────────────────┘
10
10
  import { exec } from "node:child_process"
11
11
  import { createServer } from "node:http"
12
- import { createNodeServerAdapter } from "./adapter.mjs"
13
- import { INDEX_TEMPLATE } from "./gallery.mjs"
14
- import { createHandler } from "./routes.mjs"
15
- import { clearState, writeState } from "./state.mjs"
16
- import { FileWatcher } from "./watch.mjs"
17
- import { WebSocketServer } from "./websocket.mjs"
18
- import { WS_PATH } from "./inject.mjs"
12
+ import { toNodeHandler } from "h3/node"
13
+ import { createApp } from "./app.mjs"
14
+ import { GALLERY_TEMPLATE } from "../paths.mjs"
15
+ import { clearState, writeState } from "../instances/state.mjs"
16
+ import { FileWatcher } from "../live/watch.mjs"
17
+ import { WebSocketServer } from "../live/websocket.mjs"
18
+ import { WS_PATH } from "../docs/inject.mjs"
19
19
 
20
20
  const MAX_PORT_TRIES = 20 // on conflict, try the next port up to 20 times
21
21
 
@@ -24,11 +24,11 @@ const MAX_PORT_TRIES = 20 // on conflict, try the next port up to 20 times
24
24
  */
25
25
  export async function runServer({ docsDir, port: initialPort, open = false }) {
26
26
  const wss = new WebSocketServer({ path: WS_PATH })
27
- const fileWatcher = new FileWatcher({ wss, docsDir, templatePath: INDEX_TEMPLATE })
27
+ const fileWatcher = new FileWatcher({ wss, docsDir, templatePath: GALLERY_TEMPLATE })
28
28
  let port = initialPort
29
29
  let closed = false
30
30
 
31
- const server = createServer(createNodeServerAdapter(createHandler({ docsDir })))
31
+ const server = createServer(toNodeHandler(createApp({ docsDir })))
32
32
  wss.attach(server)
33
33
 
34
34
  const close = () => {
@@ -4,7 +4,7 @@
4
4
  // (name = sanitized folder name), written once the port is bound and removed
5
5
  // on clean shutdown. Readers verify the PID is alive and treat dead-PID state
6
6
  // as stale (removed in place). DOCSERVE_HOME overrides the docserve home
7
- // (test isolation).
7
+ // (test isolation). Newest instances are listed first by startedAt.
8
8
  import fs from "node:fs"
9
9
  import os from "node:os"
10
10
  import path from "node:path"
@@ -43,7 +43,10 @@ function readStateFile(file) {
43
43
  typeof state?.url === "string" &&
44
44
  typeof state?.docsDir === "string"
45
45
  ) {
46
- return state
46
+ return {
47
+ ...state,
48
+ startedAt: typeof state.startedAt === "number" ? state.startedAt : 0,
49
+ }
47
50
  }
48
51
  return null
49
52
  } catch {
@@ -62,9 +65,10 @@ export function isProcessAlive(pid) {
62
65
 
63
66
  export function writeState(state) {
64
67
  fs.mkdirSync(stateDir(), { recursive: true })
65
- const file = path.join(stateDir(), fileName(state))
68
+ const record = { ...state, startedAt: state.startedAt ?? Date.now() }
69
+ const file = path.join(stateDir(), fileName(record))
66
70
  const tmp = `${file}.${process.pid}.tmp`
67
- fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n")
71
+ fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + "\n")
68
72
  fs.renameSync(tmp, file)
69
73
  ownFile = file
70
74
  }
@@ -106,7 +110,7 @@ export function listLiveStates() {
106
110
  }
107
111
  states.push(state)
108
112
  }
109
- return states.sort((a, b) => a.port - b.port)
113
+ return states.sort((a, b) => b.startedAt - a.startedAt || b.port - a.port)
110
114
  }
111
115
 
112
116
  export function findByDir(docsDir) {
@@ -0,0 +1,19 @@
1
+ import { resolve } from "node:path"
2
+ import { docsInfo } from "../docs/info.mjs"
3
+
4
+ /**
5
+ * @param {Array<{ docsDir: string, port: number, url: string }>} states
6
+ * @param {string} currentDocsDir
7
+ * @returns {DocServer[]}
8
+ */
9
+ export function publicServers(states, currentDocsDir) {
10
+ const current = resolve(currentDocsDir)
11
+ return states
12
+ .map((state) => ({
13
+ ...docsInfo(state.docsDir),
14
+ url: state.url,
15
+ port: state.port,
16
+ current: resolve(state.docsDir) === current,
17
+ }))
18
+ .sort((a, b) => Number(b.current) - Number(a.current) || a.name.localeCompare(b.name, "ja") || a.port - b.port)
19
+ }
@@ -3,7 +3,7 @@
3
3
  // only additions/removals flip contentSetChanged.
4
4
  import { existsSync, watch } from "node:fs"
5
5
  import { basename, dirname, resolve } from "node:path"
6
- import { isWithin, listHtmlFiles, normalizedRelative, shouldIgnore } from "./scan.mjs"
6
+ import { isWithin, listHtmlFiles, normalizedRelative, shouldIgnore } from "../docs/scan.mjs"
7
7
 
8
8
  const DEBOUNCE_MS = 50
9
9
 
@@ -0,0 +1,10 @@
1
+ import { join } from "node:path"
2
+ import { fileURLToPath } from "node:url"
3
+
4
+ export const PACKAGE_ROOT = fileURLToPath(new URL("../..", import.meta.url))
5
+ export const PACKAGE_JSON = join(PACKAGE_ROOT, "package.json")
6
+ export const GALLERY_TEMPLATE = join(PACKAGE_ROOT, "dist", "gallery", "index.html")
7
+ export const GALLERY_DIST_DIR = join(PACKAGE_ROOT, "dist", "gallery")
8
+ export const WIDGET_SOURCE_DIR = join(PACKAGE_ROOT, "src", "widget")
9
+ export const PLUGINS_SOURCE_DIR = join(PACKAGE_ROOT, "src", "plugins")
10
+ export const WIDGET_DIST_DIR = join(PACKAGE_ROOT, "dist", "widget")
@@ -0,0 +1,5 @@
1
+ import { apiFiles } from "../docs/files.mjs"
2
+
3
+ export function registerFiles(rpc, { docsDir }) {
4
+ rpc.register("docserve:pages:list", () => apiFiles(docsDir))
5
+ }
@@ -0,0 +1,39 @@
1
+ export class RpcError extends Error {
2
+ constructor(message, status = 500) {
3
+ super(message)
4
+ this.name = "RpcError"
5
+ this.status = status
6
+ }
7
+ }
8
+
9
+ export function createRpc() {
10
+ /** @type {Map<string, (...args: any[]) => any>} */
11
+ const methods = new Map()
12
+
13
+ return {
14
+ register(name, handler) {
15
+ if (typeof name !== "string" || !name) throw new TypeError("rpc.register expects a method name")
16
+ if (typeof handler !== "function") throw new TypeError(`rpc.register(${name}) expects a function`)
17
+ if (methods.has(name)) throw new Error(`rpc method already registered: ${name}`)
18
+ methods.set(name, handler)
19
+ return () => {
20
+ if (methods.get(name) === handler) methods.delete(name)
21
+ }
22
+ },
23
+
24
+ has(name) {
25
+ return methods.has(name)
26
+ },
27
+
28
+ names() {
29
+ return [...methods.keys()]
30
+ },
31
+
32
+ async call(name, args = []) {
33
+ if (!Array.isArray(args)) throw new RpcError("args must be an array", 400)
34
+ const handler = methods.get(name)
35
+ if (!handler) throw new RpcError(`Unknown RPC method: ${name}`, 404)
36
+ return handler(...args)
37
+ },
38
+ }
39
+ }
@@ -0,0 +1,34 @@
1
+ import { readBody } from "h3/node"
2
+ import { json } from "../http/response.mjs"
3
+ import { RpcError } from "./index.mjs"
4
+
5
+ /**
6
+ * @param {import("h3/node").H3} app
7
+ * @param {{ call: (name: string, args?: any[]) => Promise<any> }} rpc
8
+ */
9
+ export function registerRpcRoute(app, rpc) {
10
+ app.post("/__docserve/rpc", async (event) => {
11
+ let payload
12
+ try {
13
+ payload = await readBody(event)
14
+ } catch {
15
+ return json({ error: { message: "Invalid JSON body" } }, 400)
16
+ }
17
+
18
+ const data = /** @type {{ method?: unknown, args?: unknown }} */ (payload)
19
+ const method = data?.method
20
+ const args = data?.args ?? []
21
+ if (typeof method !== "string" || !method)
22
+ return json({ error: { message: "method must be a string" } }, 400)
23
+ if (!Array.isArray(args))
24
+ return json({ error: { message: "args must be an array" } }, 400)
25
+
26
+ try {
27
+ return json({ result: await rpc.call(method, args) })
28
+ } catch (error) {
29
+ const status = error instanceof RpcError ? error.status : 500
30
+ if (!(error instanceof RpcError)) console.error(error)
31
+ return json({ error: { message: error instanceof Error ? error.message : String(error) } }, status)
32
+ }
33
+ })
34
+ }
@@ -0,0 +1,16 @@
1
+ import { publicServers } from "../instances/view.mjs"
2
+ import { listLiveStates } from "../instances/state.mjs"
3
+
4
+ export function registerServers(rpc, { docsDir, ttl = 1000 }) {
5
+ let cached = null
6
+ let cachedAt = 0
7
+
8
+ rpc.register("docserve:servers:list", (force = false) => {
9
+ const now = Date.now()
10
+ if (force || !cached || now - cachedAt >= ttl) {
11
+ cached = publicServers(listLiveStates(), docsDir)
12
+ cachedAt = now
13
+ }
14
+ return cached
15
+ })
16
+ }