@noy4/docserve 0.1.2 → 0.3.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/bin.mjs CHANGED
@@ -4,18 +4,18 @@
4
4
  // docserve [dir] [command] [options]
5
5
  //
6
6
  // Flow:
7
- // parse args ──▶ stop / status ──▶ state.json
7
+ // parse args ──▶ stop / status ──▶ state files
8
8
  // └─ start
9
- // ├─ single-instance check (readLiveState)
10
- // ├─ --background ──▶ spawn detached ──▶ wait for state.json
11
- // └─ foreground ──▶ runServer() (writes state.json on bind)
9
+ // ├─ single-instance check (findByDir)
10
+ // ├─ --background ──▶ spawn detached ──▶ wait for the state file
11
+ // └─ foreground ──▶ runServer() (writes its state file on bind)
12
12
  import fs from "node:fs"
13
13
  import path from "node:path"
14
14
  import { exec, spawn } from "node:child_process"
15
15
  import { fileURLToPath } from "node:url"
16
16
  import { parseArgs } from "node:util"
17
17
  import { runServer } from "./server/index.mjs"
18
- import { clearState, readLiveState } from "./server/state.mjs"
18
+ import { findByDir, listLiveStates, removeState } from "./server/state.mjs"
19
19
 
20
20
  const pkg = JSON.parse(fs.readFileSync(new URL("./package.json", import.meta.url), "utf8"))
21
21
  const VERSION = pkg.version
@@ -32,20 +32,20 @@ Arguments:
32
32
  dir Folder of HTML files to serve (default: current directory)
33
33
 
34
34
  Commands:
35
- stop Stop the running docserve server
36
- status Show whether a server is running (exit 1 if none)
35
+ stop Stop the server serving [dir], or every server when [dir] is omitted
36
+ status List the running servers (url + docs); exit 1 if none
37
37
 
38
38
  Options:
39
39
  --open Open the gallery in the browser once the port is bound
40
40
  --port <number> Port to bind (default: ${DEFAULT_PORT}); falls back +1 up to 20 tries
41
- --background Start detached; the bound port and pid land in state.json
41
+ --background Start detached; the bound port and pid land in the state dir
42
42
  -h, --help Show this help
43
43
  -v, --version Show version
44
44
  `
45
45
 
46
46
  async function main() {
47
47
  const args = parseCliArgs()
48
- if (args.command === "stop") return stopServer()
48
+ if (args.command === "stop") return stopServer(args)
49
49
  if (args.command === "status") return showStatus()
50
50
  return startServer(args)
51
51
  }
@@ -114,27 +114,39 @@ function parseCliArgs() {
114
114
  }
115
115
  }
116
116
 
117
- function stopServer() {
118
- const state = readLiveState() // stale state (dead pid) is removed silently
119
- if (!state) {
117
+ function stopServer(args) {
118
+ const dir = args.dir ? path.resolve(args.dir) : null
119
+ // listLiveStates() prunes stale state (dead pid) silently.
120
+ const states = dir ? [findByDir(dir)].filter(Boolean) : listLiveStates()
121
+ if (!states.length) {
122
+ if (dir) {
123
+ console.error(`docserve is not serving ${dir}.`)
124
+ process.exit(1)
125
+ }
120
126
  console.log("docserve is not running.")
121
127
  return
122
128
  }
123
- try {
124
- process.kill(state.pid, "SIGTERM")
125
- } catch {}
126
- clearState()
127
- console.log(`Stopped docserve (${state.url})`)
129
+ for (const state of states) {
130
+ try {
131
+ process.kill(state.pid, "SIGTERM")
132
+ } catch {}
133
+ removeState(state)
134
+ console.log(`Stopped docserve (${state.url})`)
135
+ console.log(` docs : ${state.docsDir}`)
136
+ }
128
137
  }
129
138
 
130
139
  function showStatus() {
131
- const state = readLiveState()
132
- if (!state) {
140
+ const states = listLiveStates()
141
+ if (!states.length) {
133
142
  console.error("docserve is not running.")
134
143
  process.exit(1)
135
144
  }
136
- console.log(state.url)
137
- console.log(`docs : ${state.docsDir}`)
145
+ for (const [index, state] of states.entries()) {
146
+ if (index > 0) console.log()
147
+ console.log(state.url)
148
+ console.log(`docs : ${state.docsDir}`)
149
+ }
138
150
  }
139
151
 
140
152
  async function startServer(args) {
@@ -144,22 +156,13 @@ async function startServer(args) {
144
156
  process.exit(1)
145
157
  }
146
158
 
147
- // Single instance: same docsDir just opens its URL; a different docsDir
148
- // requires docserve stop first.
149
- const running = readLiveState()
159
+ // Single instance per folder: same docsDir just opens its URL; a different
160
+ // docsDir starts its own instance (the port fallback avoids collisions).
161
+ const running = findByDir(docsDir)
150
162
  if (running) {
151
- if (running.docsDir === docsDir) {
152
- if (args.open) openBrowser(running.url)
153
- console.log(`docserve is already serving this folder: ${running.url}`)
154
- return
155
- }
156
- console.error([
157
- "[docserve] A server is already running for a different folder.",
158
- ` url : ${running.url}`,
159
- ` docs : ${running.docsDir}`,
160
- "Stop it first: docserve stop",
161
- ].join("\n"))
162
- process.exit(1)
163
+ if (args.open) openBrowser(running.url)
164
+ console.log(`docserve is already serving this folder: ${running.url}`)
165
+ return
163
166
  }
164
167
 
165
168
  if (args.background) return startBackground(args, docsDir)
@@ -177,7 +180,7 @@ async function startBackground(args, docsDir) {
177
180
  const child = spawn(process.execPath, childArgs, { detached: true, stdio: "ignore" })
178
181
  child.unref()
179
182
 
180
- const state = await waitForState()
183
+ const state = await waitForState(child.pid)
181
184
  if (!state) {
182
185
  console.error("[docserve] Server did not report startup (no state file). Try running in the foreground.")
183
186
  process.exit(1)
@@ -189,10 +192,11 @@ async function startBackground(args, docsDir) {
189
192
  console.log(" stop : docserve stop")
190
193
  }
191
194
 
192
- async function waitForState({ timeoutMs = 10000, intervalMs = 200 } = {}) {
195
+ // Poll the state dir until the server with the given pid reports its state.
196
+ async function waitForState(pid, { timeoutMs = 10000, intervalMs = 200 } = {}) {
193
197
  const deadline = Date.now() + timeoutMs
194
198
  while (Date.now() < deadline) {
195
- const state = readLiveState()
199
+ const state = listLiveStates().find((entry) => entry.pid === pid)
196
200
  if (state) return state
197
201
  await new Promise((resolve) => setTimeout(resolve, intervalMs))
198
202
  }
package/index.html CHANGED
@@ -3,8 +3,8 @@
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>docserve</title>
7
- <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%236c8cff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'/%3E%3Cpath d='M14 2v6h6'/%3E%3Cpath d='M8 13h8M8 17h5'/%3E%3C/svg%3E">
6
+ <title>__DOCS_DIR_NAME__</title>
7
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20width='64'%20height='64'%20viewBox='244.5%20242.5%20546%20546'%20xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3ClinearGradient%20id='frontFill'%20x1='0%25'%20y1='0%25'%20x2='0%25'%20y2='100%25'%3E%3Cstop%20offset='0%25'%20stop-color='%23223047'/%3E%3Cstop%20offset='55%25'%20stop-color='%23141C2B'/%3E%3Cstop%20offset='100%25'%20stop-color='%230F1520'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cg%20transform='rotate(-6%20462%20452)'%3E%3Crect%20x='262'%20y='312'%20width='400'%20height='280'%20rx='34'%20fill='%234C5FD6'%20stroke='%23818CF8'%20stroke-width='8'/%3E%3C/g%3E%3Cg%20transform='rotate(5%20575%20440)'%3E%3Crect%20x='375'%20y='300'%20width='400'%20height='280'%20rx='34'%20fill='%233E76C9'%20stroke='%235B8DEF'%20stroke-width='8'/%3E%3C/g%3E%3Cg%20transform='rotate(6%20562%20588)'%3E%3Crect%20x='362'%20y='448'%20width='400'%20height='280'%20rx='34'%20fill='%232E93C4'%20stroke='%2338BDF8'%20stroke-width='8'/%3E%3C/g%3E%3Cg%20transform='rotate(-6%20512%20536)'%3E%3Crect%20x='280'%20y='375'%20width='464'%20height='322'%20rx='38'%20fill='url(%23frontFill)'%20stroke='%2338BDF8'%20stroke-width='8'/%3E%3Cg%20stroke='%23EAF8FF'%20stroke-width='10'%20stroke-linecap='round'%20stroke-opacity='0.62'%3E%3Cline%20x1='334'%20y1='578'%20x2='690'%20y2='578'/%3E%3Cline%20x1='334'%20y1='628'%20x2='548'%20y2='628'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E">
8
8
  <style>
9
9
  :root {
10
10
  --bg: #0f1117;
@@ -166,11 +166,11 @@
166
166
 
167
167
  <body>
168
168
  <h1>
169
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M8 13h8M8 17h5"/></svg>
170
- docserve
169
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>
170
+ __DOCS_DIR_NAME__
171
171
  </h1>
172
172
  <p class="sub">
173
- <code id="docs-dir">__DOCSERVE_DIR__</code> - <b id="total">0</b> files
173
+ <code id="docs-dir">__DOCS_DIR__</code> — <b id="total">0</b> files
174
174
  </p>
175
175
 
176
176
  <div class="grid" id="grid" hidden></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy4/docserve",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Serves a folder of HTML as a card gallery with live reload.",
5
5
  "type": "module",
6
6
  "bin": {
package/server/files.mjs CHANGED
@@ -11,24 +11,33 @@ import { promisify } from "node:util"
11
11
 
12
12
  const run = promisify(execFile)
13
13
 
14
- // Walk docsDir recursively and collect .html files; any index.html is excluded
15
- // from the gallery.
16
- export async function listHtmlFiles(docsDir, out = []) {
17
- let entries
18
- try {
19
- entries = await readdir(docsDir, { withFileTypes: true })
20
- } catch {
21
- return out
22
- }
23
- for (const entry of entries) {
24
- const full = join(docsDir, entry.name)
25
- if (entry.isDirectory()) {
26
- await listHtmlFiles(full, out)
27
- } else if (entry.name.endsWith(".html") && entry.name !== "index.html") {
28
- out.push(full)
14
+ // Walk docsDir recursively and collect .html files; only the root index.html is
15
+ // excluded from the gallery.
16
+ const MAX_DEPTH = 3
17
+
18
+ export async function listHtmlFiles(docsDir) {
19
+ const out = []
20
+ await walk(docsDir, docsDir, 0)
21
+ return out
22
+
23
+ async function walk(dir, root, depth) {
24
+ if (depth > MAX_DEPTH) return
25
+ let entries
26
+ try {
27
+ entries = await readdir(dir, { withFileTypes: true })
28
+ } catch {
29
+ return
30
+ }
31
+ for (const entry of entries) {
32
+ const full = join(dir, entry.name)
33
+ if (shouldIgnore(entry.name)) continue
34
+ if (entry.isDirectory()) {
35
+ await walk(full, root, depth + 1)
36
+ } else if (entry.name.endsWith(".html") && !(dir === root && entry.name === "index.html")) {
37
+ out.push(full)
38
+ }
29
39
  }
30
40
  }
31
- return out
32
41
  }
33
42
 
34
43
  // /api/files payload, sorted by created desc with title/path tiebreaks.
@@ -215,3 +224,10 @@ export function isWithin(base, path) {
215
224
  export function normalizedRelative(base, path) {
216
225
  return relative(base, path).split(sep).join("/")
217
226
  }
227
+
228
+ export function shouldIgnore(relPath) {
229
+ return relPath
230
+ .split(/[/\\]/)
231
+ .filter(Boolean)
232
+ .some((part) => part.startsWith(".") || part === "node_modules")
233
+ }
package/server/index.mjs CHANGED
@@ -11,7 +11,8 @@
11
11
  // └────────────────────────────────────────────────────────┘
12
12
  import { createServer } from "node:http"
13
13
  import { readFile } from "node:fs/promises"
14
- import { extname, resolve } from "node:path"
14
+ import os from "node:os"
15
+ import { basename, extname, resolve } from "node:path"
15
16
  import { exec } from "node:child_process"
16
17
  import { clearState, writeState } from "./state.mjs"
17
18
  import { apiFiles, isWithin, normalizedRelative } from "./files.mjs"
@@ -49,17 +50,21 @@ const MIME = {
49
50
  export async function runServer({ docsDir, port: initialPort, open = false }) {
50
51
  const wss = new WebSocketServer({ path: WS_PATH })
51
52
  const updateListener = new UpdateListener({ wss, docsDir, templatePath: INDEX_TEMPLATE })
52
- let port = initialPort // actually bound port (may fall back +1 on conflict)
53
+ let port = initialPort
54
+
55
+ const server = createServer(createNodeServerAdapter(createHandler({ docsDir })))
56
+ wss.attach(server)
53
57
 
54
58
  const cleanup = () => {
55
59
  updateListener.close()
60
+ wss.close()
56
61
  clearState()
62
+ server.closeAllConnections()
63
+ if (server.listening) server.close()
57
64
  }
58
65
  process.on("SIGINT", () => { cleanup(); process.exit(0) })
59
66
  process.on("SIGTERM", () => { cleanup(); process.exit(0) })
60
67
 
61
- const server = createServer(createNodeServerAdapter(createHandler({ docsDir })))
62
- wss.attach(server)
63
68
  server.on("error", (err) => {
64
69
  if (err.code === "EADDRINUSE" && port < initialPort + MAX_PORT_TRIES) {
65
70
  port += 1
@@ -76,7 +81,7 @@ export async function runServer({ docsDir, port: initialPort, open = false }) {
76
81
  console.log(state.url)
77
82
  if (open && process.platform === "darwin") exec(`open ${state.url}`)
78
83
  })
79
- return { server, wss, updateListener }
84
+ return { server, wss, updateListener, close: cleanup }
80
85
  }
81
86
 
82
87
  // --- Node server adapter ---
@@ -152,17 +157,25 @@ function createHandler({ docsDir }) {
152
157
  }
153
158
 
154
159
  // The gallery is an embedded template served at / and /index.html; docsDir's own
155
- // index.html is shadowed by it. __DOCSERVE_DIR__ is substituted for display.
160
+ // index.html is shadowed by it. Directory markers are substituted for display.
156
161
  async function galleryResponse(docsDir) {
157
162
  try {
158
163
  let html = await readFile(INDEX_TEMPLATE, "utf8")
159
- html = html.replaceAll("__DOCSERVE_DIR__", escapeHtml(docsDir))
164
+ html = html
165
+ .replaceAll("__DOCS_DIR_NAME__", escapeHtml(basename(docsDir) || docsDir))
166
+ .replaceAll("__DOCS_DIR__", escapeHtml(displayPath(docsDir)))
160
167
  return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } })
161
168
  } catch {
162
169
  return new Response("Gallery template missing", { status: 500 })
163
170
  }
164
171
  }
165
172
 
173
+ // Collapse the home directory prefix to ~ for display.
174
+ function displayPath(p) {
175
+ const home = os.homedir()
176
+ return p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p
177
+ }
178
+
166
179
  function escapeHtml(s) {
167
180
  return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
168
181
  }
@@ -0,0 +1,88 @@
1
+ <script>
2
+ (() => {
3
+ // iframes: no reload loop from dropped sockets, no copy button
4
+ if (window.self !== window.top) return
5
+
6
+ const pageId = __DOCSERVE_PAGE_ID__
7
+ const absPath = __DOCSERVE_ABS_PATH__
8
+ const wsPath = __DOCSERVE_WS_PATH__
9
+
10
+ const proto = location.protocol === "https:" ? "wss:" : "ws:"
11
+ const ws = new WebSocket(proto + "//" + location.host + wsPath)
12
+ ws.addEventListener("message", (e) => {
13
+ let change
14
+ try { change = JSON.parse(e.data) } catch { return }
15
+ if (change?.type === "change" && Array.isArray(change.pages) && change.pages.includes(pageId)) {
16
+ location.reload()
17
+ }
18
+ })
19
+ ws.addEventListener("close", () => setTimeout(() => location.reload(), 1000))
20
+
21
+ const style = document.createElement("style")
22
+ style.textContent = `#docserve-copy {
23
+ position: fixed;
24
+ top: 12px;
25
+ right: 12px;
26
+ z-index: 2147483647;
27
+ display: inline-flex;
28
+ align-items: center;
29
+ gap: 6px;
30
+ height: 28px;
31
+ padding: 0 10px 0 9px;
32
+ border: 1px solid rgba(127, 127, 138, 0.35);
33
+ border-radius: 8px;
34
+ background: rgba(127, 127, 138, 0.14);
35
+ color: inherit;
36
+ cursor: pointer;
37
+ opacity: 0.55;
38
+ transition: opacity 0.15s ease, color 0.15s ease, border-color 0.15s ease;
39
+ }
40
+ #docserve-copy svg {
41
+ width: 14px;
42
+ height: 14px;
43
+ pointer-events: none;
44
+ }
45
+ #docserve-copy .label {
46
+ font: 500 11.5px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", "Hiragino Sans", sans-serif;
47
+ letter-spacing: 0.01em;
48
+ white-space: nowrap;
49
+ }
50
+ #docserve-copy:hover {
51
+ opacity: 1;
52
+ border-color: #6c8cff;
53
+ color: #6c8cff;
54
+ }
55
+ #docserve-copy.copied {
56
+ opacity: 1;
57
+ color: #4ade80;
58
+ border-color: #4ade80;
59
+ }
60
+ @media (prefers-color-scheme: light) {
61
+ #docserve-copy:hover { border-color: #2563eb; color: #2563eb; }
62
+ #docserve-copy.copied { color: #16a34a; border-color: #16a34a; }
63
+ }
64
+ #docserve-copy .ic-check { display: none; }
65
+ #docserve-copy.copied .ic-copy { display: none; }
66
+ #docserve-copy.copied .ic-check { display: block; }`
67
+ const COPY = '<svg class="ic-copy" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>'
68
+ const CHECK = '<svg class="ic-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
69
+ const btn = document.createElement("button")
70
+ btn.id = "docserve-copy"
71
+ btn.type = "button"
72
+ btn.title = absPath
73
+ btn.innerHTML = COPY + CHECK + '<span class="label">Copy file path</span>'
74
+ btn.addEventListener("click", async () => {
75
+ try {
76
+ await navigator.clipboard.writeText(absPath)
77
+ btn.classList.add("copied")
78
+ btn.querySelector(".label").textContent = "Copied"
79
+ setTimeout(() => {
80
+ btn.classList.remove("copied")
81
+ btn.querySelector(".label").textContent = "Copy file path"
82
+ }, 1200)
83
+ } catch {}
84
+ })
85
+ document.head.appendChild(style)
86
+ document.body.appendChild(btn)
87
+ })()
88
+ </script>
package/server/inject.mjs CHANGED
@@ -1,10 +1,13 @@
1
1
  // Injection: every text/html response served from docsDir gets one client script
2
2
  // before the last </body> (appended at the end if the tag is missing). The script
3
3
  // exits immediately inside iframes, so previews get neither part; the gallery
4
- // template ships its own client.
4
+ // template ships its own client. The client template is loaded once at startup.
5
+ import { readFileSync } from "node:fs"
5
6
 
6
7
  export const WS_PATH = "/__reload"
7
8
 
9
+ const clientTemplate = readFileSync(new URL("./inject.html", import.meta.url), "utf8")
10
+
8
11
  export function injectIntoHtml(html, pageId, absPath) {
9
12
  const idx = html.toLowerCase().lastIndexOf("</body>")
10
13
  if (idx === -1) return html + clientJs(pageId, absPath)
@@ -12,89 +15,14 @@ export function injectIntoHtml(html, pageId, absPath) {
12
15
  }
13
16
 
14
17
  function clientJs(pageId, absPath) {
15
- return `<script>
16
- (() => {
17
- // iframes: no reload loop from dropped sockets, no copy button
18
- if (window.self !== window.top) return
19
- const pageId = ${JSON.stringify(pageId).replaceAll("<", "\\u003c")}
20
- const proto = location.protocol === "https:" ? "wss:" : "ws:"
21
- const ws = new WebSocket(proto + "//" + location.host + "${WS_PATH}")
22
- ws.addEventListener("message", (e) => {
23
- let change
24
- try { change = JSON.parse(e.data) } catch { return }
25
- if (change?.type === "change" && Array.isArray(change.pages) && change.pages.includes(pageId)) {
26
- location.reload()
27
- }
28
- })
29
- ws.addEventListener("close", () => setTimeout(() => location.reload(), 1000))
30
-
31
- const absPath = ${JSON.stringify(absPath).replaceAll("<", "\\u003c")}
32
- const style = document.createElement("style")
33
- style.textContent = \`#docserve-copy {
34
- position: fixed;
35
- top: 12px;
36
- right: 12px;
37
- z-index: 2147483647;
38
- display: inline-flex;
39
- align-items: center;
40
- gap: 6px;
41
- height: 28px;
42
- padding: 0 10px 0 9px;
43
- border: 1px solid rgba(127, 127, 138, 0.35);
44
- border-radius: 8px;
45
- background: rgba(127, 127, 138, 0.14);
46
- color: inherit;
47
- cursor: pointer;
48
- opacity: 0.55;
49
- transition: opacity 0.15s ease, color 0.15s ease, border-color 0.15s ease;
50
- }
51
- #docserve-copy svg {
52
- width: 14px;
53
- height: 14px;
54
- pointer-events: none;
55
- }
56
- #docserve-copy .label {
57
- font: 500 11.5px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", "Hiragino Sans", sans-serif;
58
- letter-spacing: 0.01em;
59
- white-space: nowrap;
60
- }
61
- #docserve-copy:hover {
62
- opacity: 1;
63
- border-color: #6c8cff;
64
- color: #6c8cff;
65
- }
66
- #docserve-copy.copied {
67
- opacity: 1;
68
- color: #4ade80;
69
- border-color: #4ade80;
70
- }
71
- @media (prefers-color-scheme: light) {
72
- #docserve-copy:hover { border-color: #2563eb; color: #2563eb; }
73
- #docserve-copy.copied { color: #16a34a; border-color: #16a34a; }
74
- }
75
- #docserve-copy .ic-check { display: none; }
76
- #docserve-copy.copied .ic-copy { display: none; }
77
- #docserve-copy.copied .ic-check { display: block; }\`
78
- const COPY = '<svg class="ic-copy" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>'
79
- const CHECK = '<svg class="ic-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
80
- const btn = document.createElement("button")
81
- btn.id = "docserve-copy"
82
- btn.type = "button"
83
- btn.title = absPath
84
- btn.innerHTML = COPY + CHECK + '<span class="label">Copy file path</span>'
85
- btn.addEventListener("click", async () => {
86
- try {
87
- await navigator.clipboard.writeText(absPath)
88
- btn.classList.add("copied")
89
- btn.querySelector(".label").textContent = "Copied"
90
- setTimeout(() => {
91
- btn.classList.remove("copied")
92
- btn.querySelector(".label").textContent = "Copy file path"
93
- }, 1200)
94
- } catch {}
95
- })
96
- document.head.appendChild(style)
97
- document.body.appendChild(btn)
98
- })()
99
- </script>`
18
+ const values = {
19
+ PAGE_ID: JSON.stringify(pageId).replaceAll("<", "\\u003c"),
20
+ ABS_PATH: JSON.stringify(absPath).replaceAll("<", "\\u003c"),
21
+ WS_PATH: JSON.stringify(WS_PATH),
22
+ }
23
+ let rendered = clientTemplate
24
+ for (const [key, value] of Object.entries(values)) {
25
+ rendered = rendered.replaceAll(`__DOCSERVE_${key}__`, () => value)
26
+ }
27
+ return rendered
100
28
  }
package/server/state.mjs CHANGED
@@ -1,20 +1,42 @@
1
- // state.json read/write + pid liveness.
1
+ // Per-instance state files + pid liveness.
2
2
  //
3
- // The server writes ~/.cache/docserve/state.json once the port is bound and
4
- // removes it on clean shutdown. Readers verify the PID is alive and treat
5
- // dead-PID state as stale (removed in place).
3
+ // Each server owns one file: ~/.docserve/state/<port>-<name>.json
4
+ // (name = sanitized folder name), written once the port is bound and removed
5
+ // on clean shutdown. Readers verify the PID is alive and treat dead-PID state
6
+ // as stale (removed in place). DOCSERVE_HOME overrides the docserve home
7
+ // (test isolation).
6
8
  import fs from "node:fs"
7
9
  import os from "node:os"
8
10
  import path from "node:path"
9
11
 
10
- // DOCSERVE_STATE overrides the state file path (test isolation).
11
- export function statePath() {
12
- return process.env.DOCSERVE_STATE || path.join(os.homedir(), ".cache", "docserve", "state.json")
12
+ let ownFile = null // file written by this process, removed by clearState()
13
+
14
+ // DOCSERVE_HOME overrides the docserve home (test isolation).
15
+ export function homeDir() {
16
+ return process.env.DOCSERVE_HOME || path.join(os.homedir(), ".docserve")
17
+ }
18
+
19
+ export function stateDir() {
20
+ return path.join(homeDir(), "state")
13
21
  }
14
22
 
15
- export function readState() {
23
+ // <port>-<name>.json, e.g. 4242-reports.json. The port prefix keeps files
24
+ // unique (the port is exclusively bound while the server runs); the folder
25
+ // name is cosmetic. Parsing always reads the file contents, never the name.
26
+ function fileName(state) {
27
+ const name = path
28
+ .basename(state.docsDir)
29
+ .replace(/[\0\\/:*?"<>|]/g, "-")
30
+ .replace(/\p{Cc}/gu, "")
31
+ .replace(/^\.+/, "")
32
+ .slice(0, 40)
33
+ .replace(/^[-.]+|[-.]+$/g, "")
34
+ return `${state.port}-${name || "docs"}.json`
35
+ }
36
+
37
+ function readStateFile(file) {
16
38
  try {
17
- const state = JSON.parse(fs.readFileSync(statePath(), "utf8"))
39
+ const state = JSON.parse(fs.readFileSync(file, "utf8"))
18
40
  if (
19
41
  typeof state?.pid === "number" &&
20
42
  typeof state?.port === "number" &&
@@ -29,33 +51,65 @@ export function readState() {
29
51
  }
30
52
  }
31
53
 
54
+ export function isProcessAlive(pid) {
55
+ try {
56
+ process.kill(pid, 0)
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
32
63
  export function writeState(state) {
33
- fs.mkdirSync(path.dirname(statePath()), { recursive: true })
34
- fs.writeFileSync(statePath(), JSON.stringify(state, null, 2) + "\n")
64
+ fs.mkdirSync(stateDir(), { recursive: true })
65
+ const file = path.join(stateDir(), fileName(state))
66
+ const tmp = `${file}.${process.pid}.tmp`
67
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n")
68
+ fs.renameSync(tmp, file)
69
+ ownFile = file
35
70
  }
36
71
 
72
+ // Remove this process's own instance file (server shutdown).
37
73
  export function clearState() {
74
+ if (!ownFile) return
38
75
  try {
39
- fs.rmSync(statePath(), { force: true })
76
+ fs.rmSync(ownFile, { force: true })
40
77
  } catch {}
78
+ ownFile = null
41
79
  }
42
80
 
43
- export function isProcessAlive(pid) {
81
+ // Remove the file of a specific instance (CLI stop).
82
+ export function removeState(state) {
44
83
  try {
45
- process.kill(pid, 0)
46
- return true
47
- } catch {
48
- return false
49
- }
84
+ fs.rmSync(path.join(stateDir(), fileName(state)), { force: true })
85
+ } catch {}
50
86
  }
51
87
 
52
- // Read the state and drop stale entries (dead pid) in place.
53
- export function readLiveState() {
54
- const state = readState()
55
- if (!state) return null
56
- if (!isProcessAlive(state.pid)) {
57
- clearState()
58
- return null
88
+ // All live instances, sorted by port. Stale files (dead pid) are pruned in
89
+ // place; unparseable files are left for inspection.
90
+ export function listLiveStates() {
91
+ let entries = []
92
+ try {
93
+ entries = fs.readdirSync(stateDir())
94
+ } catch {}
95
+ const states = []
96
+ for (const entry of entries) {
97
+ if (!entry.endsWith(".json")) continue
98
+ const file = path.join(stateDir(), entry)
99
+ const state = readStateFile(file)
100
+ if (!state) continue
101
+ if (!isProcessAlive(state.pid)) {
102
+ try {
103
+ fs.rmSync(file, { force: true })
104
+ } catch {}
105
+ continue
106
+ }
107
+ states.push(state)
59
108
  }
60
- return state
109
+ return states.sort((a, b) => a.port - b.port)
110
+ }
111
+
112
+ export function findByDir(docsDir) {
113
+ const resolved = path.resolve(docsDir)
114
+ return listLiveStates().find((state) => state.docsDir === resolved) ?? null
61
115
  }
package/server/watch.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  // set never flip contentSetChanged.
8
8
  import { existsSync, watch } from "node:fs"
9
9
  import { basename, dirname, resolve } from "node:path"
10
- import { isWithin, listHtmlFiles, normalizedRelative } from "./files.mjs"
10
+ import { isWithin, listHtmlFiles, normalizedRelative, shouldIgnore } from "./files.mjs"
11
11
 
12
12
  const DEBOUNCE_MS = 50 // like livePreview.previewDebounceDelay
13
13
  const TEMPLATE_TOUCH = "\u0000template" // sentinel: never a real docsDir-relative path
@@ -41,6 +41,7 @@ export class UpdateListener {
41
41
  this.watchers.push(
42
42
  watch(this.docsDir, { recursive: true }, (event, filename) => {
43
43
  if (!filename?.endsWith(".html")) return
44
+ if (shouldIgnore(filename)) return
44
45
  const full = resolve(this.docsDir, filename)
45
46
  if (!isWithin(this.docsDir, full)) return
46
47
  this.queueBroadcast(normalizedRelative(this.docsDir, full))
@@ -54,6 +54,15 @@ export class WebSocketServer {
54
54
  }
55
55
  }
56
56
  }
57
+
58
+ close() {
59
+ for (const socket of this.clients) {
60
+ try {
61
+ socket.destroy()
62
+ } catch {}
63
+ }
64
+ this.clients.clear()
65
+ }
57
66
  }
58
67
 
59
68
  function acceptKey(key) {