@maxbill/dsh-file-explorer 0.0.0-stage → 1.1.1
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/LICENSE +201 -0
- package/README.en.md +512 -0
- package/README.md +510 -2
- package/assets/icon-180.png +0 -0
- package/assets/icons/archive.svg +5 -0
- package/assets/icons/audio.svg +5 -0
- package/assets/icons/excel.svg +5 -0
- package/assets/icons/file-outline.svg +4 -0
- package/assets/icons/folder.svg +4 -0
- package/assets/icons/image.svg +6 -0
- package/assets/icons/other.svg +5 -0
- package/assets/icons/pdf.svg +5 -0
- package/assets/icons/ppt.svg +5 -0
- package/assets/icons/text.svg +3 -0
- package/assets/icons/video.svg +5 -0
- package/assets/icons/word.svg +5 -0
- package/cordis.patch.yml +7 -0
- package/docs/drag-session.png +0 -0
- package/docs/editor.png +0 -0
- package/docs/grouped.png +0 -0
- package/docs/icon-view.png +0 -0
- package/docs/panel.png +0 -0
- package/docs/preview-sheet.png +0 -0
- package/docs/quick-look.png +0 -0
- package/docs/search.png +0 -0
- package/docs/session-menu.png +0 -0
- package/docs/workspace-menu.png +0 -0
- package/docs/workspace-switch.png +0 -0
- package/icon.svg +5 -0
- package/lib/client.js +5536 -0
- package/lib/index.js +1914 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +65 -4
- package/screenshots.json +10 -0
- package/scripts/export-icons.mjs +85 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1914 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-file-explorer — host half.
|
|
3
|
+
*
|
|
4
|
+
* Serves a small file API on the DSH web server for the 文件管理器 panel:
|
|
5
|
+
* browse, preview, and the common write actions behind the panel's context
|
|
6
|
+
* menu (rename, duplicate, copy/move, new folder, new file, move to Trash).
|
|
7
|
+
*
|
|
8
|
+
* Every path is confined to the user's home directory: requests are resolved
|
|
9
|
+
* through realpath() first, so neither ".." segments nor symbolic links can
|
|
10
|
+
* escape the root. Write routes never overwrite an existing item.
|
|
11
|
+
*
|
|
12
|
+
* Routes (prefix /api/file-explorer):
|
|
13
|
+
* GET /meta plugin name, version, author
|
|
14
|
+
* GET /roots allowed browsing roots
|
|
15
|
+
* GET /list?path= directory listing
|
|
16
|
+
* GET /read?path= text / image / binary preview
|
|
17
|
+
* POST /reveal?path= reveal in the OS file manager
|
|
18
|
+
* POST /open?path= open with the default application
|
|
19
|
+
* POST /rename?path=&name= rename an item
|
|
20
|
+
* POST /duplicate?path= copy an item beside itself
|
|
21
|
+
* POST /mkdir?path=&name= create a directory inside path
|
|
22
|
+
* POST /newfile?path=&name= create an empty file inside path
|
|
23
|
+
* POST /trash?path= move an item into ~/.Trash
|
|
24
|
+
* POST /transfer JSON {sources, target, mode: copy|move}
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { execFile } from 'node:child_process'
|
|
28
|
+
import { once } from 'node:events'
|
|
29
|
+
import { createWriteStream } from 'node:fs'
|
|
30
|
+
import { access, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
31
|
+
import { homedir, platform } from 'node:os'
|
|
32
|
+
import { pathToFileURL } from 'node:url'
|
|
33
|
+
import { basename, dirname, extname, join, resolve, sep } from 'node:path'
|
|
34
|
+
import { Readable } from 'node:stream'
|
|
35
|
+
import { deflateRawSync, inflateRawSync } from 'node:zlib'
|
|
36
|
+
|
|
37
|
+
/** Services this plugin waits for. */
|
|
38
|
+
export const inject = ['connection']
|
|
39
|
+
|
|
40
|
+
/** Route prefix; the client half fetches <prefix>/... . */
|
|
41
|
+
const PREFIX = '/api/file-explorer'
|
|
42
|
+
|
|
43
|
+
/** Browsing root: the user's home directory. */
|
|
44
|
+
const ROOT = homedir()
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* DSH's filesystem service when the host mounts one. The plugin never requires
|
|
48
|
+
* it: a sandboxed backend may refuse paths outside its root, and browsing stays
|
|
49
|
+
* possible through the plain node:fs fallbacks.
|
|
50
|
+
*/
|
|
51
|
+
let fsApi = null
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Ask DSH's filesystem service about one path.
|
|
55
|
+
* @param {string} target - absolute path
|
|
56
|
+
* @returns {Promise<{ target: object, info: object } | null>} target and metadata, or null
|
|
57
|
+
*/
|
|
58
|
+
async function fsPeek(target) {
|
|
59
|
+
if (!fsApi) return null
|
|
60
|
+
try {
|
|
61
|
+
const resolved = await fsApi.resolve(target)
|
|
62
|
+
const info = await fsApi.stat(resolved)
|
|
63
|
+
return { target: resolved, info }
|
|
64
|
+
} catch {
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The platform this process is really on, unless a test says otherwise.
|
|
71
|
+
* Exposed through __test so the shells for the other two operating systems can
|
|
72
|
+
* be exercised without one of those machines.
|
|
73
|
+
*/
|
|
74
|
+
let platformOverride = null
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @returns {string} 'darwin' | 'win32' | 'linux' | ...
|
|
78
|
+
*/
|
|
79
|
+
function currentPlatform() {
|
|
80
|
+
return platformOverride || platform()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Pretend to run on another platform (tests only).
|
|
85
|
+
* @param {string | null} value - platform name, or null to restore
|
|
86
|
+
* @returns {void}
|
|
87
|
+
*/
|
|
88
|
+
export function __setPlatform(value) {
|
|
89
|
+
platformOverride = value || null
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Largest file the preview route will read, in bytes. */
|
|
93
|
+
const MAX_TEXT_BYTES = 512 * 1024
|
|
94
|
+
const MAX_IMAGE_BYTES = 8 * 1024 * 1024
|
|
95
|
+
|
|
96
|
+
/** Largest workbook we will parse for the preview. */
|
|
97
|
+
const MAX_SHEET_BYTES = 32 * 1024 * 1024
|
|
98
|
+
|
|
99
|
+
/** Most rows and columns a sheet preview returns. */
|
|
100
|
+
const MAX_SHEET_ROWS = 500
|
|
101
|
+
const MAX_SHEET_COLS = 60
|
|
102
|
+
|
|
103
|
+
/** Directory listings are capped so one huge folder cannot stall the panel. */
|
|
104
|
+
const MAX_ENTRIES = 2000
|
|
105
|
+
|
|
106
|
+
/** Extensions rendered as text even when they are unusual. */
|
|
107
|
+
const TEXT_EXTENSIONS = new Set([
|
|
108
|
+
'txt', 'md', 'markdown', 'mdx', 'json', 'jsonc', 'json5', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf', 'env',
|
|
109
|
+
'js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'mts', 'cts', 'vue', 'svelte', 'css', 'scss', 'less', 'html', 'htm',
|
|
110
|
+
'xml', 'svg', 'csv', 'tsv', 'log', 'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'py', 'rb', 'go', 'rs', 'java',
|
|
111
|
+
'kt', 'swift', 'c', 'h', 'cc', 'cpp', 'hpp', 'cs', 'php', 'lua', 'pl', 'r', 'sql', 'graphql', 'gql', 'diff',
|
|
112
|
+
'patch', 'gitignore', 'npmrc', 'editorconfig', 'lock', 'properties', 'gradle', 'dockerfile', 'makefile',
|
|
113
|
+
])
|
|
114
|
+
|
|
115
|
+
/** Extensions rendered as images. */
|
|
116
|
+
const IMAGE_MIME = new Map([
|
|
117
|
+
['.png', 'image/png'],
|
|
118
|
+
['.jpg', 'image/jpeg'],
|
|
119
|
+
['.jpeg', 'image/jpeg'],
|
|
120
|
+
['.gif', 'image/gif'],
|
|
121
|
+
['.webp', 'image/webp'],
|
|
122
|
+
['.bmp', 'image/bmp'],
|
|
123
|
+
['.ico', 'image/x-icon'],
|
|
124
|
+
['.avif', 'image/avif'],
|
|
125
|
+
['.svg', 'image/svg+xml'],
|
|
126
|
+
])
|
|
127
|
+
|
|
128
|
+
/** Extensions grouped for the listing icons; anything else falls back to a plain file. */
|
|
129
|
+
const AUDIO_EXTENSIONS = new Set(['.mp3', '.wav', '.aac', '.flac', '.m4a', '.ogg', '.oga', '.opus', '.aiff', '.aif', '.wma', '.mid', '.midi', '.amr', '.ape'])
|
|
130
|
+
const VIDEO_EXTENSIONS = new Set(['.mp4', '.m4v', '.mov', '.avi', '.mkv', '.webm', '.wmv', '.flv', '.mpg', '.mpeg', '.3gp', '.m2ts', '.mts', '.ogv'])
|
|
131
|
+
const WORD_EXTENSIONS = new Set(['.doc', '.docx', '.dot', '.dotx', '.rtf', '.wps'])
|
|
132
|
+
const EXCEL_EXTENSIONS = new Set(['.xls', '.xlsx', '.xlsm', '.xlsb', '.et'])
|
|
133
|
+
const PPT_EXTENSIONS = new Set(['.ppt', '.pptx', '.pps', '.ppsx', '.dps'])
|
|
134
|
+
const ARCHIVE_EXTENSIONS = new Set(['.zip', '.rar', '.7z', '.tar', '.gz', '.tgz', '.bz2', '.tbz', '.xz', '.txz', '.zst', '.lz', '.lzma', '.dmg', '.iso', '.cab', '.jar', '.war'])
|
|
135
|
+
|
|
136
|
+
/** Error carrying the HTTP status the route should answer with. */
|
|
137
|
+
class RouteError extends Error {
|
|
138
|
+
constructor(status, message) {
|
|
139
|
+
super(message)
|
|
140
|
+
this.status = status
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Whether a resolved absolute path stays inside the browsing root.
|
|
146
|
+
* @param {string} target - absolute, already-real path
|
|
147
|
+
* @returns {boolean} true when inside
|
|
148
|
+
*/
|
|
149
|
+
function insideRoot(target) {
|
|
150
|
+
return target === ROOT || target.startsWith(ROOT + sep)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Expand "~", then resolve a request path to a real absolute path inside ROOT.
|
|
155
|
+
* @param {string | null | undefined} input - path from the query string or body
|
|
156
|
+
* @returns {Promise<string>} canonical absolute path
|
|
157
|
+
*/
|
|
158
|
+
async function safePath(input) {
|
|
159
|
+
const raw = typeof input === 'string' && input.trim().length > 0 ? input.trim() : ROOT
|
|
160
|
+
const expanded = raw === '~' ? ROOT : raw.startsWith('~/') ? join(ROOT, raw.slice(2)) : raw
|
|
161
|
+
const absolute = resolve(expanded)
|
|
162
|
+
if (!insideRoot(absolute)) throw new RouteError(403, 'path is outside the allowed root')
|
|
163
|
+
let real
|
|
164
|
+
try {
|
|
165
|
+
real = await realpath(absolute)
|
|
166
|
+
} catch {
|
|
167
|
+
throw new RouteError(404, 'path does not exist')
|
|
168
|
+
}
|
|
169
|
+
if (!insideRoot(real)) throw new RouteError(403, 'path is outside the allowed root')
|
|
170
|
+
return real
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Validate a single path segment supplied by the client.
|
|
175
|
+
* @param {unknown} name - proposed entry name
|
|
176
|
+
* @returns {string} the trimmed name
|
|
177
|
+
*/
|
|
178
|
+
function safeName(name) {
|
|
179
|
+
if (typeof name !== 'string') throw new RouteError(400, 'name is required')
|
|
180
|
+
const trimmed = name.trim()
|
|
181
|
+
if (trimmed.length === 0) throw new RouteError(400, 'name is empty')
|
|
182
|
+
if (trimmed === '.' || trimmed === '..') throw new RouteError(400, 'invalid name')
|
|
183
|
+
if (trimmed.length > 255) throw new RouteError(400, 'name is too long')
|
|
184
|
+
if (/[\\/\u0000]/.test(trimmed)) throw new RouteError(400, 'name cannot contain a path separator')
|
|
185
|
+
// Windows refuses these outright; checking here turns a 500 into a clear 400
|
|
186
|
+
if (currentPlatform() === 'win32' && /[<>:"|?*]/.test(trimmed)) {
|
|
187
|
+
throw new RouteError(400, 'name contains a character Windows does not allow')
|
|
188
|
+
}
|
|
189
|
+
if (currentPlatform() === 'win32' && /[. ]$/.test(trimmed)) {
|
|
190
|
+
throw new RouteError(400, 'name cannot end with a dot or space on Windows')
|
|
191
|
+
}
|
|
192
|
+
return trimmed
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Whether a path exists.
|
|
197
|
+
* @param {string} target - absolute path
|
|
198
|
+
* @returns {Promise<boolean>} true when present
|
|
199
|
+
*/
|
|
200
|
+
async function exists(target) {
|
|
201
|
+
try {
|
|
202
|
+
await access(target)
|
|
203
|
+
return true
|
|
204
|
+
} catch {
|
|
205
|
+
return false
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Pick a path beside `name` that does not exist yet.
|
|
211
|
+
* @param {string} dir - destination directory
|
|
212
|
+
* @param {string} name - preferred file name
|
|
213
|
+
* @returns {Promise<string>} absolute free path
|
|
214
|
+
*/
|
|
215
|
+
async function freePath(dir, name) {
|
|
216
|
+
const first = join(dir, name)
|
|
217
|
+
if (!(await exists(first))) return first
|
|
218
|
+
const extension = extname(name)
|
|
219
|
+
const stem = extension.length > 0 ? name.slice(0, -extension.length) : name
|
|
220
|
+
for (let index = 2; index < 1000; index += 1) {
|
|
221
|
+
const candidate = join(dir, stem + ' ' + index + extension)
|
|
222
|
+
if (!(await exists(candidate))) return candidate
|
|
223
|
+
}
|
|
224
|
+
throw new RouteError(409, 'too many items with that name')
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* "name.ext" -> "name 副本.ext"
|
|
229
|
+
* @param {string} name - source entry name
|
|
230
|
+
* @returns {string} duplicate name
|
|
231
|
+
*/
|
|
232
|
+
function duplicateName(name) {
|
|
233
|
+
const extension = extname(name)
|
|
234
|
+
const stem = extension.length > 0 ? name.slice(0, -extension.length) : name
|
|
235
|
+
return stem + ' 副本' + extension
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Stable kind classification for the file icon and the preview route.
|
|
240
|
+
* @param {string} name - entry basename
|
|
241
|
+
* @param {boolean} isDir - directory flag
|
|
242
|
+
* @returns {string} kind word
|
|
243
|
+
*/
|
|
244
|
+
function kindOf(name, isDir) {
|
|
245
|
+
if (isDir) return 'folder'
|
|
246
|
+
const ext = extname(name).toLowerCase()
|
|
247
|
+
if (IMAGE_MIME.has(ext)) return 'image'
|
|
248
|
+
// Text is matched before media so a .ts source file is not read as a transport stream.
|
|
249
|
+
if (TEXT_EXTENSIONS.has(ext.slice(1)) || TEXT_EXTENSIONS.has(name.toLowerCase())) return 'text'
|
|
250
|
+
if (ext === '.pdf') return 'pdf'
|
|
251
|
+
if (WORD_EXTENSIONS.has(ext)) return 'word'
|
|
252
|
+
if (EXCEL_EXTENSIONS.has(ext)) return 'excel'
|
|
253
|
+
if (PPT_EXTENSIONS.has(ext)) return 'ppt'
|
|
254
|
+
if (ARCHIVE_EXTENSIONS.has(ext)) return 'archive'
|
|
255
|
+
if (AUDIO_EXTENSIONS.has(ext)) return 'audio'
|
|
256
|
+
if (VIDEO_EXTENSIONS.has(ext)) return 'video'
|
|
257
|
+
return 'binary'
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Follow a symbolic link to decide whether it points at a directory.
|
|
262
|
+
* @param {string} target - absolute link path
|
|
263
|
+
* @returns {Promise<boolean>} true for a directory target
|
|
264
|
+
*/
|
|
265
|
+
async function isDirectoryTarget(target) {
|
|
266
|
+
try {
|
|
267
|
+
return (await stat(target)).isDirectory()
|
|
268
|
+
} catch {
|
|
269
|
+
return false
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Read a directory into the wire shape the client renders.
|
|
275
|
+
* @param {string} dir - canonical directory path
|
|
276
|
+
* @returns {Promise<object>} listing payload
|
|
277
|
+
*/
|
|
278
|
+
async function listDirectory(dir) {
|
|
279
|
+
let entries
|
|
280
|
+
try {
|
|
281
|
+
entries = await readdir(dir, { withFileTypes: true })
|
|
282
|
+
} catch (error) {
|
|
283
|
+
throw new RouteError(error && error.code === 'EACCES' ? 403 : 500, String(error && error.message))
|
|
284
|
+
}
|
|
285
|
+
const visible = entries.slice(0, MAX_ENTRIES)
|
|
286
|
+
const rows = await Promise.all(visible.map(async (entry) => {
|
|
287
|
+
const full = join(dir, entry.name)
|
|
288
|
+
const isDir = entry.isDirectory() || (entry.isSymbolicLink() && await isDirectoryTarget(full))
|
|
289
|
+
let size = 0
|
|
290
|
+
let mtime = 0
|
|
291
|
+
try {
|
|
292
|
+
const info = await stat(full)
|
|
293
|
+
size = info.size
|
|
294
|
+
mtime = info.mtimeMs
|
|
295
|
+
} catch {
|
|
296
|
+
// A dangling link or a permission-denied entry still lists, without stats.
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
name: entry.name,
|
|
300
|
+
path: full,
|
|
301
|
+
dir: isDir,
|
|
302
|
+
link: entry.isSymbolicLink(),
|
|
303
|
+
hidden: entry.name.startsWith('.'),
|
|
304
|
+
size,
|
|
305
|
+
mtime,
|
|
306
|
+
kind: kindOf(entry.name, isDir),
|
|
307
|
+
}
|
|
308
|
+
}))
|
|
309
|
+
const parent = dir === ROOT ? null : dirname(dir)
|
|
310
|
+
return {
|
|
311
|
+
root: ROOT,
|
|
312
|
+
path: dir,
|
|
313
|
+
name: basename(dir),
|
|
314
|
+
parent: parent && insideRoot(parent) ? parent : null,
|
|
315
|
+
truncated: entries.length > visible.length,
|
|
316
|
+
entries: rows,
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Answer the metadata route: the plugin's own manifest, for the About dialog.
|
|
322
|
+
* @returns {Promise<object>} name, version, description, author, links
|
|
323
|
+
*/
|
|
324
|
+
async function readMeta() {
|
|
325
|
+
const file = new URL('../package.json', import.meta.url)
|
|
326
|
+
const raw = await readFile(file, 'utf8')
|
|
327
|
+
const pkg = JSON.parse(raw)
|
|
328
|
+
let build = null
|
|
329
|
+
try {
|
|
330
|
+
const info = await stat(file)
|
|
331
|
+
const stamp = new Date(info.mtimeMs)
|
|
332
|
+
build = String(stamp.getFullYear()) +
|
|
333
|
+
String(stamp.getMonth() + 1).padStart(2, '0') +
|
|
334
|
+
String(stamp.getDate()).padStart(2, '0')
|
|
335
|
+
} catch {
|
|
336
|
+
build = null
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
name: pkg.name,
|
|
340
|
+
version: pkg.version,
|
|
341
|
+
description: pkg.description,
|
|
342
|
+
author: pkg.author,
|
|
343
|
+
homepage: pkg.homepage,
|
|
344
|
+
repository: pkg.repository,
|
|
345
|
+
license: pkg.license,
|
|
346
|
+
build,
|
|
347
|
+
root: ROOT,
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Render POSIX permission bits the way ls does.
|
|
353
|
+
* @param {number} mode - st_mode from stat()
|
|
354
|
+
* @returns {string} e.g. "-rw-r--r--"
|
|
355
|
+
*/
|
|
356
|
+
function modeString(mode) {
|
|
357
|
+
const type = mode & 0o170000
|
|
358
|
+
const lead = type === 0o040000 ? 'd' : type === 0o120000 ? 'l' : type === 0o010000 ? 'p' : type === 0o140000 ? 's' : '-'
|
|
359
|
+
const bits = ['r', 'w', 'x']
|
|
360
|
+
let out = lead
|
|
361
|
+
for (let shift = 6; shift >= 0; shift -= 3) {
|
|
362
|
+
for (let bit = 0; bit < 3; bit += 1) {
|
|
363
|
+
out += (mode >> (shift + (2 - bit))) & 1 ? bits[bit] : '-'
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return out
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Answer the details route: everything the info pane shows about one entry.
|
|
371
|
+
* @param {string} target - canonical path
|
|
372
|
+
* @returns {Promise<object>} details payload
|
|
373
|
+
*/
|
|
374
|
+
async function statEntry(target) {
|
|
375
|
+
const info = await stat(target)
|
|
376
|
+
const linkInfo = await lstat(target)
|
|
377
|
+
const isDir = info.isDirectory()
|
|
378
|
+
const entry = {
|
|
379
|
+
path: target,
|
|
380
|
+
name: basename(target),
|
|
381
|
+
parent: dirname(target),
|
|
382
|
+
dir: isDir,
|
|
383
|
+
link: linkInfo.isSymbolicLink(),
|
|
384
|
+
kind: kindOf(basename(target), isDir),
|
|
385
|
+
size: info.size,
|
|
386
|
+
mtime: info.mtimeMs,
|
|
387
|
+
birthtime: info.birthtimeMs || info.ctimeMs,
|
|
388
|
+
mode: modeString(info.mode),
|
|
389
|
+
modeOctal: '0o' + (info.mode & 0o7777).toString(8),
|
|
390
|
+
items: null,
|
|
391
|
+
}
|
|
392
|
+
if (isDir) {
|
|
393
|
+
try {
|
|
394
|
+
entry.items = (await readdir(target)).length
|
|
395
|
+
} catch {
|
|
396
|
+
entry.items = null
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return entry
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Answer the preview route for one file.
|
|
404
|
+
* @param {string} file - canonical file path
|
|
405
|
+
* @returns {Promise<object>} preview payload
|
|
406
|
+
*/
|
|
407
|
+
async function readPreview(file) {
|
|
408
|
+
const info = await stat(file)
|
|
409
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a directory')
|
|
410
|
+
const ext = extname(file).toLowerCase()
|
|
411
|
+
const mime = IMAGE_MIME.get(ext)
|
|
412
|
+
if (mime && info.size <= MAX_IMAGE_BYTES) {
|
|
413
|
+
const data = await readFile(file)
|
|
414
|
+
return {
|
|
415
|
+
kind: 'image',
|
|
416
|
+
mime,
|
|
417
|
+
size: info.size,
|
|
418
|
+
mtime: info.mtimeMs,
|
|
419
|
+
dataUrl: 'data:' + mime + ';base64,' + data.toString('base64'),
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
const base = { size: info.size, mtime: info.mtimeMs, mime: mime ?? null }
|
|
423
|
+
if (info.size > MAX_TEXT_BYTES) {
|
|
424
|
+
return { ...base, kind: 'too-large', limit: MAX_TEXT_BYTES }
|
|
425
|
+
}
|
|
426
|
+
const buffer = await readFile(file)
|
|
427
|
+
if (buffer.includes(0)) {
|
|
428
|
+
return { ...base, kind: 'binary' }
|
|
429
|
+
}
|
|
430
|
+
return { ...base, kind: 'text', text: buffer.toString('utf8'), truncated: false }
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Run a desktop helper, e.g. `open`.
|
|
435
|
+
* @param {string} command - executable name
|
|
436
|
+
* @param {string[]} args - arguments
|
|
437
|
+
* @returns {Promise<void>} resolves when the helper exits 0
|
|
438
|
+
*/
|
|
439
|
+
function runHelper(command, args) {
|
|
440
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
441
|
+
execFile(command, args, (error) => {
|
|
442
|
+
if (error) rejectPromise(new RouteError(500, String(error.message)))
|
|
443
|
+
else resolvePromise(undefined)
|
|
444
|
+
})
|
|
445
|
+
})
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Reveal a path in the OS file manager.
|
|
450
|
+
* @param {string} target - canonical absolute path
|
|
451
|
+
* @returns {Promise<object>} outcome
|
|
452
|
+
*/
|
|
453
|
+
function revealPlan(target, os = currentPlatform()) {
|
|
454
|
+
if (os === 'darwin') return { command: 'open', args: ['-R', target] }
|
|
455
|
+
// explorer selects the item when the switch is glued to the path
|
|
456
|
+
if (os === 'win32') return { command: 'explorer', args: ['/select,' + target] }
|
|
457
|
+
return {
|
|
458
|
+
command: 'dbus-send',
|
|
459
|
+
args: [
|
|
460
|
+
'--session', '--print-reply',
|
|
461
|
+
'--dest=org.freedesktop.FileManager1',
|
|
462
|
+
'--type=method_call', '/org/freedesktop/FileManager1',
|
|
463
|
+
'org.freedesktop.FileManager1.ShowItems',
|
|
464
|
+
'array:string:' + pathToFileURL(target).href,
|
|
465
|
+
'string:',
|
|
466
|
+
],
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Reveal a path in the OS file manager.
|
|
472
|
+
* @param {string} target - canonical absolute path
|
|
473
|
+
* @returns {Promise<object>} outcome
|
|
474
|
+
*/
|
|
475
|
+
async function reveal(target) {
|
|
476
|
+
const plan = revealPlan(target)
|
|
477
|
+
try {
|
|
478
|
+
await runHelper(plan.command, plan.args)
|
|
479
|
+
return { ok: true }
|
|
480
|
+
} catch (error) {
|
|
481
|
+
// A Linux desktop without a FileManager1 service can still show the folder.
|
|
482
|
+
if (currentPlatform() === 'linux') {
|
|
483
|
+
try {
|
|
484
|
+
await runHelper('xdg-open', [dirname(target)])
|
|
485
|
+
return { ok: true, fallback: 'parent-folder' }
|
|
486
|
+
} catch { /* fall through to the unsupported answer */ }
|
|
487
|
+
}
|
|
488
|
+
return { ok: false, reason: 'unsupported-platform', message: String((error && error.message) || error) }
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Open a path with the desktop's default application.
|
|
494
|
+
* @param {string} target - canonical absolute path
|
|
495
|
+
* @returns {Promise<object>} outcome
|
|
496
|
+
*/
|
|
497
|
+
async function openWithDefault(target) {
|
|
498
|
+
const os = currentPlatform()
|
|
499
|
+
if (os === 'darwin') {
|
|
500
|
+
await runHelper('open', [target])
|
|
501
|
+
return { ok: true }
|
|
502
|
+
}
|
|
503
|
+
if (os === 'win32') {
|
|
504
|
+
await runHelper('cmd', ['/c', 'start', '', target])
|
|
505
|
+
return { ok: true }
|
|
506
|
+
}
|
|
507
|
+
await runHelper('xdg-open', [target])
|
|
508
|
+
return { ok: true }
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Rename one entry in place.
|
|
513
|
+
* @param {string} source - canonical path
|
|
514
|
+
* @param {string} name - new entry name
|
|
515
|
+
* @returns {Promise<object>} outcome
|
|
516
|
+
*/
|
|
517
|
+
async function renameEntry(source, name) {
|
|
518
|
+
if (source === ROOT) throw new RouteError(403, 'cannot rename the browsing root')
|
|
519
|
+
const clean = safeName(name)
|
|
520
|
+
const parent = dirname(source)
|
|
521
|
+
const target = join(parent, clean)
|
|
522
|
+
if (target === source) return { ok: true, path: source }
|
|
523
|
+
if (await exists(target)) throw new RouteError(409, '同名项已存在')
|
|
524
|
+
await rename(source, target)
|
|
525
|
+
return { ok: true, path: target }
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Copy one entry beside itself.
|
|
530
|
+
* @param {string} source - canonical path
|
|
531
|
+
* @returns {Promise<object>} outcome
|
|
532
|
+
*/
|
|
533
|
+
async function duplicateEntry(source) {
|
|
534
|
+
if (source === ROOT) throw new RouteError(403, 'cannot duplicate the browsing root')
|
|
535
|
+
const parent = dirname(source)
|
|
536
|
+
const target = await freePath(parent, duplicateName(basename(source)))
|
|
537
|
+
await cp(source, target, { recursive: true, errorOnExist: true, force: false })
|
|
538
|
+
return { ok: true, path: target }
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Create a directory inside `parent`.
|
|
543
|
+
* @param {string} parent - canonical directory path
|
|
544
|
+
* @param {string} name - new directory name
|
|
545
|
+
* @returns {Promise<object>} outcome
|
|
546
|
+
*/
|
|
547
|
+
async function createDirectory(parent, name) {
|
|
548
|
+
const clean = safeName(name)
|
|
549
|
+
const target = join(parent, clean)
|
|
550
|
+
if (await exists(target)) throw new RouteError(409, '同名项已存在')
|
|
551
|
+
await mkdir(target)
|
|
552
|
+
return { ok: true, path: target }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Create an empty file inside `parent`.
|
|
557
|
+
* @param {string} parent - canonical directory path
|
|
558
|
+
* @param {string} name - new file name
|
|
559
|
+
* @returns {Promise<object>} outcome
|
|
560
|
+
*/
|
|
561
|
+
async function createFile(parent, name) {
|
|
562
|
+
const clean = safeName(name)
|
|
563
|
+
const target = join(parent, clean)
|
|
564
|
+
if (await exists(target)) throw new RouteError(409, '同名项已存在')
|
|
565
|
+
await writeFile(target, '', { flag: 'wx' })
|
|
566
|
+
return { ok: true, path: target }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Where a path goes when the user trashes it, per platform.
|
|
571
|
+
* @param {string} target - canonical absolute path
|
|
572
|
+
* @param {string} os - platform name
|
|
573
|
+
* @param {boolean} isDirectory - whether the target is a folder
|
|
574
|
+
* @param {string} home - home directory to build the trash paths from
|
|
575
|
+
* @returns {object} plan
|
|
576
|
+
*/
|
|
577
|
+
function trashPlan(target, os, isDirectory, home) {
|
|
578
|
+
if (os === 'linux') {
|
|
579
|
+
// freedesktop.org trash: files/ holds the entry, info/ holds where it came from
|
|
580
|
+
const base = join(home, '.local', 'share', 'Trash')
|
|
581
|
+
return { kind: 'freedesktop', filesDir: join(base, 'files'), infoDir: join(base, 'info') }
|
|
582
|
+
}
|
|
583
|
+
if (os === 'win32') {
|
|
584
|
+
const method = isDirectory ? 'DeleteDirectory' : 'DeleteFile'
|
|
585
|
+
const literal = target.replace(/'/g, "''")
|
|
586
|
+
return {
|
|
587
|
+
kind: 'recycle-bin',
|
|
588
|
+
command: 'powershell.exe',
|
|
589
|
+
args: [
|
|
590
|
+
'-NoProfile', '-NonInteractive', '-Command',
|
|
591
|
+
`Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.FileIO.FileSystem]::${method}('${literal}','OnlyErrorDialogs','SendToRecycleBin')`,
|
|
592
|
+
],
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return { kind: 'move', dir: join(home, '.Trash') }
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Percent-encode an absolute path the way a .trashinfo file wants it.
|
|
600
|
+
* @param {string} target - absolute path
|
|
601
|
+
* @returns {string} encoded path
|
|
602
|
+
*/
|
|
603
|
+
function trashInfoPath(target) {
|
|
604
|
+
return target.split('/').map(function (part) { return encodeURIComponent(part) }).join('/')
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* Write the freedesktop .trashinfo sidecar so the desktop can restore the entry.
|
|
609
|
+
* @param {string} infoFile - sidecar path
|
|
610
|
+
* @param {string} originalPath - where the entry used to live
|
|
611
|
+
* @returns {Promise<void>} resolves once written
|
|
612
|
+
*/
|
|
613
|
+
async function writeTrashInfo(infoFile, originalPath) {
|
|
614
|
+
const stamp = new Date().toISOString().slice(0, 19)
|
|
615
|
+
await writeFile(infoFile, `[Trash Info]\nPath=${trashInfoPath(originalPath)}\nDeletionDate=${stamp}\n`, 'utf8')
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Move one entry into the platform's trash, never deleting it outright.
|
|
620
|
+
* @param {string} source - canonical path
|
|
621
|
+
* @returns {Promise<object>} outcome
|
|
622
|
+
*/
|
|
623
|
+
async function moveToTrash(source) {
|
|
624
|
+
if (source === ROOT) throw new RouteError(403, 'cannot trash the browsing root')
|
|
625
|
+
const info = await stat(source)
|
|
626
|
+
const plan = trashPlan(source, currentPlatform(), info.isDirectory(), ROOT)
|
|
627
|
+
|
|
628
|
+
if (plan.kind === 'recycle-bin') {
|
|
629
|
+
try {
|
|
630
|
+
await runHelper(plan.command, plan.args)
|
|
631
|
+
return { ok: true, path: null, from: source, trash: 'recycle-bin' }
|
|
632
|
+
} catch (error) {
|
|
633
|
+
// No PowerShell (or a stripped Windows image): fall back to a folder trash.
|
|
634
|
+
const dir = join(ROOT, '.Trash')
|
|
635
|
+
await mkdir(dir, { recursive: true })
|
|
636
|
+
const target = await freePath(dir, basename(source))
|
|
637
|
+
await rename(source, target)
|
|
638
|
+
return { ok: true, path: target, from: source, trash: 'folder', message: String((error && error.message) || error) }
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
if (plan.kind === 'freedesktop') {
|
|
643
|
+
await mkdir(plan.filesDir, { recursive: true })
|
|
644
|
+
await mkdir(plan.infoDir, { recursive: true })
|
|
645
|
+
const target = await freePath(plan.filesDir, basename(source))
|
|
646
|
+
await rename(source, target)
|
|
647
|
+
const infoFile = join(plan.infoDir, basename(target) + '.trashinfo')
|
|
648
|
+
await writeTrashInfo(infoFile, source).catch(() => undefined)
|
|
649
|
+
return { ok: true, path: target, from: source, trash: 'freedesktop' }
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
await mkdir(plan.dir, { recursive: true })
|
|
653
|
+
const target = await freePath(plan.dir, basename(source))
|
|
654
|
+
await rename(source, target)
|
|
655
|
+
return { ok: true, path: target, from: source, trash: 'folder' }
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/** Internals a test needs to reach without a second operating system. */
|
|
659
|
+
export const __test = { revealPlan, trashPlan }
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Copy or move several entries into one directory.
|
|
663
|
+
* @param {object} body - { sources, target, mode }
|
|
664
|
+
* @returns {Promise<object>} outcome
|
|
665
|
+
*/
|
|
666
|
+
async function transfer(body) {
|
|
667
|
+
const mode = body.mode === 'move' ? 'move' : 'copy'
|
|
668
|
+
const sources = Array.isArray(body.sources) ? body.sources : []
|
|
669
|
+
if (sources.length === 0) throw new RouteError(400, '没有要处理的项目')
|
|
670
|
+
const targetDir = await safePath(body.target)
|
|
671
|
+
if (!(await stat(targetDir)).isDirectory()) throw new RouteError(400, '目标不是文件夹')
|
|
672
|
+
const results = []
|
|
673
|
+
for (const raw of sources) {
|
|
674
|
+
const source = await safePath(raw)
|
|
675
|
+
if (source === ROOT) throw new RouteError(403, 'cannot transfer the browsing root')
|
|
676
|
+
if (targetDir === source || targetDir.startsWith(source + sep)) {
|
|
677
|
+
throw new RouteError(400, '不能把文件夹移动到它自己里面')
|
|
678
|
+
}
|
|
679
|
+
if (dirname(source) === targetDir) {
|
|
680
|
+
if (mode === 'move') {
|
|
681
|
+
results.push({ path: source, from: source, skipped: '已在目标文件夹' })
|
|
682
|
+
continue
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
// Never overwrite: a name clash becomes "name 2", the way the panel's copy does.
|
|
686
|
+
const target = await freePath(targetDir, basename(source))
|
|
687
|
+
if (mode === 'move') {
|
|
688
|
+
try {
|
|
689
|
+
await rename(source, target)
|
|
690
|
+
} catch (error) {
|
|
691
|
+
if (!error || error.code !== 'EXDEV') throw error
|
|
692
|
+
await cp(source, target, { recursive: true, errorOnExist: true, force: false })
|
|
693
|
+
await rm(source, { recursive: true, force: true })
|
|
694
|
+
}
|
|
695
|
+
} else {
|
|
696
|
+
await cp(source, target, { recursive: true, errorOnExist: true, force: false })
|
|
697
|
+
}
|
|
698
|
+
results.push({ path: target, from: source })
|
|
699
|
+
}
|
|
700
|
+
return { ok: true, mode, target: targetDir, results }
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Write one JSON response.
|
|
705
|
+
* @param {import('node:http').ServerResponse} res - response
|
|
706
|
+
* @param {number} status - HTTP status
|
|
707
|
+
* @param {unknown} payload - serializable body
|
|
708
|
+
*/
|
|
709
|
+
function send(res, status, payload) {
|
|
710
|
+
const body = JSON.stringify(payload)
|
|
711
|
+
res.writeHead(status, {
|
|
712
|
+
'content-type': 'application/json; charset=utf-8',
|
|
713
|
+
'cache-control': 'no-store',
|
|
714
|
+
'content-length': Buffer.byteLength(body),
|
|
715
|
+
})
|
|
716
|
+
res.end(body)
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Read every entry out of a ZIP archive (stored or deflated).
|
|
721
|
+
* @param {Buffer} buffer - whole archive
|
|
722
|
+
* @returns {Map<string, Buffer>} entry name -> inflated bytes
|
|
723
|
+
*/
|
|
724
|
+
function readZip(buffer) {
|
|
725
|
+
const entries = new Map()
|
|
726
|
+
let eocd = -1
|
|
727
|
+
for (let i = buffer.length - 22; i >= 0 && i > buffer.length - 66_000; i -= 1) {
|
|
728
|
+
if (buffer.readUInt32LE(i) === 0x06054b50) { eocd = i; break }
|
|
729
|
+
}
|
|
730
|
+
if (eocd < 0) throw new RouteError(415, 'not a zip archive')
|
|
731
|
+
const count = buffer.readUInt16LE(eocd + 10)
|
|
732
|
+
let offset = buffer.readUInt32LE(eocd + 16)
|
|
733
|
+
for (let index = 0; index < count; index += 1) {
|
|
734
|
+
if (buffer.readUInt32LE(offset) !== 0x02014b50) break
|
|
735
|
+
const method = buffer.readUInt16LE(offset + 10)
|
|
736
|
+
const compressedSize = buffer.readUInt32LE(offset + 20)
|
|
737
|
+
const nameLength = buffer.readUInt16LE(offset + 28)
|
|
738
|
+
const extraLength = buffer.readUInt16LE(offset + 30)
|
|
739
|
+
const commentLength = buffer.readUInt16LE(offset + 32)
|
|
740
|
+
const localOffset = buffer.readUInt32LE(offset + 42)
|
|
741
|
+
const name = buffer.toString('utf8', offset + 46, offset + 46 + nameLength)
|
|
742
|
+
offset += 46 + nameLength + extraLength + commentLength
|
|
743
|
+
// offset 0 is a legitimate entry: an archive whose first member starts the file
|
|
744
|
+
if (buffer.readUInt32LE(localOffset) !== 0x04034b50) continue
|
|
745
|
+
const localNameLength = buffer.readUInt16LE(localOffset + 26)
|
|
746
|
+
const localExtraLength = buffer.readUInt16LE(localOffset + 28)
|
|
747
|
+
const dataStart = localOffset + 30 + localNameLength + localExtraLength
|
|
748
|
+
if (name.endsWith('/')) { entries.set(name, Buffer.alloc(0)); continue }
|
|
749
|
+
const data = buffer.subarray(dataStart, dataStart + compressedSize)
|
|
750
|
+
try {
|
|
751
|
+
entries.set(name, method === 8 ? inflateRawSync(data) : data)
|
|
752
|
+
} catch {
|
|
753
|
+
// A corrupt entry is skipped rather than failing the whole workbook.
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return entries
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Pull the text out of one shared-string entry.
|
|
761
|
+
* @param {string} xml - <si> block
|
|
762
|
+
* @returns {string} joined text
|
|
763
|
+
*/
|
|
764
|
+
function sharedStringText(xml) {
|
|
765
|
+
const parts = []
|
|
766
|
+
const pattern = /<t[^>]*>([\s\S]*?)<\/t>/g
|
|
767
|
+
let match = pattern.exec(xml)
|
|
768
|
+
while (match) {
|
|
769
|
+
parts.push(decodeXml(match[1]))
|
|
770
|
+
match = pattern.exec(xml)
|
|
771
|
+
}
|
|
772
|
+
return parts.join('')
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Decode the five XML entities spreadsheets use.
|
|
777
|
+
* @param {string} text - raw text
|
|
778
|
+
* @returns {string} decoded text
|
|
779
|
+
*/
|
|
780
|
+
function decodeXml(text) {
|
|
781
|
+
return String(text)
|
|
782
|
+
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCodePoint(parseInt(hex, 16)))
|
|
783
|
+
.replace(/&#(\d+);/g, (match, dec) => String.fromCodePoint(Number(dec)))
|
|
784
|
+
.replace(/</g, '<')
|
|
785
|
+
.replace(/>/g, '>')
|
|
786
|
+
.replace(/"/g, '"')
|
|
787
|
+
.replace(/'/g, "'")
|
|
788
|
+
.replace(/&/g, '&')
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Column letters to a zero-based index (A -> 0, AA -> 26).
|
|
793
|
+
* @param {string} letters - cell column
|
|
794
|
+
* @returns {number} index
|
|
795
|
+
*/
|
|
796
|
+
function columnIndex(letters) {
|
|
797
|
+
let value = 0
|
|
798
|
+
for (const ch of letters) value = value * 26 + (ch.charCodeAt(0) - 64)
|
|
799
|
+
return value - 1
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* Read one worksheet into rows of strings.
|
|
804
|
+
* @param {string} xml - sheet XML
|
|
805
|
+
* @param {string[]} shared - shared string table
|
|
806
|
+
* @returns {Array<Array<string>>} rows
|
|
807
|
+
*/
|
|
808
|
+
function sheetRows(xml, shared) {
|
|
809
|
+
const rows = []
|
|
810
|
+
const rowPattern = /<row[^>]*>([\s\S]*?)<\/row>/g
|
|
811
|
+
let rowMatch = rowPattern.exec(xml)
|
|
812
|
+
while (rowMatch && rows.length < MAX_SHEET_ROWS) {
|
|
813
|
+
const cells = []
|
|
814
|
+
const cellPattern = /<c([^>]*)>([\s\S]*?)<\/c>/g
|
|
815
|
+
let cellMatch = cellPattern.exec(rowMatch[1])
|
|
816
|
+
while (cellMatch && cells.length < MAX_SHEET_COLS) {
|
|
817
|
+
const attrs = cellMatch[1]
|
|
818
|
+
const body = cellMatch[2]
|
|
819
|
+
const ref = /r="([A-Z]+)\d+"/.exec(attrs)
|
|
820
|
+
const type = /t="([a-zA-Z]+)"/.exec(attrs)
|
|
821
|
+
const index = ref ? columnIndex(ref[1]) : cells.length
|
|
822
|
+
while (cells.length < index) cells.push('')
|
|
823
|
+
let value = ''
|
|
824
|
+
if (type && type[1] === 's') {
|
|
825
|
+
const raw = /<v>([\s\S]*?)<\/v>/.exec(body)
|
|
826
|
+
value = raw ? (shared[Number(raw[1])] ?? '') : ''
|
|
827
|
+
} else if (type && (type[1] === 'str' || type[1] === 'inlineStr')) {
|
|
828
|
+
const raw = /<t[^>]*>([\s\S]*?)<\/t>/.exec(body)
|
|
829
|
+
value = raw ? decodeXml(raw[1]) : ''
|
|
830
|
+
} else if (type && type[1] === 'b') {
|
|
831
|
+
const raw = /<v>([\s\S]*?)<\/v>/.exec(body)
|
|
832
|
+
value = raw && raw[1] === '1' ? 'TRUE' : 'FALSE'
|
|
833
|
+
} else if (type && type[1] === 'e') {
|
|
834
|
+
const raw = /<v>([\s\S]*?)<\/v>/.exec(body)
|
|
835
|
+
value = raw ? decodeXml(raw[1]) : '#ERR'
|
|
836
|
+
} else {
|
|
837
|
+
const raw = /<v>([\s\S]*?)<\/v>/.exec(body)
|
|
838
|
+
value = raw ? raw[1] : ''
|
|
839
|
+
}
|
|
840
|
+
cells.push(value)
|
|
841
|
+
cellMatch = cellPattern.exec(rowMatch[1])
|
|
842
|
+
}
|
|
843
|
+
rows.push(cells)
|
|
844
|
+
rowMatch = rowPattern.exec(xml)
|
|
845
|
+
}
|
|
846
|
+
return rows
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* Parse an .xlsx/.xlsm workbook into its sheets.
|
|
851
|
+
* @param {Buffer} buffer - file bytes
|
|
852
|
+
* @returns {{sheets: Array<{name: string, rows: Array<Array<string>>}>}} preview payload
|
|
853
|
+
*/
|
|
854
|
+
function readWorkbook(buffer) {
|
|
855
|
+
const zip = readZip(buffer)
|
|
856
|
+
const workbook = zip.get('xl/workbook.xml')
|
|
857
|
+
const relationships = zip.get('xl/_rels/workbook.xml.rels')
|
|
858
|
+
if (!workbook || !relationships) throw new RouteError(415, 'not a workbook')
|
|
859
|
+
const relTargets = new Map()
|
|
860
|
+
const relText = relationships.toString('utf8')
|
|
861
|
+
const relPattern = /<Relationship\b([^>]*)\/?>/g
|
|
862
|
+
let relMatch = relPattern.exec(relText)
|
|
863
|
+
while (relMatch) {
|
|
864
|
+
const attrs = relMatch[1]
|
|
865
|
+
const id = /Id="([^"]+)"/.exec(attrs)
|
|
866
|
+
const target = /Target="([^"]+)"/.exec(attrs)
|
|
867
|
+
if (id && target) {
|
|
868
|
+
relTargets.set(id[1], target[1].replace(/^\/?xl\//, '').replace(/^\//, ''))
|
|
869
|
+
}
|
|
870
|
+
relMatch = relPattern.exec(relText)
|
|
871
|
+
}
|
|
872
|
+
const shared = []
|
|
873
|
+
const strings = zip.get('xl/sharedStrings.xml')
|
|
874
|
+
if (strings) {
|
|
875
|
+
const text = strings.toString('utf8')
|
|
876
|
+
const siPattern = /<si>([\s\S]*?)<\/si>/g
|
|
877
|
+
let siMatch = siPattern.exec(text)
|
|
878
|
+
while (siMatch) {
|
|
879
|
+
shared.push(sharedStringText(siMatch[1]))
|
|
880
|
+
siMatch = siPattern.exec(text)
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
const sheets = []
|
|
884
|
+
const sheetXml = workbook.toString('utf8')
|
|
885
|
+
const sheetPattern = /<sheet\b([^>]*)\/?>/g
|
|
886
|
+
let sheetMatch = sheetPattern.exec(sheetXml)
|
|
887
|
+
while (sheetMatch && sheets.length < 12) {
|
|
888
|
+
const attrs = sheetMatch[1]
|
|
889
|
+
const name = /name="([^"]+)"/.exec(attrs)
|
|
890
|
+
const rid = /r:id="([^"]+)"/.exec(attrs) || /relationshipId="([^"]+)"/.exec(attrs)
|
|
891
|
+
const target = rid ? relTargets.get(rid[1]) : null
|
|
892
|
+
const body = target ? zip.get('xl/' + target) : null
|
|
893
|
+
if (body && name) {
|
|
894
|
+
sheets.push({ name: decodeXml(name[1]), rows: sheetRows(body.toString('utf8'), shared) })
|
|
895
|
+
}
|
|
896
|
+
sheetMatch = sheetPattern.exec(sheetXml)
|
|
897
|
+
}
|
|
898
|
+
if (sheets.length === 0) throw new RouteError(415, 'no sheets found')
|
|
899
|
+
return { sheets }
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Pull the text of a docx paragraph, keeping tabs and line breaks.
|
|
903
|
+
* @param {string} xml - paragraph body
|
|
904
|
+
* @returns {string} plain text
|
|
905
|
+
*/
|
|
906
|
+
function docxParagraphText(xml) {
|
|
907
|
+
// Tabs and breaks are empty elements, so swap them in before lifting the text.
|
|
908
|
+
const prepared = String(xml)
|
|
909
|
+
.replace(/<w:tab\b[^>]*\/?>/g, '\t')
|
|
910
|
+
.replace(/<w:(?:br|cr)\b[^>]*\/?>/g, '\n')
|
|
911
|
+
const parts = []
|
|
912
|
+
prepared.replace(/<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g, (match, inner) => {
|
|
913
|
+
parts.push(decodeXml(inner))
|
|
914
|
+
return match
|
|
915
|
+
})
|
|
916
|
+
return parts.join('')
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* Turn one docx table into rows of cell text.
|
|
921
|
+
* @param {string} xml - <w:tbl> block
|
|
922
|
+
* @returns {Array<Array<string>>} rows
|
|
923
|
+
*/
|
|
924
|
+
function docxTableRows(xml) {
|
|
925
|
+
const rows = []
|
|
926
|
+
const rowPattern = /<w:tr\b[^>]*>([\s\S]*?)<\/w:tr>/g
|
|
927
|
+
let rowMatch = rowPattern.exec(xml)
|
|
928
|
+
while (rowMatch && rows.length < 200) {
|
|
929
|
+
const cells = []
|
|
930
|
+
const cellPattern = /<w:tc\b[^>]*>([\s\S]*?)<\/w:tc>/g
|
|
931
|
+
let cellMatch = cellPattern.exec(rowMatch[1])
|
|
932
|
+
while (cellMatch && cells.length < 40) {
|
|
933
|
+
const paragraphs = []
|
|
934
|
+
const pPattern = /<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g
|
|
935
|
+
let pMatch = pPattern.exec(cellMatch[1])
|
|
936
|
+
while (pMatch) {
|
|
937
|
+
paragraphs.push(docxParagraphText(pMatch[1]))
|
|
938
|
+
pMatch = pPattern.exec(cellMatch[1])
|
|
939
|
+
}
|
|
940
|
+
cells.push(paragraphs.join(' ').trim())
|
|
941
|
+
cellMatch = cellPattern.exec(rowMatch[1])
|
|
942
|
+
}
|
|
943
|
+
rows.push(cells)
|
|
944
|
+
rowMatch = rowPattern.exec(xml)
|
|
945
|
+
}
|
|
946
|
+
return rows
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* Read the body of a docx into blocks the pane can lay out.
|
|
951
|
+
* @param {Buffer} buffer - file bytes
|
|
952
|
+
* @returns {{blocks: Array<object>, truncated: boolean, maxBlocks: number}} payload
|
|
953
|
+
*/
|
|
954
|
+
function readDocument(buffer) {
|
|
955
|
+
const zip = readZip(buffer)
|
|
956
|
+
const document = zip.get('word/document.xml')
|
|
957
|
+
if (!document) throw new RouteError(415, 'not a Word document')
|
|
958
|
+
let xml = document.toString('utf8')
|
|
959
|
+
const tables = []
|
|
960
|
+
xml = xml.replace(/<w:tbl\b[\s\S]*?<\/w:tbl>/g, (block) => {
|
|
961
|
+
tables.push(docxTableRows(block))
|
|
962
|
+
return '\u0000TBL' + (tables.length - 1) + '\u0000'
|
|
963
|
+
})
|
|
964
|
+
const blocks = []
|
|
965
|
+
const body = /<w:body\b[^>]*>([\s\S]*?)<\/w:body>/.exec(xml)
|
|
966
|
+
const source = body ? body[1] : xml
|
|
967
|
+
const chunkPattern = /<w:p\b([^>]*)>([\s\S]*?)<\/w:p>|\u0000TBL(\d+)\u0000/g
|
|
968
|
+
let chunk = chunkPattern.exec(source)
|
|
969
|
+
while (chunk && blocks.length < 4000) {
|
|
970
|
+
if (chunk[3] !== undefined) {
|
|
971
|
+
const rows = tables[Number(chunk[3])] || []
|
|
972
|
+
if (rows.length > 0) blocks.push({ type: 'table', rows })
|
|
973
|
+
} else {
|
|
974
|
+
const inner = chunk[2]
|
|
975
|
+
const text = docxParagraphText(inner).trim()
|
|
976
|
+
if (text.length > 0) {
|
|
977
|
+
const style = /<w:pStyle w:val="([^"]+)"/.exec(inner)
|
|
978
|
+
const numbered = /<w:numPr>/.test(inner)
|
|
979
|
+
const name = style ? style[1] : ''
|
|
980
|
+
let type = 'p'
|
|
981
|
+
if (/^Heading([1-4])$/.test(name)) type = 'h' + name.slice(7)
|
|
982
|
+
else if (numbered || /list/i.test(name)) type = 'li'
|
|
983
|
+
blocks.push({ type, text })
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
chunk = chunkPattern.exec(source)
|
|
987
|
+
}
|
|
988
|
+
if (blocks.length === 0) throw new RouteError(415, 'the document has no text')
|
|
989
|
+
return { blocks, truncated: blocks.length >= 4000, maxBlocks: 4000 }
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Whether a request plausibly came from the DSH page itself.
|
|
993
|
+
*
|
|
994
|
+
* The route is served by the host web server, but plugin prefix handlers see
|
|
995
|
+
* the request before the app shell does, so a page on any other origin could
|
|
996
|
+
* otherwise read files or trigger the write routes. Browsers mark cross-site
|
|
997
|
+
* requests with Sec-Fetch-Site and Origin, so refuse those; requests without
|
|
998
|
+
* them (curl, the CLI, tests) keep working.
|
|
999
|
+
* @param {import('node:http').IncomingMessage} req - request
|
|
1000
|
+
* @returns {boolean} true when the request may be served
|
|
1001
|
+
*/
|
|
1002
|
+
/**
|
|
1003
|
+
* Every route the plugin serves, with the methods it answers.
|
|
1004
|
+
* The connection gate authenticates each one before this table runs.
|
|
1005
|
+
*/
|
|
1006
|
+
const ROUTES = [
|
|
1007
|
+
{ suffix: '/meta', methods: ['GET'] },
|
|
1008
|
+
{ suffix: '/env', methods: ['GET'] },
|
|
1009
|
+
{ suffix: '/roots', methods: ['GET'] },
|
|
1010
|
+
{ suffix: '/list', methods: ['GET'] },
|
|
1011
|
+
{ suffix: '/read', methods: ['GET'] },
|
|
1012
|
+
{ suffix: '/stat', methods: ['GET'] },
|
|
1013
|
+
{ suffix: '/raw', methods: ['GET'] },
|
|
1014
|
+
{ suffix: '/sheet', methods: ['GET'] },
|
|
1015
|
+
{ suffix: '/document', methods: ['GET'] },
|
|
1016
|
+
{ suffix: '/reveal', methods: ['POST'] },
|
|
1017
|
+
{ suffix: '/open', methods: ['POST'] },
|
|
1018
|
+
{ suffix: '/rename', methods: ['POST'] },
|
|
1019
|
+
{ suffix: '/duplicate', methods: ['POST'] },
|
|
1020
|
+
{ suffix: '/mkdir', methods: ['POST'] },
|
|
1021
|
+
{ suffix: '/newfile', methods: ['POST'] },
|
|
1022
|
+
{ suffix: '/trash', methods: ['POST'] },
|
|
1023
|
+
{ suffix: '/transfer', methods: ['POST'] },
|
|
1024
|
+
{ suffix: '/write', methods: ['POST'] },
|
|
1025
|
+
{ suffix: '/download', methods: ['GET'] },
|
|
1026
|
+
{ suffix: '/upload', methods: ['POST'] },
|
|
1027
|
+
{ suffix: '/archive', methods: ['POST'] },
|
|
1028
|
+
{ suffix: '/extract', methods: ['POST'] },
|
|
1029
|
+
{ suffix: '/git', methods: ['GET'] },
|
|
1030
|
+
{ suffix: '/watch', methods: ['GET'] },
|
|
1031
|
+
{ suffix: '/search', methods: ['GET'] },
|
|
1032
|
+
]
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Adapt one Fetch request to the Node-style dispatcher underneath and turn the
|
|
1036
|
+
* captured response back into a Fetch response.
|
|
1037
|
+
* @param {Request} request - fetch request from the connection gate
|
|
1038
|
+
* @returns {Promise<Response>} fetch response
|
|
1039
|
+
*/
|
|
1040
|
+
async function handleFetch(request) {
|
|
1041
|
+
const url = new URL(request.url)
|
|
1042
|
+
// Uploads are the one route whose body must not be buffered in memory.
|
|
1043
|
+
if (url.pathname === PREFIX + '/upload') return handleUpload(request, url)
|
|
1044
|
+
const raw = request.method === 'GET' || request.method === 'HEAD'
|
|
1045
|
+
? Buffer.alloc(0)
|
|
1046
|
+
: Buffer.from(await request.arrayBuffer())
|
|
1047
|
+
const req = Readable.from([raw])
|
|
1048
|
+
req.method = request.method
|
|
1049
|
+
req.url = url.pathname + url.search
|
|
1050
|
+
req.headers = Object.fromEntries(request.headers.entries())
|
|
1051
|
+
|
|
1052
|
+
let status = 200
|
|
1053
|
+
let headers = {}
|
|
1054
|
+
let payload = Buffer.alloc(0)
|
|
1055
|
+
const res = {
|
|
1056
|
+
writeHead(code, extra) {
|
|
1057
|
+
status = code
|
|
1058
|
+
headers = extra || {}
|
|
1059
|
+
},
|
|
1060
|
+
end(chunk) {
|
|
1061
|
+
if (chunk === undefined || chunk === null) return
|
|
1062
|
+
payload = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
1063
|
+
},
|
|
1064
|
+
}
|
|
1065
|
+
await handleRequest(req, res)
|
|
1066
|
+
return new Response(payload, { status, headers })
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Answer the sheet route: an .xlsx/.xlsm workbook parsed into named sheets.
|
|
1070
|
+
* @param {string} target - canonical file path
|
|
1071
|
+
* @returns {Promise<object>} { sheets, truncated }
|
|
1072
|
+
*/
|
|
1073
|
+
async function readDocumentRoute(target) {
|
|
1074
|
+
const info = await stat(target)
|
|
1075
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1076
|
+
const ext = extname(target).toLowerCase()
|
|
1077
|
+
if (ext !== '.docx' && ext !== '.docm') throw new RouteError(415, 'only .docx and .docm can be parsed')
|
|
1078
|
+
if (info.size > MAX_SHEET_BYTES) throw new RouteError(413, 'document is too large')
|
|
1079
|
+
return readDocument(await readFile(target))
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
async function readSheet(target) {
|
|
1083
|
+
const info = await stat(target)
|
|
1084
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1085
|
+
const ext = extname(target).toLowerCase()
|
|
1086
|
+
if (ext !== '.xlsx' && ext !== '.xlsm') throw new RouteError(415, 'only .xlsx and .xlsm can be parsed')
|
|
1087
|
+
if (info.size > MAX_SHEET_BYTES) throw new RouteError(413, 'workbook is too large')
|
|
1088
|
+
const parsed = readWorkbook(await readFile(target))
|
|
1089
|
+
return {
|
|
1090
|
+
sheets: parsed.sheets,
|
|
1091
|
+
truncated: parsed.sheets.some(sheet => sheet.rows.length >= MAX_SHEET_ROWS),
|
|
1092
|
+
maxRows: MAX_SHEET_ROWS,
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/**
|
|
1097
|
+
* Answer one file with its bytes, so the browser can build a File and hand it
|
|
1098
|
+
* to the conversation composer (the "添加到会话" action).
|
|
1099
|
+
* @param {import('node:http').ServerResponse} res - response
|
|
1100
|
+
* @param {string} target - absolute path inside the root
|
|
1101
|
+
* @returns {Promise<void>} resolves after the response is written
|
|
1102
|
+
*/
|
|
1103
|
+
async function sendRaw(res, target) {
|
|
1104
|
+
const info = await stat(target)
|
|
1105
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1106
|
+
if (info.size > 64 * 1024 * 1024) throw new RouteError(413, '文件超过 64 MB')
|
|
1107
|
+
const data = await readFile(target)
|
|
1108
|
+
const type = mimeOf(target)
|
|
1109
|
+
res.writeHead(200, {
|
|
1110
|
+
'Content-Type': type,
|
|
1111
|
+
'Content-Length': data.length,
|
|
1112
|
+
'Cache-Control': 'no-store',
|
|
1113
|
+
})
|
|
1114
|
+
res.end(data)
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function mimeOf(target) {
|
|
1118
|
+
const ext = extname(target).toLowerCase()
|
|
1119
|
+
const table = {
|
|
1120
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
|
|
1121
|
+
'.webp': 'image/webp', '.bmp': 'image/bmp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
|
|
1122
|
+
'.txt': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
|
|
1123
|
+
'.json': 'application/json; charset=utf-8', '.csv': 'text/csv; charset=utf-8',
|
|
1124
|
+
'.pdf': 'application/pdf', '.zip': 'application/zip',
|
|
1125
|
+
'.doc': 'application/msword',
|
|
1126
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
1127
|
+
'.xls': 'application/vnd.ms-excel',
|
|
1128
|
+
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
1129
|
+
'.ppt': 'application/vnd.ms-powerpoint',
|
|
1130
|
+
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
1131
|
+
'.htm': 'text/html; charset=utf-8', '.html': 'text/html; charset=utf-8',
|
|
1132
|
+
'.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
1133
|
+
'.mjs': 'text/javascript; charset=utf-8', '.jsx': 'text/javascript; charset=utf-8',
|
|
1134
|
+
'.xml': 'application/xml; charset=utf-8', '.svgz': 'image/svg+xml',
|
|
1135
|
+
'.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
|
|
1136
|
+
'.wasm': 'application/wasm', '.map': 'application/json; charset=utf-8',
|
|
1137
|
+
'.tsv': 'text/tab-separated-values; charset=utf-8',
|
|
1138
|
+
'.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.aac': 'audio/aac',
|
|
1139
|
+
'.flac': 'audio/flac', '.ogg': 'audio/ogg', '.oga': 'audio/ogg', '.opus': 'audio/opus',
|
|
1140
|
+
'.aiff': 'audio/aiff', '.aif': 'audio/aiff',
|
|
1141
|
+
'.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime',
|
|
1142
|
+
'.webm': 'video/webm', '.ogv': 'video/ogg',
|
|
1143
|
+
}
|
|
1144
|
+
if (table[ext]) return table[ext]
|
|
1145
|
+
if (TEXT_EXTENSIONS.has(ext.slice(1)) || TEXT_EXTENSIONS.has(ext)) return 'text/plain; charset=utf-8'
|
|
1146
|
+
return 'application/octet-stream'
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* Collect a request body, refusing anything unreasonably large.
|
|
1151
|
+
* @param {import('node:http').IncomingMessage} req - request
|
|
1152
|
+
* @returns {Promise<string>} raw body text
|
|
1153
|
+
*/
|
|
1154
|
+
function readBody(req) {
|
|
1155
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1156
|
+
let raw = ''
|
|
1157
|
+
req.on('data', (chunk) => {
|
|
1158
|
+
raw += chunk
|
|
1159
|
+
if (raw.length > 1_000_000) {
|
|
1160
|
+
rejectPromise(new RouteError(413, '请求内容过大'))
|
|
1161
|
+
req.destroy()
|
|
1162
|
+
}
|
|
1163
|
+
})
|
|
1164
|
+
req.on('end', () => resolvePromise(raw))
|
|
1165
|
+
req.on('error', error => rejectPromise(error))
|
|
1166
|
+
})
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
/**
|
|
1170
|
+
* Dispatch one HTTP request to its route. The web server's `resource` routes
|
|
1171
|
+
* answer GET and HEAD only, so the whole API is registered as one handler that
|
|
1172
|
+
* owns its responses and can therefore also serve the write actions.
|
|
1173
|
+
* @param {import('node:http').IncomingMessage} req - request
|
|
1174
|
+
* @param {import('node:http').ServerResponse} res - response
|
|
1175
|
+
* @returns {Promise<void>} resolves after the response is written
|
|
1176
|
+
*/
|
|
1177
|
+
async function handleRequest(req, res) {
|
|
1178
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
1179
|
+
const route = url.pathname.slice(PREFIX.length) || '/'
|
|
1180
|
+
const method = req.method || 'GET'
|
|
1181
|
+
const path = url.searchParams.get('path')
|
|
1182
|
+
const name = url.searchParams.get('name')
|
|
1183
|
+
try {
|
|
1184
|
+
if (route === '/env' && method === 'GET') {
|
|
1185
|
+
// "local" means the browser reached us over loopback, so desktop actions
|
|
1186
|
+
// (reveal, open with the default app, trash) act on the machine the user
|
|
1187
|
+
// is looking at. Any other host name means a remote browser.
|
|
1188
|
+
const hostHeader = String((req.headers && req.headers.host) || '').toLowerCase()
|
|
1189
|
+
const hostName = hostHeader.replace(/:\d+$/, '')
|
|
1190
|
+
const loopback = hostName === '127.0.0.1' || hostName === 'localhost' ||
|
|
1191
|
+
hostName === '[::1]' || hostName === '0.0.0.0' || hostName === ''
|
|
1192
|
+
send(res, 200, { local: loopback, platform: currentPlatform(), hostname: hostName })
|
|
1193
|
+
return
|
|
1194
|
+
}
|
|
1195
|
+
if (route === '/meta' && method === 'GET') {
|
|
1196
|
+
send(res, 200, await readMeta())
|
|
1197
|
+
return
|
|
1198
|
+
}
|
|
1199
|
+
if (route === '/roots' && method === 'GET') {
|
|
1200
|
+
send(res, 200, { roots: [{ label: basename(ROOT), path: ROOT }] })
|
|
1201
|
+
return
|
|
1202
|
+
}
|
|
1203
|
+
if (route === '/list' && method === 'GET') {
|
|
1204
|
+
send(res, 200, await listDirectory(await safePath(path)))
|
|
1205
|
+
return
|
|
1206
|
+
}
|
|
1207
|
+
if (route === '/read' && method === 'GET') {
|
|
1208
|
+
const target = await safePath(path)
|
|
1209
|
+
const payload = await readPreview(target)
|
|
1210
|
+
const peek = await fsPeek(target)
|
|
1211
|
+
payload.version = peek && peek.info && peek.info.version ? String(peek.info.version) : null
|
|
1212
|
+
send(res, 200, payload)
|
|
1213
|
+
return
|
|
1214
|
+
}
|
|
1215
|
+
if (route === '/stat' && method === 'GET') {
|
|
1216
|
+
send(res, 200, await statEntry(await safePath(path)))
|
|
1217
|
+
return
|
|
1218
|
+
}
|
|
1219
|
+
if (route === '/raw' && method === 'GET') {
|
|
1220
|
+
await sendRaw(res, await safePath(path))
|
|
1221
|
+
return
|
|
1222
|
+
}
|
|
1223
|
+
if (route === '/sheet' && method === 'GET') {
|
|
1224
|
+
send(res, 200, await readSheet(await safePath(path)))
|
|
1225
|
+
return
|
|
1226
|
+
}
|
|
1227
|
+
if (route === '/document' && method === 'GET') {
|
|
1228
|
+
send(res, 200, await readDocumentRoute(await safePath(path)))
|
|
1229
|
+
return
|
|
1230
|
+
}
|
|
1231
|
+
if (route === '/reveal' && method === 'POST') {
|
|
1232
|
+
send(res, 200, await reveal(await safePath(path)))
|
|
1233
|
+
return
|
|
1234
|
+
}
|
|
1235
|
+
if (route === '/open' && method === 'POST') {
|
|
1236
|
+
send(res, 200, await openWithDefault(await safePath(path)))
|
|
1237
|
+
return
|
|
1238
|
+
}
|
|
1239
|
+
if (route === '/rename' && method === 'POST') {
|
|
1240
|
+
send(res, 200, await renameEntry(await safePath(path), name))
|
|
1241
|
+
return
|
|
1242
|
+
}
|
|
1243
|
+
if (route === '/duplicate' && method === 'POST') {
|
|
1244
|
+
send(res, 200, await duplicateEntry(await safePath(path)))
|
|
1245
|
+
return
|
|
1246
|
+
}
|
|
1247
|
+
if (route === '/mkdir' && method === 'POST') {
|
|
1248
|
+
send(res, 200, await createDirectory(await safePath(path), name))
|
|
1249
|
+
return
|
|
1250
|
+
}
|
|
1251
|
+
if (route === '/newfile' && method === 'POST') {
|
|
1252
|
+
send(res, 200, await createFile(await safePath(path), name))
|
|
1253
|
+
return
|
|
1254
|
+
}
|
|
1255
|
+
if (route === '/trash' && method === 'POST') {
|
|
1256
|
+
send(res, 200, await moveToTrash(await safePath(path)))
|
|
1257
|
+
return
|
|
1258
|
+
}
|
|
1259
|
+
if (route === '/transfer' && method === 'POST') {
|
|
1260
|
+
const raw = await readBody(req)
|
|
1261
|
+
let body = {}
|
|
1262
|
+
try {
|
|
1263
|
+
body = raw.length > 0 ? JSON.parse(raw) : {}
|
|
1264
|
+
} catch {
|
|
1265
|
+
throw new RouteError(400, '请求内容无法解析')
|
|
1266
|
+
}
|
|
1267
|
+
send(res, 200, await transfer(body || {}))
|
|
1268
|
+
return
|
|
1269
|
+
}
|
|
1270
|
+
if (route === '/write' && method === 'POST') {
|
|
1271
|
+
const body = await readJsonBody(req)
|
|
1272
|
+
send(res, 200, await writeTextRoute(path, body.text, body ? body.version : null))
|
|
1273
|
+
return
|
|
1274
|
+
}
|
|
1275
|
+
if (route === '/watch' && method === 'GET') {
|
|
1276
|
+
send(res, 200, await watchRoute(path, url.searchParams.get('preview')))
|
|
1277
|
+
return
|
|
1278
|
+
}
|
|
1279
|
+
if (route === '/search' && method === 'GET') {
|
|
1280
|
+
send(res, 200, await searchRoute(
|
|
1281
|
+
path,
|
|
1282
|
+
url.searchParams.get('query') || '',
|
|
1283
|
+
url.searchParams.get('mode') === 'content' ? 'content' : 'name',
|
|
1284
|
+
url.searchParams.get('hidden') === '1',
|
|
1285
|
+
))
|
|
1286
|
+
return
|
|
1287
|
+
}
|
|
1288
|
+
if (route === '/download' && method === 'GET') {
|
|
1289
|
+
await sendAttachment(res, await safePath(path))
|
|
1290
|
+
return
|
|
1291
|
+
}
|
|
1292
|
+
if (route === '/archive' && method === 'POST') {
|
|
1293
|
+
send(res, 200, await createArchive(await readJsonBody(req)))
|
|
1294
|
+
return
|
|
1295
|
+
}
|
|
1296
|
+
if (route === '/extract' && method === 'POST') {
|
|
1297
|
+
send(res, 200, await extractArchive(await readJsonBody(req)))
|
|
1298
|
+
return
|
|
1299
|
+
}
|
|
1300
|
+
if (route === '/git' && method === 'GET') {
|
|
1301
|
+
send(res, 200, await gitStatusRoute(await safePath(path)))
|
|
1302
|
+
return
|
|
1303
|
+
}
|
|
1304
|
+
send(res, 404, { error: 'not-found', route, method })
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
if (error instanceof RouteError) {
|
|
1307
|
+
send(res, error.status, { error: 'request-failed', message: error.message })
|
|
1308
|
+
return
|
|
1309
|
+
}
|
|
1310
|
+
const code = error && error.code
|
|
1311
|
+
const status = code === 'EACCES' || code === 'EPERM' ? 403 : code === 'ENOENT' ? 404 : code === 'EEXIST' ? 409 : 500
|
|
1312
|
+
send(res, status, { error: 'request-failed', message: String(error && error.message ? error.message : error) })
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
/**
|
|
1317
|
+
* Read a JSON request body, tolerating an empty one.
|
|
1318
|
+
* @param {import('node:http').IncomingMessage} req - request
|
|
1319
|
+
* @returns {Promise<Record<string, any>>} parsed body
|
|
1320
|
+
*/
|
|
1321
|
+
async function readJsonBody(req) {
|
|
1322
|
+
const raw = await readBody(req)
|
|
1323
|
+
if (raw.length === 0) return {}
|
|
1324
|
+
try {
|
|
1325
|
+
const parsed = JSON.parse(raw)
|
|
1326
|
+
return parsed && typeof parsed === 'object' ? parsed : {}
|
|
1327
|
+
} catch {
|
|
1328
|
+
throw new RouteError(400, '请求内容无法解析')
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/* --------------------------------------------------------------- uploads */
|
|
1333
|
+
|
|
1334
|
+
/** Largest single upload written to disk, in bytes. */
|
|
1335
|
+
const MAX_UPLOAD_BYTES = 512 * 1024 * 1024
|
|
1336
|
+
|
|
1337
|
+
/**
|
|
1338
|
+
* Build a JSON Fetch response.
|
|
1339
|
+
* @param {number} status - HTTP status
|
|
1340
|
+
* @param {unknown} payload - serializable body
|
|
1341
|
+
* @returns {Response} response
|
|
1342
|
+
*/
|
|
1343
|
+
function json(status, payload) {
|
|
1344
|
+
return new Response(JSON.stringify(payload), {
|
|
1345
|
+
status,
|
|
1346
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
1347
|
+
})
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* Turn any thrown error into the response shape the client expects.
|
|
1352
|
+
* @param {unknown} error - thrown value
|
|
1353
|
+
* @returns {Response} response
|
|
1354
|
+
*/
|
|
1355
|
+
function errorResponse(error) {
|
|
1356
|
+
if (error instanceof RouteError) {
|
|
1357
|
+
return json(error.status, { error: 'request-failed', message: error.message })
|
|
1358
|
+
}
|
|
1359
|
+
const code = error && error.code
|
|
1360
|
+
const status = code === 'EACCES' || code === 'EPERM' ? 403 : code === 'ENOENT' ? 404 : code === 'EEXIST' ? 409 : 500
|
|
1361
|
+
return json(status, { error: 'request-failed', message: String(error && error.message ? error.message : error) })
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
/**
|
|
1365
|
+
* Stream one browser upload into the target folder. The bytes never sit in
|
|
1366
|
+
* memory: the connection gate hands over the request body as a stream.
|
|
1367
|
+
* @param {Request} request - fetch request
|
|
1368
|
+
* @param {URL} url - request URL
|
|
1369
|
+
* @returns {Promise<Response>} response
|
|
1370
|
+
*/
|
|
1371
|
+
async function handleUpload(request, url) {
|
|
1372
|
+
let temp
|
|
1373
|
+
try {
|
|
1374
|
+
const dir = await safePath(url.searchParams.get('path'))
|
|
1375
|
+
const info = await stat(dir)
|
|
1376
|
+
if (!info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1377
|
+
const name = safeName(url.searchParams.get('name'))
|
|
1378
|
+
const target = await freePath(dir, name)
|
|
1379
|
+
temp = join(dir, `.dsh-upload-${process.pid}-${Date.now()}`)
|
|
1380
|
+
const sink = createWriteStream(temp, { flags: 'wx' })
|
|
1381
|
+
const finished = new Promise((resolvePromise, rejectPromise) => {
|
|
1382
|
+
sink.on('close', resolvePromise)
|
|
1383
|
+
sink.on('error', rejectPromise)
|
|
1384
|
+
})
|
|
1385
|
+
let total = 0
|
|
1386
|
+
try {
|
|
1387
|
+
if (request.body) {
|
|
1388
|
+
for await (const chunk of request.body) {
|
|
1389
|
+
total += chunk.length
|
|
1390
|
+
if (total > MAX_UPLOAD_BYTES) throw new RouteError(413, 'upload is larger than 512 MB')
|
|
1391
|
+
if (!sink.write(chunk)) await once(sink, 'drain')
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
sink.end()
|
|
1395
|
+
await finished
|
|
1396
|
+
} catch (error) {
|
|
1397
|
+
sink.destroy()
|
|
1398
|
+
await rm(temp, { force: true }).catch(() => undefined)
|
|
1399
|
+
throw error
|
|
1400
|
+
}
|
|
1401
|
+
await rename(temp, target)
|
|
1402
|
+
temp = undefined
|
|
1403
|
+
return json(200, { ok: true, path: target, name: basename(target), size: total })
|
|
1404
|
+
} catch (error) {
|
|
1405
|
+
if (temp) await rm(temp, { force: true }).catch(() => undefined)
|
|
1406
|
+
return errorResponse(error)
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
/** Largest archive built in memory, in bytes. */
|
|
1411
|
+
const MAX_ARCHIVE_BYTES = 256 * 1024 * 1024
|
|
1412
|
+
/** Most entries one archive may hold. */
|
|
1413
|
+
const MAX_ARCHIVE_ENTRIES = 5000
|
|
1414
|
+
|
|
1415
|
+
/** CRC-32 lookup table for the ZIP writer. */
|
|
1416
|
+
const CRC_TABLE = (() => {
|
|
1417
|
+
const table = new Uint32Array(256)
|
|
1418
|
+
for (let i = 0; i < 256; i += 1) {
|
|
1419
|
+
let value = i
|
|
1420
|
+
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1
|
|
1421
|
+
table[i] = value >>> 0
|
|
1422
|
+
}
|
|
1423
|
+
return table
|
|
1424
|
+
})()
|
|
1425
|
+
|
|
1426
|
+
/**
|
|
1427
|
+
* CRC-32 of a buffer, as the ZIP format stores it.
|
|
1428
|
+
* @param {Buffer} buffer - bytes
|
|
1429
|
+
* @returns {number} checksum
|
|
1430
|
+
*/
|
|
1431
|
+
function crc32(buffer) {
|
|
1432
|
+
let crc = 0xffffffff
|
|
1433
|
+
for (let i = 0; i < buffer.length; i += 1) crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ buffer[i]) & 0xff]
|
|
1434
|
+
return (crc ^ 0xffffffff) >>> 0
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/**
|
|
1438
|
+
* MS-DOS date and time fields for one entry.
|
|
1439
|
+
* @param {Date} date - timestamp
|
|
1440
|
+
* @returns {{ time: number, day: number }} packed fields
|
|
1441
|
+
*/
|
|
1442
|
+
function dosStamp(date) {
|
|
1443
|
+
const time = (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2)
|
|
1444
|
+
const day = ((Math.max(1980, date.getFullYear()) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()
|
|
1445
|
+
return { time, day }
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/**
|
|
1449
|
+
* Write a ZIP archive in memory, deflating each entry when that helps.
|
|
1450
|
+
* @param {{ name: string, data: Buffer, mtime: Date }[]} entries - archive contents
|
|
1451
|
+
* @returns {Buffer} the archive
|
|
1452
|
+
*/
|
|
1453
|
+
function buildZip(entries) {
|
|
1454
|
+
const parts = []
|
|
1455
|
+
const central = []
|
|
1456
|
+
let offset = 0
|
|
1457
|
+
for (const entry of entries) {
|
|
1458
|
+
const nameBuffer = Buffer.from(entry.name.replaceAll('\\\\', '/'), 'utf8')
|
|
1459
|
+
const deflated = deflateRawSync(entry.data, { level: 6 })
|
|
1460
|
+
const method = deflated.length < entry.data.length ? 8 : 0
|
|
1461
|
+
const body = method === 8 ? deflated : entry.data
|
|
1462
|
+
const checksum = crc32(entry.data)
|
|
1463
|
+
const stamp = dosStamp(entry.mtime instanceof Date ? entry.mtime : new Date())
|
|
1464
|
+
const local = Buffer.alloc(30)
|
|
1465
|
+
local.writeUInt32LE(0x04034b50, 0)
|
|
1466
|
+
local.writeUInt16LE(20, 4)
|
|
1467
|
+
local.writeUInt16LE(0x0800, 6)
|
|
1468
|
+
local.writeUInt16LE(method, 8)
|
|
1469
|
+
local.writeUInt16LE(stamp.time, 10)
|
|
1470
|
+
local.writeUInt16LE(stamp.day, 12)
|
|
1471
|
+
local.writeUInt32LE(checksum, 14)
|
|
1472
|
+
local.writeUInt32LE(body.length, 18)
|
|
1473
|
+
local.writeUInt32LE(entry.data.length, 22)
|
|
1474
|
+
local.writeUInt16LE(nameBuffer.length, 26)
|
|
1475
|
+
local.writeUInt16LE(0, 28)
|
|
1476
|
+
parts.push(local, nameBuffer, body)
|
|
1477
|
+
central.push({ nameBuffer, method, checksum, size: body.length, raw: entry.data.length, offset, stamp })
|
|
1478
|
+
offset += local.length + nameBuffer.length + body.length
|
|
1479
|
+
}
|
|
1480
|
+
const directoryStart = offset
|
|
1481
|
+
for (const entry of central) {
|
|
1482
|
+
const header = Buffer.alloc(46)
|
|
1483
|
+
header.writeUInt32LE(0x02014b50, 0)
|
|
1484
|
+
header.writeUInt16LE(20, 4)
|
|
1485
|
+
header.writeUInt16LE(20, 6)
|
|
1486
|
+
header.writeUInt16LE(0x0800, 8)
|
|
1487
|
+
header.writeUInt16LE(entry.method, 10)
|
|
1488
|
+
header.writeUInt16LE(entry.stamp.time, 12)
|
|
1489
|
+
header.writeUInt16LE(entry.stamp.day, 14)
|
|
1490
|
+
header.writeUInt32LE(entry.checksum, 16)
|
|
1491
|
+
header.writeUInt32LE(entry.size, 20)
|
|
1492
|
+
header.writeUInt32LE(entry.raw, 24)
|
|
1493
|
+
header.writeUInt16LE(entry.nameBuffer.length, 28)
|
|
1494
|
+
header.writeUInt16LE(0, 30)
|
|
1495
|
+
header.writeUInt16LE(0, 32)
|
|
1496
|
+
header.writeUInt16LE(0, 34)
|
|
1497
|
+
header.writeUInt16LE(0, 36)
|
|
1498
|
+
header.writeUInt32LE(0, 38)
|
|
1499
|
+
header.writeUInt32LE(entry.offset, 42)
|
|
1500
|
+
parts.push(header, entry.nameBuffer)
|
|
1501
|
+
offset += header.length + entry.nameBuffer.length
|
|
1502
|
+
}
|
|
1503
|
+
const end = Buffer.alloc(22)
|
|
1504
|
+
end.writeUInt32LE(0x06054b50, 0)
|
|
1505
|
+
end.writeUInt16LE(central.length, 8)
|
|
1506
|
+
end.writeUInt16LE(central.length, 10)
|
|
1507
|
+
end.writeUInt32LE(offset - directoryStart, 12)
|
|
1508
|
+
end.writeUInt32LE(directoryStart, 16)
|
|
1509
|
+
parts.push(end)
|
|
1510
|
+
return Buffer.concat(parts)
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
/**
|
|
1514
|
+
* Gather files for an archive, keeping relative names under one folder.
|
|
1515
|
+
* @param {string[]} targets - canonical absolute paths
|
|
1516
|
+
* @returns {Promise<{ entries: { name: string, data: Buffer, mtime: Date }[], total: number, truncated: boolean }>} archive contents
|
|
1517
|
+
*/
|
|
1518
|
+
async function collectZipEntries(targets) {
|
|
1519
|
+
const entries = []
|
|
1520
|
+
let total = 0
|
|
1521
|
+
let truncated = false
|
|
1522
|
+
const walk = async (target, prefix) => {
|
|
1523
|
+
if (entries.length >= MAX_ARCHIVE_ENTRIES) { truncated = true; return }
|
|
1524
|
+
const info = await lstat(target)
|
|
1525
|
+
if (info.isSymbolicLink()) return
|
|
1526
|
+
if (info.isDirectory()) {
|
|
1527
|
+
const children = await readdir(target, { withFileTypes: true })
|
|
1528
|
+
entries.push({ name: prefix + '/', data: Buffer.alloc(0), mtime: info.mtime })
|
|
1529
|
+
for (const child of children) {
|
|
1530
|
+
await walk(join(target, child.name), prefix + '/' + child.name)
|
|
1531
|
+
if (entries.length >= MAX_ARCHIVE_ENTRIES) { truncated = true; return }
|
|
1532
|
+
}
|
|
1533
|
+
return
|
|
1534
|
+
}
|
|
1535
|
+
if (total + info.size > MAX_ARCHIVE_BYTES) { truncated = true; return }
|
|
1536
|
+
const data = await readFile(target)
|
|
1537
|
+
total += data.length
|
|
1538
|
+
entries.push({ name: prefix, data, mtime: info.mtime })
|
|
1539
|
+
}
|
|
1540
|
+
for (const target of targets) await walk(target, basename(target))
|
|
1541
|
+
return { entries, total, truncated }
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/**
|
|
1545
|
+
* Answer the archive route: zip one or more items beside themselves.
|
|
1546
|
+
* @param {object} body - { sources: string[] }
|
|
1547
|
+
* @returns {Promise<object>} { path, size, entries, truncated }
|
|
1548
|
+
*/
|
|
1549
|
+
async function createArchive(body) {
|
|
1550
|
+
const sources = Array.isArray(body?.sources) ? body.sources : []
|
|
1551
|
+
if (sources.length === 0) throw new RouteError(400, 'nothing to archive')
|
|
1552
|
+
const targets = []
|
|
1553
|
+
for (const source of sources) targets.push(await safePath(source))
|
|
1554
|
+
const { entries, total, truncated } = await collectZipEntries(targets)
|
|
1555
|
+
if (entries.length === 0) throw new RouteError(400, 'nothing to archive')
|
|
1556
|
+
const archive = buildZip(entries)
|
|
1557
|
+
if (archive.length > MAX_ARCHIVE_BYTES) throw new RouteError(413, 'archive would be larger than 256 MB')
|
|
1558
|
+
const first = targets[0]
|
|
1559
|
+
const dir = (await stat(first)).isDirectory() ? dirname(first) : dirname(first)
|
|
1560
|
+
const target = await freePath(dir, (basename(first) || 'archive') + '.zip')
|
|
1561
|
+
await writeFile(target, archive)
|
|
1562
|
+
const written = await stat(target)
|
|
1563
|
+
return { ok: true, path: target, name: basename(target), size: written.size, entries: entries.length, bytes: total, truncated }
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* Answer the extract route: unpack a .zip beside itself or into a folder.
|
|
1568
|
+
* @param {object} body - { path: string, target?: string }
|
|
1569
|
+
* @returns {Promise<object>} { path, files, skipped }
|
|
1570
|
+
*/
|
|
1571
|
+
async function extractArchive(body) {
|
|
1572
|
+
const source = await safePath(body?.path)
|
|
1573
|
+
const info = await stat(source)
|
|
1574
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1575
|
+
if (!/\.zip$/i.test(source)) throw new RouteError(415, 'only .zip archives can be extracted')
|
|
1576
|
+
if (info.size > MAX_ARCHIVE_BYTES) throw new RouteError(413, 'archive is larger than 256 MB')
|
|
1577
|
+
const buffer = await readFile(source)
|
|
1578
|
+
const entries = readZip(buffer)
|
|
1579
|
+
if (entries.size === 0) throw new RouteError(400, 'archive is empty')
|
|
1580
|
+
let dir
|
|
1581
|
+
if (body?.target) {
|
|
1582
|
+
dir = await safePath(body.target)
|
|
1583
|
+
if (!(await stat(dir)).isDirectory()) throw new RouteError(400, 'target is not a folder')
|
|
1584
|
+
dir = await freePath(dirname(join(dir, '.')), basename(source).replace(/\.zip$/i, ''))
|
|
1585
|
+
await mkdir(dir, { recursive: true })
|
|
1586
|
+
} else {
|
|
1587
|
+
dir = await freePath(dirname(source), basename(source).replace(/\.zip$/i, ''))
|
|
1588
|
+
await mkdir(dir, { recursive: true })
|
|
1589
|
+
}
|
|
1590
|
+
let files = 0
|
|
1591
|
+
let skipped = 0
|
|
1592
|
+
for (const [name, data] of entries) {
|
|
1593
|
+
if (name.endsWith('/')) { skipped += 1; continue }
|
|
1594
|
+
const relative = name.replace(/^\/+/, '')
|
|
1595
|
+
if (relative.split('/').some(segment => segment === '..')) { skipped += 1; continue }
|
|
1596
|
+
const target = resolve(dir, relative)
|
|
1597
|
+
if (target !== dir && !target.startsWith(dir + sep)) { skipped += 1; continue }
|
|
1598
|
+
await mkdir(dirname(target), { recursive: true })
|
|
1599
|
+
await writeFile(target, data)
|
|
1600
|
+
files += 1
|
|
1601
|
+
}
|
|
1602
|
+
return { ok: true, path: dir, files, skipped }
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
/**
|
|
1606
|
+
* Answer the download route: send one file as an attachment.
|
|
1607
|
+
* @param {import('node:http').ServerResponse} res - response sink
|
|
1608
|
+
* @param {string} target - canonical file path
|
|
1609
|
+
* @returns {Promise<void>} resolves after the response is written
|
|
1610
|
+
*/
|
|
1611
|
+
async function sendAttachment(res, target) {
|
|
1612
|
+
const info = await stat(target)
|
|
1613
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1614
|
+
if (info.size > 512 * 1024 * 1024) throw new RouteError(413, 'file is larger than 512 MB')
|
|
1615
|
+
const data = await readFile(target)
|
|
1616
|
+
res.writeHead(200, {
|
|
1617
|
+
'Content-Type': mimeOf(target),
|
|
1618
|
+
'Content-Length': data.length,
|
|
1619
|
+
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(basename(target))}`,
|
|
1620
|
+
'Cache-Control': 'no-store',
|
|
1621
|
+
})
|
|
1622
|
+
res.end(data)
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
/**
|
|
1626
|
+
* Save the text the editor holds, refusing anything that would not round-trip.
|
|
1627
|
+
* @param {string | null} rawPath - path from the query string
|
|
1628
|
+
* @param {unknown} text - new file contents
|
|
1629
|
+
* @returns {Promise<object>} { ok, path, size, mtime }
|
|
1630
|
+
*/
|
|
1631
|
+
async function writeTextRoute(rawPath, text, version) {
|
|
1632
|
+
const target = await safePath(rawPath)
|
|
1633
|
+
const info = await stat(target)
|
|
1634
|
+
if (info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1635
|
+
if (typeof text !== 'string') throw new RouteError(400, 'text is required')
|
|
1636
|
+
const bytes = Buffer.byteLength(text, 'utf8')
|
|
1637
|
+
if (bytes > MAX_TEXT_BYTES * 8) throw new RouteError(413, 'text is too large')
|
|
1638
|
+
// Prefer DSH's filesystem service: it publishes atomically and rejects a
|
|
1639
|
+
// stale version, so the panel and the host agree on what changed.
|
|
1640
|
+
const peek = await fsPeek(target)
|
|
1641
|
+
if (peek) {
|
|
1642
|
+
try {
|
|
1643
|
+
// The panel is a file manager: its writes are explicit user actions, not
|
|
1644
|
+
// agent tool calls, so they run outside the workspace sandbox. Passing the
|
|
1645
|
+
// policy explicitly keeps the guard/atomic publish without fencing to the
|
|
1646
|
+
// workspace root.
|
|
1647
|
+
const intent = version ? { kind: 'replaceIfVersion', version } : undefined
|
|
1648
|
+
const outcome = await fsApi.writeText(peek.target, text, intent, undefined, {
|
|
1649
|
+
mode: 'danger-full-access',
|
|
1650
|
+
workspaceRoot: ROOT,
|
|
1651
|
+
})
|
|
1652
|
+
const after = await stat(target)
|
|
1653
|
+
return {
|
|
1654
|
+
ok: true,
|
|
1655
|
+
path: target,
|
|
1656
|
+
size: after.size,
|
|
1657
|
+
mtime: after.mtimeMs,
|
|
1658
|
+
version: outcome && outcome.version ? String(outcome.version) : null,
|
|
1659
|
+
via: 'fs',
|
|
1660
|
+
}
|
|
1661
|
+
} catch (error) {
|
|
1662
|
+
if (error && (error.code === 'FS_STALE_VERSION' || error.code === 'FS_NOT_OBSERVED')) {
|
|
1663
|
+
throw new RouteError(409, '文件已被其它程序修改,请重新打开后再保存')
|
|
1664
|
+
}
|
|
1665
|
+
// Any other refusal still falls back to the plain node:fs write, so the
|
|
1666
|
+
// panel never becomes unable to save a file it can read.
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
await writeFile(target, text, 'utf8')
|
|
1670
|
+
const after = await stat(target)
|
|
1671
|
+
const fresh = await fsPeek(target)
|
|
1672
|
+
return {
|
|
1673
|
+
ok: true,
|
|
1674
|
+
path: target,
|
|
1675
|
+
size: after.size,
|
|
1676
|
+
mtime: after.mtimeMs,
|
|
1677
|
+
version: fresh && fresh.info && fresh.info.version ? String(fresh.info.version) : null,
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
/** Search limits: a bounded walk keeps one keystroke from freezing the host. */
|
|
1682
|
+
const SEARCH_MAX_ENTRIES = 4000
|
|
1683
|
+
const SEARCH_MAX_HITS = 200
|
|
1684
|
+
const SEARCH_MAX_DEPTH = 12
|
|
1685
|
+
const SEARCH_TIMEOUT_MS = 4000
|
|
1686
|
+
const SEARCH_MAX_FILE_BYTES = 512 * 1024
|
|
1687
|
+
const SEARCH_HITS_PER_FILE = 20
|
|
1688
|
+
const SEARCH_SKIP_DIRS = new Set(['.git', 'node_modules', '.svn', '.hg', '.Trash', '.cache', 'dist', 'build'])
|
|
1689
|
+
const SEARCH_TEXT_EXT = /\.(txt|md|markdown|json|jsonc|json5|ya?ml|toml|ini|conf|cfg|env|log|csv|tsv|js|mjs|cjs|jsx|ts|tsx|vue|svelte|css|scss|less|html?|xml|svg|sh|bash|zsh|fish|py|rb|go|rs|java|kt|swift|c|h|cc|cpp|hpp|cs|php|sql|graphql|lua|pl|r|tex|dockerfile|gitignore|editorconfig)$/i
|
|
1690
|
+
|
|
1691
|
+
/**
|
|
1692
|
+
* A cheap fingerprint of a directory and one previewed file, so the panel can
|
|
1693
|
+
* notice that an agent (or another program) changed something.
|
|
1694
|
+
* @param {string} rawDir - directory on screen
|
|
1695
|
+
* @param {string | null} rawPreview - file being previewed
|
|
1696
|
+
* @returns {Promise<object>} { dir, preview, at }
|
|
1697
|
+
*/
|
|
1698
|
+
async function watchRoute(rawDir, rawPreview) {
|
|
1699
|
+
const dir = await safePath(rawDir)
|
|
1700
|
+
const dirInfo = await stat(dir).catch(() => null)
|
|
1701
|
+
let count = 0
|
|
1702
|
+
try {
|
|
1703
|
+
count = (await readdir(dir)).length
|
|
1704
|
+
} catch {
|
|
1705
|
+
count = 0
|
|
1706
|
+
}
|
|
1707
|
+
let preview = null
|
|
1708
|
+
if (rawPreview) {
|
|
1709
|
+
try {
|
|
1710
|
+
const file = await safePath(rawPreview)
|
|
1711
|
+
const fileInfo = await stat(file)
|
|
1712
|
+
preview = fileInfo.isDirectory() ? 'dir:' + fileInfo.mtimeMs : fileInfo.mtimeMs + ':' + fileInfo.size
|
|
1713
|
+
} catch {
|
|
1714
|
+
preview = 'gone'
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
return {
|
|
1718
|
+
dir: dirInfo ? dirInfo.mtimeMs + ':' + dirInfo.size + ':' + count : 'gone',
|
|
1719
|
+
preview,
|
|
1720
|
+
at: Date.now(),
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/**
|
|
1725
|
+
* Read one file's matching lines for a content search.
|
|
1726
|
+
* @param {string} file - absolute path
|
|
1727
|
+
* @param {string} needle - lower-case needle
|
|
1728
|
+
* @param {number} left - hit budget left for the whole search
|
|
1729
|
+
* @returns {Promise<object[]>} hits
|
|
1730
|
+
*/
|
|
1731
|
+
async function searchFileContent(file, needle, left) {
|
|
1732
|
+
let info
|
|
1733
|
+
try {
|
|
1734
|
+
info = await stat(file)
|
|
1735
|
+
} catch {
|
|
1736
|
+
return []
|
|
1737
|
+
}
|
|
1738
|
+
if (!info.isFile() || info.size > SEARCH_MAX_FILE_BYTES) return []
|
|
1739
|
+
let text
|
|
1740
|
+
try {
|
|
1741
|
+
text = await readFile(file, 'utf8')
|
|
1742
|
+
} catch {
|
|
1743
|
+
return []
|
|
1744
|
+
}
|
|
1745
|
+
if (text.indexOf(String.fromCharCode(0)) !== -1) return []
|
|
1746
|
+
const hits = []
|
|
1747
|
+
const lines = text.split(/\r?\n/)
|
|
1748
|
+
for (let i = 0; i < lines.length && hits.length < Math.min(left, SEARCH_HITS_PER_FILE); i += 1) {
|
|
1749
|
+
const line = lines[i]
|
|
1750
|
+
if (!line || line.length > 4000) continue
|
|
1751
|
+
if (line.toLowerCase().indexOf(needle) === -1) continue
|
|
1752
|
+
hits.push({
|
|
1753
|
+
path: file,
|
|
1754
|
+
parent: dirname(file),
|
|
1755
|
+
name: basename(file),
|
|
1756
|
+
line: i + 1,
|
|
1757
|
+
text: line.trim().slice(0, 200),
|
|
1758
|
+
size: info.size,
|
|
1759
|
+
mtime: info.mtimeMs,
|
|
1760
|
+
})
|
|
1761
|
+
}
|
|
1762
|
+
return hits
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/**
|
|
1766
|
+
* Walk one directory tree for names or contents.
|
|
1767
|
+
* @param {string} rawDir - directory to start from
|
|
1768
|
+
* @param {string} rawQuery - text to look for
|
|
1769
|
+
* @param {'name' | 'content'} mode - what to match
|
|
1770
|
+
* @param {boolean} hidden - include dot entries
|
|
1771
|
+
* @returns {Promise<object>} { hits, truncated, scanned, tookMs }
|
|
1772
|
+
*/
|
|
1773
|
+
async function searchRoute(rawDir, rawQuery, mode, hidden) {
|
|
1774
|
+
const start = await safePath(rawDir)
|
|
1775
|
+
const info = await stat(start)
|
|
1776
|
+
if (!info.isDirectory()) throw new RouteError(400, 'path is not a folder')
|
|
1777
|
+
const query = String(rawQuery || '').trim()
|
|
1778
|
+
if (query.length === 0) return { hits: [], truncated: false, scanned: 0, tookMs: 0, mode: mode }
|
|
1779
|
+
const needle = query.toLowerCase()
|
|
1780
|
+
const hits = []
|
|
1781
|
+
let scanned = 0
|
|
1782
|
+
let stopped = false
|
|
1783
|
+
const began = Date.now()
|
|
1784
|
+
const stop = () => stopped || hits.length >= SEARCH_MAX_HITS || scanned >= SEARCH_MAX_ENTRIES || Date.now() - began > SEARCH_TIMEOUT_MS
|
|
1785
|
+
const walk = async (folder, depth) => {
|
|
1786
|
+
if (stop()) { stopped = true; return }
|
|
1787
|
+
let entries
|
|
1788
|
+
try {
|
|
1789
|
+
entries = await readdir(folder, { withFileTypes: true })
|
|
1790
|
+
} catch {
|
|
1791
|
+
return
|
|
1792
|
+
}
|
|
1793
|
+
for (const dirent of entries) {
|
|
1794
|
+
if (stop()) { stopped = true; return }
|
|
1795
|
+
if (SEARCH_SKIP_DIRS.has(dirent.name)) continue
|
|
1796
|
+
if (!hidden && dirent.name.startsWith('.')) continue
|
|
1797
|
+
scanned += 1
|
|
1798
|
+
const child = join(folder, dirent.name)
|
|
1799
|
+
const isDir = dirent.isDirectory()
|
|
1800
|
+
if (mode === 'content') {
|
|
1801
|
+
if (!isDir && SEARCH_TEXT_EXT.test(dirent.name)) {
|
|
1802
|
+
const found = await searchFileContent(child, needle, SEARCH_MAX_HITS - hits.length)
|
|
1803
|
+
for (const hit of found) {
|
|
1804
|
+
hits.push(hit)
|
|
1805
|
+
if (hits.length >= SEARCH_MAX_HITS) { stopped = true; break }
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
} else if (dirent.name.toLowerCase().indexOf(needle) !== -1) {
|
|
1809
|
+
const childInfo = await lstat(child).catch(() => null)
|
|
1810
|
+
if (childInfo) {
|
|
1811
|
+
hits.push({
|
|
1812
|
+
path: child,
|
|
1813
|
+
parent: folder,
|
|
1814
|
+
name: dirent.name,
|
|
1815
|
+
dir: isDir,
|
|
1816
|
+
size: childInfo.size,
|
|
1817
|
+
mtime: childInfo.mtimeMs,
|
|
1818
|
+
hidden: dirent.name.startsWith('.'),
|
|
1819
|
+
})
|
|
1820
|
+
if (hits.length >= SEARCH_MAX_HITS) { stopped = true; break }
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
if (isDir && depth < SEARCH_MAX_DEPTH) await walk(child, depth + 1)
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
await walk(start, 0)
|
|
1827
|
+
return { hits, truncated: stopped, scanned, tookMs: Date.now() - began, mode }
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
/** Most git entries the status route reports. */
|
|
1831
|
+
const MAX_GIT_ENTRIES = 5000
|
|
1832
|
+
|
|
1833
|
+
/**
|
|
1834
|
+
* Run one git command inside a directory, with optional locks disabled so the
|
|
1835
|
+
* index is never rewritten by a read-only status call.
|
|
1836
|
+
* @param {string} dir - working directory
|
|
1837
|
+
* @param {string[]} args - git arguments
|
|
1838
|
+
* @returns {Promise<string>} stdout
|
|
1839
|
+
*/
|
|
1840
|
+
function gitIn(dir, args) {
|
|
1841
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1842
|
+
execFile('git', ['-C', dir, ...args], {
|
|
1843
|
+
timeout: 8000,
|
|
1844
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
1845
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
|
|
1846
|
+
}, (error, stdout) => {
|
|
1847
|
+
if (error) rejectPromise(error)
|
|
1848
|
+
else resolvePromise(String(stdout))
|
|
1849
|
+
})
|
|
1850
|
+
})
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
/**
|
|
1854
|
+
* Answer the git route: porcelain status for the repository that holds a folder.
|
|
1855
|
+
* @param {string} dir - canonical directory
|
|
1856
|
+
* @returns {Promise<object>} { repo, entries: Record<string, string> }
|
|
1857
|
+
*/
|
|
1858
|
+
async function gitStatusRoute(dir) {
|
|
1859
|
+
const info = await stat(dir)
|
|
1860
|
+
if (!info.isDirectory()) throw new RouteError(400, 'path is a folder')
|
|
1861
|
+
let repo
|
|
1862
|
+
try {
|
|
1863
|
+
repo = (await gitIn(dir, ['rev-parse', '--show-toplevel'])).trim()
|
|
1864
|
+
} catch {
|
|
1865
|
+
return { repo: null, entries: {} }
|
|
1866
|
+
}
|
|
1867
|
+
if (!repo) return { repo: null, entries: {} }
|
|
1868
|
+
let out = ''
|
|
1869
|
+
try {
|
|
1870
|
+
out = await gitIn(dir, ['status', '--porcelain', '-z', '--untracked-files=normal'])
|
|
1871
|
+
} catch {
|
|
1872
|
+
return { repo, entries: {} }
|
|
1873
|
+
}
|
|
1874
|
+
const entries = {}
|
|
1875
|
+
const records = out.split('\u0000')
|
|
1876
|
+
for (let i = 0; i < records.length && Object.keys(entries).length < MAX_GIT_ENTRIES; i += 1) {
|
|
1877
|
+
const record = records[i]
|
|
1878
|
+
if (record.length < 4) continue
|
|
1879
|
+
const code = record.slice(0, 2)
|
|
1880
|
+
const relative = record.slice(3)
|
|
1881
|
+
if (code.startsWith('R') || code.startsWith('C')) i += 1
|
|
1882
|
+
const absolute = join(repo, relative)
|
|
1883
|
+
const letter = code === '??' ? 'untracked' : code.includes('U') || code === 'AA' || code === 'DD' ? 'conflict' : code[0] !== ' ' ? code[0] : code[1]
|
|
1884
|
+
entries[absolute] = letter
|
|
1885
|
+
}
|
|
1886
|
+
return { repo, entries }
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
/**
|
|
1890
|
+
* Register the file API while the plugin is active.
|
|
1891
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - host context
|
|
1892
|
+
*/
|
|
1893
|
+
export function apply(ctx) {
|
|
1894
|
+
// The filesystem service is optional: a host without it keeps the plain
|
|
1895
|
+
// node:fs behaviour. A nested inject scope activates only once it exists.
|
|
1896
|
+
try {
|
|
1897
|
+
ctx.inject(['fs'], function (fsCtx) {
|
|
1898
|
+
fsApi = fsCtx.fs || null
|
|
1899
|
+
})
|
|
1900
|
+
} catch {
|
|
1901
|
+
fsApi = null
|
|
1902
|
+
}
|
|
1903
|
+
for (const route of ROUTES) {
|
|
1904
|
+
ctx.effect(
|
|
1905
|
+
() => ctx.connection.fetch.register({
|
|
1906
|
+
path: PREFIX + route.suffix,
|
|
1907
|
+
methods: route.methods,
|
|
1908
|
+
requestBody: 'buffered',
|
|
1909
|
+
fetch: handleFetch,
|
|
1910
|
+
}),
|
|
1911
|
+
`dsh-file-explorer: ${route.suffix} route`,
|
|
1912
|
+
)
|
|
1913
|
+
}
|
|
1914
|
+
}
|