宿主半: - /sidebar/file 与 /sidebar/html 改为 createReadStream + pipeline(新增 file-stream.ts),删除 mediaLimit;流开始后失败由 writeJson 的 headersSent 守卫降级为 destroy,不再抛 ERR_HTTP_HEADERS_SENT - 上传本就是流式的,只删掉客户端 MAX_UPLOAD_BYTES 预检与宿主 limit 逐块检查 - 删除 readLimit / mediaLimit / uploadLimit 三个配置键,新增共享常量模块 editor-limits.ts(MAX_EDITABLE_BYTES = 5 MiB、PAGE_BYTES、写入体护栏) - fs.read 重塑为 text | binary | too-large 三态,不再有「截断文本」这个 既不可信又不可保存的中间态;新增 fs.readPage 字节窗口分页(按行对齐、 按 path+size+mtime 缓存首次探测到的编码) - 删除 JSON 版 fs.write,改为 /sidebar/write raw 路由(文档即请求体), 拆掉 MAX_BODY_BYTES=1MiB 这道保存墙;编码与行尾还原逻辑原样搬到 fs-operations.writeWorkspaceText - 打包改原生命令:新增 archive-tools.ts(zip → tar 探测、公共祖先定位、 argv 规划、stdio 重定向),archive-route 改为后台写临时文件 + 流式下发, 删除手写 ZIP writer src/zip.ts;新增 unavailable 错误码 客户端半: - 新增 text-pages.ts(字节偏移分页游标,显式翻页)、jsonl.ts(逐行记录 解析与摘要)、lang-jsonl.ts(每行独立的 JSON tokenizer,替代会为每条记录 产生错误节点的 json() 语法)、LargeFileView.tsx(记录卡片 / 日志行两种 只读分页视图) - 新增 jsonl viewer 描述符(预览 = 记录列表,编辑 = 可保存的 CodeMirror) - FileViewerProps 用 size/largeFile 取代 truncated;超限文件改为只读分页 预览并可下载,不再提供编辑器 - tags.invalid 由纯白改为红色波浪线(浅色主题下原本白底白字不可见) - zip 下载改回普通 <a download> 直链,不再把整包放进浏览器内存
169 lines
6.3 KiB
TypeScript
169 lines
6.3 KiB
TypeScript
/**
|
|
* Wire helpers for the /sidebar JSON API: bounded body reading, response
|
|
* writing, and the shared error envelope. Every API method returns
|
|
* `{ok: true, value}` on success and `{ok: false, error: {code, message}}`
|
|
* (HTTP 4xx/5xx matching the code) on failure.
|
|
*/
|
|
import type { SidebarHttpRequest, SidebarHttpResponse } from './context-types.ts'
|
|
// Value import for the error-class branch in writeError. git.ts imports only
|
|
// node builtins, so this introduces no cycle; wire.ts is host-half only and is
|
|
// never reachable from the browser bundle.
|
|
import { GitCommandError } from './git.ts'
|
|
|
|
/** Machine-readable error codes of the sidebar API. */
|
|
export type SidebarErrorCode =
|
|
| 'bad-request'
|
|
| 'not-found'
|
|
| 'forbidden'
|
|
| 'method-error'
|
|
| 'too-large'
|
|
| 'unavailable'
|
|
| 'fs-error'
|
|
| 'fs-conflict'
|
|
| 'git-error'
|
|
| 'git-suggest-empty'
|
|
| 'git-suggest-error'
|
|
| 'job-error'
|
|
| 'team-error'
|
|
| 'team-conflict'
|
|
| 'sidechat-error'
|
|
| 'subagents-unavailable'
|
|
| 'settings-rejected'
|
|
| 'settings-conflict'
|
|
| 'internal'
|
|
|
|
/** One API failure with its wire code and HTTP status. */
|
|
export class SidebarError extends Error {
|
|
constructor(
|
|
readonly code: SidebarErrorCode,
|
|
message: string,
|
|
readonly status = 400,
|
|
/** Optional structured context carried alongside the code. */
|
|
readonly meta?: Record<string, string>,
|
|
) {
|
|
super(message)
|
|
}
|
|
}
|
|
|
|
/** Body size bound of one JSON request (defense against unbounded reads). */
|
|
const MAX_BODY_BYTES = 1 << 20
|
|
|
|
/** Success envelope of one API method. */
|
|
export interface SidebarOk<T> { ok: true; value: T }
|
|
|
|
/** Failure envelope of one API method. */
|
|
export interface SidebarErr { ok: false; error: { code: SidebarErrorCode; message: string } }
|
|
|
|
/** Read and parse the JSON request body (bounded; malformed → bad-request). */
|
|
export async function readJsonBody(req: SidebarHttpRequest): Promise<unknown> {
|
|
const chunks: Buffer[] = []
|
|
let total = 0
|
|
for await (const chunk of req) {
|
|
// The structural request yields string | Uint8Array; Buffer.from accepts
|
|
// both (and the real runtime chunks are node Buffers anyway).
|
|
const buffer = Buffer.from(chunk)
|
|
total += buffer.length
|
|
if (total > MAX_BODY_BYTES) {
|
|
throw new SidebarError('bad-request', 'request body too large')
|
|
}
|
|
chunks.push(buffer)
|
|
}
|
|
const text = Buffer.concat(chunks).toString('utf8')
|
|
if (text.trim() === '') return {}
|
|
try {
|
|
return JSON.parse(text) as unknown
|
|
} catch {
|
|
throw new SidebarError('bad-request', 'request body is not valid JSON')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Read a raw text request body (the editor save route).
|
|
*
|
|
* JSON framing was what capped a save at {@link MAX_BODY_BYTES}: the whole
|
|
* document had to be string-escaped into one JSON payload, so a file the
|
|
* editor could legitimately open could not be written back. The save route
|
|
* therefore takes the document as the raw body.
|
|
*
|
|
* `limit` is a server-side sanity guard rather than a product limit — the UI
|
|
* cannot produce more than the editable size — because the encoding transform
|
|
* the caller runs afterwards needs the document as one string.
|
|
*
|
|
* @param req - the request face (async-iterable body).
|
|
* @param limit - maximum accepted body size in bytes.
|
|
* @returns the body decoded as UTF-8.
|
|
* @throws {SidebarError} too-large beyond the limit, bad-request on invalid UTF-8.
|
|
*/
|
|
export async function readTextBody(req: SidebarHttpRequest, limit: number): Promise<string> {
|
|
const chunks: Buffer[] = []
|
|
let total = 0
|
|
for await (const chunk of req) {
|
|
const buffer = Buffer.from(chunk)
|
|
total += buffer.length
|
|
if (total > limit) {
|
|
throw new SidebarError('too-large', `request body exceeds the ${limit} byte limit`, 413)
|
|
}
|
|
chunks.push(buffer)
|
|
}
|
|
// `fatal` so a body that is not valid UTF-8 is refused instead of silently
|
|
// becoming replacement characters in the saved file.
|
|
try {
|
|
return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))
|
|
} catch {
|
|
throw new SidebarError('bad-request', 'request body is not valid UTF-8')
|
|
}
|
|
}
|
|
|
|
/** Write a JSON response with the given status. */export function writeJson(res: SidebarHttpResponse, status: number, body: unknown): void {
|
|
// The response may already be committed by one of the raw byte routes (a
|
|
// file stream that failed mid-flight): `writeHead` would then throw
|
|
// ERR_HTTP_HEADERS_SENT, and the route's catch block would turn a merely
|
|
// truncated download into a crashed request. There is nothing left to say to
|
|
// the client once the status line is out — tear the socket down instead.
|
|
if (res.headersSent === true) {
|
|
res.destroy?.()
|
|
return
|
|
}
|
|
const payload = JSON.stringify(body)
|
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
res.end(payload)
|
|
}
|
|
|
|
/** Write the success envelope. */
|
|
export function writeOk(res: SidebarHttpResponse, value: unknown): void {
|
|
writeJson(res, 200, { ok: true, value })
|
|
}
|
|
|
|
/** Write the failure envelope for any thrown value (unknown → internal 500). */
|
|
export function writeError(res: SidebarHttpResponse, error: unknown): void {
|
|
if (error instanceof SidebarError) {
|
|
writeJson(res, error.status, { ok: false, error: { code: error.code, message: error.message } })
|
|
return
|
|
}
|
|
// A git failure is a state/input problem the user caused (unknown ref, path
|
|
// outside the repository, not a repository), not a plugin fault. Reporting it
|
|
// as 500 "internal" reads as a crash and hides the localized not-a-repository
|
|
// copy the client already knows how to render; `not-repo` carries its own
|
|
// code (409) so that path is reachable at all.
|
|
if (error instanceof GitCommandError) {
|
|
const notRepo = error.code === 'not-repo'
|
|
writeJson(res, notRepo ? 409 : 400, {
|
|
ok: false,
|
|
error: { code: notRepo ? 'not-repo' : 'git-error', message: error.message },
|
|
})
|
|
return
|
|
}
|
|
const message = error instanceof Error ? error.message : String(error)
|
|
writeJson(res, 500, { ok: false, error: { code: 'internal', message } })
|
|
}
|
|
|
|
/** Narrow an unknown payload value to a string, else throw bad-request. */
|
|
export function requireString(payload: unknown, key: string): string {
|
|
const record = payload as Record<string, unknown> | null
|
|
const value = record?.[key]
|
|
if (typeof value !== 'string' || value === '') {
|
|
throw new SidebarError('bad-request', `missing or invalid "${key}"`)
|
|
}
|
|
return value
|
|
}
|