@evandu/super-pi 0.1.233 → 0.1.234

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.
Files changed (44) hide show
  1. package/dist/client/.super-pi-client-sources.json +8 -8
  2. package/dist/client/assets/CodeMirrorEditor-Bghp-U4C.js +2 -0
  3. package/dist/client/assets/{dist-BxJsFYNz.js → dist-B8NaV9Cv.js} +1 -1
  4. package/dist/client/assets/{dist-Dv5RvBil.js → dist-BESOLyaG.js} +1 -1
  5. package/dist/client/assets/{dist-BH-kaMWJ.js → dist-BNTyu0GR.js} +1 -1
  6. package/dist/client/assets/{dist-BX6V-2ch.js → dist-BOLAeWpo.js} +1 -1
  7. package/dist/client/assets/{dist-D6L_I39S.js → dist-BXS7H8-R.js} +1 -1
  8. package/dist/client/assets/{dist-CXQ72jK0.js → dist-BfJ86nxw.js} +1 -1
  9. package/dist/client/assets/{dist-CADYSFwN.js → dist-Bs7CHuCU.js} +1 -1
  10. package/dist/client/assets/{dist-Qu_JVRdm.js → dist-C7Frt-j5.js} +1 -1
  11. package/dist/client/assets/{dist-8ntSzuyc.js → dist-CWI_J8Y8.js} +1 -1
  12. package/dist/client/assets/{dist-BTFTY60x.js → dist-CXgcMgdt.js} +1 -1
  13. package/dist/client/assets/{dist-n9h1Tr_V.js → dist-CeyskXU5.js} +1 -1
  14. package/dist/client/assets/{dist-DfIfNI5O.js → dist-CpJDmC2s.js} +1 -1
  15. package/dist/client/assets/{dist-RRg5quSb.js → dist-DDQEsi6d.js} +1 -1
  16. package/dist/client/assets/{dist-DsaVwWTi.js → dist-DkGaMCuB.js} +1 -1
  17. package/dist/client/assets/{dist-CBkmTbun.js → dist-DzEYlfwN.js} +1 -1
  18. package/dist/client/assets/{dist-CNOENBsx.js → dist-Ka-oeqiz.js} +1 -1
  19. package/dist/client/assets/{dist-BboHMFNI.js → dist-Zo5WaMe0.js} +1 -1
  20. package/dist/client/assets/{dist-DTpnIL-S.js → dist-gzowmwC2.js} +1 -1
  21. package/dist/client/assets/{dist-BdS5YuVr.js → dist-jtZ_yT6e.js} +1 -1
  22. package/dist/client/assets/{dist-mIg0RKXQ.js → dist-pz-FtJ-_.js} +1 -1
  23. package/dist/client/assets/{dist-DILlxwEE.js → dist-qY4JuH16.js} +1 -1
  24. package/dist/client/assets/{dist-DlyF9NDv.js → dist-vqHBACjg.js} +1 -1
  25. package/dist/client/assets/{index-ULLf_i7J.css → index-CYevEn2Z.css} +1 -1
  26. package/dist/client/assets/{index-09FegZJi.js → index-_JUMqd3d.js} +51 -50
  27. package/dist/client/index.html +2 -2
  28. package/dist/server/explicit-file-open.d.ts +34 -0
  29. package/dist/server/explicit-file-open.js +105 -0
  30. package/dist/server/file-name-index.d.ts +5 -5
  31. package/dist/server/file-name-index.js +22 -19
  32. package/dist/server/files.d.ts +5 -0
  33. package/dist/server/files.js +12 -6
  34. package/dist/server/git.d.ts +10 -0
  35. package/dist/server/git.js +135 -1
  36. package/dist/server/http-server.js +88 -5
  37. package/dist/server/workspace-file-response.d.ts +6 -2
  38. package/dist/server/workspace-file-response.js +6 -6
  39. package/dist/shared/git-commit.d.ts +11 -0
  40. package/dist/shared/git-commit.js +1 -0
  41. package/dist/shared/git-graph.d.ts +38 -0
  42. package/dist/shared/git-graph.js +30 -0
  43. package/package.json +1 -1
  44. package/dist/client/assets/CodeMirrorEditor-D30doKD5.js +0 -2
@@ -8,8 +8,8 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-09FegZJi.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-ULLf_i7J.css">
11
+ <script type="module" crossorigin src="/assets/index-_JUMqd3d.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-CYevEn2Z.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -0,0 +1,34 @@
1
+ export declare function createExplicitFileOpen(): {
2
+ open(workspaceId: string, workspace: string, root: string, input: string): Promise<{
3
+ meta: import("./files.js").FileMeta;
4
+ text: boolean;
5
+ path: string;
6
+ name: string;
7
+ } | {
8
+ content: string;
9
+ eol: "\n" | "\r\n";
10
+ bom: boolean;
11
+ meta: import("./files.js").FileMeta;
12
+ text: boolean;
13
+ path: string;
14
+ name: string;
15
+ } | {
16
+ meta: import("./files.js").FileMeta;
17
+ text: boolean;
18
+ path: string;
19
+ name: string;
20
+ targetName?: string | undefined;
21
+ ticket: `${string}-${string}-${string}-${string}-${string}`;
22
+ } | {
23
+ content: string;
24
+ eol: "\n" | "\r\n";
25
+ bom: boolean;
26
+ meta: import("./files.js").FileMeta;
27
+ text: boolean;
28
+ path: string;
29
+ name: string;
30
+ targetName?: string | undefined;
31
+ ticket: `${string}-${string}-${string}-${string}-${string}`;
32
+ }>;
33
+ target(workspaceId: string, root: string, ticket: string): Promise<string>;
34
+ };
@@ -0,0 +1,105 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, realpath } from "node:fs/promises";
4
+ import { basename, isAbsolute, posix, resolve } from "node:path";
5
+ import { contains, decodeWorkspaceText, fileMetaFromStat, FilesError, hasBinaryExtension, MAX_FILE_BYTES, toRelative } from "./files.js";
6
+ import { explorerInternalPath, explorerPath } from "./workspace-file-operations.js";
7
+ const MAX_OPEN_TICKETS = 256;
8
+ function localAbsolute(path) {
9
+ return process.platform === "win32" ? /^[a-z]:[\\/]/i.test(path) : path.startsWith("/") && !path.startsWith("//");
10
+ }
11
+ async function selectedFile(workspace, root, input) {
12
+ if (input.includes("\0"))
13
+ throw new FilesError(400, "文件路径包含非法字符。", "bad_path");
14
+ if (process.platform === "win32" && input.slice(localAbsolute(input) ? 2 : 0).includes(":")) {
15
+ throw new FilesError(400, "请输入完整的本机文件路径。", "bad_path");
16
+ }
17
+ if (localAbsolute(input))
18
+ return resolve(input);
19
+ if (isAbsolute(input) || /^[\\/]|^[a-z]:/i.test(input)) {
20
+ throw new FilesError(400, "请输入完整的本机文件路径。", "bad_path");
21
+ }
22
+ const relative = input.replaceAll("\\", "/");
23
+ const name = posix.basename(relative);
24
+ if (!name || name === "." || name === "..")
25
+ throw new FilesError(400, "请选择一个文件。", "not_a_file");
26
+ const parent = await explorerPath(workspace, root, posix.dirname(relative), true);
27
+ const file = resolve(parent, name);
28
+ if (explorerInternalPath(toRelative(workspace, file))) {
29
+ throw new FilesError(403, "不能直接访问应用的回收目录。", "protected_path");
30
+ }
31
+ if (!(await lstat(file)).isSymbolicLink())
32
+ await explorerPath(workspace, root, relative);
33
+ return file;
34
+ }
35
+ async function readOpenedFile(path) {
36
+ if (!(await lstat(path)).isFile())
37
+ throw new FilesError(400, "请选择一个普通文件。", "not_a_file");
38
+ const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
39
+ try {
40
+ const info = await handle.stat({ bigint: true });
41
+ if (!info.isFile())
42
+ throw new FilesError(400, "请选择一个普通文件。", "not_a_file");
43
+ const meta = fileMetaFromStat(info);
44
+ if (meta.size > MAX_FILE_BYTES || hasBinaryExtension(path))
45
+ return { meta, text: false };
46
+ const buffer = Buffer.alloc(meta.size + 1);
47
+ let read = 0;
48
+ while (read < buffer.length) {
49
+ const { bytesRead } = await handle.read(buffer, read, buffer.length - read, read);
50
+ if (!bytesRead)
51
+ break;
52
+ read += bytesRead;
53
+ }
54
+ if (read !== meta.size)
55
+ throw new FilesError(409, "读取时文件发生变化,请重新打开。", "stale");
56
+ try {
57
+ return { meta, text: true, ...decodeWorkspaceText(buffer.subarray(0, read), path) };
58
+ }
59
+ catch (error) {
60
+ if (error instanceof FilesError && error.code === "binary")
61
+ return { meta, text: false };
62
+ throw error;
63
+ }
64
+ }
65
+ finally {
66
+ await handle.close();
67
+ }
68
+ }
69
+ export function createExplicitFileOpen() {
70
+ const tickets = new Map();
71
+ return {
72
+ async open(workspaceId, workspace, root, input) {
73
+ const selected = await selectedFile(workspace, root, input);
74
+ const [path, canonicalRoot, canonicalWorkspace] = await Promise.all([realpath(selected), realpath(root), realpath(workspace)]);
75
+ if (contains(canonicalWorkspace, path) && explorerInternalPath(toRelative(canonicalWorkspace, path))) {
76
+ throw new FilesError(403, "不能直接访问应用的回收目录。", "protected_path");
77
+ }
78
+ if (contains(canonicalRoot, path)) {
79
+ const scoped = toRelative(canonicalRoot, path);
80
+ await explorerPath(workspace, root, scoped);
81
+ return { path: scoped, name: basename(path), ...await readOpenedFile(path) };
82
+ }
83
+ const contents = await readOpenedFile(path);
84
+ const ticket = randomUUID();
85
+ if (tickets.size === MAX_OPEN_TICKETS)
86
+ tickets.delete(tickets.keys().next().value);
87
+ tickets.set(ticket, { workspaceId, root: canonicalRoot, path });
88
+ const name = basename(selected);
89
+ const targetName = basename(path);
90
+ return { path: input, name, ...(targetName !== name ? { targetName } : {}), ticket, ...contents };
91
+ },
92
+ async target(workspaceId, root, ticket) {
93
+ const entry = tickets.get(ticket);
94
+ if (!entry || entry.workspaceId !== workspaceId || entry.root !== await realpath(root)) {
95
+ throw new FilesError(404, "请重新打开这个外部文件。", "missing_open_file");
96
+ }
97
+ if (entry.path !== await realpath(entry.path)) {
98
+ throw new FilesError(404, "文件目标已改变,请重新打开。", "missing_open_file");
99
+ }
100
+ tickets.delete(ticket);
101
+ tickets.set(ticket, entry);
102
+ return entry.path;
103
+ },
104
+ };
105
+ }
@@ -18,6 +18,7 @@ export type NameEntry = {
18
18
  /** The directory holding it, `""` for the root itself. */
19
19
  directory: string;
20
20
  kind: "file" | "directory";
21
+ openLink?: true;
21
22
  };
22
23
  /** What the index knows about its own state, for the "正在建立索引… 42%" line. */
23
24
  export type IndexProgress = {
@@ -111,7 +112,7 @@ export declare class FileNameIndex {
111
112
  /** Rebuild from scratch. The ↻ button. */
112
113
  reset(root: string): void;
113
114
  /** Record a path that appeared or changed. Used for agent writes and user saves. */
114
- upsert(relativePath: string, kind?: "file" | "directory"): void;
115
+ upsert(relativePath: string, kind?: "file" | "directory", openLink?: true): void;
115
116
  /** Forget a path that is gone. */
116
117
  remove(relativePath: string): void;
117
118
  removeTree(path: string): void;
@@ -123,7 +124,7 @@ export declare class FileNameIndex {
123
124
  * different feature ("find everything under src/server"), and mixing the two makes a search for
124
125
  * `app` return every file in `application/` as well - a result set nobody can read.
125
126
  */
126
- search(needle: string): NameSearchResult;
127
+ search(needle: string, linksOnly?: boolean): NameSearchResult;
127
128
  /**
128
129
  * Wait until the first scan has finished, or until the deadline passes.
129
130
  *
@@ -143,9 +144,8 @@ export declare class FileNameIndex {
143
144
  /**
144
145
  * The background scan.
145
146
  *
146
- * `readdir` only, with `withFileTypes` so the kind of every entry arrives without a `stat`.
147
- * Symlinks are recorded but never followed - following one is how a scan becomes an infinite
148
- * walk, and a link inside the workspace is the one path the tree refuses to descend as well.
147
+ * `readdir` provides ordinary entry types. Symlink targets are checked only for file type.
148
+ * Link names can be found, and linked directories never enter this traversal's queue.
149
149
  */
150
150
  private scan;
151
151
  /** Stop a running scan. Used when a workspace goes away. */
@@ -24,14 +24,15 @@
24
24
  * WHY THE SCAN HAS NO `stat`. The measurements are unambiguous: `readdir` over the whole tree is
25
25
  * 960ms and `stat` over every directory is 166ms, but a per-FILE `stat` is what costs seconds
26
26
  * (the documented 2-3s figure). This index does not need file sizes or etags - it needs NAMES -
27
- * so it never stats a file. `readdir` with `withFileTypes` gives the kind for free.
27
+ * so it stats only symbolic links to tell whether their names can open a single file.
28
28
  *
29
29
  * THE LIMITS ARE HONEST AND LOOSE. 20000 directories and 200000 files are three to four orders of
30
30
  * magnitude above a real repository, and hitting one is reported (`complete: false`) rather than
31
31
  * silently applied - a search that quietly stopped at a limit is the exact defect this file
32
32
  * replaces.
33
33
  */
34
- import { readdir } from "node:fs/promises";
34
+ import { readdir, stat } from "node:fs/promises";
35
+ import { resolve } from "node:path";
35
36
  import { createRootGuard, toRelative } from "./files.js";
36
37
  import { belowPath, blockedBy, inScope, matchesDirectoryReads } from "./file-index.js";
37
38
  import { explorerInternalPath } from "./workspace-file-operations.js";
@@ -201,14 +202,14 @@ export class FileNameIndex {
201
202
  this.start(root);
202
203
  }
203
204
  /** Record a path that appeared or changed. Used for agent writes and user saves. */
204
- upsert(relativePath, kind = "file") {
205
+ upsert(relativePath, kind = "file", openLink) {
205
206
  const path = relativePath.replace(/\\/g, "/").replace(/^\/+/, "");
206
207
  if (!path)
207
208
  return;
208
209
  const cut = path.lastIndexOf("/");
209
210
  const name = cut < 0 ? path : path.slice(cut + 1);
210
211
  const directory = cut < 0 ? "" : path.slice(0, cut);
211
- this.entries.set(path, { path, name, directory, kind });
212
+ this.entries.set(path, { path, name, directory, kind, ...(openLink ? { openLink } : {}) });
212
213
  }
213
214
  /** Forget a path that is gone. */
214
215
  remove(relativePath) {
@@ -224,19 +225,19 @@ export class FileNameIndex {
224
225
  this.entries.delete(key);
225
226
  }
226
227
  reconcileDirectory(directory, entries) {
227
- const present = new Map(entries.map(entry => [entry.path, entry]));
228
+ const indexed = entries.filter(entry => entry.openLink || !entry.symlink && entry.kind !== "symlink");
229
+ const present = new Map(indexed.map(entry => [entry.path, entry]));
228
230
  if (this.building)
229
- this.directoriesReadDuringScan.set(directory, new Set(entries.filter(entry => !entry.symlink && entry.kind !== "symlink").map(entry => entry.path)));
231
+ this.directoriesReadDuringScan.set(directory, new Set(present.keys()));
230
232
  for (const [path, existing] of this.entries) {
231
233
  if (existing.directory !== directory)
232
234
  continue;
233
235
  const entry = present.get(path);
234
- if (!entry || entry.symlink || entry.kind !== existing.kind)
236
+ if (!entry || (entry.openLink ? "file" : entry.kind) !== existing.kind)
235
237
  this.removeTree(path);
236
238
  }
237
- for (const entry of entries)
238
- if (!entry.symlink && entry.kind !== "symlink")
239
- this.upsert(entry.path, entry.kind);
239
+ for (const entry of indexed)
240
+ this.upsert(entry.path, entry.kind === "directory" ? "directory" : "file", entry.openLink);
240
241
  }
241
242
  /**
242
243
  * The query. A substring filter over an in-memory map - no filesystem access at all.
@@ -245,14 +246,14 @@ export class FileNameIndex {
245
246
  * different feature ("find everything under src/server"), and mixing the two makes a search for
246
247
  * `app` return every file in `application/` as well - a result set nobody can read.
247
248
  */
248
- search(needle) {
249
+ search(needle, linksOnly = false) {
249
250
  const query = needle.trim().toLowerCase();
250
251
  if (!query) {
251
252
  return { hits: [], total: 0, indexed: this.indexed, progress: this.progress, incomplete: this.incomplete };
252
253
  }
253
254
  const hits = [];
254
255
  for (const entry of this.entries.values()) {
255
- if (entry.kind !== "file")
256
+ if (entry.kind !== "file" || linksOnly && !entry.openLink)
256
257
  continue;
257
258
  if (entry.name.toLowerCase().includes(query))
258
259
  hits.push(entry);
@@ -297,9 +298,8 @@ export class FileNameIndex {
297
298
  /**
298
299
  * The background scan.
299
300
  *
300
- * `readdir` only, with `withFileTypes` so the kind of every entry arrives without a `stat`.
301
- * Symlinks are recorded but never followed - following one is how a scan becomes an infinite
302
- * walk, and a link inside the workspace is the one path the tree refuses to descend as well.
301
+ * `readdir` provides ordinary entry types. Symlink targets are checked only for file type.
302
+ * Link names can be found, and linked directories never enter this traversal's queue.
303
303
  */
304
304
  async scan(generation) {
305
305
  const started = Date.now();
@@ -347,8 +347,6 @@ export class FileNameIndex {
347
347
  if (generation !== this.generation || this.stopped)
348
348
  return;
349
349
  for (const entry of entries) {
350
- if (entry.isSymbolicLink())
351
- continue;
352
350
  const relative = directory ? `${directory}/${entry.name}` : entry.name;
353
351
  if (explorerInternalPath(this.cwd ? `${this.cwd}/${relative}` : relative) || blockedBy(relative, this.removedDuringScan)
354
352
  || !matchesDirectoryReads(relative, this.directoriesReadDuringScan))
@@ -358,13 +356,18 @@ export class FileNameIndex {
358
356
  queue.push(relative);
359
357
  continue;
360
358
  }
361
- if (!entry.isFile())
359
+ const openLink = entry.isSymbolicLink() && await stat(resolve(this.root, relative)).then(info => info.isFile(), () => false);
360
+ if (generation !== this.generation || this.stopped)
361
+ return;
362
+ if (openLink && (blockedBy(relative, this.removedDuringScan) || !matchesDirectoryReads(relative, this.directoriesReadDuringScan)))
363
+ continue;
364
+ if (!entry.isFile() && !openLink)
362
365
  continue;
363
366
  if (this.entries.size >= MAX_FILES) {
364
367
  this.incomplete = true;
365
368
  break;
366
369
  }
367
- this.entries.set(relative, { path: relative, name: entry.name, directory, kind: "file" });
370
+ this.entries.set(relative, { path: relative, name: entry.name, directory, kind: "file", ...(openLink ? { openLink: true } : {}) });
368
371
  }
369
372
  // Yield between directories so a large tree does not monopolise the event loop and starve
370
373
  // the WebSocket heartbeat. `setTimeout(0)` is the cheapest yield that still lets timers run.
@@ -1,3 +1,4 @@
1
+ import type { BigIntStats } from "node:fs";
1
2
  /**
2
3
  * Above this a read is refused rather than served. 5MB is roughly a large source file or a long document,
3
4
  * and it is deliberately far below the point where an editor tab stops being useful: this panel is for
@@ -82,6 +83,7 @@ export type FileMeta = {
82
83
  modifiedAt: string;
83
84
  };
84
85
  export declare function fileMeta(path: string): Promise<FileMeta>;
86
+ export declare function fileMetaFromStat(info: BigIntStats): FileMeta;
85
87
  export declare function looksBinary(sample: Uint8Array): boolean;
86
88
  /**
87
89
  * Whether the NAME alone says this is binary.
@@ -147,6 +149,8 @@ export type DirEntry = {
147
149
  symlink?: boolean;
148
150
  /** Set when a link points outside: the containment check's own verdict, surfaced rather than swallowed. */
149
151
  outside?: boolean;
152
+ /** A file link can be opened individually from the workbench. */
153
+ openLink?: true;
150
154
  };
151
155
  export type DirListing = {
152
156
  /** The directory that was listed, relative to the root. `""` is the root itself. */
@@ -222,6 +226,7 @@ export type FileContents = {
222
226
  * which is mojibake, and mojibake that then gets SAVED is how a text editor destroys a binary file.
223
227
  */
224
228
  export declare function readWorkspaceFile(root: string, requested: string): Promise<FileContents>;
229
+ export declare function decodeWorkspaceText(raw: Uint8Array, requested: string): Pick<FileContents, "content" | "bom" | "eol">;
225
230
  export type WriteOutcome = {
226
231
  path: string;
227
232
  meta: FileMeta;
@@ -309,11 +309,13 @@ export function resolveInsideRoot(root, requested) {
309
309
  * user has been told it is safe to save.
310
310
  */
311
311
  export async function fileEtag(path) {
312
- const info = await stat(path, { bigint: true });
313
- return createHash("sha1").update(`${info.size}:${info.mtimeNs}:${info.ino}`).digest("hex").slice(0, 20);
312
+ return fileMetaFromStat(await stat(path, { bigint: true })).etag;
314
313
  }
315
314
  export async function fileMeta(path) {
316
- const [info, etag] = await Promise.all([stat(path), fileEtag(path)]);
315
+ return fileMetaFromStat(await stat(path, { bigint: true }));
316
+ }
317
+ export function fileMetaFromStat(info) {
318
+ const etag = createHash("sha1").update(`${info.size}:${info.mtimeNs}:${info.ino}`).digest("hex").slice(0, 20);
317
319
  return { etag, size: Number(info.size), modifiedAt: info.mtime.toISOString() };
318
320
  }
319
321
  /**
@@ -468,7 +470,8 @@ export async function listDirectory(root, requested) {
468
470
  outside = true;
469
471
  }
470
472
  }
471
- const isDir = dirent.isDirectory() || (isLink && !outside && await stat(absolute).then((item) => item.isDirectory()).catch(() => false));
473
+ const linked = isLink ? await stat(absolute).catch(() => undefined) : undefined;
474
+ const isDir = dirent.isDirectory() || (!outside && linked?.isDirectory() === true);
472
475
  entries.push({
473
476
  path: toRelative(root, absolute),
474
477
  name: dirent.name,
@@ -477,6 +480,7 @@ export async function listDirectory(root, requested) {
477
480
  ...(isDir ? {} : { document: !outside && isDocumentName(dirent.name) }),
478
481
  ...(isLink ? { symlink: true } : {}),
479
482
  ...(outside ? { outside: true } : {}),
483
+ ...(linked?.isFile() ? { openLink: true } : {}),
480
484
  });
481
485
  }
482
486
  entries.sort((a, b) => {
@@ -604,7 +608,9 @@ export async function readWorkspaceFile(root, requested) {
604
608
  if (meta.size > MAX_FILE_BYTES) {
605
609
  throw new FilesError(413, `文件过大(${(meta.size / 1024 / 1024).toFixed(1)}MB),上限 ${MAX_FILE_BYTES / 1024 / 1024}MB:${requested}`, "too_large");
606
610
  }
607
- const raw = await readFile(target);
611
+ return { path: toRelative(root, target), meta, ...decodeWorkspaceText(await readFile(target), requested) };
612
+ }
613
+ export function decodeWorkspaceText(raw, requested) {
608
614
  if (looksBinary(raw))
609
615
  throw new FilesError(415, `不支持的文件类型(二进制内容):${requested}`, "binary");
610
616
  // `fatal: true` so a truncated multi-byte sequence - a file written by something that cut a UTF-8
@@ -617,7 +623,7 @@ export async function readWorkspaceFile(root, requested) {
617
623
  catch {
618
624
  throw new FilesError(415, `不是有效的 UTF-8 文本,不支持编辑:${requested}`, "binary");
619
625
  }
620
- return { path: toRelative(root, target), content, meta, bom, eol: content.includes("\r\n") ? "\r\n" : "\n" };
626
+ return { content, bom, eol: content.includes("\r\n") ? "\r\n" : "\n" };
621
627
  }
622
628
  const writeLocks = new Map();
623
629
  /**
@@ -1,3 +1,5 @@
1
+ import type { GitCommitDetail } from "../shared/git-commit.js";
2
+ import type { GitGraphPage } from "../shared/git-graph.js";
1
3
  export type GitWorkspace = {
2
4
  branch: string | null;
3
5
  detached: boolean;
@@ -24,6 +26,14 @@ export declare function gitLog(root: string, limit: number, cwd?: string, query?
24
26
  }[];
25
27
  truncated: boolean;
26
28
  }>;
29
+ export declare function gitGraph(root: string, limit: number, offset: number, snapshot: string, after: string): Promise<GitGraphPage>;
30
+ export declare function gitCommit(root: string, cwd: string, hash: string): Promise<GitCommitDetail>;
31
+ export declare function gitCommitDiff(root: string, cwd: string, hash: string, path: string): Promise<{
32
+ path: string;
33
+ staged: boolean;
34
+ kind: "binary" | "text";
35
+ diff: string | null;
36
+ }>;
27
37
  export type GitWorktree = {
28
38
  id: string;
29
39
  path: string;
@@ -1,7 +1,7 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { promisify } from "node:util";
4
- import { basename, join, relative, resolve, sep } from "node:path";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { existsSync } from "node:fs";
6
6
  import { mkdir, readFile, realpath, stat } from "node:fs/promises";
7
7
  const exec = promisify(execFile);
@@ -82,6 +82,140 @@ function parseGitCommits(raw) {
82
82
  }
83
83
  return commits;
84
84
  }
85
+ const COMMIT_HASH = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
86
+ export async function gitGraph(root, limit, offset, snapshot, after) {
87
+ const size = pageNumber(limit, 50, 1, 100);
88
+ const start = pageNumber(offset, 0, 0, 2_147_483_647);
89
+ const repo = await worktreeRoot(root);
90
+ const [refs, checkout] = await Promise.all([
91
+ git(repo, ["for-each-ref", "--format=%(refname)%00%(objectname)%00%(*objectname)%00%(symref)"], { maxBuffer: 32 * 1024 * 1024, timeout: 12_000 }),
92
+ gitWorktrees(repo),
93
+ ]);
94
+ const worktrees = checkout.worktrees.filter(entry => !entry.missing && COMMIT_HASH.test(entry.head) && !/^0+$/.test(entry.head));
95
+ const heads = worktrees.map(({ id, branch, head, current, name }) => ({ id, branch, head, current, name }));
96
+ const version = createHash("sha256").update(refs.stdout).update(JSON.stringify(heads)).digest("hex");
97
+ const changed = () => gitFailure("提交图已变化,请刷新后继续查看。", "graph_changed");
98
+ if (start && snapshot !== version)
99
+ throw changed();
100
+ const labels = new Map();
101
+ const mark = (hash, label) => {
102
+ const list = labels.get(hash) ?? [];
103
+ list.push(label);
104
+ labels.set(hash, list);
105
+ };
106
+ for (const entry of worktrees) {
107
+ if (entry.current)
108
+ mark(entry.head, { kind: "head", name: entry.branch ? `HEAD → ${entry.branch}` : "HEAD" });
109
+ else {
110
+ const repeatedName = worktrees.some(other => other.id !== entry.id && other.name === entry.name);
111
+ const name = entry.branch ?? (repeatedName ? `${basename(dirname(entry.path))}/${entry.name}` : entry.name);
112
+ mark(entry.head, { kind: "worktree", name, checkoutId: entry.id });
113
+ }
114
+ }
115
+ for (const line of refs.stdout.split(/\r?\n/)) {
116
+ const [ref, hash, peeled, symbolic] = line.split("\0");
117
+ if (!ref || symbolic)
118
+ continue;
119
+ if (ref.startsWith("refs/heads/"))
120
+ mark(hash, { kind: "branch", name: ref.slice("refs/heads/".length) });
121
+ else if (ref.startsWith("refs/remotes/"))
122
+ mark(hash, { kind: "remote", name: ref.slice("refs/remotes/".length) });
123
+ else if (ref.startsWith("refs/tags/"))
124
+ mark(peeled || hash, { kind: "tag", name: ref.slice("refs/tags/".length) });
125
+ else if (ref === "refs/stash")
126
+ mark(hash, { kind: "stash", name: "Stash" });
127
+ }
128
+ const overlap = start ? 1 : 0;
129
+ const detached = worktrees.filter(entry => !entry.branch).map(entry => entry.head);
130
+ const format = "--format=%H%x00%h%x00%P%x00%s%x00%an%x00%aI";
131
+ const { stdout } = await git(repo, ["-c", "log.showSignature=false", "log", "--all", "--topo-order", "--no-notes", "--no-decorate",
132
+ "--no-patch", "--encoding=UTF-8", "-z", `--skip=${start - overlap}`, `-${size + 1 + overlap}`, format, ...detached, "--"], { timeout: 12_000 });
133
+ const parts = stdout.split("\0");
134
+ const commits = [];
135
+ for (let index = 0; index + 5 < parts.length; index += 6) {
136
+ const [hash, short, parents, subject, author, date] = parts.slice(index, index + 6);
137
+ commits.push({ hash, short, parents: parents ? parents.split(" ") : [], subject, author, date, refs: labels.get(hash) ?? [] });
138
+ }
139
+ if (overlap && commits.shift()?.hash !== after)
140
+ throw changed();
141
+ return { commits: commits.slice(0, size), snapshot: version, hasMore: commits.length > size };
142
+ }
143
+ const HISTORY_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--submodule=short", "--find-renames"];
144
+ async function readCommitDiff(repo, args) {
145
+ try {
146
+ return (await git(repo, args, { timeout: 12_000 })).stdout;
147
+ }
148
+ catch (error) {
149
+ if (error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
150
+ throw gitFailure("该提交的文件列表或差异超过了查看上限。", "commit_diff_too_large");
151
+ }
152
+ throw error;
153
+ }
154
+ }
155
+ async function commitSnapshot(root, cwd, revision) {
156
+ if (!COMMIT_HASH.test(revision))
157
+ throw gitFailure("请选择有效的提交哈希。", "bad_revision");
158
+ const hash = revision.toLowerCase();
159
+ const [repo, session] = await Promise.all([worktreeRoot(root).then(path => realpath(path)), realpath(resolve(root, cwd))]);
160
+ const scope = relative(repo, session).split(sep).join("/");
161
+ if (scope === ".." || scope.startsWith("../") || isAbsolute(scope)) {
162
+ throw gitFailure("会话目录位于 Git 仓库之外。", "outside_scope");
163
+ }
164
+ const type = await git(repo, ["cat-file", "-t", hash], { timeout: 12_000 }).then(result => result.stdout.trim()).catch(() => "");
165
+ if (type !== "commit")
166
+ throw gitFailure("找不到这个 Git 提交。", "not_found");
167
+ const raw = await readCommitDiff(repo, ["cat-file", "commit", hash]);
168
+ const messageOffset = raw.indexOf("\n\n");
169
+ const message = messageOffset < 0 ? "" : raw.slice(messageOffset + 2).trimEnd();
170
+ const parents = (messageOffset < 0 ? raw : raw.slice(0, messageOffset)).split("\n")
171
+ .filter(line => line.startsWith("parent ")).map(line => line.slice(7));
172
+ if (parents.some(parent => !COMMIT_HASH.test(parent)))
173
+ throw gitFailure("这个提交的父版本记录无效。", "bad_revision");
174
+ const firstParent = parents[0];
175
+ const diff = (options, paths, exact = false) => {
176
+ const flags = [...HISTORY_DIFF_OPTIONS, scope ? `--relative=${scope}` : "--no-relative", ...options];
177
+ // An escaped glob matches the file itself, even when that path was a directory in one tree.
178
+ const specs = exact ? paths.map(path => `:(top,glob)${path.replace(/[^/]/gu, "\\$&")}`) : paths;
179
+ const args = firstParent
180
+ ? ["diff", ...flags, firstParent, hash, "--", ...specs]
181
+ : ["diff-tree", "--root", "--no-commit-id", "-r", ...flags, hash, "--", ...specs];
182
+ return readCommitDiff(repo, exact ? ["--no-literal-pathspecs", ...args] : args);
183
+ };
184
+ // Read the parent from the stored commit. A shallow boundary is not a root commit.
185
+ if (firstParent && !await git(repo, ["cat-file", "-e", firstParent], { timeout: 12_000 }).then(() => true, () => false)) {
186
+ throw gitFailure("这个提交的父版本不在本地仓库中。", "not_found");
187
+ }
188
+ const records = (await diff(["--name-status", "-z"], scope ? [scope] : [])).split("\0");
189
+ const files = [];
190
+ for (let index = 0; index + 1 < records.length;) {
191
+ const status = records[index++];
192
+ const firstPath = records[index++];
193
+ if (status.startsWith("R") || status.startsWith("C")) {
194
+ files.push({ status, previousPath: firstPath, path: records[index++] });
195
+ }
196
+ else {
197
+ files.push({ status, path: firstPath });
198
+ }
199
+ }
200
+ return { detail: { hash, parents, message, files }, scope, diff };
201
+ }
202
+ export async function gitCommit(root, cwd, hash) {
203
+ return (await commitSnapshot(root, cwd, hash)).detail;
204
+ }
205
+ export async function gitCommitDiff(root, cwd, hash, path) {
206
+ if (!path || path.includes("\0"))
207
+ throw gitFailure("请选择提交中的变更文件。", "path");
208
+ const { detail, scope, diff } = await commitSnapshot(root, cwd, hash);
209
+ // Match exact Git paths from the scoped tree diff. No live filesystem lookup is needed.
210
+ const file = detail.files.find(entry => entry.path === path);
211
+ if (!file)
212
+ throw gitFailure("这个提交在当前目录内没有该文件的差异。", "not_found");
213
+ const paths = (file.previousPath === undefined ? [file.path] : [file.previousPath, file.path])
214
+ .map(name => scope ? `${scope}/${name}` : name);
215
+ const patch = await diff(["--patch"], paths, true);
216
+ const binary = /^Binary files .* differ$/m.test(patch);
217
+ return { path, staged: false, kind: binary ? "binary" : "text", diff: binary ? null : patch };
218
+ }
85
219
  const normalizedPath = (path) => process.platform === "win32" ? resolve(path).toLowerCase() : resolve(path);
86
220
  async function worktreeRoot(root) {
87
221
  return (await git(root, ["rev-parse", "--show-toplevel"])).stdout.replace(/\r?\n$/, "");