@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.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/CHANGELOG.md +28 -0
- package/README.md +55 -5
- package/README.zh.md +55 -5
- package/SECURITY.md +14 -0
- 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 +54 -10
- 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 +11 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +359 -37
- 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 +32 -10
- 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 +44 -24
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +103 -39
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +1 -1
- package/docs/technical-reference.zh.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +3 -1
- 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 +45 -11
- 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 +10 -7
- package/src/local-files/LocalFileViewerServer.ts +330 -37
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +35 -9
- 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 +44 -24
- package/src/terminal/TerminalServer.ts +98 -36
|
@@ -4,6 +4,7 @@ import fs from "node:fs";
|
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import http from "node:http";
|
|
6
6
|
import path from "node:path";
|
|
7
|
+
import { z } from "zod";
|
|
7
8
|
import hljs from "highlight.js/lib/common";
|
|
8
9
|
import dos from "highlight.js/lib/languages/dos";
|
|
9
10
|
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
|
@@ -11,6 +12,10 @@ import powershell from "highlight.js/lib/languages/powershell";
|
|
|
11
12
|
import MarkdownIt from "markdown-it";
|
|
12
13
|
import { CSV_PREVIEW_CSS, renderCsvPreview, csvSourcePreview } from "./CsvPreview.js";
|
|
13
14
|
import { GIT_DIFF_PREVIEW_CSS, readGitFileDiff, renderGitFileDiff } from "./GitDiffPreview.js";
|
|
15
|
+
import { renderWorkspacePage, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
16
|
+
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
17
|
+
import { readWebPageTitle } from "./WebPageTitle.js";
|
|
18
|
+
import { WorkspaceError, readWorkspaceAddress, readWorkspaceEntries, readWorkspaceGitStatus, readWorkspaceChanges, readWorkspaceFileVersions, createWorkspaceDiff, renderWorkspaceDiff, resolveWorkspacePath } from "./WorkspaceFiles.js";
|
|
14
19
|
import { enableDiagramFences, DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
|
|
15
20
|
import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
|
|
16
21
|
import { selectPreferredNetworkAddress, } from "./NetworkAddressSelector.js";
|
|
@@ -25,6 +30,13 @@ const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
|
|
|
25
30
|
const MAX_CONTENT_SAMPLE_BYTES = 64 * 1024;
|
|
26
31
|
const MAX_SYNTAX_HIGHLIGHT_BYTES = 512 * 1024;
|
|
27
32
|
const DIRECTORY_PAGE_SIZE = 100;
|
|
33
|
+
const WORKSPACE_QUERY = z.object({
|
|
34
|
+
api: z.string().optional(), entry: z.string().default(""),
|
|
35
|
+
page: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
36
|
+
mode: z.enum(["all", "staged", "unstaged"]).default("all"), original: z.string().optional(),
|
|
37
|
+
prefetch: z.enum(["0", "1"]).optional(), query: z.string().trim().max(160).optional(),
|
|
38
|
+
instance: z.string().regex(/^[a-f0-9]{16}$/u).optional(),
|
|
39
|
+
});
|
|
28
40
|
const MARKDOWN_EXTENSIONS = new Set([".markdown", ".md", ".mdown", ".mkd", ".mkdn"]);
|
|
29
41
|
const HTML_EXTENSIONS = new Set([".html", ".htm"]);
|
|
30
42
|
hljs.registerLanguage("dos", dos);
|
|
@@ -36,8 +48,8 @@ const MARKDOWN_RENDERER = new MarkdownIt({
|
|
|
36
48
|
linkify: true,
|
|
37
49
|
typographer: false,
|
|
38
50
|
highlight(value, language) {
|
|
39
|
-
const highlighted = language && hljs.getLanguage(language)
|
|
40
|
-
?
|
|
51
|
+
const highlighted = language && hljs.getLanguage(language) && Buffer.byteLength(value, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
52
|
+
? highlightLines(value, language).join("\n")
|
|
41
53
|
: escapeHtml(value);
|
|
42
54
|
const languageAttribute = language && hljs.getLanguage(language)
|
|
43
55
|
? ` class="language-${escapeAttribute(language)}"`
|
|
@@ -74,6 +86,8 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
74
86
|
const header = document.getElementById("viewer-header");
|
|
75
87
|
const title = document.getElementById("viewer-title");
|
|
76
88
|
const viewSwitch = document.getElementById("viewer-view-switch");
|
|
89
|
+
const diffPrevious = document.getElementById("diff-previous");
|
|
90
|
+
const diffNext = document.getElementById("diff-next");
|
|
77
91
|
const viewButtons = Array.from(document.querySelectorAll("[data-view-mode-button]"));
|
|
78
92
|
if (!content || !metadata || !header || !title) return;
|
|
79
93
|
const filePath = title.dataset.filePath || title.textContent || "";
|
|
@@ -109,29 +123,96 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
109
123
|
selection.addRange(range);
|
|
110
124
|
});
|
|
111
125
|
|
|
126
|
+
const diffBlocks = [];
|
|
127
|
+
if (diffPrevious && diffNext) {
|
|
128
|
+
for (const line of content.querySelectorAll(".git-diff .diff-addition, .git-diff .diff-deletion")) {
|
|
129
|
+
const previous = diffBlocks.at(-1);
|
|
130
|
+
if (previous && line.previousElementSibling === previous.last) previous.last = line;
|
|
131
|
+
else diffBlocks.push({ first: line, last: line, hash: "#diff-" + line.id });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
let diffPositions = [], selectedDiff = -1;
|
|
135
|
+
const updateDiffNavigation = () => {
|
|
136
|
+
let previous = -1, next = -1;
|
|
137
|
+
const top = window.scrollY;
|
|
138
|
+
// Adjacent blocks can share a scroll position near the ends of the file.
|
|
139
|
+
const current = Math.abs(diffPositions[selectedDiff] - top) <= 1
|
|
140
|
+
? selectedDiff : diffPositions.findIndex(position => Math.abs(position - top) <= 1);
|
|
141
|
+
if (current >= 0) {
|
|
142
|
+
previous = current - 1;
|
|
143
|
+
next = current + 1 < diffPositions.length ? current + 1 : -1;
|
|
144
|
+
} else {
|
|
145
|
+
for (let i = 0; i < diffPositions.length; i++) {
|
|
146
|
+
if (diffPositions[i] < top) previous = i;
|
|
147
|
+
else { next = i; break; }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (diffPrevious && diffNext) {
|
|
151
|
+
diffPrevious.disabled = previous < 0;
|
|
152
|
+
diffNext.disabled = next < 0;
|
|
153
|
+
}
|
|
154
|
+
return { previous, next };
|
|
155
|
+
};
|
|
156
|
+
const measureDiffPositions = () => {
|
|
157
|
+
if (!diffBlocks.length) return;
|
|
158
|
+
const height = window.innerHeight;
|
|
159
|
+
const readerCenter = (header.getBoundingClientRect().height + height) / 2;
|
|
160
|
+
const maxTop = Math.max(0, document.documentElement.scrollHeight - height);
|
|
161
|
+
diffPositions = diffBlocks.map(({ first, last }) => {
|
|
162
|
+
const center = (first.getBoundingClientRect().top + last.getBoundingClientRect().bottom) / 2;
|
|
163
|
+
return Math.min(maxTop, Math.max(0, window.scrollY + center - readerCenter));
|
|
164
|
+
});
|
|
165
|
+
updateDiffNavigation();
|
|
166
|
+
};
|
|
112
167
|
const updateHeaderOffset = () => {
|
|
113
168
|
const offset = Math.ceil(header.getBoundingClientRect().height) + 8;
|
|
114
169
|
document.documentElement.style.setProperty("--viewer-header-offset", offset + "px");
|
|
170
|
+
measureDiffPositions();
|
|
115
171
|
};
|
|
116
172
|
const highlightHashTarget = () => {
|
|
117
|
-
|
|
173
|
+
content.querySelector(".line.is-target-line")?.classList.remove("is-target-line");
|
|
174
|
+
const hash = window.location.hash;
|
|
175
|
+
selectedDiff = hash ? diffBlocks.findIndex(block => block.hash === hash) : (diffBlocks.length ? 0 : -1);
|
|
118
176
|
let id;
|
|
119
|
-
try {
|
|
120
|
-
id = decodeURIComponent(window.location.hash.slice(1));
|
|
121
|
-
} catch {
|
|
122
|
-
title.textContent = filePath;
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
177
|
+
try { id = decodeURIComponent(hash.slice(1)); } catch { id = ""; }
|
|
125
178
|
const lineNumber = /^L(\\d+)$/.exec(id)?.[1];
|
|
126
179
|
title.textContent = lineNumber ? filePath + ":" + lineNumber : filePath;
|
|
127
|
-
|
|
128
|
-
const target = document.getElementById(id);
|
|
180
|
+
const target = diffBlocks[selectedDiff]?.first ?? (lineNumber ? document.getElementById(id) : null);
|
|
129
181
|
target?.classList.add("is-target-line");
|
|
130
182
|
return target;
|
|
131
183
|
};
|
|
184
|
+
const centerDiffBlock = () => {
|
|
185
|
+
measureDiffPositions();
|
|
186
|
+
const top = diffPositions[selectedDiff];
|
|
187
|
+
if (top !== undefined) window.scrollTo(window.scrollX, top);
|
|
188
|
+
updateDiffNavigation();
|
|
189
|
+
};
|
|
132
190
|
const positionHashTarget = () => {
|
|
133
|
-
|
|
191
|
+
const target = highlightHashTarget();
|
|
192
|
+
if (window.location.hash && selectedDiff >= 0) centerDiffBlock();
|
|
193
|
+
else if (selectedDiff < 0) target?.scrollIntoView({ block: "start" });
|
|
194
|
+
if (diffBlocks.length) updateDiffNavigation();
|
|
195
|
+
};
|
|
196
|
+
const positionInitialContent = () => {
|
|
197
|
+
if (!diffBlocks.length) return positionHashTarget();
|
|
198
|
+
if (["reload", "back_forward"].includes(performance.getEntriesByType("navigation")[0]?.type)) {
|
|
199
|
+
highlightHashTarget();
|
|
200
|
+
updateDiffNavigation();
|
|
201
|
+
} else if (window.location.hash) positionHashTarget();
|
|
202
|
+
else { highlightHashTarget(); centerDiffBlock(); }
|
|
134
203
|
};
|
|
204
|
+
const jumpDiff = (direction) => {
|
|
205
|
+
const index = updateDiffNavigation()[direction];
|
|
206
|
+
if (index < 0) return;
|
|
207
|
+
window.history.pushState(null, "", diffBlocks[index].hash);
|
|
208
|
+
positionHashTarget();
|
|
209
|
+
};
|
|
210
|
+
if (diffBlocks.length) {
|
|
211
|
+
diffPrevious.addEventListener("click", () => jumpDiff("previous"));
|
|
212
|
+
diffNext.addEventListener("click", () => jumpDiff("next"));
|
|
213
|
+
window.addEventListener("scroll", updateDiffNavigation, { passive: true });
|
|
214
|
+
window.addEventListener("resize", measureDiffPositions);
|
|
215
|
+
}
|
|
135
216
|
if (/^#L\\d+$/u.test(window.location.hash)) document.body.dataset.viewMode = "code";
|
|
136
217
|
syncViewMode();
|
|
137
218
|
updateHeaderOffset();
|
|
@@ -142,7 +223,7 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
142
223
|
if (/^#L\\d+$/u.test(window.location.hash)) setViewMode("code");
|
|
143
224
|
else requestAnimationFrame(positionHashTarget);
|
|
144
225
|
});
|
|
145
|
-
requestAnimationFrame(
|
|
226
|
+
requestAnimationFrame(positionInitialContent);
|
|
146
227
|
if (!eventsUrl || typeof EventSource !== "function") return;
|
|
147
228
|
|
|
148
229
|
const restoreScroll = (top, left, atBottom, codeScrollLeft, tablePositions) => {
|
|
@@ -234,6 +315,11 @@ export class LocalFileViewerServer {
|
|
|
234
315
|
address;
|
|
235
316
|
basePath = "";
|
|
236
317
|
services = new Map();
|
|
318
|
+
workspaceAppBase;
|
|
319
|
+
enableWorkspaceApp(base) { this.workspaceAppBase = base; }
|
|
320
|
+
serveWorkspaceAppPage(response, url, headOnly) {
|
|
321
|
+
this.sendHtml(response, 200, renderWorkspacePage("", url.toString(), this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
322
|
+
}
|
|
237
323
|
constructor(options) {
|
|
238
324
|
this.options = options;
|
|
239
325
|
}
|
|
@@ -371,6 +457,30 @@ export class LocalFileViewerServer {
|
|
|
371
457
|
url.hash = `L${line}`;
|
|
372
458
|
return url.toString();
|
|
373
459
|
}
|
|
460
|
+
createWorkspaceUrl(directory, origin) {
|
|
461
|
+
if (!this.address || !this.secret)
|
|
462
|
+
return undefined;
|
|
463
|
+
try {
|
|
464
|
+
const root = fs.realpathSync(directory);
|
|
465
|
+
if (!fs.statSync(root).isDirectory())
|
|
466
|
+
return undefined;
|
|
467
|
+
const url = new URL(origin ?? this.address.publicBaseUrl);
|
|
468
|
+
url.pathname = this.basePath + "/workspace/" + this.createShortToken("workspace:" + root);
|
|
469
|
+
url.searchParams.set("path", root);
|
|
470
|
+
return url.toString();
|
|
471
|
+
}
|
|
472
|
+
catch {
|
|
473
|
+
return undefined;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
serveWorkspaceChatImage(request, response, root, entry) {
|
|
477
|
+
const file = resolveWorkspacePath(root, entry);
|
|
478
|
+
const stat = fs.statSync(file);
|
|
479
|
+
if (!stat.isFile() || !contentTypeFor(path.extname(file).toLowerCase()).startsWith("image/")) {
|
|
480
|
+
throw new WorkspaceError("图片格式不可预览。", 404);
|
|
481
|
+
}
|
|
482
|
+
this.serveRawFile(request, response, file, stat, false);
|
|
483
|
+
}
|
|
374
484
|
createTurnPreviewUrl(turnId) {
|
|
375
485
|
const normalizedTurnId = normalizeTurnId(turnId);
|
|
376
486
|
if (!this.address || !this.secret || !this.options.getTurnSnapshot || !normalizedTurnId)
|
|
@@ -396,6 +506,27 @@ export class LocalFileViewerServer {
|
|
|
396
506
|
}
|
|
397
507
|
const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
398
508
|
const route = routeWithinBasePath(requestUrl.pathname, this.basePath);
|
|
509
|
+
if (route === "/assets/workspace.js") {
|
|
510
|
+
this.sendJavascript(response, request.method === "HEAD", WORKSPACE_SCRIPT);
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
const workspaceMatch = new RegExp("^/workspace/([A-Za-z0-9_-]{" + SHORT_TOKEN_LENGTH + "})$", "u").exec(route);
|
|
514
|
+
if (workspaceMatch) {
|
|
515
|
+
const root = normalizeAbsolutePath(requestUrl.searchParams.get("path") ?? "");
|
|
516
|
+
const expected = root ? this.createShortToken("workspace:" + root) : "";
|
|
517
|
+
if (!root || !timingSafeEqual(Buffer.from(expected), Buffer.from(workspaceMatch[1]))) {
|
|
518
|
+
this.sendWorkspaceJson(response, 403, { error: "工作台链接无效,项目签名校验失败。" }, request.method === "HEAD");
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
try {
|
|
522
|
+
await this.handleWorkspace(request, response, requestUrl, root);
|
|
523
|
+
}
|
|
524
|
+
catch (error) {
|
|
525
|
+
const code = error.code;
|
|
526
|
+
this.sendWorkspaceJson(response, error instanceof WorkspaceError ? error.status : code === "ENOENT" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500, { error: error instanceof Error ? error.message : String(error) }, request.method === "HEAD");
|
|
527
|
+
}
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
399
530
|
if (!route.startsWith("/")) {
|
|
400
531
|
this.sendHtml(response, 404, errorPage("文件链接无效", "请从 Agent Bot 的回答中重新打开文件链接。"), request.method === "HEAD");
|
|
401
532
|
return;
|
|
@@ -480,8 +611,14 @@ export class LocalFileViewerServer {
|
|
|
480
611
|
if (snapshot.previewCursor !== undefined)
|
|
481
612
|
eventsUrl.searchParams.set("after", String(snapshot.previewCursor));
|
|
482
613
|
const language = detectTurnPreviewLanguage(request.headers["accept-language"]);
|
|
614
|
+
const projectWorkspaceUrl = snapshot.projectCwd ? this.createWorkspaceUrl(snapshot.projectCwd) : undefined;
|
|
615
|
+
const workspaceUrl = projectWorkspaceUrl ? new URL(projectWorkspaceUrl) : undefined;
|
|
616
|
+
workspaceUrl?.searchParams.set("list", "changes");
|
|
617
|
+
if (this.workspaceAppBase && snapshot.sessionId)
|
|
618
|
+
workspaceUrl?.searchParams.set("task", snapshot.sessionId);
|
|
483
619
|
const html = renderTurnPreviewPage({
|
|
484
620
|
state: snapshot,
|
|
621
|
+
workspaceUrl: workspaceUrl?.toString(),
|
|
485
622
|
eventsUrl: eventsUrl.toString(),
|
|
486
623
|
scriptPath: `${this.basePath}/assets/turn-preview.js`.replace(/\/{2,}/gu, "/"),
|
|
487
624
|
localFileUrl: (filePath, options) => this.createFileUrl(filePath, undefined, options),
|
|
@@ -523,7 +660,8 @@ export class LocalFileViewerServer {
|
|
|
523
660
|
actions.push({ href: original, label: "查看文件" }, { href: raw.toString(), label: "打开原始文件" }, { href: download.toString(), label: "下载" });
|
|
524
661
|
}
|
|
525
662
|
this.sendHtml(response, 200, renderViewerPage({ title: path.basename(filePath), filePath,
|
|
526
|
-
metadata: ["Git diff", "完整文件", "当前工作区"], actions, content
|
|
663
|
+
metadata: ["Git diff", "完整文件", "当前工作区"], actions, content, gitDiff: true,
|
|
664
|
+
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/") }), request.method === "HEAD");
|
|
527
665
|
return;
|
|
528
666
|
}
|
|
529
667
|
}
|
|
@@ -649,10 +787,8 @@ export class LocalFileViewerServer {
|
|
|
649
787
|
content: snapshot.content,
|
|
650
788
|
viewMode: snapshot.viewMode,
|
|
651
789
|
diagramScriptPath: isMarkdownFile(filePath) ? `${this.basePath}/assets/mermaid.js`.replace(/\/{2,}/gu, "/") : undefined,
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/"),
|
|
655
|
-
},
|
|
790
|
+
eventsUrl: eventsUrl.toString(),
|
|
791
|
+
scriptPath: `${this.basePath}/assets/viewer.js`.replace(/\/{2,}/gu, "/"),
|
|
656
792
|
});
|
|
657
793
|
}
|
|
658
794
|
renderFileSnapshot(filePath, stat) {
|
|
@@ -925,6 +1061,150 @@ export class LocalFileViewerServer {
|
|
|
925
1061
|
request.once("aborted", cleanup);
|
|
926
1062
|
response.once("close", cleanup);
|
|
927
1063
|
}
|
|
1064
|
+
sendWorkspaceJson(response, status, value, headOnly) {
|
|
1065
|
+
const body = Buffer.from(JSON.stringify(value), "utf8");
|
|
1066
|
+
setSecurityHeaders(response);
|
|
1067
|
+
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "Content-Length": body.length });
|
|
1068
|
+
response.end(headOnly ? undefined : body);
|
|
1069
|
+
}
|
|
1070
|
+
async handleWorkspace(request, response, url, root) {
|
|
1071
|
+
resolveWorkspacePath(root);
|
|
1072
|
+
const headOnly = request.method === "HEAD";
|
|
1073
|
+
const published = new URL(this.address.publicBaseUrl);
|
|
1074
|
+
const origin = request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request);
|
|
1075
|
+
const workspaceUrl = this.createWorkspaceUrl(root, origin);
|
|
1076
|
+
if (!url.searchParams.has("api")) {
|
|
1077
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
const parsed = WORKSPACE_QUERY.safeParse(Object.fromEntries(url.searchParams));
|
|
1081
|
+
if (!parsed.success)
|
|
1082
|
+
throw new WorkspaceError("工作台参数无效:" + parsed.error.issues.map((issue) => issue.message).join(";"));
|
|
1083
|
+
const { api, entry, page, mode, original, prefetch, query, instance } = parsed.data;
|
|
1084
|
+
if (!api) {
|
|
1085
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js", this.workspaceAppBase), headOnly, true);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (api === "tree") {
|
|
1089
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceEntries(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
if (api === "address") {
|
|
1093
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceAddress(root, entry, query), headOnly);
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
if (api === "web-title") {
|
|
1097
|
+
this.sendWorkspaceJson(response, 200, headOnly ? {} : await readWebPageTitle(entry), headOnly);
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
if (api === "changes") {
|
|
1101
|
+
this.sendWorkspaceJson(response, 200, await readWorkspaceChanges(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
if (api === "terminal") {
|
|
1105
|
+
if (!instance)
|
|
1106
|
+
throw new WorkspaceError("终端标签标识无效。");
|
|
1107
|
+
if (!this.options.createWorkspaceTerminalUrl)
|
|
1108
|
+
throw new WorkspaceError("网页终端服务未启用。", 503);
|
|
1109
|
+
if (!headOnly)
|
|
1110
|
+
this.sendWorkspaceJson(response, 200, { url: this.options.createWorkspaceTerminalUrl(root, instance, request) }, false);
|
|
1111
|
+
else
|
|
1112
|
+
this.sendWorkspaceJson(response, 200, {}, true);
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
if (api === "diff") {
|
|
1116
|
+
const versions = await readWorkspaceFileVersions(root, entry, mode, original);
|
|
1117
|
+
const file = resolveWorkspacePath(root, entry, true);
|
|
1118
|
+
const before = classifyContentSample(versions.before, true), after = classifyContentSample(versions.after, true);
|
|
1119
|
+
let html;
|
|
1120
|
+
if (before.kind === "binary" || after.kind === "binary")
|
|
1121
|
+
html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff;可以查看文件预览或下载。</div>';
|
|
1122
|
+
else {
|
|
1123
|
+
const previous = decodeText(versions.before, before.encoding, true), current = decodeText(versions.after, after.encoding, true);
|
|
1124
|
+
html = renderWorkspaceDiff(await createWorkspaceDiff(root, previous, current), current, (value) => highlightTextLines(value, file));
|
|
1125
|
+
}
|
|
1126
|
+
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly);
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
if (api !== "file" && api !== "raw")
|
|
1130
|
+
throw new WorkspaceError("工作台接口不存在。", 404);
|
|
1131
|
+
const file = resolveWorkspacePath(root, entry);
|
|
1132
|
+
const stat = fs.statSync(file);
|
|
1133
|
+
if (!stat.isFile())
|
|
1134
|
+
throw new WorkspaceError("这不是普通文件,未读取内容。");
|
|
1135
|
+
if (api === "raw") {
|
|
1136
|
+
this.serveRawFile(request, response, file, stat, url.searchParams.get("download") === "1");
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
const raw = new URL(workspaceUrl);
|
|
1140
|
+
raw.searchParams.set("api", "raw");
|
|
1141
|
+
raw.searchParams.set("entry", entry);
|
|
1142
|
+
const classification = classifyFileContent(file, stat.size);
|
|
1143
|
+
const type = binaryContentTypeFor(path.extname(file).toLowerCase());
|
|
1144
|
+
let html;
|
|
1145
|
+
if (classification.kind === "text") {
|
|
1146
|
+
const preview = readTextPreview(file, stat.size, classification.encoding);
|
|
1147
|
+
const lines = preview.text.split(/\r\n?|\n/u);
|
|
1148
|
+
html = (preview.truncated || lines.length > 10_000 ? '<div class="workspace-notice">文件较大,仅显示前 2 MiB 或 10000 行;可下载完整文件。</div>' : "")
|
|
1149
|
+
+ (isMarkdownFile(file) ? this.renderWorkspaceMarkdown(root, file, lines.slice(0, 10_000).join("\n"), workspaceUrl) : renderText(lines.slice(0, 10_000).join("\n"), file));
|
|
1150
|
+
}
|
|
1151
|
+
else if (type.startsWith("image/")) {
|
|
1152
|
+
html = '<div class="workspace-media"><img src="' + escapeAttribute(raw.toString()) + '" alt="' + escapeAttribute(path.basename(file)) + '"></div>';
|
|
1153
|
+
}
|
|
1154
|
+
else if (type === "application/pdf") {
|
|
1155
|
+
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '">浏览器不支持 PDF 预览,请下载文件。</object>';
|
|
1156
|
+
}
|
|
1157
|
+
else {
|
|
1158
|
+
html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本内容;可下载到本地查看。</div>';
|
|
1159
|
+
}
|
|
1160
|
+
let change, gitError;
|
|
1161
|
+
try {
|
|
1162
|
+
const relative = path.relative(root, file).split(path.sep).join("/");
|
|
1163
|
+
const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
1164
|
+
change = (await readWorkspaceGitStatus(root)).changes.find(item => normalize(item.path) === normalize(relative));
|
|
1165
|
+
}
|
|
1166
|
+
catch (error) {
|
|
1167
|
+
gitError = error instanceof Error ? error.message : String(error);
|
|
1168
|
+
}
|
|
1169
|
+
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly);
|
|
1170
|
+
}
|
|
1171
|
+
renderWorkspaceMarkdown(root, file, value, workspaceUrl) {
|
|
1172
|
+
const environment = {}, tokens = MARKDOWN_RENDERER.parse(value, environment), targets = new Map();
|
|
1173
|
+
rewriteMarkdownFileLinks(tokens, file, (target) => {
|
|
1174
|
+
const entry = path.relative(root, target).split(path.sep).join("/");
|
|
1175
|
+
try {
|
|
1176
|
+
const resolved = resolveWorkspacePath(root, entry);
|
|
1177
|
+
if (!fs.statSync(resolved).isFile())
|
|
1178
|
+
return undefined;
|
|
1179
|
+
}
|
|
1180
|
+
catch {
|
|
1181
|
+
return undefined;
|
|
1182
|
+
}
|
|
1183
|
+
const url = new URL(workspaceUrl);
|
|
1184
|
+
url.searchParams.set("api", "raw");
|
|
1185
|
+
url.searchParams.set("entry", entry);
|
|
1186
|
+
targets.set(url.toString(), entry);
|
|
1187
|
+
return url;
|
|
1188
|
+
});
|
|
1189
|
+
const rewriteLinks = (items) => {
|
|
1190
|
+
for (const token of items) {
|
|
1191
|
+
const href = token.type === "link_open" ? token.attrGet("href") : null;
|
|
1192
|
+
if (typeof href === "string" && href) {
|
|
1193
|
+
const entry = targets.get(href.split("#")[0]);
|
|
1194
|
+
if (entry !== undefined) {
|
|
1195
|
+
const url = new URL(href);
|
|
1196
|
+
url.searchParams.delete("api");
|
|
1197
|
+
token.attrSet("href", url.toString());
|
|
1198
|
+
token.attrSet("data-workspace-entry", entry);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
if (token.children)
|
|
1202
|
+
rewriteLinks(token.children);
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
rewriteLinks(tokens);
|
|
1206
|
+
return '<article class="markdown-body">' + MARKDOWN_RENDERER.renderer.render(tokens, MARKDOWN_RENDERER.options, environment) + '</article>';
|
|
1207
|
+
}
|
|
928
1208
|
renderDirectoryViewer(directory, stat, requestedPage) {
|
|
929
1209
|
const entries = fs.readdirSync(directory, { withFileTypes: true })
|
|
930
1210
|
.flatMap((entry) => {
|
|
@@ -964,7 +1244,7 @@ export class LocalFileViewerServer {
|
|
|
964
1244
|
title,
|
|
965
1245
|
filePath: directory,
|
|
966
1246
|
metadata: [`${entries.length} 项`, stat.mtime.toLocaleString()],
|
|
967
|
-
actions: [],
|
|
1247
|
+
actions: [{ href: this.createWorkspaceUrl(directory), label: "打开项目工作台" }],
|
|
968
1248
|
content: `<div class="directory-list">${rows}</div>${pagination}`,
|
|
969
1249
|
});
|
|
970
1250
|
}
|
|
@@ -1015,9 +1295,15 @@ export class LocalFileViewerServer {
|
|
|
1015
1295
|
stream.on("error", (error) => response.destroy(error));
|
|
1016
1296
|
stream.pipe(response);
|
|
1017
1297
|
}
|
|
1018
|
-
sendHtml(response, status, html, headOnly = false) {
|
|
1298
|
+
sendHtml(response, status, html, headOnly = false, workspace = false) {
|
|
1019
1299
|
const body = Buffer.from(html, "utf8");
|
|
1020
1300
|
setSecurityHeaders(response);
|
|
1301
|
+
// External frame redirects must not expose privileged viewer documents.
|
|
1302
|
+
response.setHeader("X-Frame-Options", "DENY");
|
|
1303
|
+
if (workspace)
|
|
1304
|
+
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'");
|
|
1305
|
+
else
|
|
1306
|
+
response.setHeader("Content-Security-Policy", String(response.getHeader("Content-Security-Policy")).replace("frame-ancestors 'self'", "frame-ancestors 'none'"));
|
|
1021
1307
|
response.statusCode = status;
|
|
1022
1308
|
response.setHeader("Cache-Control", "no-store");
|
|
1023
1309
|
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
@@ -1042,14 +1328,17 @@ function renderViewerPage(input) {
|
|
|
1042
1328
|
const viewSwitch = input.viewMode
|
|
1043
1329
|
? '<div class="view-switch" id="viewer-view-switch" role="tablist" aria-label="预览模式"><button class="is-active" type="button" role="tab" aria-selected="true" data-view-mode-button="rendered">预览</button><button type="button" role="tab" aria-selected="false" data-view-mode-button="code">代码</button></div>'
|
|
1044
1330
|
: "";
|
|
1045
|
-
const
|
|
1046
|
-
|
|
1331
|
+
const diffNavigation = input.gitDiff ? `<div class="diff-navigation" role="group" aria-label="Git Diff 导航">${[
|
|
1332
|
+
["previous", "上一处改动", "M12 20V4m-6 6 6-6 6 6"], ["next", "下一处改动", "M12 4v16m-6-6 6 6 6-6"],
|
|
1333
|
+
].map(([direction, label, arrow]) => `<button type="button" id="diff-${direction}" title="${label}" aria-label="${label}" disabled><svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="${arrow}"/></svg></button>`).join("")}</div>` : "";
|
|
1334
|
+
const toolbar = viewSwitch || actions || diffNavigation
|
|
1335
|
+
? `<div class="toolbar">${viewSwitch}${diffNavigation}${actions}</div>`
|
|
1047
1336
|
: "";
|
|
1048
|
-
const liveAttributes = input.
|
|
1049
|
-
? ` data-events-url="${escapeAttribute(input.
|
|
1337
|
+
const liveAttributes = input.eventsUrl
|
|
1338
|
+
? ` data-events-url="${escapeAttribute(input.eventsUrl)}"`
|
|
1050
1339
|
: "";
|
|
1051
|
-
const
|
|
1052
|
-
? `<script src="${escapeAttribute(input.
|
|
1340
|
+
const clientScript = input.scriptPath
|
|
1341
|
+
? `<script src="${escapeAttribute(input.scriptPath)}" defer></script>`
|
|
1053
1342
|
: "";
|
|
1054
1343
|
return `<!doctype html>
|
|
1055
1344
|
<html lang="zh-CN">
|
|
@@ -1068,6 +1357,12 @@ function renderViewerPage(input) {
|
|
|
1068
1357
|
.toolbar { margin-left: auto; display: flex; gap: 8px; align-items: center; }
|
|
1069
1358
|
.actions { display: flex; gap: 8px; }
|
|
1070
1359
|
.actions a { color: #1456f0; text-decoration: none; padding: 3px 7px; border: 1px solid #c9d0db; border-radius: 4px; background: #fff; }
|
|
1360
|
+
.diff-navigation { display: inline-flex; gap: 4px; }
|
|
1361
|
+
.diff-navigation button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 1px solid #c9d0db; border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
|
|
1362
|
+
.diff-navigation button:disabled { opacity: .4; cursor: default; }
|
|
1363
|
+
.diff-navigation button:not(:disabled):hover { background: #f0f4ff; color: #1456f0; }
|
|
1364
|
+
.diff-navigation button:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
|
1365
|
+
.diff-navigation svg { width: 16px; height: 16px; }
|
|
1071
1366
|
.view-switch { display: inline-flex; padding: 2px; border: 1px solid #c9d0db; border-radius: 5px; background: #f2f3f5; }
|
|
1072
1367
|
.view-switch[hidden] { display: none; }
|
|
1073
1368
|
.view-switch button { min-width: 46px; padding: 2px 8px; border: 0; border-radius: 3px; background: transparent; color: #646a73; cursor: pointer; font: inherit; }
|
|
@@ -1140,6 +1435,8 @@ function renderViewerPage(input) {
|
|
|
1140
1435
|
.meta, .pagination { color: #a6a9ad; }
|
|
1141
1436
|
.actions a, .pagination a { color: #8ab4ff; }
|
|
1142
1437
|
.actions a { border-color: #55585c; background: #292a2d; }
|
|
1438
|
+
.diff-navigation button { border-color: #55585c; }
|
|
1439
|
+
.diff-navigation button:not(:disabled):hover { background: #292f3d; color: #8ab4ff; }
|
|
1143
1440
|
.view-switch { border-color: #55585c; background: #292a2d; }
|
|
1144
1441
|
.view-switch button { color: #a6a9ad; }
|
|
1145
1442
|
.view-switch button.is-active { background: #3a3b3d; color: #8ab4ff; box-shadow: none; }
|
|
@@ -1175,7 +1472,7 @@ function renderViewerPage(input) {
|
|
|
1175
1472
|
<div class="meta"><span class="metadata-values" id="viewer-metadata">${metadata}</span>${toolbar}</div>
|
|
1176
1473
|
</header>
|
|
1177
1474
|
<main id="viewer-content">${input.content}</main>
|
|
1178
|
-
${
|
|
1475
|
+
${clientScript}
|
|
1179
1476
|
</body>
|
|
1180
1477
|
</html>`;
|
|
1181
1478
|
}
|
|
@@ -1331,13 +1628,33 @@ async function readGitDiffPreview(filePath) {
|
|
|
1331
1628
|
text = preview.text;
|
|
1332
1629
|
}
|
|
1333
1630
|
const diff = await readGitFileDiff(filePath);
|
|
1334
|
-
|
|
1335
|
-
|
|
1631
|
+
let content = diff ? renderGitFileDiff(diff, text, (value) => highlightTextLines(value, filePath)) : undefined;
|
|
1632
|
+
if (!content && !fs.lstatSync(filePath, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
1633
|
+
let directory = path.dirname(filePath);
|
|
1634
|
+
while (!fs.existsSync(directory)) {
|
|
1635
|
+
const parent = path.dirname(directory);
|
|
1636
|
+
if (parent === directory)
|
|
1637
|
+
return undefined;
|
|
1638
|
+
directory = parent;
|
|
1639
|
+
}
|
|
1640
|
+
const root = fs.realpathSync(directory), entry = path.relative(directory, filePath).split(path.sep).join("/");
|
|
1641
|
+
const versions = await readWorkspaceFileVersions(root, entry, "all");
|
|
1642
|
+
if (!versions.beforeExists)
|
|
1643
|
+
return undefined;
|
|
1644
|
+
const previous = classifyContentSample(versions.before, true), current = classifyContentSample(versions.after, true);
|
|
1645
|
+
if (previous.kind !== "text" || current.kind !== "text")
|
|
1646
|
+
return undefined;
|
|
1647
|
+
const previousText = decodeText(versions.before, previous.encoding, true), currentText = decodeText(versions.after, current.encoding, true);
|
|
1648
|
+
const patch = await createWorkspaceDiff(root, previousText, currentText);
|
|
1649
|
+
if (!patch)
|
|
1650
|
+
return undefined;
|
|
1651
|
+
content = renderGitFileDiff(patch, currentText, (value) => highlightTextLines(value, filePath));
|
|
1652
|
+
}
|
|
1336
1653
|
const after = fs.statSync(filePath, { throwIfNoEntry: false });
|
|
1337
1654
|
if (before?.size !== after?.size || before?.mtimeMs !== after?.mtimeMs || before?.ctimeMs !== after?.ctimeMs
|
|
1338
1655
|
|| before?.ino !== after?.ino || before?.dev !== after?.dev)
|
|
1339
1656
|
return undefined;
|
|
1340
|
-
return
|
|
1657
|
+
return content;
|
|
1341
1658
|
}
|
|
1342
1659
|
catch {
|
|
1343
1660
|
return undefined;
|
|
@@ -1424,17 +1741,20 @@ function hasTextLikeCharacters(value) {
|
|
|
1424
1741
|
return controls <= 2 || controls / Math.max(1, characters) <= 0.02;
|
|
1425
1742
|
}
|
|
1426
1743
|
function renderText(value, filePath) {
|
|
1427
|
-
const
|
|
1428
|
-
const language = syntaxLanguageFor(filePath);
|
|
1429
|
-
const lines = language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1430
|
-
? highlightLines(normalized, language)
|
|
1431
|
-
: normalized.split("\n").map(escapeHtml);
|
|
1744
|
+
const language = syntaxLanguageFor(filePath), lines = highlightTextLines(value, filePath);
|
|
1432
1745
|
const languageClass = language ? ` class="language-${escapeAttribute(language)}"` : "";
|
|
1433
1746
|
return `<pre class="code hljs"><code${languageClass}>${lines.map((line, index) => {
|
|
1434
1747
|
const lineNumber = index + 1;
|
|
1435
1748
|
return `<span class="line" id="L${lineNumber}"><a class="line-number" href="#L${lineNumber}">${lineNumber}</a>${line}</span>`;
|
|
1436
1749
|
}).join("")}</code></pre>`;
|
|
1437
1750
|
}
|
|
1751
|
+
function highlightTextLines(value, filePath) {
|
|
1752
|
+
const normalized = value.replace(/\r\n?/gu, "\n");
|
|
1753
|
+
const language = syntaxLanguageFor(filePath);
|
|
1754
|
+
return language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1755
|
+
? highlightLines(normalized, language)
|
|
1756
|
+
: normalized.split("\n").map(escapeHtml);
|
|
1757
|
+
}
|
|
1438
1758
|
function renderMarkdownDocument(value, filePath, createPreviewUrl) {
|
|
1439
1759
|
const environment = {};
|
|
1440
1760
|
const tokens = MARKDOWN_RENDERER.parse(value, environment);
|
|
@@ -1446,9 +1766,11 @@ function isMarkdownFile(filePath) {
|
|
|
1446
1766
|
return MARKDOWN_EXTENSIONS.has(path.extname(filePath).toLowerCase());
|
|
1447
1767
|
}
|
|
1448
1768
|
function syntaxLanguageFor(filePath) {
|
|
1769
|
+
if (isMarkdownFile(filePath))
|
|
1770
|
+
return "markdown";
|
|
1449
1771
|
const fileName = path.basename(filePath).toLowerCase();
|
|
1450
|
-
return HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1451
|
-
|
|
1772
|
+
return Object.hasOwn(HIGHLIGHT_LANGUAGE_BY_FILENAME, fileName) ? HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1773
|
+
: HIGHLIGHT_LANGUAGE_BY_EXTENSION[path.extname(fileName)];
|
|
1452
1774
|
}
|
|
1453
1775
|
function highlightLines(value, language) {
|
|
1454
1776
|
try {
|