@keyou007/agent-bot 0.1.27-alpha.0 → 0.1.27-alpha.2
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/CHANGELOG.md +35 -0
- package/README.md +63 -7
- package/README.zh.md +62 -6
- package/SECURITY.md +18 -4
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +56 -12
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +167 -0
- package/dist/local-files/GitDiffPreview.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +332 -30
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +138 -58
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +75 -26
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +125 -56
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +14 -4
- package/docs/technical-reference.zh.md +15 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +6 -2
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +47 -13
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +144 -0
- package/src/local-files/LocalFileViewerServer.ts +294 -31
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +159 -69
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +76 -26
- package/src/terminal/TerminalServer.ts +119 -48
|
@@ -5,12 +5,18 @@ import { createRequire } from "node:module";
|
|
|
5
5
|
import http, { type IncomingMessage, type ServerResponse } from "node:http";
|
|
6
6
|
import type { Duplex } from "node:stream";
|
|
7
7
|
import path from "node:path";
|
|
8
|
+
import { z } from "zod";
|
|
8
9
|
import hljs from "highlight.js/lib/common";
|
|
9
10
|
import dos from "highlight.js/lib/languages/dos";
|
|
10
11
|
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
|
11
12
|
import powershell from "highlight.js/lib/languages/powershell";
|
|
12
13
|
import MarkdownIt from "markdown-it";
|
|
13
14
|
import { CSV_PREVIEW_CSS, renderCsvPreview, csvSourcePreview } from "./CsvPreview.js";
|
|
15
|
+
import { GIT_DIFF_PREVIEW_CSS, readGitFileDiff, renderGitFileDiff } from "./GitDiffPreview.js";
|
|
16
|
+
import { renderWorkspacePage, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
17
|
+
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
18
|
+
import { readWebPageTitle } from "./WebPageTitle.js";
|
|
19
|
+
import { WorkspaceError, readWorkspaceAddress, readWorkspaceEntries, readWorkspaceGitStatus, readWorkspaceChanges, readWorkspaceFileVersions, createWorkspaceDiff, renderWorkspaceDiff, resolveWorkspacePath, type WorkspaceChange } from "./WorkspaceFiles.js";
|
|
14
20
|
import { enableDiagramFences, DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
|
|
15
21
|
import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
|
|
16
22
|
import {
|
|
@@ -38,6 +44,13 @@ const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
|
|
|
38
44
|
const MAX_CONTENT_SAMPLE_BYTES = 64 * 1024;
|
|
39
45
|
const MAX_SYNTAX_HIGHLIGHT_BYTES = 512 * 1024;
|
|
40
46
|
const DIRECTORY_PAGE_SIZE = 100;
|
|
47
|
+
const WORKSPACE_QUERY = z.object({
|
|
48
|
+
api: z.string().optional(), entry: z.string().default(""),
|
|
49
|
+
page: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
50
|
+
mode: z.enum(["all", "staged", "unstaged"]).default("all"), original: z.string().optional(),
|
|
51
|
+
prefetch: z.enum(["0", "1"]).optional(), query: z.string().trim().max(160).optional(),
|
|
52
|
+
instance: z.string().regex(/^[a-f0-9]{16}$/u).optional(),
|
|
53
|
+
});
|
|
41
54
|
const MARKDOWN_EXTENSIONS = new Set([".markdown", ".md", ".mdown", ".mkd", ".mkdn"]);
|
|
42
55
|
const HTML_EXTENSIONS = new Set([".html", ".htm"]);
|
|
43
56
|
hljs.registerLanguage("dos", dos);
|
|
@@ -50,8 +63,8 @@ const MARKDOWN_RENDERER = new MarkdownIt({
|
|
|
50
63
|
linkify: true,
|
|
51
64
|
typographer: false,
|
|
52
65
|
highlight(value, language) {
|
|
53
|
-
const highlighted = language && hljs.getLanguage(language)
|
|
54
|
-
?
|
|
66
|
+
const highlighted = language && hljs.getLanguage(language) && Buffer.byteLength(value, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
67
|
+
? highlightLines(value, language).join("\n")
|
|
55
68
|
: escapeHtml(value);
|
|
56
69
|
const languageAttribute = language && hljs.getLanguage(language)
|
|
57
70
|
? ` class="language-${escapeAttribute(language)}"`
|
|
@@ -148,6 +161,12 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
148
161
|
const positionHashTarget = () => {
|
|
149
162
|
highlightHashTarget()?.scrollIntoView({ block: "start" });
|
|
150
163
|
};
|
|
164
|
+
const positionInitialContent = () => {
|
|
165
|
+
const firstChange = content.querySelector(".git-diff .diff-addition, .git-diff .diff-deletion");
|
|
166
|
+
if (firstChange && ["reload", "back_forward"].includes(performance.getEntriesByType("navigation")[0]?.type)) { highlightHashTarget(); return; }
|
|
167
|
+
if (window.location.hash) return positionHashTarget();
|
|
168
|
+
firstChange?.scrollIntoView({ block: "center" });
|
|
169
|
+
};
|
|
151
170
|
if (/^#L\\d+$/u.test(window.location.hash)) document.body.dataset.viewMode = "code";
|
|
152
171
|
syncViewMode();
|
|
153
172
|
updateHeaderOffset();
|
|
@@ -158,7 +177,7 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
158
177
|
if (/^#L\\d+$/u.test(window.location.hash)) setViewMode("code");
|
|
159
178
|
else requestAnimationFrame(positionHashTarget);
|
|
160
179
|
});
|
|
161
|
-
requestAnimationFrame(
|
|
180
|
+
requestAnimationFrame(positionInitialContent);
|
|
162
181
|
if (!eventsUrl || typeof EventSource !== "function") return;
|
|
163
182
|
|
|
164
183
|
const restoreScroll = (top, left, atBottom, codeScrollLeft, tablePositions) => {
|
|
@@ -274,6 +293,7 @@ export interface LocalFileViewerServerOptions {
|
|
|
274
293
|
getTurnSnapshot?: (turnId: string) => unknown;
|
|
275
294
|
loadTurnSnapshot?: (turnId: string) => Promise<unknown>;
|
|
276
295
|
turnPreviewPollIntervalMs?: number;
|
|
296
|
+
createWorkspaceTerminalUrl?: (root: string, instance: string, request: IncomingMessage) => string;
|
|
277
297
|
}
|
|
278
298
|
|
|
279
299
|
export interface LocalFileViewerAddress {
|
|
@@ -296,6 +316,13 @@ export class LocalFileViewerServer {
|
|
|
296
316
|
private address?: LocalFileViewerAddress;
|
|
297
317
|
private basePath = "";
|
|
298
318
|
private readonly services = new Map<string, LocalFileViewerService>();
|
|
319
|
+
private workspaceAppBase?: string;
|
|
320
|
+
|
|
321
|
+
enableWorkspaceApp(base: string): void { this.workspaceAppBase = base; }
|
|
322
|
+
|
|
323
|
+
serveWorkspaceAppPage(response: ServerResponse, url: URL, headOnly: boolean): void {
|
|
324
|
+
this.sendHtml(response, 200, renderWorkspacePage("", url.toString(), this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
325
|
+
}
|
|
299
326
|
|
|
300
327
|
constructor(private readonly options: LocalFileViewerServerOptions) {}
|
|
301
328
|
|
|
@@ -404,23 +431,46 @@ export class LocalFileViewerServer {
|
|
|
404
431
|
} catch { return undefined; }
|
|
405
432
|
}
|
|
406
433
|
|
|
407
|
-
createFileUrl(filePath: string, reference?: string): string | undefined {
|
|
434
|
+
createFileUrl(filePath: string, reference?: string, options?: { diff?: boolean }): string | undefined {
|
|
408
435
|
if (!this.address || !this.secret) return undefined;
|
|
409
436
|
const absolutePath = normalizeAbsolutePath(filePath);
|
|
410
437
|
if (!absolutePath) return undefined;
|
|
411
438
|
try {
|
|
412
439
|
const stat = fs.statSync(absolutePath);
|
|
413
440
|
if (!stat.isFile() && !stat.isDirectory()) return undefined;
|
|
414
|
-
|
|
415
|
-
|
|
441
|
+
if (options?.diff && stat.isDirectory()) return undefined;
|
|
442
|
+
} catch (error) {
|
|
443
|
+
if (!options?.diff || !["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return undefined;
|
|
416
444
|
}
|
|
417
445
|
|
|
418
446
|
const url = this.createPreviewUrl(absolutePath);
|
|
447
|
+
if (options?.diff) url.searchParams.set("diff", "1");
|
|
419
448
|
const line = parseLineReference(reference);
|
|
420
449
|
if (line !== undefined) url.hash = `L${line}`;
|
|
421
450
|
return url.toString();
|
|
422
451
|
}
|
|
423
452
|
|
|
453
|
+
createWorkspaceUrl(directory: string, origin?: string): string | undefined {
|
|
454
|
+
if (!this.address || !this.secret) return undefined;
|
|
455
|
+
try {
|
|
456
|
+
const root = fs.realpathSync(directory);
|
|
457
|
+
if (!fs.statSync(root).isDirectory()) return undefined;
|
|
458
|
+
const url = new URL(origin ?? this.address.publicBaseUrl);
|
|
459
|
+
url.pathname = this.basePath + "/workspace/" + this.createShortToken("workspace:" + root);
|
|
460
|
+
url.searchParams.set("path", root);
|
|
461
|
+
return url.toString();
|
|
462
|
+
} catch { return undefined; }
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
serveWorkspaceChatImage(request: IncomingMessage, response: ServerResponse, root: string, entry: string): void {
|
|
466
|
+
const file = resolveWorkspacePath(root, entry);
|
|
467
|
+
const stat = fs.statSync(file);
|
|
468
|
+
if (!stat.isFile() || !contentTypeFor(path.extname(file).toLowerCase()).startsWith("image/")) {
|
|
469
|
+
throw new WorkspaceError("图片格式不可预览。", 404);
|
|
470
|
+
}
|
|
471
|
+
this.serveRawFile(request, response, file, stat, false);
|
|
472
|
+
}
|
|
473
|
+
|
|
424
474
|
createTurnPreviewUrl(turnId: string): string | undefined {
|
|
425
475
|
const normalizedTurnId = normalizeTurnId(turnId);
|
|
426
476
|
if (!this.address || !this.secret || !this.options.getTurnSnapshot || !normalizedTurnId) return undefined;
|
|
@@ -444,6 +494,26 @@ export class LocalFileViewerServer {
|
|
|
444
494
|
|
|
445
495
|
const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
446
496
|
const route = routeWithinBasePath(requestUrl.pathname, this.basePath);
|
|
497
|
+
if (route === "/assets/workspace.js") {
|
|
498
|
+
this.sendJavascript(response, request.method === "HEAD", WORKSPACE_SCRIPT);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const workspaceMatch = new RegExp("^/workspace/([A-Za-z0-9_-]{" + SHORT_TOKEN_LENGTH + "})$", "u").exec(route);
|
|
502
|
+
if (workspaceMatch) {
|
|
503
|
+
const root = normalizeAbsolutePath(requestUrl.searchParams.get("path") ?? "");
|
|
504
|
+
const expected = root ? this.createShortToken("workspace:" + root) : "";
|
|
505
|
+
if (!root || !timingSafeEqual(Buffer.from(expected), Buffer.from(workspaceMatch[1]!))) {
|
|
506
|
+
this.sendWorkspaceJson(response, 403, { error: "工作台链接无效,项目签名校验失败。" }, request.method === "HEAD");
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
try { await this.handleWorkspace(request, response, requestUrl, root); }
|
|
510
|
+
catch (error) {
|
|
511
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
512
|
+
this.sendWorkspaceJson(response, error instanceof WorkspaceError ? error.status : code === "ENOENT" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500,
|
|
513
|
+
{ error: error instanceof Error ? error.message : String(error) }, request.method === "HEAD");
|
|
514
|
+
}
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
447
517
|
if (!route.startsWith("/")) {
|
|
448
518
|
this.sendHtml(response, 404, errorPage("文件链接无效", "请从 Agent Bot 的回答中重新打开文件链接。"), request.method === "HEAD");
|
|
449
519
|
return;
|
|
@@ -513,7 +583,7 @@ export class LocalFileViewerServer {
|
|
|
513
583
|
&& (snapshot.fullToolOutputs?.[tool.id]?.length ?? 0) > outputAppend.length
|
|
514
584
|
? { key, revision: String(tool.tool.previewRevision), content: "", outputAppend,
|
|
515
585
|
footer: renderToolFooter(tool.tool, snapshot.fullToolOutputs?.[tool.id]?.length ?? 0, language) }
|
|
516
|
-
: renderTurnPreviewDetail(snapshot, key, (filePath) => this.createFileUrl(filePath), language);
|
|
586
|
+
: renderTurnPreviewDetail(snapshot, key, (filePath, options) => this.createFileUrl(filePath, undefined, options), language);
|
|
517
587
|
setSecurityHeaders(response);
|
|
518
588
|
response.statusCode = detail ? 200 : 404;
|
|
519
589
|
response.setHeader("Cache-Control", "no-store");
|
|
@@ -529,11 +599,16 @@ export class LocalFileViewerServer {
|
|
|
529
599
|
eventsUrl.searchParams.set("events", "1");
|
|
530
600
|
if (snapshot.previewCursor !== undefined) eventsUrl.searchParams.set("after", String(snapshot.previewCursor));
|
|
531
601
|
const language = detectTurnPreviewLanguage(request.headers["accept-language"]);
|
|
602
|
+
const projectWorkspaceUrl = snapshot.projectCwd ? this.createWorkspaceUrl(snapshot.projectCwd) : undefined;
|
|
603
|
+
const workspaceUrl = projectWorkspaceUrl ? new URL(projectWorkspaceUrl) : undefined;
|
|
604
|
+
workspaceUrl?.searchParams.set("list", "changes");
|
|
605
|
+
if (this.workspaceAppBase && snapshot.sessionId) workspaceUrl?.searchParams.set("task", snapshot.sessionId);
|
|
532
606
|
const html = renderTurnPreviewPage({
|
|
533
607
|
state: snapshot,
|
|
608
|
+
workspaceUrl: workspaceUrl?.toString(),
|
|
534
609
|
eventsUrl: eventsUrl.toString(),
|
|
535
610
|
scriptPath: `${this.basePath}/assets/turn-preview.js`.replace(/\/{2,}/gu, "/"),
|
|
536
|
-
localFileUrl: (filePath) => this.createFileUrl(filePath),
|
|
611
|
+
localFileUrl: (filePath, options) => this.createFileUrl(filePath, undefined, options),
|
|
537
612
|
diagramScriptPath: `${this.basePath}/assets/mermaid.js`.replace(/\/{2,}/gu, "/"),
|
|
538
613
|
language,
|
|
539
614
|
});
|
|
@@ -558,6 +633,25 @@ export class LocalFileViewerServer {
|
|
|
558
633
|
return;
|
|
559
634
|
}
|
|
560
635
|
|
|
636
|
+
if (requestUrl.searchParams.get("diff") === "1" && requestUrl.searchParams.get("raw") !== "1"
|
|
637
|
+
&& legacyMatch?.[1] !== "raw" && requestUrl.searchParams.get("render") !== "html"
|
|
638
|
+
&& requestUrl.searchParams.get("events") !== "1") {
|
|
639
|
+
const content = await readGitDiffPreview(filePath);
|
|
640
|
+
if (content !== undefined) {
|
|
641
|
+
const original = this.createFileUrl(filePath);
|
|
642
|
+
const actions: Array<{ href: string; label: string }> = [];
|
|
643
|
+
if (original) {
|
|
644
|
+
const raw = new URL(original); raw.searchParams.set("raw", "1");
|
|
645
|
+
const download = new URL(raw); download.searchParams.set("download", "1");
|
|
646
|
+
actions.push({ href: original, label: "查看文件" }, { href: raw.toString(), label: "打开原始文件" }, { href: download.toString(), label: "下载" });
|
|
647
|
+
}
|
|
648
|
+
this.sendHtml(response, 200, renderViewerPage({ title: path.basename(filePath), filePath,
|
|
649
|
+
metadata: ["Git diff", "完整文件", "当前工作区"], actions, content,
|
|
650
|
+
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/") }), request.method === "HEAD");
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
561
655
|
let stat: fs.Stats;
|
|
562
656
|
try {
|
|
563
657
|
stat = fs.statSync(filePath);
|
|
@@ -685,10 +779,8 @@ export class LocalFileViewerServer {
|
|
|
685
779
|
content: snapshot.content,
|
|
686
780
|
viewMode: snapshot.viewMode,
|
|
687
781
|
diagramScriptPath: isMarkdownFile(filePath) ? `${this.basePath}/assets/mermaid.js`.replace(/\/{2,}/gu, "/") : undefined,
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/"),
|
|
691
|
-
},
|
|
782
|
+
eventsUrl: eventsUrl.toString(),
|
|
783
|
+
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/"),
|
|
692
784
|
});
|
|
693
785
|
}
|
|
694
786
|
|
|
@@ -853,7 +945,7 @@ export class LocalFileViewerServer {
|
|
|
853
945
|
if (!batch.records.length) {
|
|
854
946
|
const state = projection.state;
|
|
855
947
|
if (state && ["completed", "cancelled", "failed"].includes(state.status)) {
|
|
856
|
-
const update = renderTurnPreviewPatch(state, new Set(), new Set(), (file) => this.createFileUrl(file), language);
|
|
948
|
+
const update = renderTurnPreviewPatch(state, new Set(), new Set(), (file, options) => this.createFileUrl(file, undefined, options), language);
|
|
857
949
|
response.write(`id: ${offset}\nevent: patch\ndata: ${JSON.stringify(update)}\n\n`);
|
|
858
950
|
cleanup(); response.end();
|
|
859
951
|
}
|
|
@@ -864,8 +956,8 @@ export class LocalFileViewerServer {
|
|
|
864
956
|
const state = projection.state;
|
|
865
957
|
if (!state) return;
|
|
866
958
|
const render = initial
|
|
867
|
-
? renderTurnPreviewSnapshot(state, (file) => this.createFileUrl(file), language, { deferDetails: true })
|
|
868
|
-
: renderTurnPreviewPatch(state, projection.changed, projection.removed, (file) => this.createFileUrl(file), language);
|
|
959
|
+
? renderTurnPreviewSnapshot(state, (file, options) => this.createFileUrl(file, undefined, options), language, { deferDetails: true })
|
|
960
|
+
: renderTurnPreviewPatch(state, projection.changed, projection.removed, (file, options) => this.createFileUrl(file, undefined, options), language);
|
|
869
961
|
// A terminal record can share a batch with later metadata. Drain the captured prefix first.
|
|
870
962
|
render.terminal = render.terminal && batch.end;
|
|
871
963
|
waitingDrain = !response.write(`id: ${offset}\nevent: ${initial ? "update" : "patch"}\ndata: ${JSON.stringify(render)}\n\n`);
|
|
@@ -916,7 +1008,7 @@ export class LocalFileViewerServer {
|
|
|
916
1008
|
const serialized = JSON.stringify(state);
|
|
917
1009
|
if (serialized === previousSnapshot) return;
|
|
918
1010
|
previousSnapshot = serialized;
|
|
919
|
-
const snapshot = renderTurnPreviewSnapshot(state, (filePath) => this.createFileUrl(filePath), language, { deferDetails: true });
|
|
1011
|
+
const snapshot = renderTurnPreviewSnapshot(state, (filePath, options) => this.createFileUrl(filePath, undefined, options), language, { deferDetails: true });
|
|
920
1012
|
writeServerSentEvent(response, "update", JSON.stringify(snapshot));
|
|
921
1013
|
};
|
|
922
1014
|
sendSnapshot();
|
|
@@ -940,6 +1032,128 @@ export class LocalFileViewerServer {
|
|
|
940
1032
|
response.once("close", cleanup);
|
|
941
1033
|
}
|
|
942
1034
|
|
|
1035
|
+
private sendWorkspaceJson(response: ServerResponse, status: number, value: unknown, headOnly: boolean): void {
|
|
1036
|
+
const body = Buffer.from(JSON.stringify(value), "utf8");
|
|
1037
|
+
setSecurityHeaders(response);
|
|
1038
|
+
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "Content-Length": body.length });
|
|
1039
|
+
response.end(headOnly ? undefined : body);
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
private async handleWorkspace(request: IncomingMessage, response: ServerResponse, url: URL, root: string): Promise<void> {
|
|
1043
|
+
resolveWorkspacePath(root);
|
|
1044
|
+
const headOnly = request.method === "HEAD";
|
|
1045
|
+
const published = new URL(this.address!.publicBaseUrl);
|
|
1046
|
+
const origin = request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request);
|
|
1047
|
+
const workspaceUrl = this.createWorkspaceUrl(root, origin)!;
|
|
1048
|
+
if (!url.searchParams.has("api")) {
|
|
1049
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
const parsed = WORKSPACE_QUERY.safeParse(Object.fromEntries(url.searchParams));
|
|
1053
|
+
if (!parsed.success) throw new WorkspaceError("工作台参数无效:" + parsed.error.issues.map((issue) => issue.message).join(";"));
|
|
1054
|
+
const { api, entry, page, mode, original, prefetch, query, instance } = parsed.data;
|
|
1055
|
+
if (!api) {
|
|
1056
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
if (api === "tree") {
|
|
1060
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceEntries(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (api === "address") {
|
|
1064
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceAddress(root, entry, query), headOnly);
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
if (api === "web-title") {
|
|
1068
|
+
this.sendWorkspaceJson(response, 200, headOnly ? {} : await readWebPageTitle(entry), headOnly);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
if (api === "changes") {
|
|
1072
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceChanges(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
if (api === "terminal") {
|
|
1076
|
+
if (!instance) throw new WorkspaceError("终端标签标识无效。");
|
|
1077
|
+
if (!this.options.createWorkspaceTerminalUrl) throw new WorkspaceError("网页终端服务未启用。", 503);
|
|
1078
|
+
if (!headOnly) this.sendWorkspaceJson(response, 200, { url: this.options.createWorkspaceTerminalUrl(root, instance, request) }, false);
|
|
1079
|
+
else this.sendWorkspaceJson(response, 200, {}, true);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
if (api === "diff") {
|
|
1083
|
+
const versions = await readWorkspaceFileVersions(root, entry, mode, original);
|
|
1084
|
+
const file = resolveWorkspacePath(root, entry, true);
|
|
1085
|
+
const before = classifyContentSample(versions.before, true), after = classifyContentSample(versions.after, true);
|
|
1086
|
+
let html: string;
|
|
1087
|
+
if (before.kind === "binary" || after.kind === "binary") html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff;可以查看文件预览或下载。</div>';
|
|
1088
|
+
else {
|
|
1089
|
+
const previous = decodeText(versions.before, before.encoding, true), current = decodeText(versions.after, after.encoding, true);
|
|
1090
|
+
html = renderWorkspaceDiff(await createWorkspaceDiff(root, previous, current), current, (value) => highlightTextLines(value, file));
|
|
1091
|
+
}
|
|
1092
|
+
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly);
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
if (api !== "file" && api !== "raw") throw new WorkspaceError("工作台接口不存在。", 404);
|
|
1096
|
+
const file = resolveWorkspacePath(root, entry);
|
|
1097
|
+
const stat = fs.statSync(file);
|
|
1098
|
+
if (!stat.isFile()) throw new WorkspaceError("这不是普通文件,未读取内容。");
|
|
1099
|
+
if (api === "raw") {
|
|
1100
|
+
this.serveRawFile(request, response, file, stat, url.searchParams.get("download") === "1");
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
const raw = new URL(workspaceUrl);
|
|
1104
|
+
raw.searchParams.set("api", "raw"); raw.searchParams.set("entry", entry);
|
|
1105
|
+
const classification = classifyFileContent(file, stat.size);
|
|
1106
|
+
const type = binaryContentTypeFor(path.extname(file).toLowerCase());
|
|
1107
|
+
let html: string;
|
|
1108
|
+
if (classification.kind === "text") {
|
|
1109
|
+
const preview = readTextPreview(file, stat.size, classification.encoding);
|
|
1110
|
+
const lines = preview.text.split(/\r\n?|\n/u);
|
|
1111
|
+
html = (preview.truncated || lines.length > 10_000 ? '<div class="workspace-notice">文件较大,仅显示前 2 MiB 或 10000 行;可下载完整文件。</div>' : "")
|
|
1112
|
+
+ (isMarkdownFile(file) ? this.renderWorkspaceMarkdown(root, file, lines.slice(0, 10_000).join("\n"), workspaceUrl) : renderText(lines.slice(0, 10_000).join("\n"), file));
|
|
1113
|
+
} else if (type.startsWith("image/")) {
|
|
1114
|
+
html = '<div class="workspace-media"><img src="' + escapeAttribute(raw.toString()) + '" alt="' + escapeAttribute(path.basename(file)) + '"></div>';
|
|
1115
|
+
} else if (type === "application/pdf") {
|
|
1116
|
+
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '">浏览器不支持 PDF 预览,请下载文件。</object>';
|
|
1117
|
+
} else {
|
|
1118
|
+
html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本内容;可下载到本地查看。</div>';
|
|
1119
|
+
}
|
|
1120
|
+
let change: WorkspaceChange | undefined, gitError: string | undefined;
|
|
1121
|
+
try {
|
|
1122
|
+
const relative = path.relative(root, file).split(path.sep).join("/");
|
|
1123
|
+
const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
1124
|
+
change = (await readWorkspaceGitStatus(root)).changes.find(item => normalize(item.path) === normalize(relative));
|
|
1125
|
+
} catch (error) { gitError = error instanceof Error ? error.message : String(error); }
|
|
1126
|
+
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
private renderWorkspaceMarkdown(root: string, file: string, value: string, workspaceUrl: string): string {
|
|
1130
|
+
const environment = {}, tokens = MARKDOWN_RENDERER.parse(value, environment), targets = new Map<string, string>();
|
|
1131
|
+
rewriteMarkdownFileLinks(tokens, file, (target) => {
|
|
1132
|
+
const entry = path.relative(root, target).split(path.sep).join("/");
|
|
1133
|
+
try {
|
|
1134
|
+
const resolved = resolveWorkspacePath(root, entry);
|
|
1135
|
+
if (!fs.statSync(resolved).isFile()) return undefined;
|
|
1136
|
+
} catch { return undefined; }
|
|
1137
|
+
const url = new URL(workspaceUrl); url.searchParams.set("api", "raw"); url.searchParams.set("entry", entry);
|
|
1138
|
+
targets.set(url.toString(), entry); return url;
|
|
1139
|
+
});
|
|
1140
|
+
const rewriteLinks = (items: typeof tokens): void => {
|
|
1141
|
+
for (const token of items) {
|
|
1142
|
+
const href = token.type === "link_open" ? token.attrGet("href") : null;
|
|
1143
|
+
if (typeof href === "string" && href) {
|
|
1144
|
+
const entry = targets.get(href.split("#")[0]!);
|
|
1145
|
+
if (entry !== undefined) {
|
|
1146
|
+
const url = new URL(href); url.searchParams.delete("api");
|
|
1147
|
+
token.attrSet("href", url.toString()); token.attrSet("data-workspace-entry", entry);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
if (token.children) rewriteLinks(token.children);
|
|
1151
|
+
}
|
|
1152
|
+
};
|
|
1153
|
+
rewriteLinks(tokens);
|
|
1154
|
+
return '<article class="markdown-body">' + MARKDOWN_RENDERER.renderer.render(tokens, MARKDOWN_RENDERER.options, environment) + '</article>';
|
|
1155
|
+
}
|
|
1156
|
+
|
|
943
1157
|
private renderDirectoryViewer(directory: string, stat: fs.Stats, requestedPage: number): string {
|
|
944
1158
|
const entries = fs.readdirSync(directory, { withFileTypes: true })
|
|
945
1159
|
.flatMap((entry): DirectoryViewerEntry[] => {
|
|
@@ -977,7 +1191,7 @@ export class LocalFileViewerServer {
|
|
|
977
1191
|
title,
|
|
978
1192
|
filePath: directory,
|
|
979
1193
|
metadata: [`${entries.length} 项`, stat.mtime.toLocaleString()],
|
|
980
|
-
actions: [],
|
|
1194
|
+
actions: [{ href: this.createWorkspaceUrl(directory)!, label: "打开项目工作台" }],
|
|
981
1195
|
content: `<div class="directory-list">${rows}</div>${pagination}`,
|
|
982
1196
|
});
|
|
983
1197
|
}
|
|
@@ -1038,9 +1252,13 @@ export class LocalFileViewerServer {
|
|
|
1038
1252
|
stream.pipe(response);
|
|
1039
1253
|
}
|
|
1040
1254
|
|
|
1041
|
-
private sendHtml(response: ServerResponse, status: number, html: string, headOnly = false): void {
|
|
1255
|
+
private sendHtml(response: ServerResponse, status: number, html: string, headOnly = false, workspace = false): void {
|
|
1042
1256
|
const body = Buffer.from(html, "utf8");
|
|
1043
1257
|
setSecurityHeaders(response);
|
|
1258
|
+
// External frame redirects must not expose privileged viewer documents.
|
|
1259
|
+
response.setHeader("X-Frame-Options", "DENY");
|
|
1260
|
+
if (workspace) response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self' http: https:; script-src 'self'; connect-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
|
|
1261
|
+
else response.setHeader("Content-Security-Policy", String(response.getHeader("Content-Security-Policy")).replace("frame-ancestors 'self'", "frame-ancestors 'none'"));
|
|
1044
1262
|
response.statusCode = status;
|
|
1045
1263
|
response.setHeader("Cache-Control", "no-store");
|
|
1046
1264
|
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
@@ -1067,7 +1285,8 @@ function renderViewerPage(input: {
|
|
|
1067
1285
|
content: string;
|
|
1068
1286
|
viewMode?: RenderedFileSnapshot["viewMode"];
|
|
1069
1287
|
diagramScriptPath?: string;
|
|
1070
|
-
|
|
1288
|
+
eventsUrl?: string;
|
|
1289
|
+
scriptPath?: string;
|
|
1071
1290
|
}): string {
|
|
1072
1291
|
const metadata = renderMetadata(input.metadata);
|
|
1073
1292
|
const actions = input.actions.length > 0
|
|
@@ -1079,11 +1298,11 @@ function renderViewerPage(input: {
|
|
|
1079
1298
|
const toolbar = viewSwitch || actions
|
|
1080
1299
|
? `<div class="toolbar">${viewSwitch}${actions}</div>`
|
|
1081
1300
|
: "";
|
|
1082
|
-
const liveAttributes = input.
|
|
1083
|
-
? ` data-events-url="${escapeAttribute(input.
|
|
1301
|
+
const liveAttributes = input.eventsUrl
|
|
1302
|
+
? ` data-events-url="${escapeAttribute(input.eventsUrl)}"`
|
|
1084
1303
|
: "";
|
|
1085
|
-
const
|
|
1086
|
-
? `<script src="${escapeAttribute(input.
|
|
1304
|
+
const clientScript = input.scriptPath
|
|
1305
|
+
? `<script src="${escapeAttribute(input.scriptPath)}" defer></script>`
|
|
1087
1306
|
: "";
|
|
1088
1307
|
return `<!doctype html>
|
|
1089
1308
|
<html lang="zh-CN">
|
|
@@ -1149,6 +1368,7 @@ function renderViewerPage(input: {
|
|
|
1149
1368
|
.markdown-body img { max-width: 100%; height: auto; }
|
|
1150
1369
|
.markdown-body hr { height: 1px; margin: 1.5em 0; border: 0; background: #dfe3e8; }
|
|
1151
1370
|
${CSV_PREVIEW_CSS}
|
|
1371
|
+
${GIT_DIFF_PREVIEW_CSS}
|
|
1152
1372
|
.media { display: grid; place-items: center; min-height: 220px; }
|
|
1153
1373
|
.media img, .media video { max-width: 100%; max-height: calc(100vh - 70px); }
|
|
1154
1374
|
.media audio { width: min(720px, 100%); }
|
|
@@ -1208,7 +1428,7 @@ function renderViewerPage(input: {
|
|
|
1208
1428
|
<div class="meta"><span class="metadata-values" id="viewer-metadata">${metadata}</span>${toolbar}</div>
|
|
1209
1429
|
</header>
|
|
1210
1430
|
<main id="viewer-content">${input.content}</main>
|
|
1211
|
-
${
|
|
1431
|
+
${clientScript}
|
|
1212
1432
|
</body>
|
|
1213
1433
|
</html>`;
|
|
1214
1434
|
}
|
|
@@ -1350,6 +1570,44 @@ function parseDirectoryPage(value: string | null): number {
|
|
|
1350
1570
|
return Number.isSafeInteger(page) && page >= 0 ? page : 0;
|
|
1351
1571
|
}
|
|
1352
1572
|
|
|
1573
|
+
async function readGitDiffPreview(filePath: string): Promise<string | undefined> {
|
|
1574
|
+
try {
|
|
1575
|
+
const before = fs.statSync(filePath, { throwIfNoEntry: false });
|
|
1576
|
+
let text = "";
|
|
1577
|
+
if (before) {
|
|
1578
|
+
if (!before.isFile() || before.size > MAX_TEXT_PREVIEW_BYTES) return undefined;
|
|
1579
|
+
const classification = classifyFileContent(filePath, before.size);
|
|
1580
|
+
if (classification.kind !== "text") return undefined;
|
|
1581
|
+
const preview = readTextPreview(filePath, before.size, classification.encoding);
|
|
1582
|
+
if (preview.truncated) return undefined;
|
|
1583
|
+
text = preview.text;
|
|
1584
|
+
}
|
|
1585
|
+
const diff = await readGitFileDiff(filePath);
|
|
1586
|
+
let content = diff ? renderGitFileDiff(diff, text, (value) => highlightTextLines(value, filePath)) : undefined;
|
|
1587
|
+
if (!content && !fs.lstatSync(filePath, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
1588
|
+
let directory = path.dirname(filePath);
|
|
1589
|
+
while (!fs.existsSync(directory)) {
|
|
1590
|
+
const parent = path.dirname(directory); if (parent === directory) return undefined; directory = parent;
|
|
1591
|
+
}
|
|
1592
|
+
const root = fs.realpathSync(directory), entry = path.relative(directory, filePath).split(path.sep).join("/");
|
|
1593
|
+
const versions = await readWorkspaceFileVersions(root, entry, "all");
|
|
1594
|
+
if (!versions.beforeExists) return undefined;
|
|
1595
|
+
const previous = classifyContentSample(versions.before, true), current = classifyContentSample(versions.after, true);
|
|
1596
|
+
if (previous.kind !== "text" || current.kind !== "text") return undefined;
|
|
1597
|
+
const previousText = decodeText(versions.before, previous.encoding, true), currentText = decodeText(versions.after, current.encoding, true);
|
|
1598
|
+
const patch = await createWorkspaceDiff(root, previousText, currentText);
|
|
1599
|
+
if (!patch) return undefined;
|
|
1600
|
+
content = renderGitFileDiff(patch, currentText, (value) => highlightTextLines(value, filePath));
|
|
1601
|
+
}
|
|
1602
|
+
const after = fs.statSync(filePath, { throwIfNoEntry: false });
|
|
1603
|
+
if (before?.size !== after?.size || before?.mtimeMs !== after?.mtimeMs || before?.ctimeMs !== after?.ctimeMs
|
|
1604
|
+
|| before?.ino !== after?.ino || before?.dev !== after?.dev) return undefined;
|
|
1605
|
+
return content;
|
|
1606
|
+
} catch {
|
|
1607
|
+
return undefined;
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1353
1611
|
function readTextPreview(
|
|
1354
1612
|
filePath: string,
|
|
1355
1613
|
size: number,
|
|
@@ -1446,11 +1704,7 @@ function hasTextLikeCharacters(value: string): boolean {
|
|
|
1446
1704
|
}
|
|
1447
1705
|
|
|
1448
1706
|
function renderText(value: string, filePath: string): string {
|
|
1449
|
-
const
|
|
1450
|
-
const language = syntaxLanguageFor(filePath);
|
|
1451
|
-
const lines = language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1452
|
-
? highlightLines(normalized, language)
|
|
1453
|
-
: normalized.split("\n").map(escapeHtml);
|
|
1707
|
+
const language = syntaxLanguageFor(filePath), lines = highlightTextLines(value, filePath);
|
|
1454
1708
|
const languageClass = language ? ` class="language-${escapeAttribute(language)}"` : "";
|
|
1455
1709
|
return `<pre class="code hljs"><code${languageClass}>${lines.map((line, index) => {
|
|
1456
1710
|
const lineNumber = index + 1;
|
|
@@ -1458,6 +1712,14 @@ function renderText(value: string, filePath: string): string {
|
|
|
1458
1712
|
}).join("")}</code></pre>`;
|
|
1459
1713
|
}
|
|
1460
1714
|
|
|
1715
|
+
function highlightTextLines(value: string, filePath: string): string[] {
|
|
1716
|
+
const normalized = value.replace(/\r\n?/gu, "\n");
|
|
1717
|
+
const language = syntaxLanguageFor(filePath);
|
|
1718
|
+
return language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1719
|
+
? highlightLines(normalized, language)
|
|
1720
|
+
: normalized.split("\n").map(escapeHtml);
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1461
1723
|
function renderMarkdownDocument(value: string, filePath: string, createPreviewUrl: (filePath: string) => URL): string {
|
|
1462
1724
|
const environment = {};
|
|
1463
1725
|
const tokens = MARKDOWN_RENDERER.parse(value, environment);
|
|
@@ -1471,9 +1733,10 @@ function isMarkdownFile(filePath: string): boolean {
|
|
|
1471
1733
|
}
|
|
1472
1734
|
|
|
1473
1735
|
function syntaxLanguageFor(filePath: string): string | undefined {
|
|
1736
|
+
if (isMarkdownFile(filePath)) return "markdown";
|
|
1474
1737
|
const fileName = path.basename(filePath).toLowerCase();
|
|
1475
|
-
return HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1476
|
-
|
|
1738
|
+
return Object.hasOwn(HIGHLIGHT_LANGUAGE_BY_FILENAME, fileName) ? HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1739
|
+
: HIGHLIGHT_LANGUAGE_BY_EXTENSION[path.extname(fileName)];
|
|
1477
1740
|
}
|
|
1478
1741
|
|
|
1479
1742
|
function highlightLines(value: string, language: string): string[] {
|
|
@@ -10,6 +10,7 @@ export function rewriteMarkdownFileLinks(
|
|
|
10
10
|
tokens: Token[],
|
|
11
11
|
markdownPath: string | undefined,
|
|
12
12
|
createPreviewUrl: (filePath: string) => URL | undefined,
|
|
13
|
+
createImageUrl?: (filePath: string) => URL | undefined,
|
|
13
14
|
): void {
|
|
14
15
|
for (const token of tokens) {
|
|
15
16
|
const attribute = token.type === "link_open" ? "href" : token.type === "image" ? "src" : undefined;
|
|
@@ -17,10 +18,11 @@ export function rewriteMarkdownFileLinks(
|
|
|
17
18
|
if (attribute && typeof target === "string" && target) {
|
|
18
19
|
const local = resolveLocalTarget(target, markdownPath);
|
|
19
20
|
if (local) {
|
|
20
|
-
const
|
|
21
|
+
const image = token.type === "image";
|
|
22
|
+
const url = image && createImageUrl ? createImageUrl(local.filePath) : createPreviewUrl(local.filePath);
|
|
21
23
|
if (url) {
|
|
22
24
|
url.hash = local.hash;
|
|
23
|
-
if (
|
|
25
|
+
if (image && !createImageUrl) url.searchParams.set("raw", "1");
|
|
24
26
|
token.attrSet(attribute, url.toString());
|
|
25
27
|
} else {
|
|
26
28
|
token.attrs = token.attrs?.filter(([name]) => name !== attribute) ?? null;
|
|
@@ -30,7 +32,7 @@ export function rewriteMarkdownFileLinks(
|
|
|
30
32
|
token.attrs = token.attrs?.filter(([name]) => name !== attribute) ?? null;
|
|
31
33
|
}
|
|
32
34
|
}
|
|
33
|
-
if (token.children) rewriteMarkdownFileLinks(token.children, markdownPath, createPreviewUrl);
|
|
35
|
+
if (token.children) rewriteMarkdownFileLinks(token.children, markdownPath, createPreviewUrl, createImageUrl);
|
|
34
36
|
}
|
|
35
37
|
}
|
|
36
38
|
|