@banzhe/dsh-devcontainer 0.0.0-stage → 0.2.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/README.md +79 -2
- package/README.zh-CN.md +80 -0
- package/cordis.patch.yml +71 -0
- package/lib/client.js +789 -0
- package/lib/client.js.map +1 -0
- package/lib/exec-CKAAz2zz.js +241 -0
- package/lib/exec-CKAAz2zz.js.map +1 -0
- package/lib/exec-_8g5fdSx.d.ts +26 -0
- package/lib/exec-_8g5fdSx.d.ts.map +1 -0
- package/lib/fs.d.ts +530 -0
- package/lib/fs.d.ts.map +1 -0
- package/lib/fs.js +1737 -0
- package/lib/fs.js.map +1 -0
- package/lib/helper/main.mjs +1008 -0
- package/lib/index.d.ts +88 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +927 -0
- package/lib/index.js.map +1 -0
- package/lib/sbx-1GsFjQBk.js +1489 -0
- package/lib/sbx-1GsFjQBk.js.map +1 -0
- package/lib/shell.d.ts +175 -0
- package/lib/shell.d.ts.map +1 -0
- package/lib/shell.js +454 -0
- package/lib/shell.js.map +1 -0
- package/lib/types-DsF9Hz5P.d.ts +33 -0
- package/lib/types-DsF9Hz5P.d.ts.map +1 -0
- package/package.json +116 -3
|
@@ -0,0 +1,1008 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The filesystem helper that runs INSIDE the developer container.
|
|
3
|
+
*
|
|
4
|
+
* DevcontainerFileSystem keeps one of these in a persistent
|
|
5
|
+
* "docker exec -i <container> node <path>" process and speaks DSH's SSH helper
|
|
6
|
+
* framing to it: a four-byte big-endian length header followed by one UTF-8
|
|
7
|
+
* JSON document per frame, with "hello" as the handshake
|
|
8
|
+
* (packages/ssh/ssh/src/protocol.ts, SSH_PROTOCOL_VERSION = 3).
|
|
9
|
+
*
|
|
10
|
+
* The program is dependency-free on purpose: it runs on whatever Node the image
|
|
11
|
+
* ships, so it imports nothing but node: builtins and never assumes a bundler.
|
|
12
|
+
* Every path it accepts or reports is a POSIX path inside this container, which
|
|
13
|
+
* is what keeps the session's host filesystem physically out of reach.
|
|
14
|
+
*/
|
|
15
|
+
import { randomUUID } from 'node:crypto'
|
|
16
|
+
import { createReadStream } from 'node:fs'
|
|
17
|
+
import { chmod, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat } from 'node:fs/promises'
|
|
18
|
+
import { posix } from 'node:path'
|
|
19
|
+
import { pathToFileURL } from 'node:url'
|
|
20
|
+
import { TextDecoder } from 'node:util'
|
|
21
|
+
|
|
22
|
+
/** Wire version, shared with the host client and DSH's SSH helper protocol. */
|
|
23
|
+
const PROTOCOL_VERSION = 3
|
|
24
|
+
/** Largest single frame either side accepts. */
|
|
25
|
+
const MAX_FRAME_BYTES = 64 * 1024 * 1024
|
|
26
|
+
/** Largest whole-text transfer; larger files reach the caller through fs.stream. */
|
|
27
|
+
const MAX_TEXT_BYTES = 32 * 1024 * 1024
|
|
28
|
+
/** Leading bytes scanned for a NUL before a file counts as binary. */
|
|
29
|
+
const BINARY_SAMPLE_BYTES = 8192
|
|
30
|
+
/** Concurrent open text iterators one helper will hold. */
|
|
31
|
+
const MAX_TEXT_STREAMS = 64
|
|
32
|
+
const FRAME_HEADER_BYTES = 4
|
|
33
|
+
|
|
34
|
+
/** The filesystem failure codes the host maps back onto FsError. */
|
|
35
|
+
const FS_ERROR_CODES = new Set([
|
|
36
|
+
'FS_NOT_FOUND', 'FS_NOT_DIRECTORY', 'FS_NOT_TEXT', 'FS_NOT_REGULAR_FILE',
|
|
37
|
+
'FS_TOO_LARGE', 'FS_PERMISSION_DENIED', 'FS_SANDBOX_DENIED', 'FS_IO_ERROR',
|
|
38
|
+
'FS_STALE_VERSION', 'FS_NOT_OBSERVED', 'FS_AMBIGUOUS_EDIT', 'FS_EDIT_NOT_FOUND',
|
|
39
|
+
'FS_ABORTED', 'FS_PATCH_MISMATCH', 'FS_SAME_TARGET',
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
/** POSIX failure names translated to the filesystem vocabulary the host understands. */
|
|
43
|
+
const ERRNO_CODES = {
|
|
44
|
+
ENOENT: 'FS_NOT_FOUND',
|
|
45
|
+
ENOTDIR: 'FS_NOT_DIRECTORY',
|
|
46
|
+
EISDIR: 'FS_NOT_REGULAR_FILE',
|
|
47
|
+
EACCES: 'FS_PERMISSION_DENIED',
|
|
48
|
+
EPERM: 'FS_PERMISSION_DENIED',
|
|
49
|
+
EROFS: 'FS_PERMISSION_DENIED',
|
|
50
|
+
EEXIST: 'FS_NOT_OBSERVED',
|
|
51
|
+
ENOTEMPTY: 'FS_IO_ERROR',
|
|
52
|
+
ELOOP: 'FS_IO_ERROR',
|
|
53
|
+
ENAMETOOLONG: 'FS_IO_ERROR',
|
|
54
|
+
ENOSPC: 'FS_IO_ERROR',
|
|
55
|
+
EXDEV: 'FS_IO_ERROR',
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One typed filesystem failure, carrying a code the host maps back to FsError. */
|
|
59
|
+
function fsError(message, code) {
|
|
60
|
+
const error = new Error(message)
|
|
61
|
+
error.name = 'FsError'
|
|
62
|
+
error.code = code
|
|
63
|
+
return error
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Translate one Node failure into the filesystem vocabulary; unknown faults stay FS_IO_ERROR. */
|
|
67
|
+
function translateError(error, fallback = 'FS_IO_ERROR') {
|
|
68
|
+
if (error !== null && typeof error === 'object' && typeof error.code === 'string') {
|
|
69
|
+
if (FS_ERROR_CODES.has(error.code)) return error
|
|
70
|
+
const mapped = ERRNO_CODES[error.code]
|
|
71
|
+
const translated = fsError(error.message, mapped === undefined ? fallback : mapped)
|
|
72
|
+
translated.cause = error
|
|
73
|
+
return translated
|
|
74
|
+
}
|
|
75
|
+
const translated = fsError(error instanceof Error ? error.message : String(error), fallback)
|
|
76
|
+
translated.cause = error
|
|
77
|
+
return translated
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The frame body a failed request reports. */
|
|
81
|
+
function describeError(error) {
|
|
82
|
+
const detail = translateError(error)
|
|
83
|
+
const description = {
|
|
84
|
+
name: typeof detail.name === 'string' ? detail.name : 'Error',
|
|
85
|
+
message: detail.message ?? String(error),
|
|
86
|
+
}
|
|
87
|
+
if (typeof detail.code === 'string' && FS_ERROR_CODES.has(detail.code)) description.code = detail.code
|
|
88
|
+
return description
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// --- Framing -----------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
/** Encode one frame as a length header plus its JSON body. */
|
|
94
|
+
function encodeFrame(frame) {
|
|
95
|
+
const body = Buffer.from(JSON.stringify(frame), 'utf8')
|
|
96
|
+
if (body.length === 0 || body.length > MAX_FRAME_BYTES) {
|
|
97
|
+
throw new Error('devcontainer helper: frame size out of range')
|
|
98
|
+
}
|
|
99
|
+
const bytes = Buffer.allocUnsafe(FRAME_HEADER_BYTES + body.length)
|
|
100
|
+
bytes.writeUInt32BE(body.length, 0)
|
|
101
|
+
body.copy(bytes, FRAME_HEADER_BYTES)
|
|
102
|
+
return bytes
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Serialized writer: one frame at a time, honoring stdout backpressure. */
|
|
106
|
+
let writeQueue = Promise.resolve()
|
|
107
|
+
|
|
108
|
+
function send(frame) {
|
|
109
|
+
const bytes = encodeFrame(frame)
|
|
110
|
+
writeQueue = writeQueue.then(() => new Promise((resolve, reject) => {
|
|
111
|
+
if (process.stdout.write(bytes)) {
|
|
112
|
+
resolve()
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
const onDrain = () => {
|
|
116
|
+
process.stdout.off('error', onError)
|
|
117
|
+
resolve()
|
|
118
|
+
}
|
|
119
|
+
const onError = (error) => {
|
|
120
|
+
process.stdout.off('drain', onDrain)
|
|
121
|
+
reject(error)
|
|
122
|
+
}
|
|
123
|
+
process.stdout.once('drain', onDrain)
|
|
124
|
+
process.stdout.once('error', onError)
|
|
125
|
+
}))
|
|
126
|
+
return writeQueue
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Buffered decoder for arbitrary stdin chunk boundaries. */
|
|
130
|
+
class FrameDecoder {
|
|
131
|
+
constructor() {
|
|
132
|
+
this.header = Buffer.alloc(FRAME_HEADER_BYTES)
|
|
133
|
+
this.headerBytes = 0
|
|
134
|
+
this.payload = undefined
|
|
135
|
+
this.payloadBytes = 0
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Consume one chunk.
|
|
140
|
+
* @param {Buffer} chunk - bytes read from stdin.
|
|
141
|
+
* @returns {object[]} every frame the chunk completed.
|
|
142
|
+
*/
|
|
143
|
+
push(chunk) {
|
|
144
|
+
const frames = []
|
|
145
|
+
let offset = 0
|
|
146
|
+
while (offset < chunk.length) {
|
|
147
|
+
if (this.payload === undefined) {
|
|
148
|
+
const count = Math.min(FRAME_HEADER_BYTES - this.headerBytes, chunk.length - offset)
|
|
149
|
+
chunk.copy(this.header, this.headerBytes, offset, offset + count)
|
|
150
|
+
this.headerBytes += count
|
|
151
|
+
offset += count
|
|
152
|
+
if (this.headerBytes < FRAME_HEADER_BYTES) continue
|
|
153
|
+
const size = this.header.readUInt32BE(0)
|
|
154
|
+
if (size === 0 || size > MAX_FRAME_BYTES) throw new Error('devcontainer helper: invalid frame length')
|
|
155
|
+
this.payload = Buffer.alloc(size)
|
|
156
|
+
this.payloadBytes = 0
|
|
157
|
+
}
|
|
158
|
+
const count = Math.min(this.payload.length - this.payloadBytes, chunk.length - offset)
|
|
159
|
+
chunk.copy(this.payload, this.payloadBytes, offset, offset + count)
|
|
160
|
+
this.payloadBytes += count
|
|
161
|
+
offset += count
|
|
162
|
+
if (this.payloadBytes === this.payload.length) {
|
|
163
|
+
frames.push(JSON.parse(this.payload.toString('utf8')))
|
|
164
|
+
this.payload = undefined
|
|
165
|
+
this.headerBytes = 0
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return frames
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// --- Paths -------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
/** Normalize one path this helper reports into its POSIX spelling. */
|
|
175
|
+
function toPosixPath(value) {
|
|
176
|
+
return value.split('\\').join('/')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The container directory a relative request resolves against. */
|
|
180
|
+
let workspace = '/'
|
|
181
|
+
/** The realpath of the workspace, so a mount point that is itself a link still counts as inside. */
|
|
182
|
+
let workspaceReal = '/'
|
|
183
|
+
let initialized = false
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Anchor one already-normalized path under its base.
|
|
187
|
+
*
|
|
188
|
+
* Joining by hand rather than through posix.resolve keeps a drive-rooted base
|
|
189
|
+
* intact: posix.resolve treats "C:/dir" as relative and prepends the process
|
|
190
|
+
* working directory, which only happens when this program runs on Windows.
|
|
191
|
+
* @param {string} text - the path to anchor.
|
|
192
|
+
* @param {string} base - the directory relative paths resolve against.
|
|
193
|
+
* @returns {string} the normalized absolute path.
|
|
194
|
+
*/
|
|
195
|
+
function anchorPath(text, base) {
|
|
196
|
+
if (text.startsWith('/') || /^[A-Za-z]:\//.test(text)) return posix.normalize(text)
|
|
197
|
+
const parent = posix.normalize(base).replace(/\/+$/, '')
|
|
198
|
+
return posix.normalize(parent + '/' + text)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Anchor one requested path in the container namespace.
|
|
203
|
+
*
|
|
204
|
+
* A drive-letter prefix is what win32 sometimes leaves on a container path
|
|
205
|
+
* ("C:\workspaces\repo\src"). The mount point is POSIX, so such a prefix is
|
|
206
|
+
* dropped — but only when what remains is inside the mount, because a
|
|
207
|
+
* drive-rooted path on a Windows host is a real path and not a mangled one.
|
|
208
|
+
* @param {unknown} value - the caller-supplied path.
|
|
209
|
+
* @param {string} [base] - the directory relative paths resolve against.
|
|
210
|
+
* @returns {string} the absolute POSIX path.
|
|
211
|
+
*/
|
|
212
|
+
function toAbsolute(value, base) {
|
|
213
|
+
const raw = typeof value === 'string' ? value : typeof value === 'number' ? String(value) : ''
|
|
214
|
+
const text = raw.split('\\').join('/')
|
|
215
|
+
if (text.trim() === '') throw fsError('file_path must be a non-empty string', 'FS_NOT_FOUND')
|
|
216
|
+
const mangled = /^[A-Za-z]:\//.test(text) ? text.slice(2) : undefined
|
|
217
|
+
const insideMount = mangled !== undefined && workspace !== '/'
|
|
218
|
+
&& (mangled === workspace || mangled.startsWith(workspace + '/'))
|
|
219
|
+
const declaredBase = base === undefined || base === null ? workspace : String(base).split('\\').join('/')
|
|
220
|
+
return anchorPath(insideMount ? mangled : text, anchorPath(declaredBase, workspace))
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Whether one filesystem failure means the path is not a directory that exists.
|
|
225
|
+
*
|
|
226
|
+
* A file used as a directory is ENOTDIR on POSIX and ENOENT on Windows, so both
|
|
227
|
+
* read as "absent" here; whichever operation follows reports the entry itself.
|
|
228
|
+
* @param {unknown} error - the failure of one realpath, stat, or lstat call.
|
|
229
|
+
* @returns true when the path is absent rather than unreadable.
|
|
230
|
+
*/
|
|
231
|
+
function isAbsent(error) {
|
|
232
|
+
return error !== null && typeof error === 'object'
|
|
233
|
+
&& (error.code === 'ENOENT' || error.code === 'ENOTDIR')
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Resolve a path to its stable identity, keeping an absent suffix under the nearest existing ancestor.
|
|
238
|
+
* @param {string} absolute - the absolute path to identify.
|
|
239
|
+
* @returns {Promise<string>} the realpath-based identity.
|
|
240
|
+
*/
|
|
241
|
+
async function identityOf(absolute) {
|
|
242
|
+
try {
|
|
243
|
+
return toPosixPath(await realpath(absolute))
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (!isAbsent(error)) throw translateError(error)
|
|
246
|
+
}
|
|
247
|
+
const missing = [posix.basename(absolute)]
|
|
248
|
+
let ancestor = posix.dirname(absolute)
|
|
249
|
+
for (;;) {
|
|
250
|
+
try {
|
|
251
|
+
const real = toPosixPath(await realpath(ancestor))
|
|
252
|
+
return posix.join(real, ...missing)
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (!isAbsent(error)) throw translateError(error)
|
|
255
|
+
const parent = posix.dirname(ancestor)
|
|
256
|
+
if (parent === ancestor) return absolute
|
|
257
|
+
missing.unshift(posix.basename(ancestor))
|
|
258
|
+
ancestor = parent
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// --- Metadata ----------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
/** Opaque freshness token from identity and high-resolution timestamps. */
|
|
266
|
+
function versionOf(info) {
|
|
267
|
+
return [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(':')
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function typeOf(info) {
|
|
271
|
+
if (info.isFile()) return 'file'
|
|
272
|
+
if (info.isDirectory()) return 'directory'
|
|
273
|
+
return 'other'
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Stat a path, treating a missing entry and a file used as a directory as absent. */
|
|
277
|
+
async function probe(absolute, follow = true) {
|
|
278
|
+
try {
|
|
279
|
+
return await (follow ? stat : lstat)(absolute, { bigint: true })
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (isAbsent(error)) return null
|
|
282
|
+
throw translateError(error)
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Require a regular file, reporting the verb the caller used. */
|
|
287
|
+
async function requireFile(target, verb) {
|
|
288
|
+
const info = await probe(target.targetKey)
|
|
289
|
+
if (info === null) throw fsError('cannot ' + verb + ' "' + target.displayPath + '": not found', 'FS_NOT_FOUND')
|
|
290
|
+
if (!info.isFile()) {
|
|
291
|
+
throw fsError('cannot ' + verb + ' "' + target.displayPath + '": not a regular file', 'FS_NOT_REGULAR_FILE')
|
|
292
|
+
}
|
|
293
|
+
return info
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Whether one real path stays inside a workspace spelling the handshake named. */
|
|
297
|
+
function insideWorkspace(real) {
|
|
298
|
+
for (const root of workspaceReal === workspace ? [workspace] : [workspace, workspaceReal]) {
|
|
299
|
+
const base = root.replace(/\/+$/, '')
|
|
300
|
+
if (base === '' || real === base || real.startsWith(base + '/')) return true
|
|
301
|
+
}
|
|
302
|
+
return false
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Resolve one read target to the identity the read itself opens.
|
|
307
|
+
*
|
|
308
|
+
* The host fences the identity it resolved, and this resolves it once more
|
|
309
|
+
* immediately before the I/O: a link inside the workspace can be repointed
|
|
310
|
+
* outside it between the two, and reading the identity that was just verified
|
|
311
|
+
* is what closes that window.
|
|
312
|
+
* @param {{targetKey: string, displayPath: string}} target - the requested target.
|
|
313
|
+
* @returns {Promise<string>} the real path to read.
|
|
314
|
+
*/
|
|
315
|
+
async function readableTarget(target) {
|
|
316
|
+
let real
|
|
317
|
+
try {
|
|
318
|
+
real = toPosixPath(await realpath(target.targetKey))
|
|
319
|
+
} catch (error) {
|
|
320
|
+
throw translateError(error)
|
|
321
|
+
}
|
|
322
|
+
if (insideWorkspace(real)) return real
|
|
323
|
+
throw fsError(
|
|
324
|
+
'cannot read "' + target.displayPath + '": the resolved path "' + real + '" leaves the workspace',
|
|
325
|
+
'FS_PERMISSION_DENIED',
|
|
326
|
+
)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Require the guard the caller supplied to still describe the file. */
|
|
330
|
+
async function requireGuard(target, expected, verb) {
|
|
331
|
+
const info = await probe(target.targetKey)
|
|
332
|
+
const guarded = expected !== undefined && expected !== null && typeof expected.version === 'string'
|
|
333
|
+
if (info === null || !info.isFile() || (guarded && versionOf(info) !== expected.version)) {
|
|
334
|
+
throw fsError('cannot ' + verb + ' "' + target.displayPath + '": file changed since it was read', 'FS_STALE_VERSION')
|
|
335
|
+
}
|
|
336
|
+
return info
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Normalize a request's target object. */
|
|
340
|
+
function asTarget(raw) {
|
|
341
|
+
if (raw === null || typeof raw !== 'object' || typeof raw.targetKey !== 'string') {
|
|
342
|
+
throw new Error('devcontainer helper: malformed target')
|
|
343
|
+
}
|
|
344
|
+
return {
|
|
345
|
+
targetKey: raw.targetKey,
|
|
346
|
+
displayPath: typeof raw.displayPath === 'string' ? raw.displayPath : raw.targetKey,
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// --- Text decoding -----------------------------------------------------------
|
|
351
|
+
|
|
352
|
+
function decodeUtf8(buffer, verb, displayPath) {
|
|
353
|
+
try {
|
|
354
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(buffer)
|
|
355
|
+
} catch {
|
|
356
|
+
throw fsError('cannot ' + verb + ' "' + displayPath + '": invalid UTF-8 text', 'FS_NOT_TEXT')
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function normalizeLineEndings(content) {
|
|
361
|
+
return content.split('\r\n').join('\n')
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function detectLineEndings(raw) {
|
|
365
|
+
const sample = raw.slice(0, 4096)
|
|
366
|
+
const crlf = sample.split('\r\n').length - 1
|
|
367
|
+
const lf = sample.split('\n').length - 1 - crlf
|
|
368
|
+
return crlf > lf ? 'CRLF' : 'LF'
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function restoreLineEndings(content, style) {
|
|
372
|
+
return style === 'LF' ? content : normalizeLineEndings(content).split('\n').join('\r\n')
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Read a file for editing: LF-normalized text plus the style to restore on write-back. */
|
|
376
|
+
async function readForEdit(target, verb) {
|
|
377
|
+
const buffer = await readFile(target.targetKey)
|
|
378
|
+
if (buffer.includes(0)) throw fsError('cannot ' + verb + ' "' + target.displayPath + '": binary file', 'FS_NOT_TEXT')
|
|
379
|
+
const raw = decodeUtf8(buffer, verb, target.displayPath)
|
|
380
|
+
return { content: normalizeLineEndings(raw), lineEndings: detectLineEndings(raw) }
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** The bounded diff basis a mutation reports, or null when it is unavailable. */
|
|
384
|
+
async function diffBasis(target, maxBytes) {
|
|
385
|
+
try {
|
|
386
|
+
const info = await probe(target.targetKey)
|
|
387
|
+
if (info === null || !info.isFile() || Number(info.size) >= maxBytes) return null
|
|
388
|
+
const buffer = await readFile(target.targetKey)
|
|
389
|
+
if (buffer.length !== Number(info.size) || buffer.includes(0)) return null
|
|
390
|
+
return normalizeLineEndings(decodeUtf8(buffer, 'read', target.displayPath))
|
|
391
|
+
} catch {
|
|
392
|
+
return null
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// --- Literal edits and patches ----------------------------------------------
|
|
397
|
+
|
|
398
|
+
function countOccurrences(content, needle) {
|
|
399
|
+
let count = 0
|
|
400
|
+
let index = 0
|
|
401
|
+
for (;;) {
|
|
402
|
+
const found = content.indexOf(needle, index)
|
|
403
|
+
if (found === -1) return count
|
|
404
|
+
count += 1
|
|
405
|
+
index = found + needle.length
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function applyLiteralEdit(content, edit, displayPath) {
|
|
410
|
+
const oldText = normalizeLineEndings(String(edit.oldString === undefined ? '' : edit.oldString))
|
|
411
|
+
if (oldText.length === 0) throw fsError('old_string must be a non-empty string', 'FS_EDIT_NOT_FOUND')
|
|
412
|
+
const newText = normalizeLineEndings(String(edit.newString === undefined ? '' : edit.newString))
|
|
413
|
+
const replacements = countOccurrences(content, oldText)
|
|
414
|
+
if (replacements === 0) throw fsError('old_string was not found in "' + displayPath + '"', 'FS_EDIT_NOT_FOUND')
|
|
415
|
+
if (edit.replaceAll !== true && replacements > 1) {
|
|
416
|
+
throw fsError('old_string matched ' + replacements + ' times in "' + displayPath
|
|
417
|
+
+ '"; provide a more specific old_string or set replace_all to true', 'FS_AMBIGUOUS_EDIT')
|
|
418
|
+
}
|
|
419
|
+
return content.split(oldText).join(newText)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/*
|
|
423
|
+
* Hunk application ported from DeepSeek Harness' @deepseek-ai/dsh-fs-patch
|
|
424
|
+
* (itself adapted from OpenAI Codex rust-v0.158.0 NormalizeToLf, Apache-2.0), so a
|
|
425
|
+
* patch the host parsed applies here with the same matching rules.
|
|
426
|
+
*/
|
|
427
|
+
const WHITE_SPACE = /\p{White_Space}/u
|
|
428
|
+
|
|
429
|
+
function trimWhitespace(value, leading) {
|
|
430
|
+
let start = 0
|
|
431
|
+
let end = value.length
|
|
432
|
+
if (leading) while (start < end && WHITE_SPACE.test(value.charAt(start))) start += 1
|
|
433
|
+
while (end > start && WHITE_SPACE.test(value.charAt(end - 1))) end -= 1
|
|
434
|
+
return value.slice(start, end)
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function normalizePunctuation(value) {
|
|
438
|
+
return trimWhitespace(value, true)
|
|
439
|
+
.replace(/[\u2010-\u2015\u2212]/gu, '-')
|
|
440
|
+
.replace(/[\u2018-\u201B]/gu, "'")
|
|
441
|
+
.replace(/[\u201C-\u201F]/gu, '"')
|
|
442
|
+
.replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/gu, ' ')
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const MATCH_PASSES = [
|
|
446
|
+
(value) => value,
|
|
447
|
+
(value) => trimWhitespace(value, false),
|
|
448
|
+
(value) => trimWhitespace(value, true),
|
|
449
|
+
normalizePunctuation,
|
|
450
|
+
]
|
|
451
|
+
|
|
452
|
+
function seekSequence(lines, pattern, start, eof) {
|
|
453
|
+
if (pattern.length === 0) return start
|
|
454
|
+
if (pattern.length > lines.length) return undefined
|
|
455
|
+
const last = lines.length - pattern.length
|
|
456
|
+
const first = eof ? last : start
|
|
457
|
+
for (const normalize of MATCH_PASSES) {
|
|
458
|
+
const expected = pattern.map(normalize)
|
|
459
|
+
for (let index = first; index <= last; index += 1) {
|
|
460
|
+
if (expected.every((line, offset) => normalize(lines[index + offset]) === line)) return index
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return undefined
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function patchMismatch(hunk, stage) {
|
|
467
|
+
return fsError('hunk at patch line ' + hunk.lineNumber + ' (' + stage + ') does not match', 'FS_PATCH_MISMATCH')
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function applyHunks(before, hunks) {
|
|
471
|
+
const original = before.split('\n')
|
|
472
|
+
if (original[original.length - 1] === '') original.pop()
|
|
473
|
+
const replacements = []
|
|
474
|
+
let lineIndex = 0
|
|
475
|
+
for (const hunk of hunks) {
|
|
476
|
+
if (hunk.context !== undefined) {
|
|
477
|
+
const anchor = [hunk.context]
|
|
478
|
+
const found = seekSequence(original, anchor, lineIndex, false)
|
|
479
|
+
if (found === undefined) throw patchMismatch(hunk, 'context')
|
|
480
|
+
lineIndex = found + 1
|
|
481
|
+
}
|
|
482
|
+
if (hunk.oldLines.length === 0) {
|
|
483
|
+
const at = original[original.length - 1] === '' ? original.length - 1 : original.length
|
|
484
|
+
replacements.push({ start: at, oldLength: 0, newLines: hunk.newLines })
|
|
485
|
+
continue
|
|
486
|
+
}
|
|
487
|
+
let pattern = hunk.oldLines
|
|
488
|
+
let newLines = hunk.newLines
|
|
489
|
+
let found = seekSequence(original, pattern, lineIndex, hunk.isEndOfFile === true)
|
|
490
|
+
if (found === undefined && pattern[pattern.length - 1] === '') {
|
|
491
|
+
pattern = pattern.slice(0, -1)
|
|
492
|
+
if (newLines[newLines.length - 1] === '') newLines = newLines.slice(0, -1)
|
|
493
|
+
found = seekSequence(original, pattern, lineIndex, hunk.isEndOfFile === true)
|
|
494
|
+
}
|
|
495
|
+
if (found === undefined) throw patchMismatch(hunk, 'oldLines')
|
|
496
|
+
replacements.push({ start: found, oldLength: pattern.length, newLines })
|
|
497
|
+
lineIndex = found + pattern.length
|
|
498
|
+
}
|
|
499
|
+
replacements.sort((left, right) => left.start - right.start)
|
|
500
|
+
let lines = original
|
|
501
|
+
for (const replacement of replacements.reverse()) {
|
|
502
|
+
lines = [
|
|
503
|
+
...lines.slice(0, replacement.start),
|
|
504
|
+
...replacement.newLines,
|
|
505
|
+
...lines.slice(replacement.start + replacement.oldLength),
|
|
506
|
+
]
|
|
507
|
+
}
|
|
508
|
+
if (lines[lines.length - 1] !== '') lines.push('')
|
|
509
|
+
return lines.join('\n')
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// --- Mutations ---------------------------------------------------------------
|
|
513
|
+
|
|
514
|
+
/** Remove one staging directory without masking the primary failure. */
|
|
515
|
+
async function discard(path) {
|
|
516
|
+
try {
|
|
517
|
+
await rm(path, { recursive: true, force: true })
|
|
518
|
+
} catch {
|
|
519
|
+
// Staging residue must not replace the outcome the caller already earned.
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** Atomically publish text through an owner-only staging file in the destination directory. */
|
|
524
|
+
async function writeFileAtomic(absolute, content, mode, options) {
|
|
525
|
+
const directory = posix.dirname(absolute)
|
|
526
|
+
await mkdir(directory, { recursive: true })
|
|
527
|
+
const stagingDir = posix.join(
|
|
528
|
+
directory,
|
|
529
|
+
'.' + posix.basename(absolute) + '.' + process.pid + '.' + randomUUID() + '.tmpdir',
|
|
530
|
+
)
|
|
531
|
+
const tempPath = posix.join(stagingDir, 'file.tmp')
|
|
532
|
+
await mkdir(stagingDir, { mode: 0o700 })
|
|
533
|
+
try {
|
|
534
|
+
await chmod(stagingDir, 0o700)
|
|
535
|
+
const handle = await open(tempPath, 'wx', 0o600)
|
|
536
|
+
try {
|
|
537
|
+
await handle.writeFile(content, 'utf8')
|
|
538
|
+
await handle.sync()
|
|
539
|
+
if (mode !== undefined) await handle.chmod(mode)
|
|
540
|
+
} finally {
|
|
541
|
+
await handle.close()
|
|
542
|
+
}
|
|
543
|
+
if (options.createIfAbsent === true) {
|
|
544
|
+
try {
|
|
545
|
+
await link(tempPath, absolute)
|
|
546
|
+
} catch (error) {
|
|
547
|
+
const existing = await probe(absolute).catch(() => null)
|
|
548
|
+
if (existing !== null) {
|
|
549
|
+
throw fsError('cannot overwrite existing "' + options.displayPath + '": read it first', 'FS_NOT_OBSERVED')
|
|
550
|
+
}
|
|
551
|
+
throw translateError(error)
|
|
552
|
+
}
|
|
553
|
+
} else {
|
|
554
|
+
await rename(tempPath, absolute)
|
|
555
|
+
}
|
|
556
|
+
} finally {
|
|
557
|
+
await discard(stagingDir)
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Serialize mutations per path so read, guard, and write stay one critical section. */
|
|
562
|
+
const locks = new Map()
|
|
563
|
+
|
|
564
|
+
function withLock(key, operation) {
|
|
565
|
+
return withLocks([key], operation)
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function withLocks(keys, operation) {
|
|
569
|
+
const ordered = [...new Set(keys)].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))
|
|
570
|
+
const acquire = (index) => {
|
|
571
|
+
const key = ordered[index]
|
|
572
|
+
if (key === undefined) return operation()
|
|
573
|
+
const prior = locks.get(key) ?? Promise.resolve()
|
|
574
|
+
const run = prior.then(() => acquire(index + 1))
|
|
575
|
+
const tail = run.then(() => undefined, () => undefined)
|
|
576
|
+
locks.set(key, tail)
|
|
577
|
+
return run.finally(() => {
|
|
578
|
+
if (locks.get(key) === tail) locks.delete(key)
|
|
579
|
+
})
|
|
580
|
+
}
|
|
581
|
+
return Promise.resolve().then(() => acquire(0))
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// --- Streams -----------------------------------------------------------------
|
|
585
|
+
|
|
586
|
+
const streams = new Map()
|
|
587
|
+
|
|
588
|
+
/** Decoded text chunks of one file, with the same rejection rules as a whole read. */
|
|
589
|
+
async function* streamWholeText(target) {
|
|
590
|
+
const decoder = new TextDecoder('utf-8', { fatal: true })
|
|
591
|
+
let sampled = 0
|
|
592
|
+
for await (const chunk of createReadStream(target.targetKey)) {
|
|
593
|
+
if (sampled < BINARY_SAMPLE_BYTES) {
|
|
594
|
+
const sample = chunk.subarray(0, Math.min(chunk.length, BINARY_SAMPLE_BYTES - sampled))
|
|
595
|
+
if (sample.includes(0)) throw fsError('cannot read "' + target.displayPath + '": binary file', 'FS_NOT_TEXT')
|
|
596
|
+
sampled += sample.length
|
|
597
|
+
}
|
|
598
|
+
yield decodeUtf8Chunk(decoder, chunk, target.displayPath)
|
|
599
|
+
}
|
|
600
|
+
yield decodeUtf8Chunk(decoder, undefined, target.displayPath)
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function decodeUtf8Chunk(decoder, chunk, displayPath) {
|
|
604
|
+
try {
|
|
605
|
+
return chunk === undefined ? decoder.decode() : decoder.decode(chunk, { stream: true })
|
|
606
|
+
} catch {
|
|
607
|
+
throw fsError('cannot read "' + displayPath + '": invalid UTF-8 text', 'FS_NOT_TEXT')
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// --- Handlers ----------------------------------------------------------------
|
|
612
|
+
|
|
613
|
+
/** The handshake and version probe; it also fixes the workspace. */
|
|
614
|
+
function hello(params) {
|
|
615
|
+
if (initialized) throw new Error('devcontainer helper: handshake already completed')
|
|
616
|
+
if (params === null || typeof params !== 'object') throw new Error('devcontainer helper: malformed handshake')
|
|
617
|
+
if (params.protocol !== PROTOCOL_VERSION) {
|
|
618
|
+
throw new Error('devcontainer helper: protocol ' + String(params.protocol) + ' is not ' + String(PROTOCOL_VERSION))
|
|
619
|
+
}
|
|
620
|
+
const declared = String(typeof params.workspace === 'string' ? params.workspace : '/').split('\\').join('/')
|
|
621
|
+
workspace = anchorPath(declared.trim() === '' ? '/' : declared, '/')
|
|
622
|
+
initialized = true
|
|
623
|
+
const greeting = () => ({
|
|
624
|
+
protocol: PROTOCOL_VERSION,
|
|
625
|
+
platform: process.platform,
|
|
626
|
+
nodeVersion: process.version,
|
|
627
|
+
pid: process.pid,
|
|
628
|
+
workspace,
|
|
629
|
+
workspaceReal,
|
|
630
|
+
})
|
|
631
|
+
return realpath(workspace).then(
|
|
632
|
+
(real) => {
|
|
633
|
+
workspaceReal = toPosixPath(real)
|
|
634
|
+
return greeting()
|
|
635
|
+
},
|
|
636
|
+
() => {
|
|
637
|
+
// A mount that cannot be realpath'd is its own identity, never the root:
|
|
638
|
+
// the host fences resolved identities against this path.
|
|
639
|
+
workspaceReal = workspace
|
|
640
|
+
return greeting()
|
|
641
|
+
},
|
|
642
|
+
)
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function requireInitialized() {
|
|
646
|
+
if (!initialized) throw new Error('devcontainer helper: handshake required')
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
async function fsResolve(params) {
|
|
650
|
+
const absolute = toAbsolute(params.path, params.cwd)
|
|
651
|
+
return { targetKey: await identityOf(absolute), displayPath: absolute }
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
async function fsLstat(params) {
|
|
655
|
+
const absolute = toAbsolute(params.path, params.cwd)
|
|
656
|
+
const info = await probe(absolute, false)
|
|
657
|
+
if (info === null) return null
|
|
658
|
+
return {
|
|
659
|
+
version: versionOf(info),
|
|
660
|
+
type: info.isSymbolicLink() ? 'symlink' : typeOf(info),
|
|
661
|
+
size: Number(info.size),
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async function fsStat(params) {
|
|
666
|
+
const target = asTarget(params.target)
|
|
667
|
+
const info = await probe(target.targetKey)
|
|
668
|
+
if (info === null) return null
|
|
669
|
+
return { version: versionOf(info), type: typeOf(info), size: Number(info.size) }
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
async function fsReadText(params) {
|
|
673
|
+
const target = asTarget(params.target)
|
|
674
|
+
const info = await requireFile(target, 'read')
|
|
675
|
+
if (Number(info.size) > MAX_TEXT_BYTES) {
|
|
676
|
+
throw fsError(
|
|
677
|
+
'cannot read "' + target.displayPath + '": ' + Number(info.size) + ' bytes exceeds the whole-text limit; stream it instead',
|
|
678
|
+
'FS_TOO_LARGE',
|
|
679
|
+
)
|
|
680
|
+
}
|
|
681
|
+
const buffer = await readFile(await readableTarget(target))
|
|
682
|
+
if (buffer.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {
|
|
683
|
+
throw fsError('cannot read "' + target.displayPath + '": binary file', 'FS_NOT_TEXT')
|
|
684
|
+
}
|
|
685
|
+
return decodeUtf8(buffer, 'read', target.displayPath)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async function fsReadBytes(params) {
|
|
689
|
+
const target = asTarget(params.target)
|
|
690
|
+
const info = await requireFile(target, 'read')
|
|
691
|
+
const maxBytes = Math.min(Number(params.maxBytes === undefined ? MAX_TEXT_BYTES : params.maxBytes), MAX_TEXT_BYTES)
|
|
692
|
+
if (Number(info.size) > maxBytes) {
|
|
693
|
+
throw fsError(
|
|
694
|
+
'cannot read "' + target.displayPath + '": ' + Number(info.size) + ' bytes exceeds the ' + maxBytes + '-byte limit',
|
|
695
|
+
'FS_TOO_LARGE',
|
|
696
|
+
)
|
|
697
|
+
}
|
|
698
|
+
return (await readFile(await readableTarget(target))).toString('base64')
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function readWindow(absolute, offset, length) {
|
|
702
|
+
return new Promise((resolve, reject) => {
|
|
703
|
+
const chunks = []
|
|
704
|
+
const stream = createReadStream(absolute, { start: offset, end: offset + Math.max(length, 1) - 1 })
|
|
705
|
+
stream.on('data', (chunk) => { chunks.push(chunk) })
|
|
706
|
+
stream.on('error', (error) => { reject(translateError(error)) })
|
|
707
|
+
stream.on('end', () => { resolve(Buffer.concat(chunks)) })
|
|
708
|
+
})
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async function fsReadRange(params) {
|
|
712
|
+
const target = asTarget(params.target)
|
|
713
|
+
await requireFile(target, 'read')
|
|
714
|
+
const offset = Number(params.offset === undefined ? 0 : params.offset)
|
|
715
|
+
const length = Number(params.length === undefined ? 0 : params.length)
|
|
716
|
+
if (length === 0) return ''
|
|
717
|
+
return (await readWindow(await readableTarget(target), offset, length)).toString('base64')
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async function fsList(params) {
|
|
721
|
+
const target = asTarget(params.target)
|
|
722
|
+
const info = await probe(target.targetKey)
|
|
723
|
+
if (info === null) throw fsError('cannot list "' + target.displayPath + '": not found', 'FS_NOT_FOUND')
|
|
724
|
+
if (!info.isDirectory()) throw fsError('cannot list "' + target.displayPath + '": not a directory', 'FS_NOT_DIRECTORY')
|
|
725
|
+
const entries = await readdir(target.targetKey, { withFileTypes: true, encoding: 'utf8' })
|
|
726
|
+
entries.sort((left, right) => left.name.localeCompare(right.name))
|
|
727
|
+
const listed = []
|
|
728
|
+
for (const entry of entries) {
|
|
729
|
+
const childKey = await identityOf(posix.join(target.targetKey, entry.name))
|
|
730
|
+
const childInfo = await probe(childKey)
|
|
731
|
+
const child = {
|
|
732
|
+
name: entry.name,
|
|
733
|
+
type: childInfo === null ? 'other' : typeOf(childInfo),
|
|
734
|
+
target: { targetKey: childKey, displayPath: posix.join(target.displayPath, entry.name) },
|
|
735
|
+
}
|
|
736
|
+
if (childInfo !== null) child.version = versionOf(childInfo)
|
|
737
|
+
if (childInfo !== null && childInfo.isFile()) child.size = Number(childInfo.size)
|
|
738
|
+
listed.push(child)
|
|
739
|
+
}
|
|
740
|
+
return listed
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async function fsWrite(params) {
|
|
744
|
+
const target = asTarget(params.target)
|
|
745
|
+
return withLock(target.targetKey, async () => {
|
|
746
|
+
const existing = await probe(target.targetKey)
|
|
747
|
+
if (existing !== null && !existing.isFile()) {
|
|
748
|
+
throw fsError('cannot write "' + target.displayPath + '": not a regular file', 'FS_NOT_REGULAR_FILE')
|
|
749
|
+
}
|
|
750
|
+
const expected = params.expected === undefined ? null : params.expected
|
|
751
|
+
if (expected !== null && expected.kind === 'replaceIfVersion') {
|
|
752
|
+
if (existing === null || versionOf(existing) !== expected.version) {
|
|
753
|
+
throw fsError('cannot write "' + target.displayPath + '": file changed since it was read', 'FS_STALE_VERSION')
|
|
754
|
+
}
|
|
755
|
+
} else if (expected !== null && expected.kind === 'createIfAbsent' && existing !== null) {
|
|
756
|
+
throw fsError('cannot overwrite existing "' + target.displayPath + '": read it first', 'FS_NOT_OBSERVED')
|
|
757
|
+
}
|
|
758
|
+
const content = String(params.content === undefined ? '' : params.content)
|
|
759
|
+
const before = existing === null ? null : await diffBasis(target, MAX_TEXT_BYTES)
|
|
760
|
+
await writeFileAtomic(target.targetKey, content, existing === null ? undefined : Number(existing.mode & 0o777n), {
|
|
761
|
+
displayPath: target.displayPath,
|
|
762
|
+
createIfAbsent: expected !== null && expected.kind === 'createIfAbsent',
|
|
763
|
+
})
|
|
764
|
+
const after = await probe(target.targetKey)
|
|
765
|
+
return {
|
|
766
|
+
operation: existing === null ? 'create' : 'update',
|
|
767
|
+
version: after === null ? 'missing:' + target.targetKey : versionOf(after),
|
|
768
|
+
before,
|
|
769
|
+
after: normalizeLineEndings(content),
|
|
770
|
+
}
|
|
771
|
+
})
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
async function fsEdit(params) {
|
|
775
|
+
const target = asTarget(params.target)
|
|
776
|
+
return withLock(target.targetKey, async () => {
|
|
777
|
+
const existing = await requireGuard(target, params.expected, 'edit')
|
|
778
|
+
const original = await readForEdit(target, 'edit')
|
|
779
|
+
const edited = applyLiteralEdit(original.content, params.edit === undefined ? {} : params.edit, target.displayPath)
|
|
780
|
+
await writeFileAtomic(
|
|
781
|
+
target.targetKey,
|
|
782
|
+
restoreLineEndings(edited, original.lineEndings),
|
|
783
|
+
Number(existing.mode & 0o777n),
|
|
784
|
+
{ displayPath: target.displayPath },
|
|
785
|
+
)
|
|
786
|
+
const after = await probe(target.targetKey)
|
|
787
|
+
return {
|
|
788
|
+
version: after === null ? 'missing:' + target.targetKey : versionOf(after),
|
|
789
|
+
before: original.content,
|
|
790
|
+
after: edited,
|
|
791
|
+
}
|
|
792
|
+
})
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
async function fsPatch(params) {
|
|
796
|
+
const target = asTarget(params.target)
|
|
797
|
+
return withLock(target.targetKey, async () => {
|
|
798
|
+
const existing = await requireGuard(target, params.expected, 'patch')
|
|
799
|
+
const original = await readForEdit(target, 'patch')
|
|
800
|
+
const after = applyHunks(original.content, Array.isArray(params.hunks) ? params.hunks : [])
|
|
801
|
+
await writeFileAtomic(
|
|
802
|
+
target.targetKey,
|
|
803
|
+
restoreLineEndings(after, original.lineEndings),
|
|
804
|
+
Number(existing.mode & 0o777n),
|
|
805
|
+
{ displayPath: target.displayPath },
|
|
806
|
+
)
|
|
807
|
+
const info = await probe(target.targetKey)
|
|
808
|
+
return {
|
|
809
|
+
version: info === null ? 'missing:' + target.targetKey : versionOf(info),
|
|
810
|
+
before: original.content,
|
|
811
|
+
after,
|
|
812
|
+
}
|
|
813
|
+
})
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
async function fsDelete(params) {
|
|
817
|
+
const target = asTarget(params.target)
|
|
818
|
+
return withLock(target.targetKey, async () => {
|
|
819
|
+
await requireGuard(target, params.expected, 'delete')
|
|
820
|
+
const before = await diffBasis(target, MAX_TEXT_BYTES)
|
|
821
|
+
try {
|
|
822
|
+
await rm(target.targetKey)
|
|
823
|
+
} catch (error) {
|
|
824
|
+
throw translateError(error)
|
|
825
|
+
}
|
|
826
|
+
return { before }
|
|
827
|
+
})
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
async function fsMove(params) {
|
|
831
|
+
const source = asTarget(params.source)
|
|
832
|
+
const destination = asTarget(params.destination)
|
|
833
|
+
if (source.targetKey === destination.targetKey) {
|
|
834
|
+
throw fsError('cannot move "' + source.displayPath + '": source and destination are the same file', 'FS_SAME_TARGET')
|
|
835
|
+
}
|
|
836
|
+
const options = params.options === undefined || params.options === null ? {} : params.options
|
|
837
|
+
return withLocks([source.targetKey, destination.targetKey], async () => {
|
|
838
|
+
const sourceInfo = await requireGuard(source, options.expectedSource, 'move')
|
|
839
|
+
const existing = await probe(destination.targetKey)
|
|
840
|
+
if (existing !== null && !existing.isFile()) {
|
|
841
|
+
throw fsError('cannot move onto "' + destination.displayPath + '": not a regular file', 'FS_NOT_REGULAR_FILE')
|
|
842
|
+
}
|
|
843
|
+
const expectedDestination = options.expectedDestination === undefined ? null : options.expectedDestination
|
|
844
|
+
if (expectedDestination !== null && expectedDestination.kind === 'createIfAbsent' && existing !== null) {
|
|
845
|
+
throw fsError('cannot overwrite existing "' + destination.displayPath + '": read it first', 'FS_NOT_OBSERVED')
|
|
846
|
+
}
|
|
847
|
+
if (expectedDestination !== null && expectedDestination.kind === 'replaceIfVersion'
|
|
848
|
+
&& (existing === null || versionOf(existing) !== expectedDestination.version)) {
|
|
849
|
+
throw fsError('cannot move onto "' + destination.displayPath + '": file changed since it was read', 'FS_STALE_VERSION')
|
|
850
|
+
}
|
|
851
|
+
const original = await readForEdit(source, 'move')
|
|
852
|
+
const after = Array.isArray(options.hunks) ? applyHunks(original.content, options.hunks) : original.content
|
|
853
|
+
const before = existing === null ? null : await diffBasis(destination, MAX_TEXT_BYTES)
|
|
854
|
+
await writeFileAtomic(
|
|
855
|
+
destination.targetKey,
|
|
856
|
+
restoreLineEndings(after, original.lineEndings),
|
|
857
|
+
Number(sourceInfo.mode & 0o777n),
|
|
858
|
+
{
|
|
859
|
+
displayPath: destination.displayPath,
|
|
860
|
+
createIfAbsent: expectedDestination !== null && expectedDestination.kind === 'createIfAbsent',
|
|
861
|
+
},
|
|
862
|
+
)
|
|
863
|
+
const published = await probe(destination.targetKey)
|
|
864
|
+
const destinationOutcome = {
|
|
865
|
+
operation: existing === null ? 'create' : 'update',
|
|
866
|
+
version: published === null ? 'missing:' + destination.targetKey : versionOf(published),
|
|
867
|
+
before,
|
|
868
|
+
after,
|
|
869
|
+
}
|
|
870
|
+
let sourceFailure
|
|
871
|
+
try {
|
|
872
|
+
await rm(source.targetKey)
|
|
873
|
+
} catch (error) {
|
|
874
|
+
const translated = translateError(error)
|
|
875
|
+
sourceFailure = {
|
|
876
|
+
code: typeof translated.code === 'string' ? translated.code : 'FS_IO_ERROR',
|
|
877
|
+
message: translated.message,
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
return sourceFailure === undefined
|
|
881
|
+
? { sourceBefore: original.content, destination: destinationOutcome, sourceDeleted: true }
|
|
882
|
+
: { sourceBefore: original.content, destination: destinationOutcome, sourceDeleted: false, sourceFailure }
|
|
883
|
+
})
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
async function fsStreamStart(params) {
|
|
887
|
+
const target = asTarget(params.target)
|
|
888
|
+
await requireFile(target, 'read')
|
|
889
|
+
if (streams.size >= MAX_TEXT_STREAMS) throw new Error('devcontainer helper: text stream limit reached')
|
|
890
|
+
const id = randomUUID()
|
|
891
|
+
streams.set(id, streamWholeText({ ...target, targetKey: await readableTarget(target) })[Symbol.asyncIterator]())
|
|
892
|
+
return { id }
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
async function fsStreamNext(params) {
|
|
896
|
+
const id = String(params.id)
|
|
897
|
+
const record = streams.get(id)
|
|
898
|
+
if (record === undefined) throw new Error('devcontainer helper: unknown text stream')
|
|
899
|
+
const next = await record.next()
|
|
900
|
+
if (next.done === true) {
|
|
901
|
+
streams.delete(id)
|
|
902
|
+
return { done: true, value: '' }
|
|
903
|
+
}
|
|
904
|
+
return { done: false, value: next.value }
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
async function fsStreamClose(params) {
|
|
908
|
+
const id = String(params.id)
|
|
909
|
+
const record = streams.get(id)
|
|
910
|
+
if (record === undefined) return null
|
|
911
|
+
streams.delete(id)
|
|
912
|
+
await record.return()
|
|
913
|
+
return null
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// --- Dispatch ----------------------------------------------------------------
|
|
917
|
+
|
|
918
|
+
const HANDLERS = {
|
|
919
|
+
hello,
|
|
920
|
+
ping: () => ({ pong: true, now: Date.now() }),
|
|
921
|
+
'fs.resolve': fsResolve,
|
|
922
|
+
'fs.lstat': fsLstat,
|
|
923
|
+
'fs.stat': fsStat,
|
|
924
|
+
'fs.readText': fsReadText,
|
|
925
|
+
'fs.readBytes': fsReadBytes,
|
|
926
|
+
'fs.readRange': fsReadRange,
|
|
927
|
+
'fs.list': fsList,
|
|
928
|
+
'fs.write': fsWrite,
|
|
929
|
+
'fs.edit': fsEdit,
|
|
930
|
+
'fs.patch': fsPatch,
|
|
931
|
+
'fs.delete': fsDelete,
|
|
932
|
+
'fs.move': fsMove,
|
|
933
|
+
'fs.stream': fsStreamStart,
|
|
934
|
+
'fs.next': fsStreamNext,
|
|
935
|
+
'fs.streamClose': fsStreamClose,
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
const active = new Map()
|
|
939
|
+
let closing = false
|
|
940
|
+
|
|
941
|
+
async function dispatch(method, params, signal) {
|
|
942
|
+
const handler = HANDLERS[method]
|
|
943
|
+
if (handler === undefined) throw new Error('devcontainer helper: unknown operation ' + String(method))
|
|
944
|
+
if (method !== 'hello') requireInitialized()
|
|
945
|
+
if (signal.aborted) throw fsError(method + ' aborted', 'FS_ABORTED')
|
|
946
|
+
return await handler(params === undefined || params === null ? {} : params, signal)
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
function receive(frame) {
|
|
950
|
+
if (frame === null || typeof frame !== 'object') return
|
|
951
|
+
if (frame.type === 'cancel') {
|
|
952
|
+
const controller = active.get(frame.id)
|
|
953
|
+
if (controller !== undefined) controller.abort(new Error('devcontainer helper: caller cancelled the operation'))
|
|
954
|
+
return
|
|
955
|
+
}
|
|
956
|
+
if (frame.type !== 'request' || typeof frame.id !== 'string') return
|
|
957
|
+
if (active.has(frame.id)) return
|
|
958
|
+
const controller = new AbortController()
|
|
959
|
+
active.set(frame.id, controller)
|
|
960
|
+
dispatch(frame.method, frame.params, controller.signal).then(
|
|
961
|
+
(value) => send({ type: 'result', id: frame.id, value: value === undefined ? null : value }),
|
|
962
|
+
(error) => send({ type: 'error', id: frame.id, error: describeError(error) }),
|
|
963
|
+
).finally(() => {
|
|
964
|
+
active.delete(frame.id)
|
|
965
|
+
})
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
function shutdown() {
|
|
969
|
+
if (closing) return
|
|
970
|
+
closing = true
|
|
971
|
+
streams.clear()
|
|
972
|
+
for (const controller of active.values()) controller.abort(new Error('devcontainer helper: closing'))
|
|
973
|
+
active.clear()
|
|
974
|
+
process.stdin.pause()
|
|
975
|
+
void writeQueue.finally(() => { process.exit(0) })
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* Serve one request without a transport.
|
|
980
|
+
* @param {string} method - the helper operation.
|
|
981
|
+
* @param {unknown} params - the request parameters.
|
|
982
|
+
* @returns {Promise<unknown>} the operation's value.
|
|
983
|
+
*/
|
|
984
|
+
export async function handle(method, params) {
|
|
985
|
+
return await dispatch(method, params, new AbortController().signal)
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** Read framed requests from stdin and answer on stdout until the pipe closes. */
|
|
989
|
+
function main() {
|
|
990
|
+
const decoder = new FrameDecoder()
|
|
991
|
+
process.stdin.on('data', (chunk) => {
|
|
992
|
+
let frames
|
|
993
|
+
try {
|
|
994
|
+
frames = decoder.push(chunk)
|
|
995
|
+
} catch (error) {
|
|
996
|
+
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n')
|
|
997
|
+
process.exit(1)
|
|
998
|
+
}
|
|
999
|
+
for (const frame of frames) receive(frame)
|
|
1000
|
+
})
|
|
1001
|
+
process.stdin.on('end', shutdown)
|
|
1002
|
+
process.stdin.on('error', shutdown)
|
|
1003
|
+
process.on('SIGTERM', shutdown)
|
|
1004
|
+
process.on('SIGINT', shutdown)
|
|
1005
|
+
process.stdout.on('error', shutdown)
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) main()
|