@coda-console/resource-manager 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/lib/content.mjs +15 -2
- package/lib/draft.mjs +57 -0
- package/lib/info.mjs +137 -0
- package/lib/snapshots.mjs +52 -0
- package/lib/tree.mjs +237 -48
- package/main.mjs +69 -14
- package/package.json +1 -1
- package/view/app.mjs +104 -82
- package/view/chat.mjs +45 -0
- package/view/connection.mjs +50 -24
- package/view/dom.mjs +9 -0
- package/view/file-app.mjs +19 -3
- package/view/file.html +2 -0
- package/view/format.mjs +67 -0
- package/view/hint.mjs +20 -0
- package/view/icons.mjs +139 -22
- package/view/index.html +1 -0
- package/view/info.mjs +117 -0
- package/view/menu.mjs +76 -0
- package/view/model.mjs +48 -19
- package/view/preview.mjs +16 -18
- package/view/protocol.mjs +24 -5
- package/view/selection.mjs +33 -0
- package/view/style.css +60 -13
- package/view/tree.mjs +39 -14
package/README.md
CHANGED
|
@@ -10,9 +10,15 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
|
|
|
10
10
|
- 按需展开目录,超大目录分页显示。
|
|
11
11
|
- 文本预览(带行号,可跨行选中复制,最多读 1 MiB)和图片预览(PNG、JPEG、GIF、WebP、SVG,最多 8 MiB)。
|
|
12
12
|
- Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
|
|
13
|
+
- 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
|
|
14
|
+
- 可以按名称、种类、日期、大小排序,在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「排序」一组里选,当前项有对勾。每种排序的方向固定:名称、种类升序,日期、大小降序(最新、最大在前),没有升降序切换。超过 2 万条的目录,日期和大小排序不可用,退回按名称并提示。排序全局一份,换了排序滚动位置回到顶部,选当前项什么都不做。
|
|
13
15
|
- 切换会话时换成新会话的内容,切回来恢复展开状态和滚动位置。
|
|
14
|
-
- Mac
|
|
15
|
-
- iPhone
|
|
16
|
+
- 右键(Mac)或长按(iPhone)一行:添加到聊天、复制相对路径、复制绝对路径、属性。「添加到聊天」把相对路径接在输入框已有文字后面;指向工作目录外或已失效的链接、不能打开的条目没有这一项。成功时底部提示「已添加到输入框」,约 2 秒消失;写不进去时改为复制,提示「没能写入输入框,已复制」。
|
|
17
|
+
- **选中文字右键(只有 Mac)**:在文件预览(侧栏和独立窗口)里选中文字后右键,有「添加到聊天(内容)」「添加到聊天(位置)」「复制」。位置是 `src/app.ts:12-18`,只选一行时是 `src/app.ts:12`,只精确到行。选中的内容太长放不进一条消息时直接复制,提示「选中内容太长,已复制」。iPhone 用系统自带的选区菜单,不加这一项。
|
|
18
|
+
- 属性页:行菜单里选「属性」,在当前页里打开一层,用系统的返回退出。显示种类、大小、链接到、位置、完整路径、修改和创建时间、权限;文件夹的大小在打开后统计,不跟随链接,最多 20 万项或 5 秒,超出时显示下限(如「超过 3.2 GiB(已统计 20 万项)」),一轮结束后已有的结果标「上次统计」,可以重新统计。
|
|
19
|
+
- **写入输入框用的是 Coda 没有公开的接口**,以后可能失效或改变;失效时「添加到聊天」会改为复制路径或文字。**已知风险**:输入框里的附件还在上传时添加,上传完成后,这段时间里打的字和那个附件可能消失;刚打完字的一瞬间添加,也可能丢掉这几个字。
|
|
20
|
+
- Mac:把文件拖到输入框也行;预览可以开到独立窗口;工具栏只有一个「更多」按钮,按下弹出菜单(刷新、显示隐藏文件、排序),侧栏预览头部最左边的「返回」回到目录树。
|
|
21
|
+
- iPhone:长按出同样的菜单;目录树页右上角「⋯」里有刷新、显示隐藏文件和排序;文件页底部工具条有刷新和「复制路径」。
|
|
16
22
|
- 默认隐藏 `.git`、`.DS_Store`,Mac 在工具栏的「更多」菜单里、iPhone 在目录树页右上角的「⋯」里可切换显示全部。
|
|
17
23
|
|
|
18
24
|
只能读这个会话的工作目录。指向工作目录之外的符号链接只显示,不能打开。
|
|
@@ -63,6 +69,8 @@ npx --yes github:coda-console/coda-plugins#<提交> . --manifest
|
|
|
63
69
|
|
|
64
70
|
工作流用 npm 可信发布,不需要令牌。只有手动运行才会发布,合并到 `main` 不会自动发布。
|
|
65
71
|
|
|
72
|
+
发布后 npm 可能要约 10 分钟才公开,工作流最多等 15 分钟确认。超时会显示失败,但摘要写着「发布已接受,公开确认超时,不要重发」:包已经发出,不要重跑工作流,先到 npm 上查这个版本。
|
|
73
|
+
|
|
66
74
|
首次发布要先有包,可信发布才能配置:在本机 `npm login` 后手动运行 `npm publish --access public`,再到 npm 上 `@coda-console/resource-manager` 的设置里配置可信发布,仓库填 `sealiu1997/coda_plugins_resource_manager`,流程文件填 `publish.yml`,并勾选允许 `npm publish`(Allow npm publish)。新配置默认只允许 `npm stage publish`,不勾选的话工作流的发布步骤会被拒绝。之后就按上面的步骤走。
|
|
67
75
|
|
|
68
76
|
## 许可
|
package/lib/content.mjs
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
// 分块读文件并判断类型。页面一块一块要,模块不记状态。
|
|
2
|
+
import { constants } from 'node:fs';
|
|
2
3
|
import { open } from 'node:fs/promises';
|
|
3
4
|
import {
|
|
4
5
|
CHUNK_BYTES, ContentKind, ErrorCode, IMAGE_LIMIT, SNIFF_BYTES, TEXT_LIMIT, fail, imageType,
|
|
5
6
|
} from '../view/protocol.mjs';
|
|
6
7
|
import { fromFsError, parseRelative, resolveInRoot } from './paths.mjs';
|
|
7
8
|
|
|
9
|
+
// 只作用于最后一级:校验之后目标被换成链接,打开会被拒绝而不是跟过去。平台没有这个常量就退回 0。
|
|
10
|
+
const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
|
|
11
|
+
|
|
8
12
|
async function readAt(handle, position, length) {
|
|
9
13
|
const buffer = Buffer.allocUnsafe(length);
|
|
10
14
|
const { bytesRead } = length ? await handle.read(buffer, 0, length, position) : { bytesRead: 0 };
|
|
@@ -13,11 +17,20 @@ async function readAt(handle, position, length) {
|
|
|
13
17
|
|
|
14
18
|
// 返回 { data, offset, size, mtimeMs, kind, eof }。文本最多给前 TEXT_LIMIT 字节,
|
|
15
19
|
// 超过限制的图片和二进制文件不给内容(页面看 size 和 kind 说明)。
|
|
16
|
-
|
|
20
|
+
// deps.open 只给测试换,用来在校验和打开之间插入时机。
|
|
21
|
+
export async function readChunk(root, path, offset, deps = { open }) {
|
|
17
22
|
if (!Number.isSafeInteger(offset) || offset < 0) throw fail(ErrorCode.INVALID_OFFSET, '偏移无效');
|
|
18
23
|
const real = await resolveInRoot(root, path);
|
|
19
24
|
let handle;
|
|
20
|
-
try {
|
|
25
|
+
try {
|
|
26
|
+
handle = await deps.open(real, constants.O_RDONLY | NOFOLLOW);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
// 被 O_NOFOLLOW 拒绝(macOS、Linux 是 ELOOP,BSD 是 EMLINK)说明校验后被换成了链接,按越界处理。
|
|
29
|
+
if (NOFOLLOW && (error?.code === 'ELOOP' || error?.code === 'EMLINK')) {
|
|
30
|
+
throw fail(ErrorCode.OUTSIDE_ROOT, '链接指向工作目录之外');
|
|
31
|
+
}
|
|
32
|
+
throw fromFsError(error);
|
|
33
|
+
}
|
|
21
34
|
try {
|
|
22
35
|
const info = await handle.stat();
|
|
23
36
|
if (!info.isFile()) throw fail(ErrorCode.NOT_FILE, '不是文件');
|
package/lib/draft.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// 把文字追加到会话的输入框草稿(设计见 docs/design/phase-3.md 第 13.5 节)。
|
|
2
|
+
// 用的是 Coda 未公开的草稿接口:依赖它的代码只在这一个文件里,上游开放正式接口后只改这里。
|
|
3
|
+
// 流程:读草稿 → 拼文字 → 保存。保存带上现有附件的 ID,否则会删掉用户已添加的附件。
|
|
4
|
+
import { DRAFT_LIMIT, ErrorCode, fail } from '../view/protocol.mjs';
|
|
5
|
+
|
|
6
|
+
const RETRIES = 2; // 版本不符后用服务端的内容重拼,最多再试这么多次
|
|
7
|
+
|
|
8
|
+
// block 为 false(路径、位置):接在现有文字后面,前后各留一个空格(已有空白或为空时前面不加)。
|
|
9
|
+
// block 为 true(内容):另起一行,结尾换行;文字本身已以换行结尾的不再多加,免得多出空行。只能追加到末尾。
|
|
10
|
+
export function compose(current, text, block) {
|
|
11
|
+
if (block) return `${current}${current === '' || current.endsWith('\n') ? '' : '\n'}${text}${text.endsWith('\n') ? '' : '\n'}`;
|
|
12
|
+
return `${current}${current === '' || /\s$/.test(current) ? '' : ' '}${text} `;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// 接口路径只在这里写:测试和 harness 的假接口也从这里取。
|
|
16
|
+
export const draftPath = session => `threads/${encodeURIComponent(session)}/draft`;
|
|
17
|
+
// 反过来:路径是草稿接口的返回会话,不是返回 null。
|
|
18
|
+
export function draftSession(path) {
|
|
19
|
+
const match = /^threads\/([^/]+)\/draft$/.exec(path);
|
|
20
|
+
return match ? decodeURIComponent(match[1]) : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const failed = () => fail(ErrorCode.DRAFT_FAILED, '读写草稿失败');
|
|
24
|
+
|
|
25
|
+
// 接口回答里的草稿 → { text, revision, ids };形状不对算失败。
|
|
26
|
+
function parseDraft(draft) {
|
|
27
|
+
if (typeof draft?.text !== 'string' || !Array.isArray(draft.attachments)) throw failed();
|
|
28
|
+
const ids = draft.attachments.map(attachment => attachment?.id);
|
|
29
|
+
if (!ids.every(id => typeof id === 'string')) throw failed();
|
|
30
|
+
return { text: draft.text, revision: draft.revision, ids };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 追加成功返回 true;valid() 变假(会话换了、视图关了)静默结束,返回 false:不写、不报。
|
|
34
|
+
// 每次保存之前、每个 await 回来之后都核对,重试也始终写传进来的这个会话。
|
|
35
|
+
// 失败抛 draft_failed(保存的回答不带合法的 draft 也算失败),拼完超过上限抛 draft_too_long,不截断。
|
|
36
|
+
export async function addText(coda, session, { text, block }, { valid = () => true } = {}) {
|
|
37
|
+
if (typeof text !== 'string' || text.includes('\0') || typeof block !== 'boolean') throw failed();
|
|
38
|
+
const path = draftPath(session);
|
|
39
|
+
const call = async body => {
|
|
40
|
+
try { return await (body ? coda.api(path, body) : coda.api(path)); } catch { throw failed(); }
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const first = await call();
|
|
44
|
+
if (!valid()) return false;
|
|
45
|
+
let draft = parseDraft(first);
|
|
46
|
+
for (let attempt = 0; ; attempt++) {
|
|
47
|
+
const next = compose(draft.text, text, block);
|
|
48
|
+
if (next.length > DRAFT_LIMIT) throw fail(ErrorCode.DRAFT_TOO_LONG, '草稿太长,放不下');
|
|
49
|
+
const saved = await call({ text: next, attachments: draft.ids, revision: draft.revision });
|
|
50
|
+
if (!valid()) return false;
|
|
51
|
+
const reply = parseDraft(saved?.draft); // 成功和版本不符的回答都带 draft;没有或形状不对,不能当成已写入
|
|
52
|
+
if (!saved.conflict) return true;
|
|
53
|
+
if (attempt >= RETRIES) throw failed();
|
|
54
|
+
draft = reply;
|
|
55
|
+
if (!valid()) return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
package/lib/info.mjs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// 属性和文件夹大小(设计见 docs/design/phase-3.md 第 13.3、13.4 节)。
|
|
2
|
+
// 只读:都经视图共用的读取状态(lib/tree.mjs 的 createListing)的 fs 和并发上限,不另起一套。
|
|
3
|
+
import { basename, join, relative, sep } from 'node:path';
|
|
4
|
+
import { EntryKind } from '../view/protocol.mjs';
|
|
5
|
+
import { fromFsError, parseRelative, resolveInRoot } from './paths.mjs';
|
|
6
|
+
import { classifyLink } from './tree.mjs';
|
|
7
|
+
|
|
8
|
+
export const DIR_SIZE_ITEMS = 200_000;
|
|
9
|
+
export const DIR_SIZE_MS = 5000;
|
|
10
|
+
// 一批同时排进并发上限的 lstat 数;等它们回来才排下一批。
|
|
11
|
+
const BATCH = 4;
|
|
12
|
+
|
|
13
|
+
const integer = value => (Number.isFinite(value) ? Math.floor(value) : undefined);
|
|
14
|
+
|
|
15
|
+
// 一个条目自己的元数据:size 只有文件有,读不到的不带。
|
|
16
|
+
function metaOf(info, kind) {
|
|
17
|
+
const meta = {};
|
|
18
|
+
const mtimeMs = integer(info.mtimeMs), birthtimeMs = integer(info.birthtimeMs), mode = integer(info.mode);
|
|
19
|
+
if (kind === EntryKind.FILE && integer(info.size) !== undefined) meta.size = integer(info.size);
|
|
20
|
+
if (mtimeMs !== undefined) meta.mtimeMs = mtimeMs;
|
|
21
|
+
if (birthtimeMs !== undefined && birthtimeMs > 0) meta.birthtimeMs = birthtimeMs; // 0 是文件系统没有这个值
|
|
22
|
+
if (mode !== undefined) meta.mode = mode & 0o7777;
|
|
23
|
+
return meta;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const kindOf = info => (info.isDirectory() ? EntryKind.DIR : info.isFile() ? EntryKind.FILE : EntryKind.OTHER);
|
|
27
|
+
|
|
28
|
+
// 先解析父目录,再 lstat 最后一级,不跟随链接。
|
|
29
|
+
// 指向工作目录内的链接按目标显示(target 是目标的相对路径);指向外面或已失效的链接只给自己的元数据,不给目标路径。
|
|
30
|
+
export async function statPath(listing, root, path) {
|
|
31
|
+
const segments = parseRelative(path);
|
|
32
|
+
const { fs } = listing;
|
|
33
|
+
let name, dir, item;
|
|
34
|
+
try {
|
|
35
|
+
if (segments.length === 0) {
|
|
36
|
+
name = basename(root);
|
|
37
|
+
item = { kind: EntryKind.DIR, info: await listing.run(() => fs.lstat(root)) };
|
|
38
|
+
} else {
|
|
39
|
+
name = segments[segments.length - 1];
|
|
40
|
+
dir = await resolveInRoot(root, segments.slice(0, -1).join('/'));
|
|
41
|
+
const own = await listing.run(() => fs.lstat(join(dir, name)));
|
|
42
|
+
if (own.isSymbolicLink()) {
|
|
43
|
+
const linked = await listing.run(() => classifyLink(fs, root, dir, name));
|
|
44
|
+
item = linked.link
|
|
45
|
+
? { kind: linked.kind, info: linked.info, link: true, target: relative(root, linked.real).split(sep).join('/') }
|
|
46
|
+
: { kind: EntryKind.LINK, info: own, link: true };
|
|
47
|
+
} else item = { kind: kindOf(own), info: own };
|
|
48
|
+
}
|
|
49
|
+
} catch (error) { throw fromFsError(error); }
|
|
50
|
+
const { kind, info, link, target } = item;
|
|
51
|
+
const body = { name, kind };
|
|
52
|
+
if (link) body.link = true;
|
|
53
|
+
if (target !== undefined) body.target = target;
|
|
54
|
+
return { ...body, ...metaOf(info, kind) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 文件夹大小:边读边统计,不一次性为全部条目建任务。
|
|
58
|
+
// - 同一时间只读一个目录,用只取名字的 readdir(不用 opendir、withFileTypes:文件系统不报类型时它们可能同步 lstat)。
|
|
59
|
+
// - lstat 一批最多 BATCH 个,经视图的并发上限排队,等回来才排下一批;排到名额后先核对停止条件再读。
|
|
60
|
+
// - 不跟随链接:链接算一项,不计大小。
|
|
61
|
+
// - 项数到 limit 或用时到 timeoutMs,立刻回答 complete: false,已发出的读取结果不再计入;
|
|
62
|
+
// signal 中止、valid() 为假(会话、根目录变了或视图关了)静默停止,返回 null,不回答。
|
|
63
|
+
// - 5 秒从收到请求算起:计时和取消监听先建,解析起点(resolve,默认 resolveInRoot)与它们竞速;
|
|
64
|
+
// 解析回来先核对 valid() 和 signal,才读。到点还没解析完回答 items: 0、complete: false;解析失败按错误回答。
|
|
65
|
+
// - 子目录读不到、条目 lstat 失败都计入 unreadable;起点读不到才算错误。
|
|
66
|
+
export async function dirSize(listing, root, path, {
|
|
67
|
+
valid = () => true, signal, limit = DIR_SIZE_ITEMS, timeoutMs = DIR_SIZE_MS, resolve: resolvePath = resolveInRoot,
|
|
68
|
+
} = {}) {
|
|
69
|
+
const { fs } = listing;
|
|
70
|
+
const total = { size: 0, items: 0, unreadable: 0 };
|
|
71
|
+
let over = false;
|
|
72
|
+
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
let timer = null;
|
|
75
|
+
// 结算一次:之后的一切读取结果、定时器、中止都不再有影响。
|
|
76
|
+
const settle = done => {
|
|
77
|
+
if (over) return;
|
|
78
|
+
over = true;
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
signal?.removeEventListener('abort', onAbort);
|
|
81
|
+
done();
|
|
82
|
+
};
|
|
83
|
+
const end = result => settle(() => resolve(result));
|
|
84
|
+
const onAbort = () => end(null);
|
|
85
|
+
// 停了没有。valid() 为假或已中止的在这里顺便结算成静默停止。
|
|
86
|
+
const stopped = () => {
|
|
87
|
+
if (over) return true;
|
|
88
|
+
if (signal?.aborted || !valid()) { end(null); return true; }
|
|
89
|
+
return false;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
if (signal?.aborted) return end(null);
|
|
93
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
94
|
+
timer = setTimeout(() => end({ ...total, complete: false }), timeoutMs);
|
|
95
|
+
|
|
96
|
+
// 数一个条目。读失败的也算一项。
|
|
97
|
+
async function measure(dir, name, dirs) {
|
|
98
|
+
if (stopped()) return; // 排到名额之后先核对
|
|
99
|
+
let info = null;
|
|
100
|
+
try { info = await fs.lstat(join(dir, name)); } catch { /* 下面计入 unreadable */ }
|
|
101
|
+
if (stopped()) return; // 已经停了,回来的结果不再计入
|
|
102
|
+
total.items++;
|
|
103
|
+
if (!info) total.unreadable++;
|
|
104
|
+
else if (info.isDirectory()) dirs.push(join(dir, name));
|
|
105
|
+
else if (info.isFile()) total.size += Math.max(0, Math.floor(info.size) || 0);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function walk() {
|
|
109
|
+
// 解析慢时由计时和中止先结算;这里回来之后 stopped() 再核对一遍,已经停了就不读。
|
|
110
|
+
const start = await resolvePath(root, path);
|
|
111
|
+
if (stopped()) return;
|
|
112
|
+
const dirs = [start]; // 待访问的目录,数量不超过项数上限
|
|
113
|
+
while (dirs.length > 0 && !stopped()) {
|
|
114
|
+
const dir = dirs.pop();
|
|
115
|
+
let names;
|
|
116
|
+
try { names = await fs.readdir(dir); } catch (error) {
|
|
117
|
+
if (dir === start) throw fromFsError(error);
|
|
118
|
+
if (stopped()) return;
|
|
119
|
+
total.unreadable++;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
let at = 0;
|
|
123
|
+
while (at < names.length) {
|
|
124
|
+
if (stopped()) return;
|
|
125
|
+
if (total.items >= limit) return end({ ...total, complete: false });
|
|
126
|
+
const batch = names.slice(at, at + Math.min(BATCH, limit - total.items));
|
|
127
|
+
at += batch.length;
|
|
128
|
+
await Promise.all(batch.map(name => listing.run(() => measure(dir, name, dirs))));
|
|
129
|
+
}
|
|
130
|
+
if (!stopped() && total.items >= limit && dirs.length > 0) return end({ ...total, complete: false });
|
|
131
|
+
}
|
|
132
|
+
end({ ...total, complete: true });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
walk().catch(error => settle(() => reject(error)));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// 日期、大小排序的快照:第一页读全部条目并排好序,之后的页只从这里取,不再碰文件系统。
|
|
2
|
+
// 快照属于一个视图,由 main.mjs 建一份传给 lib/tree.mjs;这里只管存放、淘汰和释放,不碰 fs。
|
|
3
|
+
export const MAX_SNAPSHOTS = 8;
|
|
4
|
+
export const MAX_SNAPSHOT_ENTRIES = 100_000;
|
|
5
|
+
export const SNAPSHOT_IDLE_MS = 60_000;
|
|
6
|
+
|
|
7
|
+
export function createSnapshots({
|
|
8
|
+
now = Date.now, maxCount = MAX_SNAPSHOTS, maxEntries = MAX_SNAPSHOT_ENTRIES, idleMs = SNAPSHOT_IDLE_MS,
|
|
9
|
+
} = {}) {
|
|
10
|
+
const items = new Map(); // id → 快照;Map 的顺序就是最近使用的顺序,最前面的最久没用
|
|
11
|
+
let nextId = 1, total = 0;
|
|
12
|
+
|
|
13
|
+
const drop = id => {
|
|
14
|
+
const item = items.get(id);
|
|
15
|
+
if (item) { total -= item.entries.length; items.delete(id); }
|
|
16
|
+
};
|
|
17
|
+
// 不起定时器:每次访问任何快照时顺便清掉闲置的。
|
|
18
|
+
const sweep = () => {
|
|
19
|
+
const time = now();
|
|
20
|
+
for (const [id, item] of items) if (time - item.used > idleMs) drop(id);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
get size() { return items.size; },
|
|
25
|
+
get total() { return total; },
|
|
26
|
+
|
|
27
|
+
// 取快照并记为刚用过;已被淘汰、释放或闲置过期的返回 null。
|
|
28
|
+
get(id) {
|
|
29
|
+
sweep();
|
|
30
|
+
const item = items.get(id);
|
|
31
|
+
if (!item) return null;
|
|
32
|
+
item.used = now();
|
|
33
|
+
items.delete(id);
|
|
34
|
+
items.set(id, item);
|
|
35
|
+
return item;
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
// 存一份,替换同身份的旧快照,超出数量或总条目时淘汰最久没用的。id 递增、不复用,旧游标不会指到新快照上。
|
|
39
|
+
put({ identity, root, path, entries }) {
|
|
40
|
+
sweep();
|
|
41
|
+
for (const [id, item] of items) if (item.identity === identity) drop(id);
|
|
42
|
+
while (items.size > 0 && (items.size >= maxCount || total + entries.length > maxEntries)) drop(items.keys().next().value);
|
|
43
|
+
const item = { id: nextId++, identity, root, path, entries, used: now() };
|
|
44
|
+
items.set(item.id, item);
|
|
45
|
+
total += entries.length;
|
|
46
|
+
return item;
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
release: drop,
|
|
50
|
+
clear() { items.clear(); total = 0; },
|
|
51
|
+
};
|
|
52
|
+
}
|
package/lib/tree.mjs
CHANGED
|
@@ -1,74 +1,263 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
// 读目录:文件夹在前,按排序键排序,按序列化字节数分页。模块回答全部条目,隐藏规则在页面。
|
|
2
|
+
// 名称、种类排序每页重读目录,游标是上一条的排序键,只读当前页条目的元数据;
|
|
3
|
+
// 日期、大小排序第一页读全部条目的元数据并建快照,之后的页从快照取,不再碰文件系统(设计见 docs/design/phase-3.md 第 12.3 节)。
|
|
4
|
+
import { lstat, readdir, realpath, stat } from 'node:fs/promises';
|
|
5
|
+
import { extname, join } from 'node:path';
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_SORT, EntryKind, ENVELOPE_BYTES, ErrorCode, PAGE_BYTES, SortKey, fail, parseSort,
|
|
8
|
+
} from '../view/protocol.mjs';
|
|
9
|
+
import { fromFsError, isInside, isSafeName, parseRelative, resolveInRoot } from './paths.mjs';
|
|
10
|
+
import { createSnapshots } from './snapshots.mjs';
|
|
6
11
|
|
|
7
12
|
const MAX_ENTRIES = 100_000;
|
|
8
|
-
|
|
13
|
+
// 日期、大小排序要读全部条目的元数据,超过这个数的目录退回按名称排。
|
|
14
|
+
export const SORT_STAT_LIMIT = 20_000;
|
|
15
|
+
const CONCURRENCY = 8;
|
|
16
|
+
// 一条的元数据最多占的字节(两个都是 16 位整数),用来在读元数据之前保守地决定一页放几条。
|
|
17
|
+
const META_BYTES = Buffer.byteLength(',"size":9007199254740991,"mtimeMs":9007199254740991');
|
|
18
|
+
|
|
19
|
+
// 并发上限:每个视图一个,classify 和读元数据都经它,所以并行多个目录也不会超过 limit 个同时在读。
|
|
20
|
+
export function createLimiter(limit = CONCURRENCY) {
|
|
21
|
+
let active = 0;
|
|
22
|
+
const waiting = [];
|
|
23
|
+
return async fn => {
|
|
24
|
+
if (active < limit) active++; else await new Promise(resolve => waiting.push(resolve));
|
|
25
|
+
try { return await fn(); } finally {
|
|
26
|
+
const next = waiting.shift();
|
|
27
|
+
if (next) next(); else active--; // 有人等就把坑位直接交给它
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const realFs = { lstat, readdir, realpath, stat };
|
|
33
|
+
|
|
34
|
+
// 一个视图的读取状态:文件系统、共用的并发上限、快照、进行中的第一页读取。
|
|
35
|
+
// refresh、changed 后 detach:进行中的读取不再被新请求共用;换会话、根目录变化、视图关闭后 clear。
|
|
36
|
+
// latest 记着每个身份最新发起的读取:只有它能存快照,旧的读取晚到也不会顶掉新快照。detach 不动它,clear 才清(清了之后谁都不能存)。
|
|
37
|
+
export function createListing({ fs = realFs, limit = CONCURRENCY, snapshots = createSnapshots() } = {}) {
|
|
38
|
+
return {
|
|
39
|
+
fs, snapshots, run: createLimiter(limit), reads: new Map(), latest: new Map(), started: 0,
|
|
40
|
+
detach() { this.reads.clear(); },
|
|
41
|
+
clear() { this.reads.clear(); this.latest.clear(); this.snapshots.clear(); },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---- 排序 ----
|
|
9
46
|
|
|
10
47
|
const rank = entry => (entry.kind === EntryKind.DIR ? 0 : 1);
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
48
|
+
const extOf = name => extname(name).slice(1).toLowerCase();
|
|
49
|
+
|
|
50
|
+
// 排序键;undefined 是缺元数据(或文件夹没有大小),排在组内最后。
|
|
51
|
+
function keyOf(entry, key) {
|
|
52
|
+
switch (key) {
|
|
53
|
+
case SortKey.NAME: return entry.name.toLowerCase();
|
|
54
|
+
case SortKey.KIND: return entry.kind === EntryKind.DIR ? '' : extOf(entry.name);
|
|
55
|
+
case SortKey.DATE: return entry.mtimeMs;
|
|
56
|
+
default: return entry.kind === EntryKind.DIR ? undefined : entry.size;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 每种排序的方向,只在这里定义:名称、种类升序,日期、大小降序(最新、最大在前)。
|
|
61
|
+
const DESCENDING = new Set([SortKey.DATE, SortKey.SIZE]);
|
|
62
|
+
|
|
63
|
+
// 全序:文件夹在前(不随方向反向);键按该排序的方向,缺的不管方向都在最后;平手按名字(不分大小写)升序,最后按原名。
|
|
64
|
+
function comparer(key) {
|
|
65
|
+
const desc = DESCENDING.has(key);
|
|
66
|
+
return (a, b) => {
|
|
67
|
+
if (rank(a) !== rank(b)) return rank(a) - rank(b);
|
|
68
|
+
const x = keyOf(a, key), y = keyOf(b, key);
|
|
69
|
+
if (x !== y) {
|
|
70
|
+
if (x === undefined) return 1;
|
|
71
|
+
if (y === undefined) return -1;
|
|
72
|
+
return (x < y ? -1 : 1) * (desc ? -1 : 1);
|
|
73
|
+
}
|
|
74
|
+
const p = a.name.toLowerCase(), q = b.name.toLowerCase();
|
|
75
|
+
if (p !== q) return p < q ? -1 : 1;
|
|
76
|
+
return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
|
|
77
|
+
};
|
|
16
78
|
}
|
|
17
79
|
|
|
18
|
-
|
|
80
|
+
// ---- 游标:名称、种类用排序键,日期、大小用快照编号加下标。解不开的一律当作过期。 ----
|
|
81
|
+
|
|
82
|
+
const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
83
|
+
const encodeKeyCursor = (sort, entry) => encode(['k', sort, rank(entry), entry.name]);
|
|
84
|
+
const encodeSnapshotCursor = (id, index) => encode(['s', id, index]);
|
|
85
|
+
|
|
19
86
|
function decodeCursor(cursor) {
|
|
20
87
|
try {
|
|
21
|
-
const
|
|
22
|
-
if ((
|
|
88
|
+
const value = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8'));
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
if (value[0] === 's' && Number.isSafeInteger(value[1]) && Number.isSafeInteger(value[2]) && value[2] > 0) {
|
|
91
|
+
return { snapshot: value[1], index: value[2] };
|
|
92
|
+
}
|
|
93
|
+
const [tag, sort, group, name] = value;
|
|
94
|
+
if (value.length === 4 && tag === 'k' && (sort === SortKey.NAME || sort === SortKey.KIND)
|
|
95
|
+
&& (group === 0 || group === 1) && typeof name === 'string') {
|
|
96
|
+
return { sort, after: { name, kind: group === 0 ? EntryKind.DIR : EntryKind.FILE } };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
23
99
|
} catch { /* 下面统一报错 */ }
|
|
24
|
-
throw fail(ErrorCode.
|
|
100
|
+
throw fail(ErrorCode.CURSOR_EXPIRED, '游标已过期');
|
|
25
101
|
}
|
|
26
102
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
103
|
+
// ---- 读条目 ----
|
|
104
|
+
|
|
105
|
+
// 只有符号链接要额外解析:目标在根目录内按目标显示(目标的 lstat 带回去给读元数据用,不解析第二次),在外或已失效显示为 link。
|
|
106
|
+
// 校验之后用 lstat 读目标,不跟随链接:realpath 之后目标被换成别的链接,读到的就是符号链接,按 link 处理,不带外面的元数据。
|
|
107
|
+
export async function classifyLink(fs, root, dir, name) {
|
|
108
|
+
try {
|
|
109
|
+
const real = await fs.realpath(join(dir, name));
|
|
110
|
+
if (!isInside(root, real)) return { name, kind: EntryKind.LINK };
|
|
111
|
+
const info = await fs.lstat(real);
|
|
112
|
+
if (info.isSymbolicLink()) return { name, kind: EntryKind.LINK };
|
|
113
|
+
const kind = info.isDirectory() ? EntryKind.DIR : info.isFile() ? EntryKind.FILE : EntryKind.OTHER;
|
|
114
|
+
return { name, kind, link: true, info, real };
|
|
115
|
+
} catch { return { name, kind: EntryKind.LINK }; }
|
|
34
116
|
}
|
|
35
117
|
|
|
36
|
-
|
|
37
|
-
async function classify(root, dir, dirent) {
|
|
118
|
+
function classifyPlain(dirent) {
|
|
38
119
|
const { name } = dirent;
|
|
39
120
|
if (!isSafeName(name)) return { name, kind: EntryKind.OTHER };
|
|
40
121
|
if (dirent.isDirectory()) return { name, kind: EntryKind.DIR };
|
|
41
122
|
if (dirent.isFile()) return { name, kind: EntryKind.FILE };
|
|
42
|
-
|
|
123
|
+
return { name, kind: EntryKind.OTHER };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const needsResolve = dirent => dirent.isSymbolicLink() && isSafeName(dirent.name);
|
|
127
|
+
// 不是链接的不碰文件系统,不占并发坑位。
|
|
128
|
+
const classify = (listing, root, dir, dirent) => (needsResolve(dirent)
|
|
129
|
+
? listing.run(() => classifyLink(listing.fs, root, dir, dirent.name))
|
|
130
|
+
: classifyPlain(dirent));
|
|
131
|
+
|
|
132
|
+
// 读失败(刚被删、没权限)不算错误,这个条目不带字段。普通条目用 lstat,不跟随链接:
|
|
133
|
+
// 条目在 readdir 之后被换成指向外面的链接,lstat 读到的也只是链接自己,类型对不上就不带字段。
|
|
134
|
+
// link: true 的用 classify 校验时拿到的目标 lstat。link、other 不读。size、mtimeMs 取整后只有这一份值。
|
|
135
|
+
async function addMeta(listing, dir, item) {
|
|
136
|
+
if (item.kind !== EntryKind.DIR && item.kind !== EntryKind.FILE) return;
|
|
43
137
|
try {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
138
|
+
const info = item.link ? item.info : await listing.fs.lstat(join(dir, item.name));
|
|
139
|
+
const isDir = info.isDirectory();
|
|
140
|
+
if (isDir !== (item.kind === EntryKind.DIR) || (!isDir && !info.isFile())) return;
|
|
141
|
+
const mtimeMs = Math.floor(info.mtimeMs), size = Math.floor(info.size);
|
|
142
|
+
if (Number.isFinite(mtimeMs)) item.mtimeMs = mtimeMs;
|
|
143
|
+
if (!isDir && Number.isFinite(size)) item.size = size;
|
|
144
|
+
} catch { /* 不带字段 */ }
|
|
50
145
|
}
|
|
51
146
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
entries.sort(compare);
|
|
147
|
+
function toEntry({ name, kind, link, size, mtimeMs }) {
|
|
148
|
+
const entry = { name, kind };
|
|
149
|
+
if (link) entry.link = true;
|
|
150
|
+
if (size !== undefined) entry.size = size;
|
|
151
|
+
if (mtimeMs !== undefined) entry.mtimeMs = mtimeMs;
|
|
152
|
+
return entry;
|
|
153
|
+
}
|
|
60
154
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
155
|
+
const entryBytes = entry => Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
156
|
+
|
|
157
|
+
// 从 start 起取一页,至少一条;返回下一页的下标。
|
|
158
|
+
function cut(entries, start, pageBytes) {
|
|
159
|
+
let end = start, used = 0;
|
|
160
|
+
while (end < entries.length) {
|
|
161
|
+
const size = entryBytes(entries[end]);
|
|
162
|
+
if (end > start && used + size > pageBytes - ENVELOPE_BYTES) break;
|
|
163
|
+
used += size;
|
|
164
|
+
end++;
|
|
165
|
+
}
|
|
166
|
+
return { entries: entries.slice(start, end), end };
|
|
167
|
+
}
|
|
64
168
|
|
|
65
|
-
|
|
169
|
+
async function readDirents(listing, dir) {
|
|
170
|
+
try { return await listing.fs.readdir(dir, { withFileTypes: true }); } catch (error) { throw fromFsError(error); }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 名称、种类(和退回名称的日期、大小):读目录、classify 全部,排序,找到游标之后,只读这一页的元数据。
|
|
174
|
+
// 元数据的字节数在读之前不知道,所以按最大可能的字节数决定放几条,一页不会超。
|
|
175
|
+
async function pageByKey(listing, root, dir, dirents, sort, after, pageBytes) {
|
|
176
|
+
const items = await Promise.all(dirents.map(dirent => classify(listing, root, dir, dirent)));
|
|
177
|
+
const compare = comparer(sort);
|
|
178
|
+
items.sort(compare);
|
|
179
|
+
let index = 0;
|
|
180
|
+
if (after) while (index < items.length && compare(items[index], after) <= 0) index++;
|
|
181
|
+
const picked = [];
|
|
66
182
|
let used = 0;
|
|
67
|
-
while (index <
|
|
68
|
-
const size =
|
|
69
|
-
if (
|
|
183
|
+
while (index < items.length) {
|
|
184
|
+
const size = entryBytes(toEntry(items[index])) + META_BYTES;
|
|
185
|
+
if (picked.length && used + size > pageBytes - ENVELOPE_BYTES) break;
|
|
70
186
|
used += size;
|
|
71
|
-
|
|
187
|
+
picked.push(items[index++]);
|
|
72
188
|
}
|
|
73
|
-
|
|
189
|
+
await Promise.all(picked.map(item => listing.run(() => addMeta(listing, dir, item))));
|
|
190
|
+
return { entries: picked.map(toEntry), nextCursor: index < items.length ? encodeKeyCursor(sort, picked[picked.length - 1]) : null };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 日期、大小的第一页:读全部条目的元数据,排序,存快照。一页放得下就不存。
|
|
194
|
+
// 读完核对代次和根路径:对不上说明读的时候会话或根目录换了,不存快照也不回答内容。
|
|
195
|
+
// isLatest:这次读取是不是同身份最新发起的;不是的照常回答,但不存快照(回答里的游标指向编号 0,永远查不到,页面丢弃这份回答)。
|
|
196
|
+
async function firstSnapshotPage(listing, root, rel, path, sort, { pageBytes, maxEntries, statLimit, valid, isLatest }) {
|
|
197
|
+
const dir = await resolveInRoot(root, path);
|
|
198
|
+
const dirents = await readDirents(listing, dir);
|
|
199
|
+
if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
|
|
200
|
+
if (dirents.length > statLimit) {
|
|
201
|
+
return { ...await pageByKey(listing, root, dir, dirents, DEFAULT_SORT, null, pageBytes), sortFallback: true };
|
|
202
|
+
}
|
|
203
|
+
const items = await Promise.all(dirents.map(dirent => listing.run(async () => {
|
|
204
|
+
// 已经占着坑位,直接解析链接;再经 run 会等自己占的坑位。
|
|
205
|
+
const item = needsResolve(dirent) ? await classifyLink(listing.fs, root, dir, dirent.name) : classifyPlain(dirent);
|
|
206
|
+
await addMeta(listing, dir, item);
|
|
207
|
+
return item;
|
|
208
|
+
})));
|
|
209
|
+
const entries = items.map(toEntry).sort(comparer(sort));
|
|
210
|
+
if (!valid()) throw fail(ErrorCode.NO_ROOT, '工作目录已变化');
|
|
211
|
+
const page = cut(entries, 0, pageBytes);
|
|
212
|
+
if (page.end >= entries.length) return { entries, nextCursor: null };
|
|
213
|
+
if (!isLatest()) return { entries: page.entries, nextCursor: encodeSnapshotCursor(0, page.end) };
|
|
214
|
+
const snapshot = listing.snapshots.put({ identity: JSON.stringify([root, rel, sort]), root, path: rel, entries });
|
|
215
|
+
return { entries: page.entries, nextCursor: encodeSnapshotCursor(snapshot.id, page.end) };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function pageOfSnapshot(listing, root, rel, { snapshot: id, index }, pageBytes) {
|
|
219
|
+
const snapshot = listing.snapshots.get(id);
|
|
220
|
+
if (!snapshot || snapshot.root !== root || snapshot.path !== rel || index >= snapshot.entries.length) {
|
|
221
|
+
throw fail(ErrorCode.CURSOR_EXPIRED, '游标已过期');
|
|
222
|
+
}
|
|
223
|
+
const page = cut(snapshot.entries, index, pageBytes);
|
|
224
|
+
if (page.end < snapshot.entries.length) return { entries: page.entries, nextCursor: encodeSnapshotCursor(id, page.end) };
|
|
225
|
+
listing.snapshots.release(id);
|
|
226
|
+
return { entries: page.entries, nextCursor: null };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// options:sort(只对第一页有效,有游标时只认游标里的)、listing(视图共用的读取状态)、valid(回答前是否仍然有效,
|
|
230
|
+
// 由主模块按代次和根路径判断)、maxEntries、pageBytes、statLimit(测试可调)。
|
|
231
|
+
export async function listDirectory(root, path, cursor, options = {}) {
|
|
232
|
+
const {
|
|
233
|
+
listing = createListing(), maxEntries = MAX_ENTRIES, pageBytes = PAGE_BYTES, statLimit = SORT_STAT_LIMIT, valid = () => true,
|
|
234
|
+
} = options;
|
|
235
|
+
const requested = options.sort == null ? DEFAULT_SORT : parseSort(options.sort);
|
|
236
|
+
if (!requested) throw fail(ErrorCode.INVALID_SORT, '排序无效');
|
|
237
|
+
const rel = parseRelative(path).join('/');
|
|
238
|
+
const at = cursor == null ? null : decodeCursor(cursor);
|
|
239
|
+
if (at?.snapshot !== undefined) return pageOfSnapshot(listing, root, rel, at, pageBytes);
|
|
240
|
+
|
|
241
|
+
if (!at && (requested === SortKey.DATE || requested === SortKey.SIZE)) {
|
|
242
|
+
// 同身份的第一页并发时共用同一次读取。
|
|
243
|
+
const identity = JSON.stringify([root, rel, requested]);
|
|
244
|
+
let read = listing.reads.get(identity);
|
|
245
|
+
if (!read) {
|
|
246
|
+
const order = ++listing.started;
|
|
247
|
+
listing.latest.set(identity, order);
|
|
248
|
+
const isLatest = () => listing.latest.get(identity) === order;
|
|
249
|
+
read = firstSnapshotPage(listing, root, rel, path, requested, { pageBytes, maxEntries, statLimit, valid, isLatest })
|
|
250
|
+
.finally(() => {
|
|
251
|
+
if (listing.reads.get(identity) === read) listing.reads.delete(identity);
|
|
252
|
+
if (isLatest()) listing.latest.delete(identity);
|
|
253
|
+
});
|
|
254
|
+
listing.reads.set(identity, read);
|
|
255
|
+
}
|
|
256
|
+
return read;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const dir = await resolveInRoot(root, path);
|
|
260
|
+
const dirents = await readDirents(listing, dir);
|
|
261
|
+
if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
|
|
262
|
+
return pageByKey(listing, root, dir, dirents, at ? at.sort : requested, at?.after ?? null, pageBytes);
|
|
74
263
|
}
|