@hjd-hitsz/claudex-web 4.1.4 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.env.example +2 -0
  2. package/CHANGELOG.md +47 -0
  3. package/README.md +13 -1
  4. package/bin/auth.mjs +86 -0
  5. package/bin/claudex-web.mjs +20 -0
  6. package/bin/p2p.mjs +134 -0
  7. package/build-info.json +4 -4
  8. package/client/dist/app.js +104 -104
  9. package/client/dist/code-highlight-style.js +1 -1
  10. package/client/dist/document-editor.js +55 -54
  11. package/client/dist/file-panel.js +5 -5
  12. package/client/dist/notification-worker.js +2 -1
  13. package/client/dist/p2p-sw.js +162 -0
  14. package/client/dist/style.css +1 -1
  15. package/client/dist/terminal-panel.js +11 -11
  16. package/docs/architecture/backends.md +9 -2
  17. package/docs/architecture/behavior.md +167 -53
  18. package/docs/architecture.md +36 -337
  19. package/docs/background-tasks.md +30 -26
  20. package/docs/deployment.md +47 -6
  21. package/docs/development.md +111 -153
  22. package/docs/images/desktop-dark.png +0 -0
  23. package/docs/images/desktop-light.png +0 -0
  24. package/docs/images/mobile-sidebar.png +0 -0
  25. package/docs/images/mobile.png +0 -0
  26. package/docs/releases/v4.1.5.md +6 -0
  27. package/docs/releases/v4.2.0.md +13 -0
  28. package/docs/versioning.md +13 -3
  29. package/package.json +14 -5
  30. package/packages/background-terminal/LICENSE +674 -0
  31. package/packages/background-terminal/README.md +17 -0
  32. package/packages/background-terminal/background-jobs.mjs +457 -0
  33. package/packages/background-terminal/background-mcp.mjs +79 -0
  34. package/packages/background-terminal/background-protocol.mjs +80 -0
  35. package/packages/background-terminal/cli.mjs +14 -0
  36. package/packages/background-terminal/client.mjs +61 -0
  37. package/packages/background-terminal/codex.mjs +88 -0
  38. package/packages/background-terminal/delivery.mjs +192 -0
  39. package/packages/background-terminal/log.mjs +25 -0
  40. package/packages/background-terminal/native-watches.mjs +160 -0
  41. package/packages/background-terminal/package.json +15 -0
  42. package/packages/background-terminal/service.mjs +126 -0
  43. package/packages/translation-engine/package.json +1 -1
  44. package/server/src/application.mjs +82 -10
  45. package/server/src/auth-http.mjs +187 -0
  46. package/server/src/auth-login.mjs +144 -0
  47. package/server/src/auth-totp.mjs +233 -0
  48. package/server/src/auth.mjs +169 -220
  49. package/server/src/backends/claude/background-tasks.mjs +88 -35
  50. package/server/src/backends/claude/messages.mjs +1 -1
  51. package/server/src/backends/claude/worker-client.mjs +47 -35
  52. package/server/src/backends/claude/worker-lines.mjs +17 -0
  53. package/server/src/backends/claude/worker-server.mjs +49 -69
  54. package/server/src/backends/codex/adapter.mjs +46 -5
  55. package/server/src/backends/codex/background-service.mjs +85 -0
  56. package/server/src/backends/codex/background-task-views.mjs +87 -0
  57. package/server/src/backends/codex/background-terminals.mjs +91 -0
  58. package/server/src/backends/codex/events.mjs +11 -0
  59. package/server/src/backends/codex/methods.mjs +1 -0
  60. package/server/src/backends/codex/native-background-handoff.mjs +72 -0
  61. package/server/src/backends/codex/requests.mjs +51 -38
  62. package/server/src/backends/codex/subscriptions.mjs +34 -4
  63. package/server/src/backends/configuration.mjs +8 -0
  64. package/server/src/backends/manager.mjs +35 -33
  65. package/server/src/backends/storage.mjs +3 -14
  66. package/server/src/config.mjs +13 -0
  67. package/server/src/http/business.mjs +21 -0
  68. package/server/src/http/router.mjs +12 -25
  69. package/server/src/p2p/http.mjs +136 -0
  70. package/server/src/p2p/peers.mjs +132 -0
  71. package/server/src/p2p/service.mjs +229 -0
  72. package/server/src/p2p/storage.mjs +45 -0
  73. package/server/src/p2p/tunnel.mjs +95 -0
  74. package/server/src/p2p-http.mjs +149 -0
  75. package/server/src/p2p-peer.mjs +135 -0
  76. package/server/src/private-file.mjs +14 -0
  77. package/server/src/summary-translation.mjs +1 -1
  78. package/server/src/thread-folders.mjs +3 -13
  79. package/server/src/translation-service.mjs +3 -8
  80. package/server/src/workspace/file-search.mjs +244 -0
  81. package/server/src/workspace/service.mjs +17 -3
  82. package/shared/codex-preferences.mjs +9 -0
  83. package/shared/p2p-wire.mjs +157 -0
@@ -0,0 +1,95 @@
1
+ import { join } from "node:path";
2
+ import { setTimeout as wait } from "node:timers/promises";
3
+ import { tunnelStorage } from "./storage.mjs";
4
+
5
+ const profile = "claudex-web";
6
+ const route = "@";
7
+
8
+ export async function runPublicTunnel({
9
+ directory,
10
+ port,
11
+ signal,
12
+ onOrigin,
13
+ onState,
14
+ }) {
15
+ const endpoint = new URL(
16
+ process.env.OPENTUNNEL_API || "https://opentunnel.xyz",
17
+ );
18
+ if (endpoint.protocol !== "https:" || endpoint.href !== `${endpoint.origin}/`)
19
+ throw new Error("OPENTUNNEL_API 须为 HTTPS 来源地址");
20
+ const { create } = await import("@opentunnel/client");
21
+ const store = await tunnelStorage(
22
+ join(directory, "tunnel.json"),
23
+ endpoint.origin,
24
+ profile,
25
+ );
26
+ const client = create({ api: endpoint, store });
27
+ let retry = 1000;
28
+
29
+ async function attach(connection, activeSignal) {
30
+ let accepted = false;
31
+ const events = (async () => {
32
+ for await (const { type } of connection.events) {
33
+ if (!accepted || activeSignal.aborted) continue;
34
+ if (type === "connected") onState("online");
35
+ if (type === "disconnected" || type === "reconnecting")
36
+ onState("connecting");
37
+ }
38
+ })();
39
+ const closed = Promise.all([connection.closed, events]);
40
+ void closed.catch(() => {});
41
+ try {
42
+ if (!activeSignal.aborted) {
43
+ await onOrigin(connection.urls[route]);
44
+ accepted = true;
45
+ onState(
46
+ connection.status().state === "connected" ? "online" : "connecting",
47
+ );
48
+ }
49
+ await closed;
50
+ } finally {
51
+ await connection.close();
52
+ await closed.catch(() => {});
53
+ }
54
+ }
55
+
56
+ try {
57
+ while (!signal.aborted) {
58
+ onState("connecting");
59
+ const timeout = new AbortController();
60
+ const activeSignal = AbortSignal.any([signal, timeout.signal]);
61
+ const timer = setTimeout(() => timeout.abort(), 90000);
62
+ timer.unref();
63
+ let routeConflict = false;
64
+ try {
65
+ const connection = await client.tunnel.connect({
66
+ profile,
67
+ routes: { [route]: `127.0.0.1:${port}` },
68
+ signal: activeSignal,
69
+ onRouteConflict: "fail",
70
+ onEvent(event) {
71
+ if (event.type === "route-conflict") routeConflict = true;
72
+ },
73
+ });
74
+ clearTimeout(timer);
75
+ retry = 1000;
76
+ await attach(connection, activeSignal);
77
+ } catch {
78
+ if (!signal.aborted)
79
+ onState(
80
+ "error",
81
+ routeConflict
82
+ ? "OpenTunnel 域名被另一进程占用,正在重试"
83
+ : "OpenTunnel 暂不可用,正在重试",
84
+ );
85
+ } finally {
86
+ clearTimeout(timer);
87
+ }
88
+ if (signal.aborted) break;
89
+ await wait(retry, undefined, { signal }).catch(() => {});
90
+ retry = Math.min(retry * 2, 30000);
91
+ }
92
+ } finally {
93
+ await client.dispose();
94
+ }
95
+ }
@@ -0,0 +1,149 @@
1
+ import { Readable, Writable } from "node:stream";
2
+ import { P2P_STREAM_CHUNK_BYTES } from "../../shared/p2p-wire.mjs";
3
+
4
+ class PeerResponse extends Writable {
5
+ constructor(send, id, method) {
6
+ super();
7
+ this.send = send;
8
+ this.id = id;
9
+ this.method = method;
10
+ this.headers = {};
11
+ this.headersSent = false;
12
+ this.statusCode = 200;
13
+ }
14
+
15
+ setHeader(name, value) {
16
+ this.headers[name.toLowerCase()] = String(value);
17
+ }
18
+
19
+ writeHead(status, headers = {}) {
20
+ if (this.headersSent || this.destroyed) return this;
21
+ for (const [name, value] of Object.entries(headers))
22
+ this.setHeader(name, value);
23
+ this.statusCode = status;
24
+ this.headersSent = true;
25
+ this.headerSent = this.send({
26
+ type: "response",
27
+ id: this.id,
28
+ status,
29
+ headers: this.headers,
30
+ });
31
+ this.headerSent.catch(() => this.destroy());
32
+ return this;
33
+ }
34
+
35
+ pull() {
36
+ if (this.destroyed || this.credit) return;
37
+ this.credit = true;
38
+ this.resumeWrite?.();
39
+ }
40
+
41
+ async _write(chunk, encoding, callback) {
42
+ try {
43
+ this.writeHead(this.statusCode);
44
+ await this.headerSent;
45
+ if (this.method !== "HEAD") {
46
+ for (
47
+ let offset = 0;
48
+ offset < chunk.length;
49
+ offset += P2P_STREAM_CHUNK_BYTES
50
+ ) {
51
+ if (!this.credit && !this.destroyed)
52
+ await new Promise((resolve) => {
53
+ this.resumeWrite = resolve;
54
+ });
55
+ this.resumeWrite = null;
56
+ if (this.destroyed) break;
57
+ this.credit = false;
58
+ await this.send(
59
+ { type: "data", id: this.id },
60
+ chunk.subarray(offset, offset + P2P_STREAM_CHUNK_BYTES),
61
+ );
62
+ }
63
+ }
64
+ callback();
65
+ } catch (error) {
66
+ callback(error);
67
+ }
68
+ }
69
+
70
+ _final(callback) {
71
+ this.writeHead(this.statusCode);
72
+ this.send({ type: "end", id: this.id }).then(() => callback(), callback);
73
+ }
74
+
75
+ _destroy(error, callback) {
76
+ this.resumeWrite?.();
77
+ callback(error);
78
+ }
79
+ }
80
+
81
+ export function createPeerHttp(handle, wire) {
82
+ const active = new Map();
83
+
84
+ return {
85
+ receive(message, bytes) {
86
+ const { type, id, method, url, headers } = message;
87
+ if (!Number.isSafeInteger(id) || id < 1) throw new Error("无效请求编号");
88
+ const running = active.get(id);
89
+ if (type === "pull") {
90
+ running?.pull();
91
+ return;
92
+ }
93
+ if (type === "cancel") {
94
+ running?.destroy();
95
+ return;
96
+ }
97
+ if (type !== "request" || running) throw new Error("无效直连请求");
98
+ const fail = (message) => {
99
+ wire.send({ type: "error", id, message }).catch(() => {});
100
+ };
101
+ if (
102
+ active.size >= 32 ||
103
+ !["GET", "HEAD", "POST", "PUT"].includes(method) ||
104
+ typeof url !== "string" ||
105
+ !url.startsWith("/api/") ||
106
+ url.length > 16384
107
+ ) {
108
+ fail("直连 HTTP 请求无效或过多");
109
+ return;
110
+ }
111
+ const parsed = new URL(url, "https://localhost");
112
+ if (parsed.origin !== "https://localhost") {
113
+ fail("直连 HTTP 地址无效");
114
+ return;
115
+ }
116
+ const request = Readable.from(bytes.length ? [Buffer.from(bytes)] : []);
117
+ request.method = method;
118
+ request.url = parsed.pathname + parsed.search;
119
+ request.headers = {};
120
+ for (const name of ["range", "content-type"])
121
+ if (typeof headers?.[name] === "string" && headers[name].length <= 1024)
122
+ request.headers[name] = headers[name];
123
+ const response = new PeerResponse(wire.send, id, method);
124
+ active.set(id, response);
125
+ response.on("close", () => {
126
+ active.delete(id);
127
+ request.destroy();
128
+ });
129
+ response.on("error", () => fail("直连响应传输中断"));
130
+ Promise.resolve()
131
+ .then(() => {
132
+ if (response.destroyed) return;
133
+ return (
134
+ handle(request, response, parsed.pathname) ||
135
+ response.writeHead(404).end()
136
+ );
137
+ })
138
+ .catch(() => {
139
+ if (response.destroyed) return;
140
+ if (response.headersSent) response.destroy(new Error("请求处理失败"));
141
+ else response.writeHead(500).end();
142
+ });
143
+ },
144
+ close() {
145
+ for (const response of active.values()) response.destroy();
146
+ active.clear();
147
+ },
148
+ };
149
+ }
@@ -0,0 +1,135 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { createP2pWire } from "../../shared/p2p-wire.mjs";
3
+ import { createPeerHttp } from "./p2p-http.mjs";
4
+
5
+ export function createPeerClient(
6
+ channel,
7
+ handleBusiness,
8
+ { authentication, linkId, onAuthenticated, onLogout },
9
+ ) {
10
+ const peer = new EventEmitter();
11
+ const lifetime = new AbortController();
12
+ const authorized = () =>
13
+ peer.authSessionId && authentication.valid(peer.authSessionId, linkId);
14
+ let untrack, pendingToken;
15
+ let authenticating = false;
16
+ peer.authLinkId = linkId;
17
+ peer.readyState = 1;
18
+ peer.detach = () => {
19
+ if (peer.readyState === 3) return;
20
+ peer.readyState = 3;
21
+ lifetime.abort();
22
+ authentication.cancelPeer(pendingToken, peer);
23
+ wire.close();
24
+ http.close();
25
+ peer.emit("close");
26
+ };
27
+ peer.close = () => {
28
+ peer.detach();
29
+ channel.close();
30
+ };
31
+
32
+ async function authorize(message) {
33
+ if (authenticating) {
34
+ peer.close();
35
+ return;
36
+ }
37
+ authenticating = true;
38
+ try {
39
+ if (message.action === "logout") {
40
+ authentication.cancelPeer(pendingToken, peer);
41
+ pendingToken = undefined;
42
+ const id = peer.authSessionId;
43
+ untrack?.();
44
+ untrack = undefined;
45
+ peer.authSessionId = undefined;
46
+ http.close();
47
+ if (id) onLogout(peer);
48
+ await authentication.logoutPeer(linkId, id);
49
+ await wire.send({
50
+ type: "auth-result",
51
+ session: { authenticated: false },
52
+ });
53
+ return;
54
+ }
55
+ const current = authorized();
56
+ if (message.action === "status") {
57
+ await wire.send({
58
+ type: "auth-result",
59
+ session: current
60
+ ? authentication.describe(current)
61
+ : (authentication.pendingPeer(pendingToken, peer) ?? {
62
+ authenticated: false,
63
+ }),
64
+ });
65
+ return;
66
+ }
67
+ if (current || !["login", "resume", "totp"].includes(message.action))
68
+ throw new Error("当前连接无法执行此登录操作。", { cause: 400 });
69
+ const options = { scope: peer, pendingToken, signal: lifetime.signal };
70
+ const {
71
+ id,
72
+ token,
73
+ session,
74
+ pendingToken: nextPending,
75
+ } = message.action === "login"
76
+ ? await authentication.loginPeer(linkId, message, options)
77
+ : message.action === "totp"
78
+ ? await authentication.verifyPeer(linkId, message, options)
79
+ : authentication.resumePeer(linkId, message.token);
80
+ if (message.action === "resume")
81
+ authentication.cancelPeer(pendingToken, peer);
82
+ pendingToken = nextPending;
83
+ lifetime.signal.throwIfAborted();
84
+ if (id) untrack = authentication.attach(peer, id, linkId);
85
+ await wire.send({
86
+ type: "auth-result",
87
+ session,
88
+ ...(token && { token }),
89
+ });
90
+ if (id && authorized()) onAuthenticated(peer);
91
+ } catch (error) {
92
+ if (error.cause === 410) pendingToken = undefined;
93
+ if (!lifetime.signal.aborted)
94
+ await wire
95
+ .send({
96
+ type: "auth-result",
97
+ status: typeof error.cause === "number" ? error.cause : 503,
98
+ error:
99
+ typeof error.cause === "number"
100
+ ? error.message
101
+ : "登录暂不可用,请稍后重试。",
102
+ })
103
+ .catch(() => {});
104
+ } finally {
105
+ authenticating = false;
106
+ }
107
+ }
108
+
109
+ const wire = createP2pWire({
110
+ sendFrame: (frame) =>
111
+ channel.sendMessageBinary(
112
+ Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength),
113
+ ),
114
+ bufferedAmount: () => channel.bufferedAmount(),
115
+ maxInboundBytes: () => (peer.authSessionId ? undefined : 8192),
116
+ receive(message, bytes) {
117
+ if (message.type === "auth") {
118
+ if (bytes.length) peer.close();
119
+ else void authorize(message);
120
+ } else if (message.type === "rpc") {
121
+ if (authorized()) peer.emit("message", message.text);
122
+ } else http.receive(message, bytes);
123
+ },
124
+ close: peer.close,
125
+ });
126
+ const http = createPeerHttp((request, response, path) => {
127
+ if (!authorized()) return response.writeHead(401).end();
128
+ return handleBusiness(request, response, path);
129
+ }, wire);
130
+ peer.send = (text) => {
131
+ if (authorized()) wire.send({ type: "rpc", text }).catch(() => {});
132
+ };
133
+ channel.onMessage(wire.frame);
134
+ return peer;
135
+ }
@@ -0,0 +1,14 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+
5
+ export async function writePrivateFile(path, content) {
6
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
7
+ const temporary = `${path}.${randomUUID()}.tmp`;
8
+ try {
9
+ await writeFile(temporary, content, { mode: 0o600, flag: "wx" });
10
+ await rename(temporary, path);
11
+ } finally {
12
+ await rm(temporary, { force: true });
13
+ }
14
+ }
@@ -1,4 +1,4 @@
1
- export async function readTranslationInput(request) {
1
+ async function readTranslationInput(request) {
2
2
  const chunks = [];
3
3
  let size = 0;
4
4
  for await (const chunk of request) {
@@ -1,6 +1,6 @@
1
- import { mkdir, readFile, rename, writeFile, rm, stat } from "node:fs/promises";
1
+ import { readFile, stat } from "node:fs/promises";
2
2
  import { isAbsolute, join } from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { writePrivateFile } from "./private-file.mjs";
4
4
 
5
5
  // 网页项目归属与待应用目录由桥接保存;原生会话在下次恢复或开始轮次时应用目录。
6
6
  export function createThreadFolders(directory) {
@@ -36,17 +36,7 @@ export function createThreadFolders(directory) {
36
36
  folderRevision: (previous?.folderRevision || 0) + 1,
37
37
  };
38
38
  const next = { ...entries, [thread.id]: entry };
39
- await mkdir(directory, { recursive: true, mode: 0o700 });
40
- const temporary = `${path}.${randomUUID()}.tmp`;
41
- try {
42
- await writeFile(temporary, JSON.stringify(next, null, 2) + "\n", {
43
- mode: 0o600,
44
- flag: "wx",
45
- });
46
- await rename(temporary, path);
47
- } finally {
48
- await rm(temporary, { force: true });
49
- }
39
+ await writePrivateFile(path, JSON.stringify(next, null, 2) + "\n");
50
40
  entries = next;
51
41
  return { ...thread, ...entry };
52
42
  });
@@ -1,6 +1,6 @@
1
- import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
1
+ import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { writePrivateFile } from "./private-file.mjs";
4
4
  import {
5
5
  createTranslationEngine,
6
6
  ModelStore,
@@ -83,12 +83,7 @@ export function createTranslationService(
83
83
  setEnabled(enabled) {
84
84
  const operation = mutations.then(async () => {
85
85
  await initialize();
86
- await mkdir(configDir, { recursive: true, mode: 0o700 });
87
- const temporary = `${file}.${randomUUID()}.tmp`;
88
- await writeFile(temporary, JSON.stringify({ enabled }), {
89
- mode: 0o600,
90
- });
91
- await rename(temporary, file);
86
+ await writePrivateFile(file, JSON.stringify({ enabled }));
92
87
  state = { ...state, enabled, error: "" };
93
88
  if (!enabled) {
94
89
  state = { ...state, state: "disabled", progress: null };
@@ -0,0 +1,244 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import {
3
+ basename,
4
+ dirname,
5
+ isAbsolute,
6
+ join,
7
+ relative,
8
+ resolve,
9
+ } from "node:path";
10
+ import { setImmediate } from "node:timers/promises";
11
+ import fuzzysort from "fuzzysort";
12
+ import ignore from "ignore";
13
+
14
+ const RESULT_LIMIT = 60;
15
+ const SCAN_BATCH_SIZE = 32;
16
+ const SEARCH_BATCH_SIZE = 8192;
17
+ const PREPARED_BATCH_LIMIT = 4;
18
+ const INDEX_LIFETIME_MS = 5000;
19
+ const MAX_CACHED_ROOTS = 3;
20
+ const normalize = (text) => text.normalize("NFKC").toLowerCase();
21
+
22
+ async function readDirectory(root, path) {
23
+ try {
24
+ return await readdir(join(root, path), { withFileTypes: true });
25
+ } catch (error) {
26
+ // A descendant can disappear while the workspace is being indexed.
27
+ if (!path || !["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(error.code))
28
+ throw error;
29
+ return [];
30
+ }
31
+ }
32
+
33
+ function ignored(path, layers) {
34
+ let excluded = false;
35
+ for (const { base, rules } of layers) {
36
+ const result = rules.test(path.slice(base.length));
37
+ if (result.ignored || result.unignored) excluded = result.ignored;
38
+ }
39
+ return excluded;
40
+ }
41
+
42
+ async function directoryEntries(root, entry) {
43
+ const children = await readDirectory(root, entry.path);
44
+ const names = new Set(children.map(({ name }) => name));
45
+ const files = [".gitignore", ".ignore"].filter((name) => names.has(name));
46
+ const patterns = await Promise.all(
47
+ files.map((name) =>
48
+ readFile(join(root, entry.path, name), "utf8").catch((error) => {
49
+ if (error.code === "ENOENT") return "";
50
+ throw error;
51
+ }),
52
+ ),
53
+ );
54
+ const layers = files.length
55
+ ? [
56
+ ...entry.layers,
57
+ {
58
+ base: entry.path ? entry.path + "/" : "",
59
+ rules: ignore().add(patterns.join("\n")),
60
+ },
61
+ ]
62
+ : entry.layers;
63
+ return { path: entry.path, children, layers };
64
+ }
65
+
66
+ async function buildIndex(root, signal) {
67
+ const pending = [{ path: "", layers: [] }];
68
+ const batches = [];
69
+ const append = (entries) =>
70
+ batches.push(
71
+ batches.length < PREPARED_BATCH_LIMIT
72
+ ? fuzzysort.snapshot(entries, { key: "target" })
73
+ : entries,
74
+ );
75
+ let entries = [];
76
+ while (pending.length) {
77
+ signal.throwIfAborted();
78
+ const directories = pending.splice(-SCAN_BATCH_SIZE);
79
+ const contents = await Promise.all(
80
+ directories.map((entry) => directoryEntries(root, entry)),
81
+ );
82
+ for (const { path: parent, children, layers } of contents) {
83
+ for (const child of children) {
84
+ const path = parent ? parent + "/" + child.name : child.name;
85
+ const directory =
86
+ child.isDirectory() ||
87
+ (child.isSymbolicLink() &&
88
+ (await stat(join(root, path)).then(
89
+ (target) => target.isDirectory(),
90
+ () => false,
91
+ )));
92
+ if (ignored(directory ? path + "/" : path, layers)) continue;
93
+ if (child.isDirectory() && child.name !== ".git")
94
+ pending.push({ path, layers });
95
+ const name = normalize(child.name);
96
+ entries.push({
97
+ path,
98
+ file_name: child.name,
99
+ match_type: directory ? "directory" : "file",
100
+ name,
101
+ target: normalize(path),
102
+ depth: path.split("/").length,
103
+ hidden: path.startsWith(".") || path.includes("/."),
104
+ });
105
+ if (entries.length === SEARCH_BATCH_SIZE) {
106
+ append(entries);
107
+ entries = [];
108
+ }
109
+ }
110
+ }
111
+ }
112
+ if (entries.length) append(entries);
113
+ return batches;
114
+ }
115
+
116
+ function searchQuery(root, input) {
117
+ const text = input.replaceAll("\\", "/").trim();
118
+ const query = normalize(text);
119
+ if (!query) return null;
120
+ const anchored = /^(?:\/|\.\.?\/)/.test(query);
121
+ const pathQuery = query.includes("/");
122
+ const term = query.slice(query.lastIndexOf("/") + 1);
123
+ if (!term) return null;
124
+ const rooted = anchored ? relative(root, resolve(root, text)) : "";
125
+ if (anchored && (rooted === ".." || rooted.startsWith("../"))) return null;
126
+ return {
127
+ query: anchored ? normalize(rooted) : query,
128
+ term,
129
+ pathQuery,
130
+ parent: anchored ? dirname(normalize(rooted)) : null,
131
+ parentTerm: pathQuery ? basename(dirname(query)) : "",
132
+ explicitHidden: query.split("/").some((part) => /^\.[^.]/.test(part)),
133
+ };
134
+ }
135
+
136
+ function relevance(
137
+ match,
138
+ { query, term, pathQuery, parent, parentTerm, explicitHidden },
139
+ ) {
140
+ const { name, target, match_type, hidden, depth } = match.obj;
141
+ const directoryPath = pathQuery ? dirname(target) : "";
142
+ if (parent !== null && directoryPath !== parent) return 0;
143
+ const directory = match_type === "directory";
144
+ const nameMatch = fuzzysort.single(term, name);
145
+ if (!nameMatch && (pathQuery || directory)) return 0;
146
+ const stem = directory ? name : name.replace(/(?<=.)\.[^.]+$/, "");
147
+ const exactPath = target === query || target.endsWith("/" + query);
148
+ const prefixPath = ("/" + target).includes("/" + query);
149
+ const grade =
150
+ pathQuery && exactPath
151
+ ? 6
152
+ : pathQuery && prefixPath
153
+ ? 5
154
+ : name === term || stem === term
155
+ ? 4
156
+ : name.startsWith(term)
157
+ ? 3
158
+ : nameMatch
159
+ ? 2
160
+ : 1;
161
+ const parentMatch =
162
+ parentTerm && fuzzysort.single(parentTerm, basename(directoryPath));
163
+ const quality = pathQuery
164
+ ? 0.45 * (parentMatch?.score || 0) +
165
+ 0.35 * nameMatch.score +
166
+ 0.2 * match.score
167
+ : (nameMatch?.score ?? match.score);
168
+ return (
169
+ ((directory ? 16 : 0) +
170
+ (explicitHidden || !hidden ? 8 : 0) +
171
+ grade +
172
+ quality * 0.8 +
173
+ 0.15 / depth) /
174
+ 32
175
+ );
176
+ }
177
+
178
+ export function createFileSearch() {
179
+ const controller = new AbortController();
180
+ const indexes = new Map();
181
+
182
+ function index(root) {
183
+ const now = Date.now();
184
+ let entry = indexes.get(root);
185
+ if (!entry || entry.expires <= now) {
186
+ entry = { expires: Infinity };
187
+ const current = entry;
188
+ entry.batches = buildIndex(root, controller.signal).then(
189
+ (batches) => {
190
+ current.expires = Date.now() + INDEX_LIFETIME_MS;
191
+ return batches;
192
+ },
193
+ (error) => {
194
+ if (indexes.get(root) === current) indexes.delete(root);
195
+ throw error;
196
+ },
197
+ );
198
+ }
199
+ indexes.delete(root);
200
+ indexes.set(root, entry);
201
+ if (indexes.size > MAX_CACHED_ROOTS)
202
+ indexes.delete(indexes.keys().next().value);
203
+ return entry.batches;
204
+ }
205
+
206
+ return {
207
+ async search({ roots, query }) {
208
+ if (
209
+ typeof query !== "string" ||
210
+ !Array.isArray(roots) ||
211
+ !roots.every((root) => typeof root === "string" && isAbsolute(root))
212
+ )
213
+ throw new Error("文件搜索需要关键词和绝对工作目录");
214
+ const matches = [];
215
+ for (const root of new Set(roots.map((path) => resolve(path)))) {
216
+ const request = searchQuery(root, query);
217
+ if (!request) continue;
218
+ for (const batch of await index(root)) {
219
+ await setImmediate(undefined, { signal: controller.signal });
220
+ const results = fuzzysort.go(request.query, batch, {
221
+ ...(Array.isArray(batch) && { key: "target" }),
222
+ threshold: 0,
223
+ limit: RESULT_LIMIT,
224
+ scoreFn: (match) => relevance(match, request),
225
+ });
226
+ for (const {
227
+ obj: { path, file_name, match_type },
228
+ score,
229
+ } of results)
230
+ matches.push({ root, path, file_name, match_type, score });
231
+ if (Array.isArray(batch)) fuzzysort.cleanup();
232
+ }
233
+ }
234
+ fuzzysort.cleanup();
235
+ matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
236
+ return { files: matches.slice(0, RESULT_LIMIT), ranked: true };
237
+ },
238
+ close() {
239
+ controller.abort();
240
+ indexes.clear();
241
+ fuzzysort.cleanup();
242
+ },
243
+ };
244
+ }