@noy4/docserve 0.2.0 → 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/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.2.0",
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/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) {