@noy4/docserve 0.3.1 → 0.3.3
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 +2 -2
- package/dist/widget/index.js +11155 -0
- package/package.json +24 -3
- package/src/node/adapter.mjs +67 -0
- package/src/node/assets.mjs +36 -0
- package/src/node/dates.mjs +73 -0
- package/src/node/docs-info.mjs +39 -0
- package/src/node/files.mjs +43 -0
- package/src/node/gallery.mjs +33 -0
- package/src/node/inject.mjs +43 -0
- package/src/node/meta.mjs +137 -0
- package/src/node/routes.mjs +105 -0
- package/src/node/scan.mjs +87 -0
- package/src/node/serve-static.mjs +158 -0
- package/src/node/server.mjs +69 -0
- package/src/node/watch.mjs +119 -0
- package/src/plugins/copy/client.js +72 -0
- package/src/plugins/copy/copy.css +21 -0
- package/src/plugins/home/client.js +24 -0
- package/src/plugins/sidebar/client.js +105 -0
- package/src/plugins/sidebar/grouping.js +108 -0
- package/src/plugins/sidebar/icons.js +25 -0
- package/src/plugins/sidebar/model.ts +91 -0
- package/src/plugins/sidebar/resize-model.ts +47 -0
- package/src/plugins/sidebar/sidebar.css +663 -0
- package/src/plugins/sidebar/tree-model.ts +23 -0
- package/src/plugins/sidebar/tree.ts +69 -0
- package/src/plugins/sidebar/ui/PageList.tsx +153 -0
- package/src/plugins/sidebar/ui/RadioMenu.tsx +201 -0
- package/src/plugins/sidebar/ui/Sidebar.tsx +95 -0
- package/src/plugins/sidebar/ui/SidebarHeader.tsx +87 -0
- package/src/plugins/sidebar/ui/TreeList.tsx +121 -0
- package/src/plugins/sidebar/ui/preview-model.ts +134 -0
- package/src/plugins/sidebar/ui/useModel.ts +25 -0
- package/src/shared/types.d.ts +193 -0
- package/src/widget/commands.js +214 -0
- package/src/widget/docks.js +127 -0
- package/src/widget/host.js +187 -0
- package/src/widget/index.js +14 -0
- package/src/widget/lib/disposables.js +44 -0
- package/src/widget/lib/dom.js +106 -0
- package/src/widget/lib/events.js +65 -0
- package/src/widget/lib/persisted-signal.js +40 -0
- package/src/widget/lib/storage.js +70 -0
- package/src/widget/live.js +86 -0
- package/src/widget/pages.js +65 -0
- package/src/widget/palette.css +162 -0
- package/src/widget/palette.js +259 -0
- package/src/widget/placement.js +204 -0
- package/src/widget/plugins.js +39 -0
- package/src/widget/rpc.js +32 -0
- package/src/widget/styles.js +31 -0
- package/src/widget/ui.js +50 -0
- package/src/widget/widget.css +193 -0
- package/server/files.mjs +0 -233
- package/server/index.mjs +0 -189
- package/server/inject.html +0 -88
- package/server/inject.mjs +0 -28
- package/server/watch.mjs +0 -104
- /package/{server → src/node}/state.mjs +0 -0
- /package/{server → src/node}/websocket.mjs +0 -0
package/server/files.mjs
DELETED
|
@@ -1,233 +0,0 @@
|
|
|
1
|
-
// File metadata for /api/files: recursive *.html listing (excluding index.html),
|
|
2
|
-
// <title> / <meta name="created_at"> / <link rel="icon"> extraction, and git date
|
|
3
|
-
// maps cached per repo root.
|
|
4
|
-
//
|
|
5
|
-
// Created-date priority: meta created_at > oldest git add commit > birthtime.
|
|
6
|
-
import { open, readdir, stat } from "node:fs/promises"
|
|
7
|
-
import { realpathSync } from "node:fs"
|
|
8
|
-
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"
|
|
9
|
-
import { execFile } from "node:child_process"
|
|
10
|
-
import { promisify } from "node:util"
|
|
11
|
-
|
|
12
|
-
const run = promisify(execFile)
|
|
13
|
-
|
|
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
|
-
}
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// /api/files payload, sorted by created desc with title/path tiebreaks.
|
|
44
|
-
export async function apiFiles(docsDir) {
|
|
45
|
-
const paths = await listHtmlFiles(docsDir)
|
|
46
|
-
const { created, modified } = await gitDateMaps(docsDir)
|
|
47
|
-
const files = []
|
|
48
|
-
for (const full of paths) {
|
|
49
|
-
let st
|
|
50
|
-
try {
|
|
51
|
-
st = await stat(full)
|
|
52
|
-
} catch {
|
|
53
|
-
continue // deleted between listing and stat
|
|
54
|
-
}
|
|
55
|
-
const { title, date, favicon } = await metaOf(full, st.mtimeMs, docsDir)
|
|
56
|
-
let key
|
|
57
|
-
try {
|
|
58
|
-
key = realpathSync(full)
|
|
59
|
-
} catch {
|
|
60
|
-
continue
|
|
61
|
-
}
|
|
62
|
-
const rel = normalizedRelative(docsDir, full)
|
|
63
|
-
files.push({
|
|
64
|
-
title: title ?? basename(full),
|
|
65
|
-
url: `/${rel}`,
|
|
66
|
-
filePath: full,
|
|
67
|
-
favicon: favicon ?? undefined,
|
|
68
|
-
created: date ?? created.get(key) ?? Math.floor(st.birthtimeMs / 1000),
|
|
69
|
-
modified: modified.get(key) ?? Math.floor(st.mtimeMs / 1000),
|
|
70
|
-
})
|
|
71
|
-
}
|
|
72
|
-
files.sort((a, b) => b.created - a.created || a.title.localeCompare(b.title, "ja") || a.url.localeCompare(b.url))
|
|
73
|
-
return files
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// <title>, <meta name="created_at"> and <link rel="icon"> extracted from the head
|
|
77
|
-
// of a report; cached by path + mtime so repeated /api/files calls only re-read
|
|
78
|
-
// files that changed.
|
|
79
|
-
const metaCache = new Map() // "path:mtimeMs" -> { title, date, favicon }
|
|
80
|
-
|
|
81
|
-
async function metaOf(full, mtimeMs, docsDir) {
|
|
82
|
-
const key = `${full}:${mtimeMs}`
|
|
83
|
-
const cached = metaCache.get(key)
|
|
84
|
-
if (cached !== undefined) return cached
|
|
85
|
-
const meta = await extractMeta(full, docsDir)
|
|
86
|
-
metaCache.set(key, meta)
|
|
87
|
-
return meta
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
async function extractMeta(full, docsDir) {
|
|
91
|
-
const findTitle = (text) => text.match(/<title>([^<]*)<\/title>/)?.[1]?.trim() ?? null
|
|
92
|
-
const findDate = (text) => {
|
|
93
|
-
for (const tag of text.match(/<meta\b[^>]*>/gi) ?? []) {
|
|
94
|
-
if (!/\bname\s*=\s*["']created_at["']/i.test(tag)) continue
|
|
95
|
-
const d = new Date(tag.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1]?.trim() ?? "")
|
|
96
|
-
if (!isNaN(d.getTime())) return Math.floor(d.getTime() / 1000)
|
|
97
|
-
}
|
|
98
|
-
return null
|
|
99
|
-
}
|
|
100
|
-
// Attribute value from a tag string ("v", 'v', or bare); null when absent.
|
|
101
|
-
const attrOf = (tag, name) => {
|
|
102
|
-
const m = tag.match(new RegExp(`(?<![\\w-])${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"))
|
|
103
|
-
return m?.[1] ?? m?.[2] ?? m?.[3] ?? null
|
|
104
|
-
}
|
|
105
|
-
// First <link rel="...icon..."> href resolved to a URL served from docsDir;
|
|
106
|
-
// data: and absolute http(s) URLs are kept as-is.
|
|
107
|
-
const findFavicon = (text) => {
|
|
108
|
-
// Quoted values may contain ">" (inline SVG data URIs), so scan links
|
|
109
|
-
// value-aware instead of with a plain [^>]* tag match.
|
|
110
|
-
for (const tag of text.match(/<link\b(?:"[^"]*"|'[^']*'|[^>])*>/gi) ?? []) {
|
|
111
|
-
const rel = attrOf(tag, "rel")
|
|
112
|
-
if (!rel || !/\bicon\b/i.test(rel)) continue
|
|
113
|
-
const href = attrOf(tag, "href")?.trim()
|
|
114
|
-
if (!href) continue
|
|
115
|
-
if (/^data:/i.test(href)) return href.replaceAll("#", "%23")
|
|
116
|
-
if (/^(https?:|\/\/)/i.test(href)) return href
|
|
117
|
-
const target = href.startsWith("/")
|
|
118
|
-
? join(docsDir, href.split(/[?#]/)[0])
|
|
119
|
-
: join(dirname(full), href.split(/[?#]/)[0])
|
|
120
|
-
if (!isWithin(docsDir, target)) return null
|
|
121
|
-
return `/${normalizedRelative(docsDir, target)}`
|
|
122
|
-
}
|
|
123
|
-
return null
|
|
124
|
-
}
|
|
125
|
-
try {
|
|
126
|
-
const handle = await open(full, "r")
|
|
127
|
-
try {
|
|
128
|
-
const read = async (len, pos) => {
|
|
129
|
-
const { buffer, bytesRead } = await handle.read(Buffer.alloc(len), 0, len, pos)
|
|
130
|
-
return buffer.toString("utf8", 0, bytesRead)
|
|
131
|
-
}
|
|
132
|
-
// Titles and meta tags live in <head>; read only the first 4 KB.
|
|
133
|
-
const head = await read(4096, 0)
|
|
134
|
-
let meta = { title: findTitle(head), date: findDate(head), favicon: findFavicon(head) }
|
|
135
|
-
if (meta.title === null || meta.date === null || meta.favicon === null) {
|
|
136
|
-
// Fallback for documents with a long preamble (inline favicon etc.)
|
|
137
|
-
const text = await read(1 << 20, 0)
|
|
138
|
-
meta = {
|
|
139
|
-
title: meta.title ?? findTitle(text),
|
|
140
|
-
date: meta.date ?? findDate(text),
|
|
141
|
-
favicon: meta.favicon ?? findFavicon(text),
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
return meta
|
|
145
|
-
} finally {
|
|
146
|
-
await handle.close()
|
|
147
|
-
}
|
|
148
|
-
} catch {
|
|
149
|
-
return { title: null, date: null, favicon: null }
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// Resolve created/modified dates from git history, keyed by absolute path.
|
|
154
|
-
// A single full-repo scan with cwd set to the docs dir, cached per repo root in
|
|
155
|
-
// module scope. git log outputs newest first: overwriting keeps the oldest add
|
|
156
|
-
// (= creation date) and the newest touch (= modified date).
|
|
157
|
-
const gitMapsCache = new Map() // repo root (or docsDir when not a repo) -> { created, modified }
|
|
158
|
-
|
|
159
|
-
async function gitDateMaps(docsDir) {
|
|
160
|
-
const cwd = realpath(docsDir)
|
|
161
|
-
const top = (await git(["rev-parse", "--show-toplevel"], cwd)).trim()
|
|
162
|
-
const root = top ? realpath(top) : null
|
|
163
|
-
const cacheKey = root ?? cwd
|
|
164
|
-
let maps = gitMapsCache.get(cacheKey)
|
|
165
|
-
if (maps) return maps
|
|
166
|
-
|
|
167
|
-
maps = { created: new Map(), modified: new Map() }
|
|
168
|
-
if (root) {
|
|
169
|
-
try {
|
|
170
|
-
const [first, last] = await Promise.all([
|
|
171
|
-
git(["log", "--diff-filter=A", "--name-only", "--format=c:%at"], cwd),
|
|
172
|
-
git(["log", "--name-only", "--format=m:%at"], cwd),
|
|
173
|
-
])
|
|
174
|
-
let ts
|
|
175
|
-
for (const line of first.split("\n")) {
|
|
176
|
-
if (line.startsWith("c:")) {
|
|
177
|
-
ts = parseInt(line.slice(2), 10)
|
|
178
|
-
} else if (line && ts !== undefined) {
|
|
179
|
-
maps.created.set(join(root, line), ts) // oldest add wins
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
ts = undefined
|
|
183
|
-
for (const line of last.split("\n")) {
|
|
184
|
-
if (line.startsWith("m:")) {
|
|
185
|
-
ts = parseInt(line.slice(2), 10)
|
|
186
|
-
} else if (line && ts !== undefined) {
|
|
187
|
-
maps.modified.set(join(root, line), ts) // newest touch wins
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
} catch {
|
|
191
|
-
// unreadable history → fall back to fs dates
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
gitMapsCache.set(cacheKey, maps)
|
|
195
|
-
return maps
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
async function git(args, cwd) {
|
|
199
|
-
try {
|
|
200
|
-
const { stdout } = await run("git", args, { cwd, timeout: 10000, maxBuffer: 64 * 1024 * 1024 })
|
|
201
|
-
return stdout
|
|
202
|
-
} catch {
|
|
203
|
-
return ""
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// On macOS /var is a symlink to /private/var; canonicalize to real paths so
|
|
208
|
-
// lookups match git output.
|
|
209
|
-
function realpath(p) {
|
|
210
|
-
try {
|
|
211
|
-
return realpathSync(p)
|
|
212
|
-
} catch {
|
|
213
|
-
return p
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// --- Path utilities (shared by the HTTP handler and the watcher) ---
|
|
218
|
-
|
|
219
|
-
export function isWithin(base, path) {
|
|
220
|
-
const rel = relative(base, path)
|
|
221
|
-
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
export function normalizedRelative(base, path) {
|
|
225
|
-
return relative(base, path).split(sep).join("/")
|
|
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
DELETED
|
@@ -1,189 +0,0 @@
|
|
|
1
|
-
// docserve server core: HTTP layer + server lifecycle.
|
|
2
|
-
//
|
|
3
|
-
// ┌────────────────────────────────────────────────────────┐
|
|
4
|
-
// │ runServer() │
|
|
5
|
-
// │ ├─ createServer ──▶ handler() │ # HTTP
|
|
6
|
-
// │ │ ├─ /api/files ──▶ apiFiles() │
|
|
7
|
-
// │ │ ├─ /, /index.html ──▶ gallery template │
|
|
8
|
-
// │ │ └─ other paths ──▶ raw files ──▶ injectIntoHtml() │
|
|
9
|
-
// │ ├─ WebSocketServer("/__reload") ◀─ FileWatcher │
|
|
10
|
-
// │ └─ listen ──▶ listener.start() + writeState() │
|
|
11
|
-
// └────────────────────────────────────────────────────────┘
|
|
12
|
-
import { createServer } from "node:http"
|
|
13
|
-
import { readFile } from "node:fs/promises"
|
|
14
|
-
import os from "node:os"
|
|
15
|
-
import { basename, extname, resolve } from "node:path"
|
|
16
|
-
import { exec } from "node:child_process"
|
|
17
|
-
import { clearState, writeState } from "./state.mjs"
|
|
18
|
-
import { apiFiles, isWithin, normalizedRelative } from "./files.mjs"
|
|
19
|
-
import { injectIntoHtml, WS_PATH } from "./inject.mjs"
|
|
20
|
-
import { WebSocketServer } from "./websocket.mjs"
|
|
21
|
-
import { FileWatcher } from "./watch.mjs"
|
|
22
|
-
|
|
23
|
-
const MAX_PORT_TRIES = 20 // on conflict, try the next port up to 20 times
|
|
24
|
-
const INDEX_TEMPLATE = resolve(import.meta.dirname, "..", "index.html")
|
|
25
|
-
|
|
26
|
-
const MIME = {
|
|
27
|
-
".html": "text/html",
|
|
28
|
-
".htm": "text/html",
|
|
29
|
-
".js": "text/javascript",
|
|
30
|
-
".mjs": "text/javascript",
|
|
31
|
-
".css": "text/css",
|
|
32
|
-
".json": "application/json",
|
|
33
|
-
".txt": "text/plain",
|
|
34
|
-
".md": "text/markdown",
|
|
35
|
-
".xml": "application/xml",
|
|
36
|
-
".png": "image/png",
|
|
37
|
-
".jpg": "image/jpeg",
|
|
38
|
-
".jpeg": "image/jpeg",
|
|
39
|
-
".gif": "image/gif",
|
|
40
|
-
".svg": "image/svg+xml",
|
|
41
|
-
".webp": "image/webp",
|
|
42
|
-
".ico": "image/x-icon",
|
|
43
|
-
".pdf": "application/pdf",
|
|
44
|
-
".woff": "font/woff",
|
|
45
|
-
".woff2": "font/woff2",
|
|
46
|
-
".mp4": "video/mp4",
|
|
47
|
-
".webm": "video/webm",
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export async function runServer({ docsDir, port: initialPort, open = false }) {
|
|
51
|
-
const wss = new WebSocketServer({ path: WS_PATH })
|
|
52
|
-
const fileWatcher = new FileWatcher({ wss, docsDir, templatePath: INDEX_TEMPLATE })
|
|
53
|
-
let port = initialPort
|
|
54
|
-
|
|
55
|
-
const server = createServer(createNodeServerAdapter(createHandler({ docsDir })))
|
|
56
|
-
wss.attach(server)
|
|
57
|
-
|
|
58
|
-
const cleanup = () => {
|
|
59
|
-
fileWatcher.close()
|
|
60
|
-
wss.close()
|
|
61
|
-
clearState()
|
|
62
|
-
server.closeAllConnections()
|
|
63
|
-
if (server.listening) server.close()
|
|
64
|
-
}
|
|
65
|
-
process.on("SIGINT", () => { cleanup(); process.exit(0) })
|
|
66
|
-
process.on("SIGTERM", () => { cleanup(); process.exit(0) })
|
|
67
|
-
|
|
68
|
-
server.on("error", (err) => {
|
|
69
|
-
if (err.code === "EADDRINUSE" && port < initialPort + MAX_PORT_TRIES) {
|
|
70
|
-
port += 1
|
|
71
|
-
server.listen(port, "127.0.0.1")
|
|
72
|
-
} else {
|
|
73
|
-
console.error(err)
|
|
74
|
-
process.exit(1)
|
|
75
|
-
}
|
|
76
|
-
})
|
|
77
|
-
server.listen(port, "127.0.0.1", async () => {
|
|
78
|
-
await fileWatcher.start()
|
|
79
|
-
const state = { pid: process.pid, port, url: `http://localhost:${port}/`, docsDir }
|
|
80
|
-
writeState(state)
|
|
81
|
-
console.log(state.url)
|
|
82
|
-
if (open && process.platform === "darwin") exec(`open ${state.url}`)
|
|
83
|
-
})
|
|
84
|
-
return { server, wss, fileWatcher, close: cleanup }
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// --- Node server adapter ---
|
|
88
|
-
|
|
89
|
-
function createNodeServerAdapter(handler) {
|
|
90
|
-
return async (req, res) => {
|
|
91
|
-
try {
|
|
92
|
-
const response = await handler(toWebRequest(req))
|
|
93
|
-
res.writeHead(response.status, Object.fromEntries(response.headers))
|
|
94
|
-
res.end(Buffer.from(await response.arrayBuffer()))
|
|
95
|
-
} catch (err) {
|
|
96
|
-
console.error(err)
|
|
97
|
-
res.writeHead(500, { "content-type": "text/plain" })
|
|
98
|
-
res.end("Internal Server Error")
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function toWebRequest(req) {
|
|
104
|
-
const host = req.headers.host || "localhost"
|
|
105
|
-
return new Request(`http://${host}${req.url}`, { method: req.method, headers: req.headers })
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// --- HTTP handler ---
|
|
109
|
-
|
|
110
|
-
function createHandler({ docsDir }) {
|
|
111
|
-
return async function handler(request) {
|
|
112
|
-
const url = new URL(request.url)
|
|
113
|
-
|
|
114
|
-
if (url.pathname === "/api/files") {
|
|
115
|
-
try {
|
|
116
|
-
return Response.json(await apiFiles(docsDir))
|
|
117
|
-
} catch (err) {
|
|
118
|
-
console.error(err)
|
|
119
|
-
return Response.json([])
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
let pathname
|
|
124
|
-
try {
|
|
125
|
-
pathname = decodeURIComponent(url.pathname)
|
|
126
|
-
} catch {
|
|
127
|
-
return new Response("Bad Request", { status: 400 })
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
if (pathname === "/" || pathname === "/index.html") {
|
|
131
|
-
return galleryResponse(docsDir)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
if (pathname.includes("\0")) {
|
|
135
|
-
return new Response("Bad Request", { status: 400 })
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const path = resolve(docsDir, pathname.slice(1))
|
|
139
|
-
if (!isWithin(docsDir, path)) {
|
|
140
|
-
return new Response("Forbidden", { status: 403 })
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
try {
|
|
144
|
-
const body = await readFile(path)
|
|
145
|
-
const type = MIME[extname(path).toLowerCase()] || "application/octet-stream"
|
|
146
|
-
// Inject the reload client + copy path button into docsDir pages only;
|
|
147
|
-
// the gallery template ships its own client.
|
|
148
|
-
if (type === "text/html") {
|
|
149
|
-
const html = injectIntoHtml(body.toString(), normalizedRelative(docsDir, path), path)
|
|
150
|
-
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } })
|
|
151
|
-
}
|
|
152
|
-
return new Response(body, { headers: { "content-type": type } })
|
|
153
|
-
} catch {
|
|
154
|
-
return new Response("Not Found", { status: 404 })
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// The gallery is an embedded template served at / and /index.html; docsDir's own
|
|
160
|
-
// index.html is shadowed by it. Directory markers are substituted for display.
|
|
161
|
-
async function galleryResponse(docsDir) {
|
|
162
|
-
try {
|
|
163
|
-
let html = await readFile(INDEX_TEMPLATE, "utf8")
|
|
164
|
-
html = html
|
|
165
|
-
.replaceAll("__DOCS_DIR_NAME__", escapeHtml(basename(docsDir) || docsDir))
|
|
166
|
-
.replaceAll("__DOCS_DIR__", escapeHtml(displayPath(docsDir)))
|
|
167
|
-
.replaceAll("__FAVICON_HUE__", String(faviconHue(docsDir)))
|
|
168
|
-
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } })
|
|
169
|
-
} catch {
|
|
170
|
-
return new Response("Gallery template missing", { status: 500 })
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// Collapse the home directory prefix to ~ for display.
|
|
175
|
-
function displayPath(p) {
|
|
176
|
-
const home = os.homedir()
|
|
177
|
-
return p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// Deterministic hue for the folder favicon: the same path always yields the same color.
|
|
181
|
-
function faviconHue(s) {
|
|
182
|
-
let h = 0
|
|
183
|
-
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0
|
|
184
|
-
return ((h % 360) + 360) % 360
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function escapeHtml(s) {
|
|
188
|
-
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
|
|
189
|
-
}
|
package/server/inject.html
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
// Injection: every text/html response served from docsDir gets one client script
|
|
2
|
-
// before the last </body> (appended at the end if the tag is missing). The script
|
|
3
|
-
// exits immediately inside iframes, so previews get neither part; the gallery
|
|
4
|
-
// template ships its own client. The client template is loaded once at startup.
|
|
5
|
-
import { readFileSync } from "node:fs"
|
|
6
|
-
|
|
7
|
-
export const WS_PATH = "/__reload"
|
|
8
|
-
|
|
9
|
-
const clientTemplate = readFileSync(new URL("./inject.html", import.meta.url), "utf8")
|
|
10
|
-
|
|
11
|
-
export function injectIntoHtml(html, pageId, absPath) {
|
|
12
|
-
const idx = html.toLowerCase().lastIndexOf("</body>")
|
|
13
|
-
if (idx === -1) return html + clientJs(pageId, absPath)
|
|
14
|
-
return html.slice(0, idx) + clientJs(pageId, absPath) + html.slice(idx)
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function clientJs(pageId, absPath) {
|
|
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
|
|
28
|
-
}
|
package/server/watch.mjs
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
// FileWatcher: watch docsDir recursively for *.html changes and broadcast
|
|
2
|
-
// debounced batches over the reload socket. The gallery template is watched
|
|
3
|
-
// too; its edits set templateChanged so gallery tabs pick them up even though
|
|
4
|
-
// nothing in docsDir changed.
|
|
5
|
-
//
|
|
6
|
-
// The gallery list is every *.html except any index.html; files outside that
|
|
7
|
-
// set never flip contentSetChanged.
|
|
8
|
-
import { existsSync, watch } from "node:fs"
|
|
9
|
-
import { basename, dirname, resolve } from "node:path"
|
|
10
|
-
import { isWithin, listHtmlFiles, normalizedRelative, shouldIgnore } from "./files.mjs"
|
|
11
|
-
|
|
12
|
-
const DEBOUNCE_MS = 50 // like livePreview.previewDebounceDelay
|
|
13
|
-
const TEMPLATE_TOUCH = "\u0000template" // sentinel: never a real docsDir-relative path
|
|
14
|
-
|
|
15
|
-
export class FileWatcher {
|
|
16
|
-
constructor(options = {}) {
|
|
17
|
-
this.wss = options.wss
|
|
18
|
-
this.docsDir = options.docsDir
|
|
19
|
-
this.templatePath = options.templatePath
|
|
20
|
-
this.debounceMs = options.debounceMs ?? DEBOUNCE_MS
|
|
21
|
-
this.knownFiles = new Set()
|
|
22
|
-
this.broadcastQueue = Promise.resolve()
|
|
23
|
-
this.watchers = []
|
|
24
|
-
|
|
25
|
-
this.queueBroadcast = debounceBatch((touched) => {
|
|
26
|
-
this.broadcastQueue = this.broadcastQueue
|
|
27
|
-
.then(() => this.broadcastChanges(touched))
|
|
28
|
-
.catch((error) => console.error(error))
|
|
29
|
-
}, this.debounceMs)
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async start() {
|
|
33
|
-
try {
|
|
34
|
-
this.knownFiles = new Set(
|
|
35
|
-
(await listHtmlFiles(this.docsDir)).map((p) => normalizedRelative(this.docsDir, p)),
|
|
36
|
-
)
|
|
37
|
-
} catch {
|
|
38
|
-
this.knownFiles = new Set()
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
this.watchers.push(
|
|
42
|
-
watch(this.docsDir, { recursive: true }, (event, filename) => {
|
|
43
|
-
if (!filename?.endsWith(".html")) return
|
|
44
|
-
if (shouldIgnore(filename)) return
|
|
45
|
-
const full = resolve(this.docsDir, filename)
|
|
46
|
-
if (!isWithin(this.docsDir, full)) return
|
|
47
|
-
this.queueBroadcast(normalizedRelative(this.docsDir, full))
|
|
48
|
-
}).on("error", () => {}),
|
|
49
|
-
)
|
|
50
|
-
|
|
51
|
-
if (this.templatePath) {
|
|
52
|
-
// Watch the template's directory: atomic saves replace the file, so the
|
|
53
|
-
// file itself would miss events.
|
|
54
|
-
const templateName = basename(this.templatePath)
|
|
55
|
-
this.watchers.push(
|
|
56
|
-
watch(dirname(this.templatePath), (event, filename) => {
|
|
57
|
-
if (filename === templateName) this.queueBroadcast(TEMPLATE_TOUCH)
|
|
58
|
-
}).on("error", () => {}),
|
|
59
|
-
)
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
async broadcastChanges(touched) {
|
|
64
|
-
let contentSetChanged = false
|
|
65
|
-
const templateChanged = touched.includes(TEMPLATE_TOUCH)
|
|
66
|
-
const pages = touched.filter((rel) => rel !== TEMPLATE_TOUCH)
|
|
67
|
-
|
|
68
|
-
for (const rel of pages) {
|
|
69
|
-
if (basename(rel) === "index.html") continue // never a gallery card
|
|
70
|
-
const full = resolve(this.docsDir, rel)
|
|
71
|
-
const exists = existsSync(full)
|
|
72
|
-
const wasKnown = this.knownFiles.has(rel)
|
|
73
|
-
|
|
74
|
-
if (exists && !wasKnown) {
|
|
75
|
-
this.knownFiles.add(rel)
|
|
76
|
-
contentSetChanged = true
|
|
77
|
-
} else if (!exists && wasKnown) {
|
|
78
|
-
this.knownFiles.delete(rel)
|
|
79
|
-
contentSetChanged = true
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
this.wss.broadcast({ type: "change", pages, contentSetChanged, templateChanged })
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
close() {
|
|
87
|
-
this.watchers.forEach((w) => w.close())
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// Accumulate items during the debounce window and deliver them as one batch.
|
|
92
|
-
function debounceBatch(fn, ms) {
|
|
93
|
-
let timer = null
|
|
94
|
-
const pending = new Set()
|
|
95
|
-
return (item) => {
|
|
96
|
-
pending.add(item)
|
|
97
|
-
clearTimeout(timer)
|
|
98
|
-
timer = setTimeout(() => {
|
|
99
|
-
const items = [...pending]
|
|
100
|
-
pending.clear()
|
|
101
|
-
fn(items)
|
|
102
|
-
}, ms)
|
|
103
|
-
}
|
|
104
|
-
}
|
|
File without changes
|
|
File without changes
|