@evandu/super-pi 0.1.223 → 0.1.225
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/dist/client/.super-pi-client-sources.json +12 -8
- package/dist/client/assets/{CodeMirrorEditor-Due3YL4A.js → CodeMirrorEditor-OLbwCzUh.js} +2 -2
- package/dist/client/assets/{dist-B3qtMidG.js → dist-BQImRXFO.js} +1 -1
- package/dist/client/assets/{dist-BJ5mZEGq.js → dist-BUOU8RAm.js} +1 -1
- package/dist/client/assets/{dist-BZGq856v.js → dist-BdrKprbZ.js} +1 -1
- package/dist/client/assets/{dist-DCVXoyno.js → dist-BffuhHE1.js} +1 -1
- package/dist/client/assets/{dist-B2XX-bBx.js → dist-C8-e07vM.js} +1 -1
- package/dist/client/assets/{dist-2kMlRtqo.js → dist-C8naDDXu.js} +1 -1
- package/dist/client/assets/{dist-JSFnHR0P.js → dist-C9f0Riun.js} +1 -1
- package/dist/client/assets/{dist-1hXEE44f.js → dist-CB9Qr9C6.js} +1 -1
- package/dist/client/assets/{dist-DSCSHwdP.js → dist-CIEDxNn7.js} +1 -1
- package/dist/client/assets/{dist-CRrYz-2t.js → dist-CIsUvpC9.js} +1 -1
- package/dist/client/assets/{dist-BHlGN5Cp.js → dist-CKA2u-s7.js} +1 -1
- package/dist/client/assets/{dist-D2n9-vIx.js → dist-COIAnYiN.js} +1 -1
- package/dist/client/assets/{dist-BvUexO6W.js → dist-CXpar2cD.js} +1 -1
- package/dist/client/assets/{dist-CMws1R9h.js → dist-CZu3CzDX.js} +1 -1
- package/dist/client/assets/{dist-BJ_pU8qp.js → dist-CaePDjkH.js} +1 -1
- package/dist/client/assets/{dist-CA52X7jm.js → dist-Cro2exEx.js} +1 -1
- package/dist/client/assets/{dist-BXTbngmK.js → dist-CxJkT0iM.js} +1 -1
- package/dist/client/assets/{dist-BaUqm3zx.js → dist-D53uN01l.js} +1 -1
- package/dist/client/assets/{dist-DOJKt6Px.js → dist-D9kySnbi.js} +1 -1
- package/dist/client/assets/{dist-Cw21UX77.js → dist-MARoODS1.js} +1 -1
- package/dist/client/assets/{dist-Po3GdueN.js → dist-ot9lBE7N.js} +1 -1
- package/dist/client/assets/{dist-CQIMZ_7M.js → dist-sv2AtsDR.js} +1 -1
- package/dist/client/assets/index-B0m5CXCB.js +105 -0
- package/dist/client/assets/index-DK_mME9e.css +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/application/extension-ui-service.d.ts +6 -1
- package/dist/server/application/extension-ui-service.js +31 -2
- package/dist/server/application/run-service.d.ts +4 -1
- package/dist/server/application/run-service.js +102 -35
- package/dist/server/command-handler.js +11 -2
- package/dist/server/exec-service.d.ts +5 -2
- package/dist/server/exec-service.js +12 -2
- package/dist/server/file-index.d.ts +13 -1
- package/dist/server/file-index.js +108 -12
- package/dist/server/file-name-index.d.ts +8 -0
- package/dist/server/file-name-index.js +58 -11
- package/dist/server/files.js +4 -0
- package/dist/server/http-server.js +182 -25
- package/dist/server/index.js +14 -9
- package/dist/server/persistence/app-state-repository.d.ts +3 -1
- package/dist/server/persistence/sqlite-state-repository.js +14 -1
- package/dist/server/session-cwd.d.ts +2 -0
- package/dist/server/session-cwd.js +16 -1
- package/dist/server/store.d.ts +1 -0
- package/dist/server/store.js +49 -12
- package/dist/server/terminal.d.ts +26 -76
- package/dist/server/terminal.js +239 -172
- package/dist/server/tool-llm.d.ts +7 -0
- package/dist/server/tool-llm.js +8 -1
- package/dist/server/tool-runner.d.ts +7 -0
- package/dist/server/tool-runner.js +8 -1
- package/dist/server/types.d.ts +27 -75
- package/dist/server/workspace-file-indexes.d.ts +2 -0
- package/dist/server/workspace-file-indexes.js +61 -0
- package/dist/server/workspace-file-operations.d.ts +36 -0
- package/dist/server/workspace-file-operations.js +281 -0
- package/dist/server/workspace-file-response.d.ts +3 -0
- package/dist/server/workspace-file-response.js +79 -0
- package/dist/server/ws-server.d.ts +7 -12
- package/dist/server/ws-server.js +23 -18
- package/dist/shared/terminal-protocol.d.ts +71 -0
- package/dist/shared/terminal-protocol.js +1 -0
- package/dist/shared/workspace-file-preview.d.ts +4 -0
- package/dist/shared/workspace-file-preview.js +28 -0
- package/package.json +2 -1
- package/dist/client/assets/index-DHdzZ1mf.js +0 -103
- package/dist/client/assets/index-OmaD3l6r.css +0 -1
package/dist/server/types.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export type ModelFilterRule = {
|
|
|
7
7
|
import type { WorkflowRun } from "./workflow.js";
|
|
8
8
|
import type { ScheduledTask } from "./scheduled-tasks.js";
|
|
9
9
|
import type { ThinkingLevelMap } from "../shared/thinking-levels.js";
|
|
10
|
+
import type { TerminalCommand, TerminalEvent } from "../shared/terminal-protocol.js";
|
|
10
11
|
/**
|
|
11
12
|
* The lifecycle states a `Conversation.status` moves through while a turn is in flight. `waiting` is the
|
|
12
13
|
* gap between "prompt handed to the LLM" and "the first response token arrived" - holding it apart from
|
|
@@ -492,6 +493,8 @@ export type Conversation = {
|
|
|
492
493
|
status: RunStatus;
|
|
493
494
|
messages: Message[];
|
|
494
495
|
archivedAt?: string;
|
|
496
|
+
/** Private receipts retained even when a message is withdrawn or cut from history. */
|
|
497
|
+
acceptedSendIds?: string[];
|
|
495
498
|
warmSession?: true;
|
|
496
499
|
/**
|
|
497
500
|
* Cumulative usage observed for this conversation: its OWN assistant messages AND the one-shot
|
|
@@ -1232,6 +1235,12 @@ export type ProjectSummary = {
|
|
|
1232
1235
|
updatedAt: string;
|
|
1233
1236
|
};
|
|
1234
1237
|
export type AppState = {
|
|
1238
|
+
extensionUi?: {
|
|
1239
|
+
conversationId: string;
|
|
1240
|
+
request: ExtensionUiRequest;
|
|
1241
|
+
}[];
|
|
1242
|
+
stoppingConversationIds?: string[];
|
|
1243
|
+
sendReceipts?: true;
|
|
1235
1244
|
modelFilterRules?: ModelFilterRule[];
|
|
1236
1245
|
defaultModel?: ModelSelection;
|
|
1237
1246
|
terminalShell?: TerminalShell;
|
|
@@ -1244,11 +1253,11 @@ export type AppState = {
|
|
|
1244
1253
|
scheduledTasks?: ScheduledTask[];
|
|
1245
1254
|
projects?: Project[];
|
|
1246
1255
|
customAgentDirs?: string[]; /**
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1256
|
+
* Which conversations the reader has collapsed in the sidebar's session tree, by conversation id.
|
|
1257
|
+
* Server-side so the tree looks the same after a restart and on another machine - the sidebar is a
|
|
1258
|
+
* view of the PRODUCT's state, not of one browser's session. Absent (older state.json) means
|
|
1259
|
+
* "nothing collapsed", which is the correct reading of a preference that did not exist yet.
|
|
1260
|
+
*/
|
|
1252
1261
|
collapsedConversationIds?: string[];
|
|
1253
1262
|
/**
|
|
1254
1263
|
* WHICH CHILD SESSIONS THE READER HAS UNLOCKED, by conversation id.
|
|
@@ -1353,6 +1362,7 @@ export type ExtensionUiNotifyType = "info" | "warning" | "error";
|
|
|
1353
1362
|
export type ExtensionUiPlacement = "aboveEditor" | "belowEditor";
|
|
1354
1363
|
/** One normalized `extension_ui_request`. The method-specific fields are only present for methods that send them. */
|
|
1355
1364
|
export type ExtensionUiRequest = {
|
|
1365
|
+
deadlineAt?: number;
|
|
1356
1366
|
requestId: string;
|
|
1357
1367
|
method: ExtensionUiMethod;
|
|
1358
1368
|
/** True when Pi is blocked until the host answers. False means "display it, never ask the user to reply". */
|
|
@@ -1401,41 +1411,7 @@ export type ClientCommandBody =
|
|
|
1401
1411
|
callIndex: number;
|
|
1402
1412
|
answers?: QuestionAnswer[];
|
|
1403
1413
|
cancelled?: boolean;
|
|
1404
|
-
}
|
|
1405
|
-
/**
|
|
1406
|
-
* THE TERMINAL, and the reason `terminal.open` CARRIES NO PATH.
|
|
1407
|
-
*
|
|
1408
|
-
* Every other command in this union that names a location lets the browser supply it. This one does
|
|
1409
|
-
* not: it carries a workspace ID, and the server resolves that ID to a directory it already trusts
|
|
1410
|
-
* (`terminal.ts`). A browser that asked for `C:\Windows` gets a refusal, because there is no field on
|
|
1411
|
-
* this command for it to arrive in. That is the difference between a shell scoped to the workspaces
|
|
1412
|
-
* the user already configured and a shell scoped to the whole disk, and it is structural rather than a
|
|
1413
|
-
* check that a later edit could forget.
|
|
1414
|
-
*/
|
|
1415
|
-
| {
|
|
1416
|
-
type: "terminal.open";
|
|
1417
|
-
sessionId: string;
|
|
1418
|
-
workspaceId: string;
|
|
1419
|
-
cwd?: string;
|
|
1420
|
-
cols?: number;
|
|
1421
|
-
rows?: number;
|
|
1422
|
-
}
|
|
1423
|
-
/** Keystrokes and pasted text, as the RAW bytes a terminal would receive. */
|
|
1424
|
-
| {
|
|
1425
|
-
type: "terminal.input";
|
|
1426
|
-
sessionId: string;
|
|
1427
|
-
data: string;
|
|
1428
|
-
}
|
|
1429
|
-
/** The panel's measured character grid, so reflowed text reflows in the shell rather than wrapping twice. */
|
|
1430
|
-
| {
|
|
1431
|
-
type: "terminal.resize";
|
|
1432
|
-
sessionId: string;
|
|
1433
|
-
cols: number;
|
|
1434
|
-
rows: number;
|
|
1435
|
-
} | {
|
|
1436
|
-
type: "terminal.close";
|
|
1437
|
-
sessionId: string;
|
|
1438
|
-
} | {
|
|
1414
|
+
} | TerminalCommand | {
|
|
1439
1415
|
type: "terminal.shell.set";
|
|
1440
1416
|
command: string | null;
|
|
1441
1417
|
} | {
|
|
@@ -2008,6 +1984,10 @@ export type ChangedFile = {
|
|
|
2008
1984
|
at: number;
|
|
2009
1985
|
};
|
|
2010
1986
|
export type ServerEvent = {
|
|
1987
|
+
type: "message.accepted";
|
|
1988
|
+
conversationId: string;
|
|
1989
|
+
clientId: string;
|
|
1990
|
+
} | {
|
|
2011
1991
|
type: "run.stopping";
|
|
2012
1992
|
conversationId: string;
|
|
2013
1993
|
} | {
|
|
@@ -2036,6 +2016,10 @@ export type ServerEvent = {
|
|
|
2036
2016
|
workspaceId: string;
|
|
2037
2017
|
changes: ChangedFile[];
|
|
2038
2018
|
dropped: number;
|
|
2019
|
+
} | {
|
|
2020
|
+
type: "files.invalidated";
|
|
2021
|
+
workspaceId: string;
|
|
2022
|
+
paths?: string[];
|
|
2039
2023
|
} | {
|
|
2040
2024
|
type: "files.index";
|
|
2041
2025
|
workspaceId: string;
|
|
@@ -2269,41 +2253,7 @@ export type ServerEvent = {
|
|
|
2269
2253
|
role: "user" | "tool";
|
|
2270
2254
|
}[];
|
|
2271
2255
|
actor: "user" | "agent";
|
|
2272
|
-
}
|
|
2273
|
-
/**
|
|
2274
|
-
* Bytes from a terminal shell, as ONE event per coalescing window rather than one per `onData` call.
|
|
2275
|
-
*
|
|
2276
|
-
* `data` is RAW, including escape sequences, and is deliberately NOT modelled as a buffer of lines:
|
|
2277
|
-
* the point of `node-pty` is that the shell knows it is attached to a TTY, so it emits colours,
|
|
2278
|
-
* cursor moves and redraws that a line buffer cannot represent. The client owns rendering them.
|
|
2279
|
-
*
|
|
2280
|
-
* A failed spawn is a separate `terminal.error` rather than a `terminal.exit`, because a shell that
|
|
2281
|
-
* refused to start is a configuration problem the user must read, and an exit code would let them
|
|
2282
|
-
* scroll past it.
|
|
2283
|
-
*/
|
|
2284
|
-
| {
|
|
2285
|
-
type: "terminal.output";
|
|
2286
|
-
sessionId: string;
|
|
2287
|
-
data: string;
|
|
2288
|
-
}
|
|
2289
|
-
/** The shell ended. `exitCode` is 0 whenever the server killed the session - see `terminal.ts`. */
|
|
2290
|
-
| {
|
|
2291
|
-
type: "terminal.exit";
|
|
2292
|
-
sessionId: string;
|
|
2293
|
-
exitCode: number;
|
|
2294
|
-
}
|
|
2295
|
-
/** A refused command, with a sentence naming WHICH gate refused it. */
|
|
2296
|
-
| {
|
|
2297
|
-
type: "terminal.error";
|
|
2298
|
-
sessionId: string;
|
|
2299
|
-
message: string;
|
|
2300
|
-
}
|
|
2301
|
-
/** Whether the terminal exists at all, and if not, why. Sent on a refused command. */
|
|
2302
|
-
| {
|
|
2303
|
-
type: "terminal.status";
|
|
2304
|
-
enabled: boolean;
|
|
2305
|
-
reason?: string;
|
|
2306
|
-
}
|
|
2256
|
+
} | TerminalEvent
|
|
2307
2257
|
/**
|
|
2308
2258
|
* Output from a background exec session. Forwarded to the browser so it can stream to the terminal panel
|
|
2309
2259
|
* if that session is visible, and collected by the exec service for the final result.
|
|
@@ -2311,7 +2261,9 @@ export type ServerEvent = {
|
|
|
2311
2261
|
| {
|
|
2312
2262
|
type: "exec.output";
|
|
2313
2263
|
sessionId: string;
|
|
2264
|
+
conversationId?: string;
|
|
2314
2265
|
data: string;
|
|
2266
|
+
replace?: boolean;
|
|
2315
2267
|
}
|
|
2316
2268
|
/**
|
|
2317
2269
|
* A background exec session ended. `stdout` and `stderr` are the collected output; the exec service
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { ServerContext } from "./server-context.js";
|
|
2
|
+
export declare function updateExplorerIndexes(context: Pick<ServerContext, "fileIndexes" | "nameIndexes">, workspaceId: string, workspaceRoot: string, path: string, previousPath: string | undefined, directory: boolean, removed: boolean): Promise<void>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises";
|
|
2
|
+
import { belowPath, inScope } from "./file-index.js";
|
|
3
|
+
import { createRootGuard } from "./files.js";
|
|
4
|
+
import { explorerInternalPath } from "./workspace-file-operations.js";
|
|
5
|
+
export async function updateExplorerIndexes(context, workspaceId, workspaceRoot, path, previousPath, directory, removed) {
|
|
6
|
+
const files = [...(context.fileIndexes?.values() ?? [])].filter(index => index.workspaceId === workspaceId);
|
|
7
|
+
const names = [...(context.nameIndexes?.values() ?? [])].filter(index => index.workspaceId === workspaceId);
|
|
8
|
+
if (!files.length && !names.length)
|
|
9
|
+
return;
|
|
10
|
+
if (previousPath !== undefined) {
|
|
11
|
+
for (const index of [...files, ...names]) {
|
|
12
|
+
const scoped = inScope(workspaceRoot, index.cwd, previousPath);
|
|
13
|
+
if (scoped !== undefined)
|
|
14
|
+
index.removeTree(scoped);
|
|
15
|
+
else if (belowPath(index.cwd, previousPath))
|
|
16
|
+
index.removeTree("");
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
if (removed)
|
|
20
|
+
return;
|
|
21
|
+
if (!directory) {
|
|
22
|
+
for (const index of names) {
|
|
23
|
+
const scoped = inScope(workspaceRoot, index.cwd, path);
|
|
24
|
+
if (scoped)
|
|
25
|
+
index.upsert(scoped);
|
|
26
|
+
}
|
|
27
|
+
await Promise.all(files.map(index => {
|
|
28
|
+
const scoped = inScope(workspaceRoot, index.cwd, path);
|
|
29
|
+
return scoped ? index.refresh(scoped) : undefined;
|
|
30
|
+
}));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const guard = createRootGuard(workspaceRoot);
|
|
34
|
+
const folders = [path];
|
|
35
|
+
const entries = [{ path, kind: "directory" }];
|
|
36
|
+
for (let cursor = 0; cursor < folders.length && cursor < 4000 && entries.length < 30000; cursor += 1) {
|
|
37
|
+
const folder = folders[cursor];
|
|
38
|
+
const children = await guard(folder).then(absolute => readdir(absolute, { withFileTypes: true })).catch(() => []);
|
|
39
|
+
for (const child of children) {
|
|
40
|
+
const childPath = `${folder}/${child.name}`;
|
|
41
|
+
if (explorerInternalPath(childPath) || (!child.isDirectory() && !child.isFile()))
|
|
42
|
+
continue;
|
|
43
|
+
entries.push({ path: childPath, kind: child.isDirectory() ? "directory" : "file" });
|
|
44
|
+
if (child.isDirectory())
|
|
45
|
+
folders.push(childPath);
|
|
46
|
+
if (entries.length >= 30000)
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const index of names)
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
const scoped = inScope(workspaceRoot, index.cwd, entry.path);
|
|
53
|
+
if (scoped)
|
|
54
|
+
index.upsert(scoped, entry.kind);
|
|
55
|
+
}
|
|
56
|
+
for (const index of files)
|
|
57
|
+
index.recordEntries(entries.flatMap(entry => {
|
|
58
|
+
const scoped = inScope(workspaceRoot, index.cwd, entry.path);
|
|
59
|
+
return scoped ? [{ ...entry, path: scoped }] : [];
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
declare const MAX_INITIAL_CONTENT: number;
|
|
2
|
+
export declare function serializeWorkspaceWrite<T>(workspace: string, work: () => Promise<T>): Promise<T>;
|
|
3
|
+
export type FileTreeMutation = {
|
|
4
|
+
path: string;
|
|
5
|
+
previousPath?: string;
|
|
6
|
+
removed?: boolean;
|
|
7
|
+
directory?: boolean;
|
|
8
|
+
text?: boolean;
|
|
9
|
+
trashId?: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function explorerInternalPath(path: string): boolean;
|
|
12
|
+
export declare function explorerPath(workspace: string, root: string, path: string, allowRoot?: boolean): Promise<string>;
|
|
13
|
+
export declare function listWorkspaceTrash(workspace: string, root: string): Promise<{
|
|
14
|
+
deletedAt: string;
|
|
15
|
+
directory: boolean;
|
|
16
|
+
id: string;
|
|
17
|
+
path: string;
|
|
18
|
+
}[]>;
|
|
19
|
+
export declare function mutateWorkspaceTree(workspace: string, root: string, body: Record<string, unknown>): Promise<FileTreeMutation>;
|
|
20
|
+
export declare function inspectWorkspaceUpload(workspace: string, root: string, parent: string, name: string): Promise<{
|
|
21
|
+
exists: boolean;
|
|
22
|
+
replaceable?: undefined;
|
|
23
|
+
meta?: undefined;
|
|
24
|
+
} | {
|
|
25
|
+
exists: boolean;
|
|
26
|
+
replaceable: boolean;
|
|
27
|
+
meta?: undefined;
|
|
28
|
+
} | {
|
|
29
|
+
exists: boolean;
|
|
30
|
+
replaceable: boolean;
|
|
31
|
+
meta: import("./files.js").FileMeta;
|
|
32
|
+
}>;
|
|
33
|
+
export declare function uploadWorkspaceFile(workspace: string, root: string, parent: string, name: string, bytes: Buffer, baseEtag?: string): Promise<{
|
|
34
|
+
path: string;
|
|
35
|
+
}>;
|
|
36
|
+
export { MAX_INITIAL_CONTENT as MAX_WORKSPACE_UPLOAD_BYTES };
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, mkdirSync, renameSync, rmdirSync, unlinkSync, linkSync } from "node:fs";
|
|
3
|
+
import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { contains, fileMeta, FilesError, isTextName, resolveInsideRoot, toRelative } from "./files.js";
|
|
6
|
+
const TRASH_DIRECTORY = ".super-pi/file-trash";
|
|
7
|
+
const MAX_INITIAL_CONTENT = 32 * 1024 * 1024;
|
|
8
|
+
const trashIdFormat = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
9
|
+
const writeQueues = new Map();
|
|
10
|
+
export async function serializeWorkspaceWrite(workspace, work) {
|
|
11
|
+
const key = await realpath(workspace);
|
|
12
|
+
const previous = writeQueues.get(key) ?? Promise.resolve();
|
|
13
|
+
const next = previous.catch(() => { }).then(work);
|
|
14
|
+
writeQueues.set(key, next);
|
|
15
|
+
try {
|
|
16
|
+
return await next;
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
if (writeQueues.get(key) === next)
|
|
20
|
+
writeQueues.delete(key);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function stringField(body, key) {
|
|
24
|
+
const value = body[key];
|
|
25
|
+
if (typeof value !== "string")
|
|
26
|
+
throw new FilesError(400, `需要 ${key}。`, "bad_request");
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function isMissing(error) {
|
|
30
|
+
const code = error.code;
|
|
31
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
32
|
+
}
|
|
33
|
+
export function explorerInternalPath(path) {
|
|
34
|
+
const normalized = path.toLowerCase();
|
|
35
|
+
return normalized === TRASH_DIRECTORY || normalized.startsWith(`${TRASH_DIRECTORY}/`);
|
|
36
|
+
}
|
|
37
|
+
function validateName(name) {
|
|
38
|
+
if (!name || name !== name.trim() || name.endsWith(".") || /[<>:"/\\|?*\u0000-\u001f]/.test(name)
|
|
39
|
+
|| /^(con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(name)) {
|
|
40
|
+
throw new FilesError(400, "文件名包含不受支持的字符或保留名称。", "invalid_name");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export async function explorerPath(workspace, root, path, allowRoot = false) {
|
|
44
|
+
const target = await resolveInsideRoot(root, path);
|
|
45
|
+
const rel = toRelative(workspace, target);
|
|
46
|
+
if ((!allowRoot && root === target) || explorerInternalPath(rel)) {
|
|
47
|
+
throw new FilesError(403, "不能操作工作目录本身或应用的回收目录。", "protected_path");
|
|
48
|
+
}
|
|
49
|
+
const canonicalRoot = await realpath(workspace);
|
|
50
|
+
for (let ancestor = target; contains(workspace, ancestor); ancestor = dirname(ancestor)) {
|
|
51
|
+
const existing = await realpath(ancestor).catch((error) => { if (!isMissing(error))
|
|
52
|
+
throw error; });
|
|
53
|
+
if (!existing)
|
|
54
|
+
continue;
|
|
55
|
+
if (explorerInternalPath(toRelative(canonicalRoot, existing)))
|
|
56
|
+
throw new FilesError(403, "不能直接访问应用的回收目录。", "protected_path");
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
return target;
|
|
60
|
+
}
|
|
61
|
+
async function targetAt(workspace, root, parent, name) {
|
|
62
|
+
validateName(name);
|
|
63
|
+
const directory = await explorerPath(workspace, root, parent, true);
|
|
64
|
+
if (!(await stat(directory).catch(() => undefined))?.isDirectory()) {
|
|
65
|
+
throw new FilesError(404, "目标文件夹已不存在。", "missing_directory");
|
|
66
|
+
}
|
|
67
|
+
return explorerPath(workspace, root, toRelative(root, join(directory, name)));
|
|
68
|
+
}
|
|
69
|
+
async function entryInfo(path) {
|
|
70
|
+
const info = await lstat(path).catch((error) => {
|
|
71
|
+
if (isMissing(error))
|
|
72
|
+
throw new FilesError(404, "文件或目录已不存在。", "missing");
|
|
73
|
+
throw error;
|
|
74
|
+
});
|
|
75
|
+
if (!info.isFile() && !info.isDirectory())
|
|
76
|
+
throw new FilesError(415, "此操作只支持普通文件和目录。", "unsupported_entry");
|
|
77
|
+
return info;
|
|
78
|
+
}
|
|
79
|
+
function moveWithoutReplacing(source, destination, directory) {
|
|
80
|
+
try {
|
|
81
|
+
lstatSync(destination);
|
|
82
|
+
throw new FilesError(409, "目标名称已存在。", "already_exists");
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (!isMissing(error))
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
if (directory) {
|
|
89
|
+
if (process.platform === "win32")
|
|
90
|
+
renameSync(source, destination);
|
|
91
|
+
else {
|
|
92
|
+
mkdirSync(destination);
|
|
93
|
+
try {
|
|
94
|
+
renameSync(source, destination);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
try {
|
|
98
|
+
rmdirSync(destination);
|
|
99
|
+
}
|
|
100
|
+
catch { /* The original error describes the failed move. */ }
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
linkSync(source, destination);
|
|
107
|
+
try {
|
|
108
|
+
unlinkSync(source);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
unlinkSync(destination);
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function trashRoot(workspace, create) {
|
|
116
|
+
const path = await resolveInsideRoot(workspace, TRASH_DIRECTORY);
|
|
117
|
+
const parent = dirname(path);
|
|
118
|
+
if (create) {
|
|
119
|
+
await mkdir(parent).catch((error) => { if (error.code !== "EEXIST")
|
|
120
|
+
throw error; });
|
|
121
|
+
if (!(await lstat(parent)).isDirectory())
|
|
122
|
+
throw new FilesError(403, "无法使用回收目录。", "protected_path");
|
|
123
|
+
await mkdir(path).catch((error) => { if (error.code !== "EEXIST")
|
|
124
|
+
throw error; });
|
|
125
|
+
}
|
|
126
|
+
for (const entry of [parent, path]) {
|
|
127
|
+
const info = await lstat(entry).catch((error) => { if (!isMissing(error))
|
|
128
|
+
throw error; });
|
|
129
|
+
if (info && !info.isDirectory())
|
|
130
|
+
throw new FilesError(403, "无法使用回收目录。", "protected_path");
|
|
131
|
+
}
|
|
132
|
+
return path;
|
|
133
|
+
}
|
|
134
|
+
async function readTrashRecord(workspace, directory, id) {
|
|
135
|
+
if (!trashIdFormat.test(id))
|
|
136
|
+
throw new FilesError(400, "无效的回收项。", "bad_request");
|
|
137
|
+
const entry = join(directory, id);
|
|
138
|
+
const metadata = await resolveInsideRoot(workspace, toRelative(workspace, join(entry, "record.json")));
|
|
139
|
+
if (!(await lstat(entry)).isDirectory() || !(await lstat(metadata)).isFile()) {
|
|
140
|
+
throw new FilesError(404, "回收项已不存在。", "missing");
|
|
141
|
+
}
|
|
142
|
+
const record = JSON.parse(await readFile(metadata, "utf8"));
|
|
143
|
+
if (typeof record.path !== "string" || typeof record.deletedAt !== "string" || typeof record.directory !== "boolean") {
|
|
144
|
+
throw new FilesError(400, "回收记录无效。", "bad_request");
|
|
145
|
+
}
|
|
146
|
+
return record;
|
|
147
|
+
}
|
|
148
|
+
export async function listWorkspaceTrash(workspace, root) {
|
|
149
|
+
const directory = await trashRoot(workspace, false);
|
|
150
|
+
const ids = await readdir(directory).catch((error) => { if (isMissing(error))
|
|
151
|
+
return []; throw error; });
|
|
152
|
+
const records = await Promise.all(ids.filter(id => trashIdFormat.test(id)).map(async (id) => {
|
|
153
|
+
try {
|
|
154
|
+
const record = await readTrashRecord(workspace, directory, id);
|
|
155
|
+
const target = await resolveInsideRoot(workspace, record.path);
|
|
156
|
+
if (target === root || !contains(root, target))
|
|
157
|
+
return;
|
|
158
|
+
await entryInfo(join(directory, id, "item"));
|
|
159
|
+
return { id, ...record, path: toRelative(root, target) };
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
}));
|
|
165
|
+
return records.filter(record => record !== undefined).sort((a, b) => b.deletedAt.localeCompare(a.deletedAt));
|
|
166
|
+
}
|
|
167
|
+
export async function mutateWorkspaceTree(workspace, root, body) {
|
|
168
|
+
if (body.action === "restore") {
|
|
169
|
+
const id = stringField(body, "id");
|
|
170
|
+
const directory = await trashRoot(workspace, false);
|
|
171
|
+
const record = await readTrashRecord(workspace, directory, id);
|
|
172
|
+
const rooted = await resolveInsideRoot(workspace, record.path);
|
|
173
|
+
if (!contains(root, rooted))
|
|
174
|
+
throw new FilesError(403, "回收项属于另一个目录。", "outside_workspace");
|
|
175
|
+
const path = await explorerPath(workspace, root, toRelative(root, rooted));
|
|
176
|
+
const source = join(directory, id, "item");
|
|
177
|
+
const info = await entryInfo(source);
|
|
178
|
+
moveWithoutReplacing(source, path, info.isDirectory());
|
|
179
|
+
await rm(join(directory, id, "record.json"), { force: true }).catch(() => { });
|
|
180
|
+
await rmdir(join(directory, id)).catch(() => { });
|
|
181
|
+
return { path: toRelative(root, path), directory: info.isDirectory() };
|
|
182
|
+
}
|
|
183
|
+
if (body.action === "create-file" || body.action === "create-directory") {
|
|
184
|
+
const path = await targetAt(workspace, root, stringField(body, "parent"), stringField(body, "name"));
|
|
185
|
+
const directory = body.action === "create-directory";
|
|
186
|
+
if (directory)
|
|
187
|
+
await mkdir(path);
|
|
188
|
+
else
|
|
189
|
+
await writeFile(path, "", { flag: "wx" });
|
|
190
|
+
return { path: toRelative(root, path), directory, ...(directory ? {} : { text: isTextName(path) }) };
|
|
191
|
+
}
|
|
192
|
+
if (body.action !== "move" && body.action !== "trash")
|
|
193
|
+
throw new FilesError(400, "未知的文件操作。", "bad_request");
|
|
194
|
+
const source = await explorerPath(workspace, root, stringField(body, "path"));
|
|
195
|
+
const info = await entryInfo(source);
|
|
196
|
+
const directory = info.isDirectory();
|
|
197
|
+
const previousPath = toRelative(root, source);
|
|
198
|
+
if (body.action === "trash") {
|
|
199
|
+
// Keep the item and its recovery metadata on the same filesystem.
|
|
200
|
+
if (contains(source, join(workspace, TRASH_DIRECTORY)))
|
|
201
|
+
throw new FilesError(403, "该目录包含回收空间。", "protected_path");
|
|
202
|
+
const trash = await trashRoot(workspace, true);
|
|
203
|
+
const id = randomUUID();
|
|
204
|
+
const entry = join(trash, id);
|
|
205
|
+
await mkdir(entry);
|
|
206
|
+
try {
|
|
207
|
+
const record = { path: toRelative(workspace, source), deletedAt: new Date().toISOString(), directory };
|
|
208
|
+
await writeFile(join(entry, "record.json"), JSON.stringify(record), { flag: "wx" });
|
|
209
|
+
await rename(source, join(entry, "item"));
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
await rm(join(entry, "record.json"), { force: true }).catch(() => { });
|
|
213
|
+
await rmdir(entry).catch(() => { });
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
return { path: previousPath, removed: true, directory, trashId: id };
|
|
217
|
+
}
|
|
218
|
+
const destination = await targetAt(workspace, root, stringField(body, "parent"), stringField(body, "name"));
|
|
219
|
+
if (source === destination)
|
|
220
|
+
return { path: previousPath, directory };
|
|
221
|
+
if (contains(source, join(workspace, TRASH_DIRECTORY)))
|
|
222
|
+
throw new FilesError(403, "该目录包含回收空间。", "protected_path");
|
|
223
|
+
if (process.platform === "win32" && source.toLowerCase() === destination.toLowerCase()) {
|
|
224
|
+
const stage = await mkdtemp(join(dirname(source), ".super-pi-rename-"));
|
|
225
|
+
const parked = join(stage, basename(source));
|
|
226
|
+
try {
|
|
227
|
+
renameSync(source, parked);
|
|
228
|
+
try {
|
|
229
|
+
moveWithoutReplacing(parked, destination, directory);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
moveWithoutReplacing(parked, source, directory);
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
await rmdir(stage).catch(() => { });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
if (directory && contains(source, destination))
|
|
242
|
+
throw new FilesError(400, "不能把目录移到其子目录中。", "invalid_destination");
|
|
243
|
+
moveWithoutReplacing(source, destination, directory);
|
|
244
|
+
}
|
|
245
|
+
return { path: toRelative(root, destination), previousPath, directory, ...(directory ? {} : { text: isTextName(destination) }) };
|
|
246
|
+
}
|
|
247
|
+
export async function inspectWorkspaceUpload(workspace, root, parent, name) {
|
|
248
|
+
const path = await targetAt(workspace, root, parent, name);
|
|
249
|
+
const info = await lstat(path).catch((error) => { if (!isMissing(error))
|
|
250
|
+
throw error; });
|
|
251
|
+
if (!info)
|
|
252
|
+
return { exists: false };
|
|
253
|
+
if (!info.isFile())
|
|
254
|
+
return { exists: true, replaceable: false };
|
|
255
|
+
return { exists: true, replaceable: true, meta: await fileMeta(path) };
|
|
256
|
+
}
|
|
257
|
+
export async function uploadWorkspaceFile(workspace, root, parent, name, bytes, baseEtag) {
|
|
258
|
+
if (bytes.length > MAX_INITIAL_CONTENT)
|
|
259
|
+
throw new FilesError(413, "单个文件不能超过 32 MB。", "too_large");
|
|
260
|
+
const destination = await targetAt(workspace, root, parent, name);
|
|
261
|
+
const stage = await mkdtemp(join(dirname(destination), ".super-pi-upload-"));
|
|
262
|
+
const stagedFile = join(stage, "item");
|
|
263
|
+
try {
|
|
264
|
+
await writeFile(stagedFile, bytes, { flag: "wx" });
|
|
265
|
+
if (baseEtag) {
|
|
266
|
+
const current = await inspectWorkspaceUpload(workspace, root, parent, name);
|
|
267
|
+
if (!current.replaceable || current.meta?.etag !== baseEtag)
|
|
268
|
+
throw new FilesError(409, "目标文件在上传前已发生变化。", "stale");
|
|
269
|
+
renameSync(stagedFile, destination);
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
moveWithoutReplacing(stagedFile, destination, false);
|
|
273
|
+
}
|
|
274
|
+
return { path: toRelative(root, destination) };
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
await rm(stagedFile, { force: true }).catch(() => { });
|
|
278
|
+
await rmdir(stage).catch(() => { });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
export { MAX_INITIAL_CONTENT as MAX_WORKSPACE_UPLOAD_BYTES };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
export declare function readWorkspaceDocumentPreview(path: string): Promise<import("./documents.js").ExtractResult>;
|
|
3
|
+
export declare function respondWithWorkspaceFile(request: IncomingMessage, response: ServerResponse, path: string, download: boolean): Promise<void>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { open } from "node:fs/promises";
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { pipeline } from "node:stream/promises";
|
|
5
|
+
import { workspaceFileMime } from "../shared/workspace-file-preview.js";
|
|
6
|
+
import { FilesError } from "./files.js";
|
|
7
|
+
import { extractTextFromBytes } from "./documents.js";
|
|
8
|
+
const MAX_DOCUMENT_PREVIEW_BYTES = 16 * 1024 * 1024;
|
|
9
|
+
function openWorkspaceAsset(path) {
|
|
10
|
+
return open(path, constants.O_RDONLY | constants.O_NONBLOCK).catch((error) => {
|
|
11
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
12
|
+
throw new FilesError(404, "文件已不存在。", "missing");
|
|
13
|
+
throw error;
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export async function readWorkspaceDocumentPreview(path) {
|
|
17
|
+
if (!/\.docx$/i.test(path))
|
|
18
|
+
throw new FilesError(415, "该文件没有文字预览。", "unsupported_entry");
|
|
19
|
+
const handle = await openWorkspaceAsset(path);
|
|
20
|
+
try {
|
|
21
|
+
const info = await handle.stat();
|
|
22
|
+
if (!info.isFile())
|
|
23
|
+
throw new FilesError(400, "这个路径不是普通文件。", "not_a_file");
|
|
24
|
+
if (info.size > MAX_DOCUMENT_PREVIEW_BYTES)
|
|
25
|
+
throw new FilesError(413, "文件超过文字预览上限(16 MB)。", "too_large");
|
|
26
|
+
const { buffer, bytesRead } = await handle.read({ buffer: Buffer.alloc(info.size), length: info.size });
|
|
27
|
+
if (bytesRead !== info.size)
|
|
28
|
+
throw new FilesError(409, "文档已变化,请重试。", "stale");
|
|
29
|
+
return await extractTextFromBytes(buffer, "docx");
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
await handle.close();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function parseRange(header, size) {
|
|
36
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(header);
|
|
37
|
+
if (!match || (!match[1] && !match[2]) || size <= 0)
|
|
38
|
+
return;
|
|
39
|
+
const start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2]));
|
|
40
|
+
const end = match[1] && match[2] ? Math.min(size - 1, Number(match[2])) : size - 1;
|
|
41
|
+
if (Number.isSafeInteger(start) && Number.isSafeInteger(end) && start <= end)
|
|
42
|
+
return { start, end };
|
|
43
|
+
}
|
|
44
|
+
export async function respondWithWorkspaceFile(request, response, path, download) {
|
|
45
|
+
const mime = workspaceFileMime(path);
|
|
46
|
+
if (!download && !mime)
|
|
47
|
+
throw new FilesError(415, "该文件可下载。", "unsupported_entry");
|
|
48
|
+
const handle = await openWorkspaceAsset(path);
|
|
49
|
+
try {
|
|
50
|
+
const info = await handle.stat();
|
|
51
|
+
if (!info.isFile())
|
|
52
|
+
throw new FilesError(400, "这个路径不是普通文件。", "not_a_file");
|
|
53
|
+
const range = request.headers.range ? parseRange(request.headers.range, info.size) : undefined;
|
|
54
|
+
const filename = encodeURIComponent(basename(path)).replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16)}`);
|
|
55
|
+
const headers = {
|
|
56
|
+
"content-type": download ? "application/octet-stream" : mime,
|
|
57
|
+
"content-disposition": `${download ? "attachment" : "inline"}; filename*=UTF-8''${filename}`,
|
|
58
|
+
"x-content-type-options": "nosniff",
|
|
59
|
+
"cross-origin-resource-policy": "same-origin",
|
|
60
|
+
"cache-control": "no-store",
|
|
61
|
+
"accept-ranges": "bytes",
|
|
62
|
+
};
|
|
63
|
+
if (request.headers.range && !range) {
|
|
64
|
+
response.writeHead(416, { ...headers, "content-range": `bytes */${info.size}` }).end();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (range)
|
|
68
|
+
headers["content-range"] = `bytes ${range.start}-${range.end}/${info.size}`;
|
|
69
|
+
headers["content-length"] = range ? range.end - range.start + 1 : info.size;
|
|
70
|
+
response.writeHead(range ? 206 : 200, headers);
|
|
71
|
+
if (request.method === "HEAD" || info.size === 0)
|
|
72
|
+
response.end();
|
|
73
|
+
else
|
|
74
|
+
await pipeline(handle.createReadStream(range ?? { start: 0, end: info.size - 1 }), response).catch(() => response.destroy());
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
await handle.close().catch(() => { });
|
|
78
|
+
}
|
|
79
|
+
}
|