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