@studyllm/resume-preview 0.0.0-stage → 3.2.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/LICENSE +21 -0
- package/README.en.md +318 -0
- package/README.md +313 -2
- package/build/constants.js +217 -0
- package/build/diagram-service.js +143 -0
- package/build/file-utils.js +350 -0
- package/build/handlers.js +172 -0
- package/build/html-utils.js +20 -0
- package/build/i18n.js +198 -0
- package/build/index.js +171 -0
- package/build/live-server.js +488 -0
- package/build/logger.js +92 -0
- package/build/mermaid-cli.js +48 -0
- package/build/page-renderer.js +152 -0
- package/build/preview/favicon.svg +23 -0
- package/build/preview/gallery.css +217 -0
- package/build/preview/gallery.html +59 -0
- package/build/preview/gallery.js +259 -0
- package/build/preview/i18n/en.json +57 -0
- package/build/preview/i18n/zh-CN.json +57 -0
- package/build/preview/i18n.js +125 -0
- package/build/preview/resume-template.html +13 -0
- package/build/preview/resume.css +237 -0
- package/build/preview/resume.js +393 -0
- package/build/preview/shared.css +529 -0
- package/build/resume-renderer.js +486 -0
- package/build/resume-service.js +117 -0
- package/build/routes.js +335 -0
- package/build/serve.js +46 -0
- package/build/types.js +5 -0
- package/package.json +63 -4
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
import { createServer } from "http";
|
|
2
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
3
|
+
import { watch, existsSync } from "fs";
|
|
4
|
+
import { readFile } from "fs/promises";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
import { dirname, join } from "path";
|
|
7
|
+
import { validateResumeId, slugifyResumeId, getResumeFilePath, loadResumeContent, loadResumeOptions, } from "./file-utils.js";
|
|
8
|
+
import { createResumeHtmlWrapper, renderResumeExportHtml, renderResumePdf, } from "./resume-renderer.js";
|
|
9
|
+
import { webLogger } from "./logger.js";
|
|
10
|
+
import { getQueryParam, matchRoute } from "./routes.js";
|
|
11
|
+
import { resolveLocale } from "./i18n.js";
|
|
12
|
+
import { escapeHtml } from "./html-utils.js";
|
|
13
|
+
export { escapeHtml };
|
|
14
|
+
import { CSP_HEADER, SERVER_PORT_START, SERVER_PORT_END, SERVER_HOST, ROUTES, RESUME_ROUTES, CONTENT_TYPES, CACHE_CONTROL, WS_MESSAGES, SESSION_NAMESPACES, } from "./constants.js";
|
|
15
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
16
|
+
const __dirname = dirname(__filename);
|
|
17
|
+
const PREVIEW_DIR = join(__dirname, "preview");
|
|
18
|
+
const FAVICON_PATH = join(PREVIEW_DIR, "favicon.svg");
|
|
19
|
+
let liveServer = null;
|
|
20
|
+
let liveServerPort = null;
|
|
21
|
+
let wss = null;
|
|
22
|
+
const liveSessions = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Session keys are namespaced so a resume and anything else that happens to
|
|
25
|
+
* share an id cannot overwrite each other's live preview session.
|
|
26
|
+
*/
|
|
27
|
+
function sessionKey(namespace, id) {
|
|
28
|
+
return `${namespace}:${id}`;
|
|
29
|
+
}
|
|
30
|
+
export function resumeSessionKey(id) {
|
|
31
|
+
return sessionKey(SESSION_NAMESPACES.RESUME, id);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Resolves a WebSocket path to the live session it refers to.
|
|
35
|
+
*
|
|
36
|
+
* Only the "/resume/" prefix is a live session; every other path is unknown.
|
|
37
|
+
*/
|
|
38
|
+
export function resolveSessionFromPath(path) {
|
|
39
|
+
if (!path.startsWith(RESUME_ROUTES.LIVE)) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const resumeId = path.substring(RESUME_ROUTES.LIVE.length);
|
|
43
|
+
if (!resumeId)
|
|
44
|
+
return null;
|
|
45
|
+
return {
|
|
46
|
+
key: resumeSessionKey(resumeId),
|
|
47
|
+
label: resumeId,
|
|
48
|
+
namespace: SESSION_NAMESPACES.RESUME,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Extracts the pathname from a request URL, dropping any query string and
|
|
53
|
+
* fragment. Routing decisions are made on the pathname alone.
|
|
54
|
+
*/
|
|
55
|
+
export function getPathname(rawUrl) {
|
|
56
|
+
if (!rawUrl)
|
|
57
|
+
return "/";
|
|
58
|
+
const withoutFragment = rawUrl.split("#")[0];
|
|
59
|
+
const queryStart = withoutFragment.indexOf("?");
|
|
60
|
+
const pathname = queryStart === -1 ? withoutFragment : withoutFragment.slice(0, queryStart);
|
|
61
|
+
return pathname.length > 0 ? pathname : "/";
|
|
62
|
+
}
|
|
63
|
+
async function findAvailablePort(startPort = SERVER_PORT_START, maxPort = SERVER_PORT_END) {
|
|
64
|
+
for (let port = startPort; port <= maxPort; port++) {
|
|
65
|
+
try {
|
|
66
|
+
await new Promise((resolve, reject) => {
|
|
67
|
+
const testServer = createServer();
|
|
68
|
+
testServer.once("error", reject);
|
|
69
|
+
testServer.once("listening", () => {
|
|
70
|
+
testServer.close(() => resolve());
|
|
71
|
+
});
|
|
72
|
+
testServer.listen(port, SERVER_HOST);
|
|
73
|
+
});
|
|
74
|
+
return port;
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`No available ports found between ${startPort} and ${maxPort}`);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Extracts a resume id from a URL path segment and normalizes it to its
|
|
84
|
+
* slug. Returns null when the segment is missing or malformed.
|
|
85
|
+
*/
|
|
86
|
+
function parseResumeIdFromUrl(url, prefix) {
|
|
87
|
+
const rawId = url.substring(prefix.length);
|
|
88
|
+
if (!rawId)
|
|
89
|
+
return null;
|
|
90
|
+
let decoded;
|
|
91
|
+
try {
|
|
92
|
+
decoded = decodeURIComponent(rawId);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
validateResumeId(decoded);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
return slugifyResumeId(decoded);
|
|
104
|
+
}
|
|
105
|
+
function errorText(error) {
|
|
106
|
+
return error instanceof Error ? error.message : String(error);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Serves the live resume preview page. The page itself is assembled per
|
|
110
|
+
* request so the port and the live-reload flag always match the session.
|
|
111
|
+
*
|
|
112
|
+
* The chrome follows the request language, the resume body keeps the
|
|
113
|
+
* language stored with the resume.
|
|
114
|
+
*/
|
|
115
|
+
async function handleResumeLiveRequest(url, req, res, port) {
|
|
116
|
+
const resumeId = parseResumeIdFromUrl(url, RESUME_ROUTES.LIVE);
|
|
117
|
+
if (!resumeId) {
|
|
118
|
+
res.writeHead(400, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
119
|
+
res.end("Invalid resume ID");
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const state = liveSessions.get(resumeSessionKey(resumeId));
|
|
123
|
+
if (!state) {
|
|
124
|
+
webLogger.warn(`Resume live preview - not registered: ${resumeId}`);
|
|
125
|
+
res.writeHead(404, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
126
|
+
res.end("Resume not found");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const locale = resolveLocale({
|
|
131
|
+
query: getQueryParam(req.url, "lang"),
|
|
132
|
+
acceptLanguage: req.headers["accept-language"],
|
|
133
|
+
});
|
|
134
|
+
const options = await loadResumeOptions(resumeId);
|
|
135
|
+
const body = await readFile(state.filePath, "utf-8");
|
|
136
|
+
const html = await createResumeHtmlWrapper(body, {
|
|
137
|
+
resumeId,
|
|
138
|
+
port,
|
|
139
|
+
liveEnabled: true,
|
|
140
|
+
locale,
|
|
141
|
+
resumeLocale: options.locale,
|
|
142
|
+
path: url,
|
|
143
|
+
});
|
|
144
|
+
res.writeHead(200, {
|
|
145
|
+
"Content-Type": CONTENT_TYPES.HTML,
|
|
146
|
+
"Content-Security-Policy": CSP_HEADER,
|
|
147
|
+
"Content-Language": locale,
|
|
148
|
+
});
|
|
149
|
+
res.end(html);
|
|
150
|
+
webLogger.info(`Served resume live preview for: ${resumeId}`, { locale });
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
webLogger.error(`Error serving resume live preview for: ${resumeId}`, {
|
|
154
|
+
error: errorText(error),
|
|
155
|
+
});
|
|
156
|
+
res.writeHead(500, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
157
|
+
res.end(`Error reading resume: ${errorText(error)}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Serves the static resume preview page. It reads straight from disk, so it
|
|
162
|
+
* works even when the resume has no live preview session.
|
|
163
|
+
*/
|
|
164
|
+
async function handleResumeViewRequest(url, req, res) {
|
|
165
|
+
const resumeId = parseResumeIdFromUrl(url, RESUME_ROUTES.VIEW);
|
|
166
|
+
if (!resumeId) {
|
|
167
|
+
res.writeHead(400, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
168
|
+
res.end("Invalid resume ID");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const locale = resolveLocale({
|
|
173
|
+
query: getQueryParam(req.url, "lang"),
|
|
174
|
+
acceptLanguage: req.headers["accept-language"],
|
|
175
|
+
});
|
|
176
|
+
const options = await loadResumeOptions(resumeId);
|
|
177
|
+
const body = await readFile(getResumeFilePath(resumeId, "html"), "utf-8");
|
|
178
|
+
const html = await createResumeHtmlWrapper(body, {
|
|
179
|
+
resumeId,
|
|
180
|
+
port: 0,
|
|
181
|
+
liveEnabled: false,
|
|
182
|
+
locale,
|
|
183
|
+
resumeLocale: options.locale,
|
|
184
|
+
path: url,
|
|
185
|
+
});
|
|
186
|
+
res.writeHead(200, {
|
|
187
|
+
"Content-Type": CONTENT_TYPES.HTML,
|
|
188
|
+
"Content-Security-Policy": CSP_HEADER,
|
|
189
|
+
"Content-Language": locale,
|
|
190
|
+
});
|
|
191
|
+
res.end(html);
|
|
192
|
+
webLogger.info(`Served resume static view for: ${resumeId}`, { locale });
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
webLogger.warn(`Resume not found: ${resumeId}`, { error: errorText(error) });
|
|
196
|
+
res.writeHead(404, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
197
|
+
res.end(`Resume not found: ${errorText(error)}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Renders the resume on demand and streams it back as a download.
|
|
202
|
+
*/
|
|
203
|
+
async function handleResumeExportRequest(url, req, res) {
|
|
204
|
+
const resumeId = parseResumeIdFromUrl(url, RESUME_ROUTES.EXPORT);
|
|
205
|
+
if (!resumeId) {
|
|
206
|
+
res.writeHead(400, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
207
|
+
res.end("Invalid resume ID");
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const rawUrl = req.url ?? "";
|
|
211
|
+
const queryIndex = rawUrl.indexOf("?");
|
|
212
|
+
const format = queryIndex >= 0
|
|
213
|
+
? new URLSearchParams(rawUrl.slice(queryIndex + 1)).get("format") || "pdf"
|
|
214
|
+
: "pdf";
|
|
215
|
+
if (format !== "pdf" && format !== "html") {
|
|
216
|
+
res.writeHead(400, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
217
|
+
res.end(`Invalid format: "${format}"`);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
const content = await loadResumeContent(resumeId);
|
|
222
|
+
// The exported document is in the resume's own language. It never
|
|
223
|
+
// depends on the language of the request that triggered the export.
|
|
224
|
+
const options = await loadResumeOptions(resumeId);
|
|
225
|
+
let payload;
|
|
226
|
+
let contentType;
|
|
227
|
+
if (format === "pdf") {
|
|
228
|
+
payload = await renderResumePdf(content, options.locale);
|
|
229
|
+
contentType = CONTENT_TYPES.PDF;
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
const html = await renderResumeExportHtml(content, options.locale);
|
|
233
|
+
payload = Buffer.from(html, "utf-8");
|
|
234
|
+
contentType = CONTENT_TYPES.HTML;
|
|
235
|
+
}
|
|
236
|
+
res.writeHead(200, {
|
|
237
|
+
"Content-Type": contentType,
|
|
238
|
+
"Content-Disposition": `attachment; filename="${resumeId}.${format}"`,
|
|
239
|
+
"Content-Length": payload.byteLength,
|
|
240
|
+
"Content-Language": options.locale,
|
|
241
|
+
"Cache-Control": CACHE_CONTROL.NO_STORE,
|
|
242
|
+
});
|
|
243
|
+
res.end(payload);
|
|
244
|
+
webLogger.info(`Served resume export for: ${resumeId}`, { format });
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
webLogger.error(`Resume export failed for: ${resumeId}`, { error: errorText(error) });
|
|
248
|
+
res.writeHead(500, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
249
|
+
res.end("Failed to export resume");
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
export async function ensureLiveServer() {
|
|
253
|
+
if (liveServer && liveServerPort) {
|
|
254
|
+
webLogger.debug(`Reusing existing server on port ${liveServerPort}`);
|
|
255
|
+
return liveServerPort;
|
|
256
|
+
}
|
|
257
|
+
const port = await findAvailablePort();
|
|
258
|
+
webLogger.info(`Starting live server on port ${port}`);
|
|
259
|
+
liveServer = createServer(async (req, res) => {
|
|
260
|
+
// Routing works on the pathname only. Query strings and fragments are
|
|
261
|
+
// not part of a route, and leaving them in made requests such as
|
|
262
|
+
// "/gallery.css?v=2" or "/view/arch?x=1" fail to match.
|
|
263
|
+
const url = getPathname(req.url);
|
|
264
|
+
try {
|
|
265
|
+
// Try to match new route system first (gallery, API, new assets)
|
|
266
|
+
const route = matchRoute(url);
|
|
267
|
+
if (route) {
|
|
268
|
+
await route.handler({ req, res, url, port });
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
// Resume routes. The order matters: "/resume/export/" and
|
|
272
|
+
// "/resume/view/" are prefixes of "/resume/", so they have to be tested
|
|
273
|
+
// first or they would be read as a resume id containing a slash.
|
|
274
|
+
if (url.startsWith(RESUME_ROUTES.EXPORT)) {
|
|
275
|
+
await handleResumeExportRequest(url, req, res);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (url.startsWith(RESUME_ROUTES.VIEW)) {
|
|
279
|
+
await handleResumeViewRequest(url, req, res);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (url.startsWith(RESUME_ROUTES.LIVE)) {
|
|
283
|
+
await handleResumeLiveRequest(url, req, res, port);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (url === ROUTES.FAVICON_SVG) {
|
|
287
|
+
const icon = await readFile(FAVICON_PATH);
|
|
288
|
+
res.writeHead(200, {
|
|
289
|
+
"Content-Type": CONTENT_TYPES.SVG,
|
|
290
|
+
"Cache-Control": CACHE_CONTROL.PUBLIC_24H,
|
|
291
|
+
});
|
|
292
|
+
res.end(icon);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (url === ROUTES.FAVICON_ICO) {
|
|
296
|
+
// Redirect common .ico requests to SVG favicon
|
|
297
|
+
res.writeHead(302, { Location: ROUTES.FAVICON_SVG });
|
|
298
|
+
res.end();
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
res.writeHead(404, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
302
|
+
res.end("Not found");
|
|
303
|
+
}
|
|
304
|
+
catch (error) {
|
|
305
|
+
webLogger.error(`HTTP server error for ${url}`, {
|
|
306
|
+
error: error instanceof Error ? error.message : String(error),
|
|
307
|
+
});
|
|
308
|
+
res.writeHead(500, { "Content-Type": CONTENT_TYPES.PLAIN });
|
|
309
|
+
res.end(`Server error: ${error instanceof Error ? error.message : String(error)}`);
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
wss = new WebSocketServer({ server: liveServer });
|
|
313
|
+
wss.on("connection", (ws, req) => {
|
|
314
|
+
const path = getPathname(req.url);
|
|
315
|
+
const session = resolveSessionFromPath(path);
|
|
316
|
+
const key = session?.key ?? "";
|
|
317
|
+
const label = session?.label ?? "";
|
|
318
|
+
webLogger.info(`WebSocket connection attempt`, { id: label, url: req.url });
|
|
319
|
+
if (session && liveSessions.has(key)) {
|
|
320
|
+
const state = liveSessions.get(key);
|
|
321
|
+
state.clients.add(ws);
|
|
322
|
+
webLogger.info(`WebSocket client connected to session: ${label}`, {
|
|
323
|
+
clientCount: state.clients.size,
|
|
324
|
+
});
|
|
325
|
+
ws.on("close", () => {
|
|
326
|
+
state.clients.delete(ws);
|
|
327
|
+
webLogger.info(`WebSocket client disconnected from session: ${label}`, {
|
|
328
|
+
clientCount: state.clients.size,
|
|
329
|
+
});
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
webLogger.warn(`WebSocket connection failed - session not registered: ${label}`);
|
|
334
|
+
ws.close();
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
await new Promise((resolve) => {
|
|
338
|
+
liveServer.listen(port, SERVER_HOST, () => {
|
|
339
|
+
liveServerPort = port;
|
|
340
|
+
webLogger.info(`Live reload server listening on ${SERVER_HOST}:${port}`);
|
|
341
|
+
console.error(`Live reload server started on ${SERVER_HOST}:${port}`);
|
|
342
|
+
resolve();
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
return port;
|
|
346
|
+
}
|
|
347
|
+
export async function addLiveSession(sessionId, filePath, namespace = SESSION_NAMESPACES.RESUME) {
|
|
348
|
+
const key = sessionKey(namespace, sessionId);
|
|
349
|
+
const existingClients = liveSessions.has(key)
|
|
350
|
+
? liveSessions.get(key).clients
|
|
351
|
+
: new Set();
|
|
352
|
+
const isUpdate = liveSessions.has(key);
|
|
353
|
+
if (isUpdate) {
|
|
354
|
+
liveSessions.get(key).watcher.close();
|
|
355
|
+
webLogger.info(`Updating live session: ${sessionId}`, {
|
|
356
|
+
existingClientCount: existingClients.size,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
webLogger.info(`Registering new live session: ${sessionId}`);
|
|
361
|
+
}
|
|
362
|
+
const watcher = watch(filePath, (eventType) => {
|
|
363
|
+
if (eventType === "change") {
|
|
364
|
+
webLogger.debug(`File change detected for session: ${sessionId}`);
|
|
365
|
+
notifyClients(key);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
// "rename" fires both when the file is atomically replaced and when it
|
|
369
|
+
// is removed. Only the latter should end the preview session.
|
|
370
|
+
if (eventType === "rename" && !existsSync(filePath)) {
|
|
371
|
+
webLogger.info(`Watched file removed, ending preview session: ${sessionId}`);
|
|
372
|
+
removeLiveSession(sessionId, namespace);
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
// A watched file that is deleted (e.g. via DELETE /api/resumes/:id) makes
|
|
376
|
+
// the underlying watcher emit an 'error' event on some platforms. Without a
|
|
377
|
+
// listener Node treats that as an unhandled 'error' event and crashes the
|
|
378
|
+
// whole process, taking the MCP server down with it.
|
|
379
|
+
watcher.on("error", (error) => {
|
|
380
|
+
webLogger.warn(`Watcher error for session: ${sessionId}`, {
|
|
381
|
+
error: error instanceof Error ? error.message : String(error),
|
|
382
|
+
});
|
|
383
|
+
if (!existsSync(filePath)) {
|
|
384
|
+
removeLiveSession(sessionId, namespace);
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
liveSessions.set(key, {
|
|
388
|
+
filePath,
|
|
389
|
+
watcher,
|
|
390
|
+
clients: existingClients,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Ends the live preview session: closes its file watcher and disconnects any
|
|
395
|
+
* WebSocket clients. Safe to call for unknown IDs.
|
|
396
|
+
*/
|
|
397
|
+
export function removeLiveSession(sessionId, namespace = SESSION_NAMESPACES.RESUME) {
|
|
398
|
+
const key = sessionKey(namespace, sessionId);
|
|
399
|
+
const state = liveSessions.get(key);
|
|
400
|
+
if (!state)
|
|
401
|
+
return;
|
|
402
|
+
liveSessions.delete(key);
|
|
403
|
+
try {
|
|
404
|
+
state.watcher.close();
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
webLogger.debug("Error closing watcher", {
|
|
408
|
+
error: error instanceof Error ? error.message : String(error),
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
state.clients.forEach((client) => {
|
|
412
|
+
try {
|
|
413
|
+
client.close();
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
// Client already gone; nothing to do.
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
state.clients.clear();
|
|
420
|
+
webLogger.info(`Removed live session: ${sessionId}`);
|
|
421
|
+
}
|
|
422
|
+
export function hasActiveConnections(sessionId, namespace = SESSION_NAMESPACES.RESUME) {
|
|
423
|
+
const state = liveSessions.get(sessionKey(namespace, sessionId));
|
|
424
|
+
const hasConnections = state ? state.clients.size > 0 : false;
|
|
425
|
+
webLogger.debug(`Checking active connections for ${sessionId}`, {
|
|
426
|
+
hasConnections,
|
|
427
|
+
clientCount: state?.clients.size || 0,
|
|
428
|
+
});
|
|
429
|
+
return hasConnections;
|
|
430
|
+
}
|
|
431
|
+
function notifyClients(key) {
|
|
432
|
+
const state = liveSessions.get(key);
|
|
433
|
+
if (!state)
|
|
434
|
+
return;
|
|
435
|
+
let notifiedCount = 0;
|
|
436
|
+
state.clients.forEach((client) => {
|
|
437
|
+
if (client.readyState === WebSocket.OPEN) {
|
|
438
|
+
client.send(WS_MESSAGES.RELOAD);
|
|
439
|
+
notifiedCount++;
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
if (notifiedCount > 0) {
|
|
443
|
+
webLogger.info(`Notified clients to reload session: ${key}`, {
|
|
444
|
+
notifiedCount,
|
|
445
|
+
totalClients: state.clients.size,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Closes the live server and cleans up all resources.
|
|
451
|
+
* This is safe to call multiple times and useful for graceful shutdown.
|
|
452
|
+
*/
|
|
453
|
+
export async function closeLiveServer() {
|
|
454
|
+
// Close all file watchers
|
|
455
|
+
liveSessions.forEach((state) => {
|
|
456
|
+
try {
|
|
457
|
+
state.watcher.close();
|
|
458
|
+
}
|
|
459
|
+
catch (error) {
|
|
460
|
+
webLogger.debug("Error closing watcher", {
|
|
461
|
+
error: error instanceof Error ? error.message : String(error),
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
liveSessions.clear();
|
|
466
|
+
// Close WebSocket server
|
|
467
|
+
if (wss) {
|
|
468
|
+
await new Promise((resolve) => {
|
|
469
|
+
wss.close(() => {
|
|
470
|
+
webLogger.debug("WebSocket server closed");
|
|
471
|
+
resolve();
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
wss = null;
|
|
475
|
+
}
|
|
476
|
+
// Close HTTP server
|
|
477
|
+
if (liveServer) {
|
|
478
|
+
await new Promise((resolve) => {
|
|
479
|
+
liveServer.close(() => {
|
|
480
|
+
webLogger.info(`Live server closed (was on port ${liveServerPort})`);
|
|
481
|
+
resolve();
|
|
482
|
+
});
|
|
483
|
+
});
|
|
484
|
+
liveServer = null;
|
|
485
|
+
liveServerPort = null;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
//# sourceMappingURL=live-server.js.map
|
package/build/logger.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { appendFile, mkdir } from "fs/promises";
|
|
2
|
+
import { join } from "path";
|
|
3
|
+
import { getLogsDir } from "./file-utils.js";
|
|
4
|
+
export var LogLevel;
|
|
5
|
+
(function (LogLevel) {
|
|
6
|
+
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
|
|
7
|
+
LogLevel[LogLevel["INFO"] = 1] = "INFO";
|
|
8
|
+
LogLevel[LogLevel["WARN"] = 2] = "WARN";
|
|
9
|
+
LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
|
|
10
|
+
LogLevel[LogLevel["OFF"] = 4] = "OFF";
|
|
11
|
+
})(LogLevel || (LogLevel = {}));
|
|
12
|
+
const LOG_LEVEL_NAMES = {
|
|
13
|
+
[LogLevel.DEBUG]: "DEBUG",
|
|
14
|
+
[LogLevel.INFO]: "INFO",
|
|
15
|
+
[LogLevel.WARN]: "WARN",
|
|
16
|
+
[LogLevel.ERROR]: "ERROR",
|
|
17
|
+
[LogLevel.OFF]: "OFF",
|
|
18
|
+
};
|
|
19
|
+
function parseLogLevel(level) {
|
|
20
|
+
if (!level)
|
|
21
|
+
return LogLevel.INFO;
|
|
22
|
+
const normalized = level.toUpperCase();
|
|
23
|
+
switch (normalized) {
|
|
24
|
+
case "DEBUG":
|
|
25
|
+
return LogLevel.DEBUG;
|
|
26
|
+
case "INFO":
|
|
27
|
+
return LogLevel.INFO;
|
|
28
|
+
case "WARN":
|
|
29
|
+
return LogLevel.WARN;
|
|
30
|
+
case "ERROR":
|
|
31
|
+
return LogLevel.ERROR;
|
|
32
|
+
case "OFF":
|
|
33
|
+
return LogLevel.OFF;
|
|
34
|
+
default:
|
|
35
|
+
return LogLevel.INFO;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
class Logger {
|
|
39
|
+
logFilePath;
|
|
40
|
+
logsDir;
|
|
41
|
+
minLogLevel;
|
|
42
|
+
constructor(logFileName, baseDir) {
|
|
43
|
+
this.logsDir = baseDir || getLogsDir();
|
|
44
|
+
this.logFilePath = join(this.logsDir, logFileName);
|
|
45
|
+
this.minLogLevel = parseLogLevel(process.env.CLAUDE_MERMAID_LOG_LEVEL);
|
|
46
|
+
}
|
|
47
|
+
async ensureLogDir() {
|
|
48
|
+
await mkdir(this.logsDir, { recursive: true });
|
|
49
|
+
}
|
|
50
|
+
formatMessage(level, message, data) {
|
|
51
|
+
const timestamp = new Date().toISOString();
|
|
52
|
+
const levelName = LOG_LEVEL_NAMES[level];
|
|
53
|
+
const dataStr = data !== undefined ? ` ${JSON.stringify(data)}` : "";
|
|
54
|
+
return `[${timestamp}] ${levelName}: ${message}${dataStr}\n`;
|
|
55
|
+
}
|
|
56
|
+
async log(level, message, data) {
|
|
57
|
+
// Check if this log level should be written
|
|
58
|
+
if (level < this.minLogLevel)
|
|
59
|
+
return;
|
|
60
|
+
try {
|
|
61
|
+
await this.ensureLogDir();
|
|
62
|
+
const formatted = this.formatMessage(level, message, data);
|
|
63
|
+
await appendFile(this.logFilePath, formatted);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
// Silently fail to avoid disrupting the main application
|
|
67
|
+
console.error("Logger error:", error);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
debug(message, data) {
|
|
71
|
+
this.log(LogLevel.DEBUG, message, data);
|
|
72
|
+
}
|
|
73
|
+
info(message, data) {
|
|
74
|
+
this.log(LogLevel.INFO, message, data);
|
|
75
|
+
}
|
|
76
|
+
warn(message, data) {
|
|
77
|
+
this.log(LogLevel.WARN, message, data);
|
|
78
|
+
}
|
|
79
|
+
error(message, data) {
|
|
80
|
+
this.log(LogLevel.ERROR, message, data);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export const mcpLogger = new Logger("mcp.log");
|
|
84
|
+
export const webLogger = new Logger("web.log");
|
|
85
|
+
// For testing: create loggers with custom base directory
|
|
86
|
+
export function createTestLoggers(baseDir) {
|
|
87
|
+
return {
|
|
88
|
+
mcpLogger: new Logger("mcp.log", baseDir),
|
|
89
|
+
webLogger: new Logger("web.log", baseDir),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=logger.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createRequire } from "module";
|
|
2
|
+
import { existsSync, readFileSync } from "fs";
|
|
3
|
+
import { join } from "path";
|
|
4
|
+
const MERMAID_CLI_PACKAGE = "@mermaid-js/mermaid-cli";
|
|
5
|
+
const MERMAID_CLI_BIN = "mmdc";
|
|
6
|
+
const PACKAGE_MANIFEST = "package.json";
|
|
7
|
+
let cachedCliPath;
|
|
8
|
+
export function getMermaidCliPath() {
|
|
9
|
+
cachedCliPath ??= resolveMermaidCliPath();
|
|
10
|
+
return cachedCliPath;
|
|
11
|
+
}
|
|
12
|
+
export function buildMermaidCliArgs(inputFile, outputFile, options) {
|
|
13
|
+
const args = [
|
|
14
|
+
"-i",
|
|
15
|
+
inputFile,
|
|
16
|
+
"-o",
|
|
17
|
+
outputFile,
|
|
18
|
+
"-t",
|
|
19
|
+
options.theme,
|
|
20
|
+
"-b",
|
|
21
|
+
options.background,
|
|
22
|
+
"--size",
|
|
23
|
+
options.size.toString(),
|
|
24
|
+
"-s",
|
|
25
|
+
options.scale.toString(),
|
|
26
|
+
];
|
|
27
|
+
return args;
|
|
28
|
+
}
|
|
29
|
+
function resolveMermaidCliPath() {
|
|
30
|
+
const packageRoot = findPackageRoot();
|
|
31
|
+
const manifest = JSON.parse(readFileSync(join(packageRoot, PACKAGE_MANIFEST), "utf-8"));
|
|
32
|
+
const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.[MERMAID_CLI_BIN];
|
|
33
|
+
if (!bin) {
|
|
34
|
+
throw new Error(`${MERMAID_CLI_PACKAGE} does not provide the ${MERMAID_CLI_BIN} binary`);
|
|
35
|
+
}
|
|
36
|
+
return join(packageRoot, bin);
|
|
37
|
+
}
|
|
38
|
+
function findPackageRoot() {
|
|
39
|
+
const packageRoot = createRequire(import.meta.url)
|
|
40
|
+
.resolve.paths(MERMAID_CLI_PACKAGE)
|
|
41
|
+
?.map((nodeModulesDir) => join(nodeModulesDir, MERMAID_CLI_PACKAGE))
|
|
42
|
+
.find((dir) => existsSync(join(dir, PACKAGE_MANIFEST)));
|
|
43
|
+
if (!packageRoot) {
|
|
44
|
+
throw new Error(`Cannot find ${MERMAID_CLI_PACKAGE}. Reinstall resume-preview to restore it.`);
|
|
45
|
+
}
|
|
46
|
+
return packageRoot;
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=mermaid-cli.js.map
|