dsh-remote-vs 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +4 -11
- package/README.md +4 -8
- package/THIRD-PARTY-NOTICES.md +7 -2
- package/lib/client.js +6622 -5821
- package/lib/index.js +275 -1
- package/lib/types/client/CodeEditor.d.ts +14 -0
- package/lib/types/client/OutlinePanel.d.ts +22 -0
- package/lib/types/client/ProcessesSection.d.ts +19 -0
- package/lib/types/client/api.d.ts +5 -1
- package/lib/types/client/blame-model.d.ts +77 -0
- package/lib/types/client/i18n.d.ts +1 -1
- package/lib/types/client/outline-model.d.ts +59 -0
- package/lib/types/client/scm/actions.d.ts +12 -1
- package/lib/types/client/store.d.ts +18 -0
- package/lib/types/client/vsc/blame.d.ts +19 -0
- package/lib/types/client/vsc/kit.d.ts +0 -2
- package/lib/types/client/vsc/preview-document.d.ts +46 -0
- package/lib/types/client/vsc/preview-model.d.ts +31 -0
- package/lib/types/client/vsc/preview-services.d.ts +24 -0
- package/lib/types/git-ops.d.ts +18 -0
- package/lib/types/processes.d.ts +43 -0
- package/lib/types/protocol.d.ts +34 -0
- package/package.json +2 -1
- package/src/client/CodeEditor.tsx +43 -1
- package/src/client/EditorPane.tsx +520 -37
- package/src/client/MonitorView.tsx +16 -5
- package/src/client/OutlinePanel.tsx +287 -0
- package/src/client/ProcessesSection.tsx +292 -0
- package/src/client/api.ts +8 -0
- package/src/client/blame-model.ts +242 -0
- package/src/client/i18n.ts +194 -0
- package/src/client/index.tsx +4 -0
- package/src/client/outline-model.ts +775 -0
- package/src/client/scm/HistoryPanel.tsx +38 -1
- package/src/client/scm/actions.ts +55 -2
- package/src/client/store.tsx +54 -5
- package/src/client/vsc/blame.ts +147 -0
- package/src/client/vsc/kit.tsx +3 -11
- package/src/client/vsc/preview-document.tsx +323 -0
- package/src/client/vsc/preview-model.ts +216 -0
- package/src/client/vsc/preview-services.ts +118 -0
- package/src/client/vsc/vsc.css +6509 -5716
- package/src/git-ops.ts +34 -0
- package/src/processes.ts +177 -0
- package/src/protocol.ts +37 -0
- package/src/routes.ts +118 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Document previews for remote files.
|
|
3
|
+
*
|
|
4
|
+
* Text sources (Markdown/HTML/SVG/CSV) are rendered from the editor buffer. PDF,
|
|
5
|
+
* audio/video and Office bytes never pass through `fs.read` (it is a UTF-8 API
|
|
6
|
+
* with a 4 MiB cap): they are streamed from the existing `/download` route into
|
|
7
|
+
* a blob URL, and Office is first converted to PDF by a LibreOffice already
|
|
8
|
+
* present on the REMOTE host. When that engine is missing the notice says so;
|
|
9
|
+
* the plugin never claims a corrupt file.
|
|
10
|
+
*/
|
|
11
|
+
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
|
12
|
+
import { api, RemoteApiError } from '../api.ts'
|
|
13
|
+
import { downloadUrl } from '../download.ts'
|
|
14
|
+
import { shQuote } from '../../git-format.ts'
|
|
15
|
+
import { DEFAULT_TABLE_LIMITS, extensionOf, mediaTypeOf, parseDelimited, tableDelimiterOf } from './preview-model.ts'
|
|
16
|
+
import { readWorkspaceBytes, renderOfficePdf, type PreviewFailureReason } from './preview-services.ts'
|
|
17
|
+
|
|
18
|
+
/** Never assemble a larger preview body than this in the tab. */
|
|
19
|
+
export const MAX_PREVIEW_BYTES = 64 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
type PreviewError = { kind: PreviewFailureReason; message: string }
|
|
22
|
+
|
|
23
|
+
export function officeExtensionOf(path: string): string | undefined {
|
|
24
|
+
const ext = extensionOf(path)
|
|
25
|
+
return ext === 'doc' || ext === 'docx' || ext === 'ppt' || ext === 'pptx' || ext === 'xls' || ext === 'xlsx'
|
|
26
|
+
? ext
|
|
27
|
+
: undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Convert one remote Office document to PDF on the remote host.
|
|
32
|
+
*
|
|
33
|
+
* Paths and the extension are quoted/validated here; the only value that ends
|
|
34
|
+
* up in the shell is the remote path. A missing engine is reported as
|
|
35
|
+
* `@@RVS_NO_SOFFICE` (notice), not as a corrupt document.
|
|
36
|
+
*/
|
|
37
|
+
export function officeConvertCommand(path: string): string {
|
|
38
|
+
const ext = officeExtensionOf(path)
|
|
39
|
+
if (ext === undefined) throw new Error('unsupported office extension')
|
|
40
|
+
const input = `input.${ext}`
|
|
41
|
+
return [
|
|
42
|
+
"tmp=$(mktemp -d) || { echo '@@RVS_FAIL mktemp'; exit 2; }",
|
|
43
|
+
`cp ${shQuote(path)} "$tmp/${input}" || { rm -rf "$tmp"; echo '@@RVS_FAIL copy'; exit 3; }`,
|
|
44
|
+
'if command -v soffice >/dev/null 2>&1; then bin=soffice;',
|
|
45
|
+
'elif command -v libreoffice >/dev/null 2>&1; then bin=libreoffice;',
|
|
46
|
+
'else rm -rf "$tmp"; echo "@@RVS_NO_SOFFICE"; exit 4; fi',
|
|
47
|
+
"cd \"$tmp\" || { rm -rf \"$tmp\"; echo '@@RVS_FAIL cd'; exit 5; }",
|
|
48
|
+
`"$bin" --headless --convert-to pdf --outdir "$tmp" "$tmp/${input}" >/dev/null 2>&1`,
|
|
49
|
+
'if [ ! -f "$tmp/input.pdf" ]; then rm -rf "$tmp"; echo "@@RVS_FAIL convert"; exit 6; fi',
|
|
50
|
+
'echo "@@RVS_PDF $tmp"',
|
|
51
|
+
].join('\n')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function errorMessage(error: unknown): string {
|
|
55
|
+
return error instanceof RemoteApiError ? error.message : error instanceof Error ? error.message : String(error)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Fetch one remote file body through the streaming download route. */
|
|
59
|
+
export async function fetchRemoteBytes(alias: string, path: string, signal?: AbortSignal): Promise<Uint8Array> {
|
|
60
|
+
const response = await fetch(downloadUrl(alias, path), { signal })
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
const text = await response.text().catch(() => '')
|
|
63
|
+
let message = `download failed: HTTP ${response.status}`
|
|
64
|
+
try {
|
|
65
|
+
const body = JSON.parse(text) as { error?: unknown }
|
|
66
|
+
if (typeof body.error === 'string') message = body.error
|
|
67
|
+
} catch {
|
|
68
|
+
// Not JSON: keep the status message.
|
|
69
|
+
}
|
|
70
|
+
throw new Error(message)
|
|
71
|
+
}
|
|
72
|
+
const declared = Number(response.headers.get('content-length') ?? '0')
|
|
73
|
+
if (Number.isFinite(declared) && declared > MAX_PREVIEW_BYTES) {
|
|
74
|
+
throw Object.assign(new Error(`file is larger than ${MAX_PREVIEW_BYTES} bytes`), { previewKind: 'too-large' })
|
|
75
|
+
}
|
|
76
|
+
const bytes = new Uint8Array(await response.arrayBuffer())
|
|
77
|
+
if (bytes.byteLength > MAX_PREVIEW_BYTES) {
|
|
78
|
+
throw Object.assign(new Error(`file is larger than ${MAX_PREVIEW_BYTES} bytes`), { previewKind: 'too-large' })
|
|
79
|
+
}
|
|
80
|
+
return bytes
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function fetchOfficePdf(alias: string, path: string, signal?: AbortSignal): Promise<Uint8Array> {
|
|
84
|
+
if (officeExtensionOf(path) === undefined) throw new Error('unsupported office document')
|
|
85
|
+
const result = await api.exec(alias, officeConvertCommand(path), 60_000, { signal })
|
|
86
|
+
if (result.error !== undefined) throw new Error(result.error)
|
|
87
|
+
if (result.timedOut) throw new Error('remote LibreOffice conversion timed out')
|
|
88
|
+
const line = result.stdout.split('\n').map(item => item.trim()).find(item => item.startsWith('@@RVS_PDF '))
|
|
89
|
+
if (line === undefined) {
|
|
90
|
+
if (result.stdout.includes('@@RVS_NO_SOFFICE')) {
|
|
91
|
+
throw Object.assign(new Error('LibreOffice is not installed on the remote host'), { previewKind: 'unavailable' })
|
|
92
|
+
}
|
|
93
|
+
throw new Error(result.stderr.trim() || 'remote LibreOffice conversion failed')
|
|
94
|
+
}
|
|
95
|
+
const tempDir = line.slice('@@RVS_PDF '.length).trim()
|
|
96
|
+
try {
|
|
97
|
+
return await fetchRemoteBytes(alias, `${tempDir}/input.pdf`, signal)
|
|
98
|
+
} finally {
|
|
99
|
+
// Best-effort cleanup; a failed rm must not turn a rendered document into
|
|
100
|
+
// an error, but it also must never be skipped silently in this function.
|
|
101
|
+
void api.exec(alias, `rm -rf ${shQuote(tempDir)}`, 15_000).catch(() => undefined)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function sizeText(bytes: number): string {
|
|
106
|
+
if (!Number.isFinite(bytes) || bytes < 0) return ''
|
|
107
|
+
if (bytes < 1024) return `${bytes} B`
|
|
108
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
|
|
109
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function PreviewNotice(props: {
|
|
113
|
+
path: string
|
|
114
|
+
title: string
|
|
115
|
+
hint: string
|
|
116
|
+
detail?: string
|
|
117
|
+
t: (key: string) => string
|
|
118
|
+
onRetry?: () => void
|
|
119
|
+
}): ReactNode {
|
|
120
|
+
return (
|
|
121
|
+
<div className="rvs-preview-notice" role="alert">
|
|
122
|
+
<div className="rvs-preview-notice-title">{props.title}</div>
|
|
123
|
+
<div className="rvs-preview-notice-path">{props.path}</div>
|
|
124
|
+
<div className="rvs-preview-notice-hint">{props.hint}</div>
|
|
125
|
+
{props.detail !== undefined && <div className="rvs-preview-notice-detail">{props.detail}</div>}
|
|
126
|
+
{props.onRetry !== undefined && (
|
|
127
|
+
<button type="button" className="rvs-preview-retry" onClick={props.onRetry}>{props.t('common.retry')}</button>
|
|
128
|
+
)}
|
|
129
|
+
</div>
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function BytePreview(props: {
|
|
134
|
+
alias: string
|
|
135
|
+
path: string
|
|
136
|
+
/** DSH session; lets the host workspaceFiles/officeKit remotes resolve the
|
|
137
|
+
* same remote workspace before the plugin's own download fallback. */
|
|
138
|
+
sessionId?: string
|
|
139
|
+
kind: 'pdf' | 'office' | 'media'
|
|
140
|
+
revision: number
|
|
141
|
+
t: (key: string) => string
|
|
142
|
+
}): ReactNode {
|
|
143
|
+
const [state, setState] = useState<{ status: 'loading' } | { status: 'ready'; url: string; size: number } | { status: 'failed'; error: PreviewError }>({ status: 'loading' })
|
|
144
|
+
const [elementFailed, setElementFailed] = useState(false)
|
|
145
|
+
const [attempt, setAttempt] = useState(0)
|
|
146
|
+
|
|
147
|
+
useEffect(() => { setElementFailed(false) }, [props.path, props.kind])
|
|
148
|
+
|
|
149
|
+
useEffect(() => {
|
|
150
|
+
const controller = new AbortController()
|
|
151
|
+
let alive = true
|
|
152
|
+
let url: string | undefined
|
|
153
|
+
let hostReason: PreviewFailureReason = 'failed'
|
|
154
|
+
setState({ status: 'loading' })
|
|
155
|
+
const download = props.kind === 'office'
|
|
156
|
+
? () => fetchOfficePdf(props.alias, props.path, controller.signal)
|
|
157
|
+
: () => fetchRemoteBytes(props.alias, props.path, controller.signal)
|
|
158
|
+
const hostRead = props.kind === 'office'
|
|
159
|
+
? renderOfficePdf(props.sessionId ?? '', props.path, controller.signal)
|
|
160
|
+
: readWorkspaceBytes(props.sessionId ?? '', props.path, controller.signal)
|
|
161
|
+
void hostRead.then((host) => {
|
|
162
|
+
if (host.ok) return host.data
|
|
163
|
+
hostReason = host.reason
|
|
164
|
+
// A missing service or a path the host cannot resolve is exactly why the
|
|
165
|
+
// plugin keeps its own /download path; only the fallback can succeed.
|
|
166
|
+
return download()
|
|
167
|
+
}).then((bytes) => {
|
|
168
|
+
if (!alive) return
|
|
169
|
+
const mime = props.kind === 'media'
|
|
170
|
+
? mediaTypeOf(props.path)?.mime ?? 'application/octet-stream'
|
|
171
|
+
: 'application/pdf'
|
|
172
|
+
url = URL.createObjectURL(new Blob([bytes], { type: mime }))
|
|
173
|
+
setState({ status: 'ready', url, size: bytes.byteLength })
|
|
174
|
+
}).catch((error: unknown) => {
|
|
175
|
+
if (!alive) return
|
|
176
|
+
const reason = typeof error === 'object' && error !== null && 'previewKind' in error
|
|
177
|
+
? (error as { previewKind: PreviewError['kind'] }).previewKind
|
|
178
|
+
: hostReason
|
|
179
|
+
setState({ status: 'failed', error: { kind: reason, message: errorMessage(error) } })
|
|
180
|
+
})
|
|
181
|
+
return () => {
|
|
182
|
+
alive = false
|
|
183
|
+
controller.abort()
|
|
184
|
+
if (url !== undefined) URL.revokeObjectURL(url)
|
|
185
|
+
}
|
|
186
|
+
}, [props.alias, props.path, props.kind, props.revision, attempt, props.sessionId])
|
|
187
|
+
|
|
188
|
+
if (state.status === 'loading') {
|
|
189
|
+
return (
|
|
190
|
+
<div className="rvs-preview-loading" role="status">
|
|
191
|
+
<span className="rvs-preview-spinner" aria-hidden="true" />
|
|
192
|
+
<span>{props.kind === 'office' ? props.t('preview.converting') : props.t('common.loading')}</span>
|
|
193
|
+
{props.kind === 'office' && <span className="rvs-preview-loading-hint">{props.t('preview.convertingHint')}</span>}
|
|
194
|
+
</div>
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
if (state.status === 'failed') {
|
|
198
|
+
const title = state.error.kind === 'too-large'
|
|
199
|
+
? props.t('preview.tooLargeTitle')
|
|
200
|
+
: state.error.kind === 'unavailable'
|
|
201
|
+
? props.t(props.kind === 'office' ? 'preview.officeUnavailableTitle' : 'preview.unavailableTitle')
|
|
202
|
+
: state.error.kind === 'not-found'
|
|
203
|
+
? props.t('preview.notFoundTitle')
|
|
204
|
+
: state.error.kind === 'remote'
|
|
205
|
+
? props.t('preview.remoteTitle')
|
|
206
|
+
: props.t('preview.failedTitle')
|
|
207
|
+
const hint = state.error.kind === 'too-large'
|
|
208
|
+
? props.t('preview.tooLargeHint')
|
|
209
|
+
: state.error.kind === 'unavailable'
|
|
210
|
+
? props.t(props.kind === 'office' ? 'preview.officeUnavailableHint' : 'preview.unavailableHint')
|
|
211
|
+
: state.error.kind === 'not-found'
|
|
212
|
+
? props.t('preview.notFoundHint')
|
|
213
|
+
: state.error.kind === 'remote'
|
|
214
|
+
? props.t('preview.remoteHint')
|
|
215
|
+
: props.t('preview.failedHint')
|
|
216
|
+
return <PreviewNotice path={props.path} title={title} hint={hint} detail={state.error.message} t={props.t} onRetry={() => { setAttempt(value => value + 1) }} />
|
|
217
|
+
}
|
|
218
|
+
if (props.kind === 'media') {
|
|
219
|
+
const media = mediaTypeOf(props.path)
|
|
220
|
+
if (elementFailed) {
|
|
221
|
+
return <PreviewNotice path={props.path} title={props.t('preview.failedTitle')} hint={props.t('preview.mediaUnsupported')} t={props.t} onRetry={() => { setElementFailed(false); setAttempt(value => value + 1) }} />
|
|
222
|
+
}
|
|
223
|
+
return (
|
|
224
|
+
<div className={`rvs-preview-media${media?.kind === 'video' ? ' rvs-preview-media-video' : ''}`}>
|
|
225
|
+
{media?.kind === 'video'
|
|
226
|
+
? <video className="rvs-preview-media-el" src={state.url} controls onError={() => { setElementFailed(true) }} />
|
|
227
|
+
: <audio className="rvs-preview-media-el" src={state.url} controls onError={() => { setElementFailed(true) }} />}
|
|
228
|
+
<div className="rvs-preview-media-meta">
|
|
229
|
+
{sizeText(state.size)}
|
|
230
|
+
<span className="rvs-preview-media-hint">{props.path}</span>
|
|
231
|
+
</div>
|
|
232
|
+
</div>
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
return (
|
|
236
|
+
<div className="rvs-preview-document">
|
|
237
|
+
<iframe className="rvs-preview-document-frame" src={state.url} title={props.path} />
|
|
238
|
+
<div className="rvs-preview-document-meta">
|
|
239
|
+
{sizeText(state.size)}
|
|
240
|
+
<span className="rvs-preview-document-hint">{props.t('preview.documentHint')}</span>
|
|
241
|
+
</div>
|
|
242
|
+
</div>
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function SvgPreview(props: { path: string; text: string; truncated: boolean; t: (key: string) => string }): ReactNode {
|
|
247
|
+
const [url, setUrl] = useState<string | undefined>(undefined)
|
|
248
|
+
const [failed, setFailed] = useState(false)
|
|
249
|
+
useEffect(() => {
|
|
250
|
+
const next = URL.createObjectURL(new Blob([props.text], { type: 'image/svg+xml' }))
|
|
251
|
+
setUrl(next)
|
|
252
|
+
return () => { URL.revokeObjectURL(next) }
|
|
253
|
+
}, [props.text])
|
|
254
|
+
useEffect(() => { setFailed(false) }, [url])
|
|
255
|
+
if (failed) {
|
|
256
|
+
return <PreviewNotice path={props.path} title={props.t('preview.svgFailed')} hint={props.t('preview.svgFailedHint')} t={props.t} />
|
|
257
|
+
}
|
|
258
|
+
if (url === undefined) return null
|
|
259
|
+
return (
|
|
260
|
+
<div className="rvs-preview-svg">
|
|
261
|
+
<img className="rvs-preview-svg-img" src={url} alt={props.path} onError={() => { setFailed(true) }} />
|
|
262
|
+
<div className="rvs-preview-svg-hint">{props.truncated ? props.t('preview.truncated') : props.t('preview.svgHint')}</div>
|
|
263
|
+
</div>
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** DOM ceilings (parsing itself allows more; the rest gets a banner). */
|
|
268
|
+
const RENDER_ROWS = 400
|
|
269
|
+
const RENDER_COLUMNS = 48
|
|
270
|
+
|
|
271
|
+
function padRow(row: readonly string[], columns: number): string[] {
|
|
272
|
+
const cells = row.slice(0, columns)
|
|
273
|
+
while (cells.length < columns) cells.push('')
|
|
274
|
+
return cells
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function TablePreview(props: { path: string; text: string; truncated: boolean; t: (key: string) => string }): ReactNode {
|
|
278
|
+
const parsed = useMemo(
|
|
279
|
+
() => parseDelimited(props.text, tableDelimiterOf(props.path)),
|
|
280
|
+
[props.text, props.path],
|
|
281
|
+
)
|
|
282
|
+
const columns = Math.min(parsed.columns, RENDER_COLUMNS)
|
|
283
|
+
const rows = parsed.rows.slice(0, RENDER_ROWS)
|
|
284
|
+
const header = rows[0]
|
|
285
|
+
const body = rows.slice(1)
|
|
286
|
+
const hiddenRows = parsed.rows.length - rows.length
|
|
287
|
+
const hiddenColumns = parsed.columns - columns
|
|
288
|
+
const notes: string[] = []
|
|
289
|
+
if (props.truncated) notes.push(props.t('preview.truncated'))
|
|
290
|
+
if (parsed.truncated) {
|
|
291
|
+
notes.push(props.t('preview.tableTruncated')
|
|
292
|
+
.replace('{rows}', String(DEFAULT_TABLE_LIMITS.maxRows))
|
|
293
|
+
.replace('{cells}', String(DEFAULT_TABLE_LIMITS.maxCells)))
|
|
294
|
+
}
|
|
295
|
+
if (hiddenRows > 0) notes.push(props.t('preview.tableHiddenRows').replace('{shown}', String(rows.length)).replace('{rest}', String(hiddenRows)))
|
|
296
|
+
if (hiddenColumns > 0) notes.push(props.t('preview.tableHiddenColumns').replace('{shown}', String(columns)).replace('{rest}', String(hiddenColumns)))
|
|
297
|
+
if (parsed.rows.length === 0) {
|
|
298
|
+
return <PreviewNotice path={props.path} title={props.t('preview.tableEmptyTitle')} hint={props.t('preview.tableEmptyHint')} t={props.t} />
|
|
299
|
+
}
|
|
300
|
+
return (
|
|
301
|
+
<div className="rvs-preview-table-wrap">
|
|
302
|
+
{notes.map((note, index) => <div className="rvs-preview-banner" key={`${String(index)}:${note}`}>{note}</div>)}
|
|
303
|
+
<div className="rvs-preview-table-scroll">
|
|
304
|
+
<table className="rvs-preview-table">
|
|
305
|
+
<thead>
|
|
306
|
+
<tr>
|
|
307
|
+
<th className="rvs-preview-rownum" scope="col">#</th>
|
|
308
|
+
{padRow(header ?? [], columns).map((cell, index) => <th key={index} scope="col">{cell}</th>)}
|
|
309
|
+
</tr>
|
|
310
|
+
</thead>
|
|
311
|
+
<tbody>
|
|
312
|
+
{body.map((row, rowIndex) => (
|
|
313
|
+
<tr key={rowIndex}>
|
|
314
|
+
<th className="rvs-preview-rownum" scope="row">{rowIndex + 2}</th>
|
|
315
|
+
{padRow(row, columns).map((cell, cellIndex) => <td key={cellIndex} title={cell}>{cell}</td>)}
|
|
316
|
+
</tr>
|
|
317
|
+
))}
|
|
318
|
+
</tbody>
|
|
319
|
+
</table>
|
|
320
|
+
</div>
|
|
321
|
+
</div>
|
|
322
|
+
)
|
|
323
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote document preview classification and table parsing.
|
|
3
|
+
*
|
|
4
|
+
* Pure functions only (no React/DOM/fetch): the editor shell, the preview
|
|
5
|
+
* component and the gate all read the same classification, and CSV/TSV parsing
|
|
6
|
+
* can be tested in Node.
|
|
7
|
+
*/
|
|
8
|
+
export type PreviewKind =
|
|
9
|
+
| 'text' | 'image' | 'markdown' | 'html' | 'svg' | 'table' | 'pdf' | 'office' | 'media'
|
|
10
|
+
|
|
11
|
+
const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'avif'])
|
|
12
|
+
|
|
13
|
+
const KIND_BY_EXTENSION: Readonly<Record<string, PreviewKind>> = {
|
|
14
|
+
md: 'markdown', markdown: 'markdown', mdown: 'markdown', mkd: 'markdown', mdx: 'markdown',
|
|
15
|
+
html: 'html', htm: 'html', xhtml: 'html',
|
|
16
|
+
csv: 'table', tsv: 'table',
|
|
17
|
+
svg: 'svg',
|
|
18
|
+
pdf: 'pdf',
|
|
19
|
+
// Only the six extensions a LibreOffice/office-kit conversion can actually
|
|
20
|
+
// claim; odt/ods/odp/docm/... fall through to the binary notice instead of a
|
|
21
|
+
// guaranteed conversion error.
|
|
22
|
+
doc: 'office', docx: 'office', ppt: 'office', pptx: 'office', xls: 'office', xlsx: 'office',
|
|
23
|
+
mp3: 'media', wav: 'media', ogg: 'media', oga: 'media', opus: 'media', m4a: 'media',
|
|
24
|
+
aac: 'media', flac: 'media', weba: 'media', mp4: 'media', m4v: 'media', webm: 'media',
|
|
25
|
+
ogv: 'media', mov: 'media',
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const MEDIA_MIME: Readonly<Record<string, { kind: 'audio' | 'video'; mime: string }>> = {
|
|
29
|
+
mp3: { kind: 'audio', mime: 'audio/mpeg' },
|
|
30
|
+
wav: { kind: 'audio', mime: 'audio/wav' },
|
|
31
|
+
ogg: { kind: 'audio', mime: 'audio/ogg' },
|
|
32
|
+
oga: { kind: 'audio', mime: 'audio/ogg' },
|
|
33
|
+
opus: { kind: 'audio', mime: 'audio/ogg' },
|
|
34
|
+
m4a: { kind: 'audio', mime: 'audio/mp4' },
|
|
35
|
+
aac: { kind: 'audio', mime: 'audio/aac' },
|
|
36
|
+
flac: { kind: 'audio', mime: 'audio/flac' },
|
|
37
|
+
weba: { kind: 'audio', mime: 'audio/webm' },
|
|
38
|
+
mp4: { kind: 'video', mime: 'video/mp4' },
|
|
39
|
+
m4v: { kind: 'video', mime: 'video/mp4' },
|
|
40
|
+
webm: { kind: 'video', mime: 'video/webm' },
|
|
41
|
+
ogv: { kind: 'video', mime: 'video/ogg' },
|
|
42
|
+
mov: { kind: 'video', mime: 'video/quicktime' },
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function extensionOf(path: string): string {
|
|
46
|
+
const name = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1)
|
|
47
|
+
const dot = name.lastIndexOf('.')
|
|
48
|
+
return dot <= 0 ? '' : name.slice(dot + 1).toLowerCase()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function previewKindOf(path: string): PreviewKind {
|
|
52
|
+
const ext = extensionOf(path)
|
|
53
|
+
if (IMAGE_EXTENSIONS.has(ext)) return 'image'
|
|
54
|
+
return Object.hasOwn(KIND_BY_EXTENSION, ext) ? KIND_BY_EXTENSION[ext] as PreviewKind : 'text'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function isBytePreview(kind: PreviewKind): kind is 'pdf' | 'office' | 'media' {
|
|
58
|
+
return kind === 'pdf' || kind === 'office' || kind === 'media'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function hasTextSource(kind: PreviewKind): boolean {
|
|
62
|
+
return kind === 'markdown' || kind === 'html' || kind === 'svg' || kind === 'table'
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function previewKindLabel(kind: PreviewKind): string | undefined {
|
|
66
|
+
const labels: Record<PreviewKind, string | undefined> = {
|
|
67
|
+
text: undefined,
|
|
68
|
+
image: 'Image',
|
|
69
|
+
markdown: 'Markdown',
|
|
70
|
+
html: 'HTML',
|
|
71
|
+
svg: 'SVG',
|
|
72
|
+
table: 'Table',
|
|
73
|
+
pdf: 'PDF',
|
|
74
|
+
office: 'Office',
|
|
75
|
+
media: 'Media',
|
|
76
|
+
}
|
|
77
|
+
return labels[kind]
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function mediaTypeOf(path: string): { kind: 'audio' | 'video'; mime: string } | undefined {
|
|
81
|
+
return MEDIA_MIME[extensionOf(path)]
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function tableDelimiterOf(path: string): string {
|
|
85
|
+
return extensionOf(path) === 'tsv' ? '\t' : ','
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface TableLimits {
|
|
89
|
+
maxRows: number
|
|
90
|
+
maxColumns: number
|
|
91
|
+
maxCells: number
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export const DEFAULT_TABLE_LIMITS: TableLimits = {
|
|
95
|
+
maxRows: 5000,
|
|
96
|
+
maxColumns: 512,
|
|
97
|
+
maxCells: 200_000,
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface TableData {
|
|
101
|
+
rows: string[][]
|
|
102
|
+
columns: number
|
|
103
|
+
truncated: boolean
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** RFC 4180 parser with explicit row/column/cell bounds. */
|
|
107
|
+
export function parseDelimited(
|
|
108
|
+
text: string,
|
|
109
|
+
delimiter: string,
|
|
110
|
+
limits: TableLimits = DEFAULT_TABLE_LIMITS,
|
|
111
|
+
): TableData {
|
|
112
|
+
if (limits.maxColumns <= 0 || limits.maxRows <= 0) {
|
|
113
|
+
return { rows: [], columns: 0, truncated: text.trim() !== '' }
|
|
114
|
+
}
|
|
115
|
+
const rows: string[][] = []
|
|
116
|
+
let row: string[] = []
|
|
117
|
+
let field = ''
|
|
118
|
+
let quoted = false
|
|
119
|
+
let columns = 0
|
|
120
|
+
let stoppedAt = -1
|
|
121
|
+
let dropped = false
|
|
122
|
+
let touched = false
|
|
123
|
+
|
|
124
|
+
const finishField = (): boolean => {
|
|
125
|
+
if (row.length >= limits.maxColumns) return false
|
|
126
|
+
row.push(field)
|
|
127
|
+
field = ''
|
|
128
|
+
touched = true
|
|
129
|
+
return true
|
|
130
|
+
}
|
|
131
|
+
const finishRow = (at: number): boolean => {
|
|
132
|
+
if (!finishField()) {
|
|
133
|
+
if (touched && rows.length < limits.maxRows) {
|
|
134
|
+
if (row.length > columns) columns = row.length
|
|
135
|
+
rows.push(row)
|
|
136
|
+
}
|
|
137
|
+
row = []
|
|
138
|
+
field = ''
|
|
139
|
+
touched = false
|
|
140
|
+
dropped = true
|
|
141
|
+
stoppedAt = at
|
|
142
|
+
return false
|
|
143
|
+
}
|
|
144
|
+
if (!touched || (row.length === 1 && row[0] === '')) {
|
|
145
|
+
row = []
|
|
146
|
+
touched = false
|
|
147
|
+
return true
|
|
148
|
+
}
|
|
149
|
+
if (rows.length >= limits.maxRows) {
|
|
150
|
+
dropped = true
|
|
151
|
+
stoppedAt = at
|
|
152
|
+
return false
|
|
153
|
+
}
|
|
154
|
+
if (rows.length > 0 && (rows.length + 1) * Math.max(columns, row.length) > limits.maxCells) {
|
|
155
|
+
dropped = true
|
|
156
|
+
stoppedAt = at
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
if (row.length > columns) columns = row.length
|
|
160
|
+
rows.push(row)
|
|
161
|
+
row = []
|
|
162
|
+
touched = false
|
|
163
|
+
return true
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
|
|
167
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
168
|
+
const char = source[index] as string
|
|
169
|
+
if (quoted) {
|
|
170
|
+
if (char === '"') {
|
|
171
|
+
if (source[index + 1] === '"') {
|
|
172
|
+
field += '"'
|
|
173
|
+
index += 1
|
|
174
|
+
} else {
|
|
175
|
+
quoted = false
|
|
176
|
+
}
|
|
177
|
+
} else {
|
|
178
|
+
field += char
|
|
179
|
+
}
|
|
180
|
+
continue
|
|
181
|
+
}
|
|
182
|
+
if (char === '"' && field === '') {
|
|
183
|
+
quoted = true
|
|
184
|
+
touched = true
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
if (char === delimiter) {
|
|
188
|
+
if (!finishField()) {
|
|
189
|
+
if (touched && rows.length < limits.maxRows) {
|
|
190
|
+
if (row.length > columns) columns = row.length
|
|
191
|
+
rows.push(row)
|
|
192
|
+
}
|
|
193
|
+
row = []
|
|
194
|
+
field = ''
|
|
195
|
+
touched = false
|
|
196
|
+
dropped = true
|
|
197
|
+
stoppedAt = index
|
|
198
|
+
break
|
|
199
|
+
}
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
if (char === '\r') {
|
|
203
|
+
if (source[index + 1] === '\n') index += 1
|
|
204
|
+
if (!finishRow(index)) break
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
if (char === '\n') {
|
|
208
|
+
if (!finishRow(index)) break
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
field += char
|
|
212
|
+
touched = true
|
|
213
|
+
}
|
|
214
|
+
if (stoppedAt === -1 && (touched || field !== '' || row.length > 0)) finishRow(source.length)
|
|
215
|
+
return { rows, columns, truncated: dropped }
|
|
216
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host Client-Remote access for document previews.
|
|
3
|
+
*
|
|
4
|
+
* The reference local-workbench implementation reads bytes through
|
|
5
|
+
* `remote.workspaceFiles.readBytes` and converts Office through
|
|
6
|
+
* `remote.officeKit.render`. dsh-remote-vs replaces the global `fs` with a
|
|
7
|
+
* transparent RouterFs, so those services can route a remote session's
|
|
8
|
+
* workspace; this module keeps them as SOFT services (ctx.get) and reports
|
|
9
|
+
* `unavailable` when a profile does not mount them.
|
|
10
|
+
*/
|
|
11
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
12
|
+
|
|
13
|
+
export type PreviewFailureReason = 'unavailable' | 'too-large' | 'not-found' | 'remote' | 'failed'
|
|
14
|
+
|
|
15
|
+
export type PreviewBytesResult =
|
|
16
|
+
| { ok: true; data: Uint8Array; size: number }
|
|
17
|
+
| { ok: false; reason: PreviewFailureReason; detail: string }
|
|
18
|
+
|
|
19
|
+
type RemoteCallResult =
|
|
20
|
+
| { ok: true; value: { data: Uint8Array; bytes?: number } }
|
|
21
|
+
| { ok: false; error: { code?: unknown; message?: unknown; details?: unknown } }
|
|
22
|
+
|
|
23
|
+
interface WorkspaceFilesRemote {
|
|
24
|
+
readBytes?: (sessionId: string, path: string, options: Record<string, unknown>, signal?: AbortSignal) => Promise<RemoteCallResult>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface OfficeKitRemote {
|
|
28
|
+
render?: (sessionId: string, path: string, priority: 'foreground' | 'background', signal?: AbortSignal) => Promise<RemoteCallResult>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let rootCtx: Context | undefined
|
|
32
|
+
|
|
33
|
+
export function installPreviewServices(ctx: Context): () => void {
|
|
34
|
+
rootCtx = ctx
|
|
35
|
+
return () => {
|
|
36
|
+
if (rootCtx === ctx) rootCtx = undefined
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function remoteNamespace(name: string): Record<string, unknown> | undefined {
|
|
41
|
+
const ctx = rootCtx
|
|
42
|
+
if (ctx === undefined) return undefined
|
|
43
|
+
try {
|
|
44
|
+
const raw: unknown = (ctx as unknown as { get(service: string): unknown }).get(name)
|
|
45
|
+
return typeof raw === 'object' && raw !== null ? raw as Record<string, unknown> : undefined
|
|
46
|
+
} catch {
|
|
47
|
+
return undefined
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function failureReason(code: string, reason?: string): PreviewFailureReason {
|
|
52
|
+
const lowered = `${code} ${reason ?? ''}`.toLowerCase()
|
|
53
|
+
if (lowered.includes('too-large') || lowered.includes('too_large')) return 'too-large'
|
|
54
|
+
if (lowered.includes('workspace-file/not-found') || lowered.includes('not-regular-file')) return 'not-found'
|
|
55
|
+
if (lowered.includes('unavailable') || lowered.includes('missing')) return 'unavailable'
|
|
56
|
+
return 'failed'
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function toBytesResult(outcome: RemoteCallResult | undefined, fallbackDetail: string): PreviewBytesResult {
|
|
60
|
+
if (outcome === undefined) return { ok: false, reason: 'unavailable', detail: fallbackDetail }
|
|
61
|
+
if (outcome.ok) {
|
|
62
|
+
const data = outcome.value.data
|
|
63
|
+
if (!(data instanceof Uint8Array) || data.byteLength === 0) {
|
|
64
|
+
return { ok: false, reason: 'failed', detail: 'empty payload' }
|
|
65
|
+
}
|
|
66
|
+
return { ok: true, data, size: typeof outcome.value.bytes === 'number' ? outcome.value.bytes : data.byteLength }
|
|
67
|
+
}
|
|
68
|
+
const code = typeof outcome.error.code === 'string' ? outcome.error.code : ''
|
|
69
|
+
const message = typeof outcome.error.message === 'string' ? outcome.error.message : ''
|
|
70
|
+
const details = outcome.error.details
|
|
71
|
+
const reason = typeof details === 'object' && details !== null
|
|
72
|
+
&& typeof (details as { reason?: unknown }).reason === 'string'
|
|
73
|
+
? (details as { reason: string }).reason
|
|
74
|
+
: undefined
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
reason: failureReason(code, reason),
|
|
78
|
+
detail: [code, reason, message].filter(part => typeof part === 'string' && part !== '').join(': '),
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function readWorkspaceBytes(
|
|
83
|
+
sessionId: string,
|
|
84
|
+
path: string,
|
|
85
|
+
signal?: AbortSignal,
|
|
86
|
+
): Promise<PreviewBytesResult> {
|
|
87
|
+
if (sessionId === '') return { ok: false, reason: 'unavailable', detail: 'no session' }
|
|
88
|
+
const service = remoteNamespace('remote.workspaceFiles') as WorkspaceFilesRemote | undefined
|
|
89
|
+
if (typeof service?.readBytes !== 'function') {
|
|
90
|
+
return { ok: false, reason: 'unavailable', detail: 'remote.workspaceFiles is not mounted' }
|
|
91
|
+
}
|
|
92
|
+
let outcome: RemoteCallResult
|
|
93
|
+
try {
|
|
94
|
+
outcome = await service.readBytes(sessionId, path, {}, signal)
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return { ok: false, reason: 'failed', detail: error instanceof Error ? error.message : String(error) }
|
|
97
|
+
}
|
|
98
|
+
return toBytesResult(outcome, 'remote.workspaceFiles is not mounted')
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function renderOfficePdf(
|
|
102
|
+
sessionId: string,
|
|
103
|
+
path: string,
|
|
104
|
+
signal?: AbortSignal,
|
|
105
|
+
): Promise<PreviewBytesResult> {
|
|
106
|
+
if (sessionId === '') return { ok: false, reason: 'unavailable', detail: 'no session' }
|
|
107
|
+
const service = remoteNamespace('remote.officeKit') as OfficeKitRemote | undefined
|
|
108
|
+
if (typeof service?.render !== 'function') {
|
|
109
|
+
return { ok: false, reason: 'unavailable', detail: 'remote.officeKit is not mounted' }
|
|
110
|
+
}
|
|
111
|
+
let outcome: RemoteCallResult
|
|
112
|
+
try {
|
|
113
|
+
outcome = await service.render(sessionId, path, 'foreground', signal)
|
|
114
|
+
} catch (error) {
|
|
115
|
+
return { ok: false, reason: 'failed', detail: error instanceof Error ? error.message : String(error) }
|
|
116
|
+
}
|
|
117
|
+
return toBytesResult(outcome, 'remote.officeKit is not mounted')
|
|
118
|
+
}
|