dsh-remote-deck 0.0.0-stage → 1.46.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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -2
  3. package/README.zh-CN.md +201 -0
  4. package/client.js +8645 -0
  5. package/cordis.patch.yml +6 -0
  6. package/icon.svg +19 -0
  7. package/index.js +701 -0
  8. package/lib/api.js +1452 -0
  9. package/lib/bash-result.js +93 -0
  10. package/lib/connection.js +1133 -0
  11. package/lib/delete.js +199 -0
  12. package/lib/drafts.js +299 -0
  13. package/lib/encoding.js +247 -0
  14. package/lib/file-edit.js +339 -0
  15. package/lib/file-ops.js +402 -0
  16. package/lib/forwards.js +186 -0
  17. package/lib/fs-actions.js +235 -0
  18. package/lib/guide.js +162 -0
  19. package/lib/metrics.js +523 -0
  20. package/lib/remote-shells.js +320 -0
  21. package/lib/remote-terminal.js +427 -0
  22. package/lib/routing.js +695 -0
  23. package/lib/ssh-config.js +118 -0
  24. package/lib/terminal.js +123 -0
  25. package/lib/tool-forward.js +185 -0
  26. package/lib/transfer.js +235 -0
  27. package/lib/upload-chunks.js +306 -0
  28. package/lib/util.js +154 -0
  29. package/locale/README.md +160 -0
  30. package/locale/en-ui.json +477 -0
  31. package/locale/en.json +6 -0
  32. package/locale/zh.json +6 -0
  33. package/package.json +63 -4
  34. package/vendor/codemirror/LICENSE +21 -0
  35. package/vendor/codemirror/README.md +18 -0
  36. package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
  37. package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
  38. package/vendor/codemirror/addon/search/search.min.js +8 -0
  39. package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
  40. package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
  41. package/vendor/codemirror/lib/codemirror.css +344 -0
  42. package/vendor/codemirror/lib/codemirror.min.js +8 -0
  43. package/vendor/codemirror/mode/clike/clike.min.js +8 -0
  44. package/vendor/codemirror/mode/css/css.min.js +8 -0
  45. package/vendor/codemirror/mode/go/go.min.js +8 -0
  46. package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
  47. package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
  48. package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
  49. package/vendor/codemirror/mode/python/python.min.js +8 -0
  50. package/vendor/codemirror/mode/rust/rust.min.js +8 -0
  51. package/vendor/codemirror/mode/shell/shell.min.js +8 -0
  52. package/vendor/codemirror/mode/xml/xml.min.js +8 -0
  53. package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
  54. package/vendor/node_modules/asn1/Jenkinsfile +65 -0
  55. package/vendor/node_modules/asn1/LICENSE +19 -0
  56. package/vendor/node_modules/asn1/README.md +50 -0
  57. package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  58. package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  59. package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  60. package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  61. package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  62. package/vendor/node_modules/asn1/lib/index.js +20 -0
  63. package/vendor/node_modules/asn1/package.json +31 -0
  64. package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  65. package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  66. package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  67. package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  68. package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  69. package/vendor/node_modules/safer-buffer/LICENSE +21 -0
  70. package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  71. package/vendor/node_modules/safer-buffer/Readme.md +156 -0
  72. package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  73. package/vendor/node_modules/safer-buffer/package.json +34 -0
  74. package/vendor/node_modules/safer-buffer/safer.js +77 -0
  75. package/vendor/node_modules/safer-buffer/tests.js +406 -0
  76. package/vendor/node_modules/ssh2/LICENSE +19 -0
  77. package/vendor/node_modules/ssh2/README.md +1529 -0
  78. package/vendor/node_modules/ssh2/SFTP.md +413 -0
  79. package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  80. package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  81. package/vendor/node_modules/ssh2/lib/client.js +2176 -0
  82. package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  83. package/vendor/node_modules/ssh2/lib/index.js +44 -0
  84. package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  85. package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  86. package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  87. package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  88. package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  89. package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  90. package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  91. package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  92. package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  93. package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  94. package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  95. package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  96. package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  97. package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  98. package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  99. package/vendor/node_modules/ssh2/lib/server.js +1380 -0
  100. package/vendor/node_modules/ssh2/lib/utils.js +336 -0
  101. package/vendor/node_modules/ssh2/package.json +49 -0
  102. package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
  103. package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
  104. package/vendor/node_modules/tweetnacl/LICENSE +24 -0
  105. package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  106. package/vendor/node_modules/tweetnacl/README.md +459 -0
  107. package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
  108. package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
  109. package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  110. package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
  111. package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  112. package/vendor/node_modules/tweetnacl/package.json +58 -0
  113. package/vendor/xterm/LICENSE.addon-fit +19 -0
  114. package/vendor/xterm/LICENSE.xterm +21 -0
  115. package/vendor/xterm/README.md +9 -0
  116. package/vendor/xterm/addon-fit.js +2 -0
  117. package/vendor/xterm/xterm.css +218 -0
  118. package/vendor/xterm/xterm.js +2 -0
package/lib/delete.js ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Recursive remote deletion over SFTP, built for a request the client can cancel.
3
+ *
4
+ * The browser half deletes one path at a time, and its task bar can walk away
5
+ * mid-way by aborting the HTTP request. Three properties matter here:
6
+ *
7
+ * - **No symlink is ever followed.** `lstat` settles the type, a symlink is
8
+ * unlinked as an entry, and only a real directory is read and descended into.
9
+ * A link to `/`, to an ancestor or to another tree therefore removes the link.
10
+ * - **Cancellation is checked before every operation**, so a cancelled delete
11
+ * stops within one SFTP round trip. Counters collected so far are kept.
12
+ * - **A partial delete reports what it already removed**: the caller's counters
13
+ * object is mutated as it goes, so the counts are available with the error.
14
+ *
15
+ * The route owns the meaning of "gone" (see the delete handler in `api.js`);
16
+ * this module only asks `isCancelled()` / `signal.aborted` and never writes a
17
+ * response.
18
+ */
19
+ import { posix } from 'node:path'
20
+ import { normalizeRemotePath, sftpCall } from './util.js'
21
+
22
+ /** The path is not a plain absolute remote POSIX path. */
23
+ export const DELETE_INVALID_CODE = 'NOT_REMOTE_PATH'
24
+ /** The path is a protected root (the filesystem root, or a workspace root without `force`). */
25
+ export const DELETE_ROOT_CODE = 'REMOTE_DECK_DELETE_ROOT'
26
+ /** The path does not exist on the remote host. */
27
+ export const DELETE_MISSING_CODE = 'REMOTE_DECK_DELETE_MISSING'
28
+ /** The request went away; nothing is written back. */
29
+ export const DELETE_CANCELLED_CODE = 'REMOTE_DECK_DELETE_CANCELLED'
30
+
31
+ /** SSH_FX_NO_SUCH_FILE, as ssh2 reports it. */
32
+ const SFTP_NO_SUCH_FILE = 2
33
+ /** `fsError('FS_NOT_FOUND')` from `sftpCall`, and the raw SFTP status code. */
34
+ const FS_NOT_FOUND = 'FS_NOT_FOUND'
35
+
36
+ /**
37
+ * The one spelling of a remote path this module compares and deletes: normal
38
+ * POSIX, no trailing slash. Without it `/data/ws/` would not compare equal to a
39
+ * registered `/data/ws` and the workspace-root guard could be stepped around.
40
+ */
41
+ function canonicalPath(value) {
42
+ const normalized = normalizeRemotePath(value)
43
+ return normalized.length > 1 ? normalized.replace(/\/+$/, '') : normalized
44
+ }
45
+
46
+ /** A fresh `{ files, dirs, bytes }` tally. */
47
+ export function emptyDeleteCounts() {
48
+ return { files: 0, dirs: 0, bytes: 0 }
49
+ }
50
+
51
+ function coded(code, message) {
52
+ const error = new Error(message)
53
+ error.code = code
54
+ return error
55
+ }
56
+
57
+ /** The delete was cancelled by the client going away. */
58
+ export function isDeleteCancelled(error) {
59
+ return Boolean(error) && error.code === DELETE_CANCELLED_CODE
60
+ }
61
+
62
+ /** The path (or the whole tree) was not there to begin with. */
63
+ export function isDeleteMissing(error) {
64
+ return Boolean(error) && error.code === DELETE_MISSING_CODE
65
+ }
66
+
67
+ function isMissing(error) {
68
+ return Boolean(error) && (error.code === FS_NOT_FOUND || error.code === SFTP_NO_SUCH_FILE)
69
+ }
70
+
71
+ /**
72
+ * Validate the requested target.
73
+ *
74
+ * Only a plain absolute POSIX path survives: empty, relative, UNC-style (`//`)
75
+ * and traversal spellings are rejected rather than normalized away, so a client
76
+ * cannot smuggle a different location past the confirmation box. The filesystem
77
+ * root is refused outright — no `force` can make that sensible.
78
+ *
79
+ * @param {unknown} value `path` from the request body
80
+ * @returns {{ ok: true, path: string } | { ok: false, code: string, message: string }}
81
+ */
82
+ export function parseDeleteTarget(value) {
83
+ if (typeof value !== 'string' || value.length === 0) {
84
+ return { ok: false, code: DELETE_INVALID_CODE, message: 'A remote POSIX path is required.' }
85
+ }
86
+ if (!value.startsWith('/') || value.startsWith('//')) {
87
+ return { ok: false, code: DELETE_INVALID_CODE, message: 'Not a remote POSIX path.' }
88
+ }
89
+ if (value.split('/').includes('..')) {
90
+ return { ok: false, code: DELETE_INVALID_CODE, message: 'A delete path cannot contain "..".' }
91
+ }
92
+ const path = canonicalPath(value)
93
+ if (path === '/' || path.length === 0) {
94
+ return { ok: false, code: DELETE_ROOT_CODE, message: 'The filesystem root cannot be deleted.' }
95
+ }
96
+ return { ok: true, path }
97
+ }
98
+
99
+ /**
100
+ * Whether deleting this path needs an explicit `force` from the client.
101
+ *
102
+ * Exactly a workspace root counts: deleting the registered folder itself is the
103
+ * one operation a mis-click can turn into "my whole remote project is gone", and
104
+ * the browser half asks a second time for it. Paths below a root are ordinary.
105
+ *
106
+ * @param {string} path validated absolute path
107
+ * @param {readonly string[]} [workspaceRoots] registered roots of the connection
108
+ * @returns {boolean}
109
+ */
110
+ export function isProtectedDeleteRoot(path, workspaceRoots) {
111
+ if (typeof path !== 'string' || path.length === 0) return false
112
+ const target = canonicalPath(path)
113
+ if (target === '/') return true
114
+ if (!Array.isArray(workspaceRoots)) return false
115
+ return workspaceRoots.some((root) => typeof root === 'string' && root.length > 0 && canonicalPath(root) === target)
116
+ }
117
+
118
+ /** Directory entries that must never be re-joined or deleted. */
119
+ function usableName(entry) {
120
+ const name = entry !== null && typeof entry === 'object' ? entry.filename : undefined
121
+ if (typeof name !== 'string' || name.length === 0) return null
122
+ if (name === '.' || name === '..') return null
123
+ if (name.includes('/')) return null
124
+ return name
125
+ }
126
+
127
+ function attrsOf(value) {
128
+ const attrs = value !== null && typeof value === 'object' ? value : {}
129
+ return {
130
+ directory: typeof attrs.isDirectory === 'function' && attrs.isDirectory() === true,
131
+ link: typeof attrs.isSymbolicLink === 'function' && attrs.isSymbolicLink() === true,
132
+ size: Number.isFinite(attrs.size) && attrs.size > 0 ? Math.floor(attrs.size) : 0,
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Walk and remove one tree.
138
+ *
139
+ * @param {object} input
140
+ * @param {object} input.sftp connected SFTP session
141
+ * @param {string} input.path absolute remote path
142
+ * @param {{ files: number, dirs: number, bytes: number }} [input.counts] tally, mutated as it goes
143
+ * @param {AbortSignal} [input.signal] cancellation
144
+ * @param {() => boolean} [input.isCancelled] extra cancellation check, asked before every operation
145
+ * @param {Function} [input.call] `sftpCall`, injectable for tests
146
+ * @returns {Promise<{ files: number, dirs: number, bytes: number }>}
147
+ * @throws an error coded `REMOTE_DECK_DELETE_MISSING` for an absent root, \
148
+ * `REMOTE_DECK_DELETE_CANCELLED` once cancelled, or the failing SFTP error — \
149
+ * with `counts` already holding what was removed.
150
+ */
151
+ export async function removeRemoteTree({ sftp, path, counts, signal, isCancelled, call } = {}) {
152
+ const tally = counts !== undefined && counts !== null && typeof counts === 'object' ? counts : emptyDeleteCounts()
153
+ const invoke = typeof call === 'function' ? call : sftpCall
154
+ const cancelled = () => (typeof isCancelled === 'function' && isCancelled() === true)
155
+ || (signal !== undefined && signal !== null && signal.aborted === true)
156
+ const guard = () => {
157
+ if (cancelled()) throw coded(DELETE_CANCELLED_CODE, 'The delete was cancelled.')
158
+ }
159
+
160
+ /**
161
+ * @param {string} target
162
+ * @param {boolean} tolerateMissing a child that vanished mid-walk is already gone
163
+ */
164
+ const remove = async (target, tolerateMissing) => {
165
+ guard()
166
+ let attrs
167
+ try {
168
+ attrs = attrsOf(await invoke(sftp, 'lstat', target))
169
+ } catch (error) {
170
+ if (isMissing(error)) {
171
+ if (tolerateMissing) return
172
+ throw coded(DELETE_MISSING_CODE, `No such remote path: ${target}`)
173
+ }
174
+ throw error
175
+ }
176
+ // A symlink is an entry, never a subtree: `lstat` reports the link itself,
177
+ // so this branch unlinks it and never reads what it points at.
178
+ if (!attrs.directory || attrs.link) {
179
+ guard()
180
+ await invoke(sftp, 'unlink', target)
181
+ tally.files += 1
182
+ tally.bytes += attrs.size
183
+ return
184
+ }
185
+ guard()
186
+ const entries = await invoke(sftp, 'readdir', target)
187
+ for (const entry of Array.isArray(entries) ? entries : []) {
188
+ const name = usableName(entry)
189
+ if (name === null) continue
190
+ await remove(posix.join(target, name), true)
191
+ }
192
+ guard()
193
+ await invoke(sftp, 'rmdir', target)
194
+ tally.dirs += 1
195
+ }
196
+
197
+ await remove(path, false)
198
+ return tally
199
+ }
package/lib/drafts.js ADDED
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Editor drafts, kept on disk so an unsaved buffer survives a closed tab — or a
3
+ * closed DSH.
4
+ *
5
+ * One JSON file per (connection, path), named after the sha256 of both, inside
6
+ * `<data dir>/drafts/`. The content is the whole buffer, so a draft is written
7
+ * once, atomically: a temp file in the same directory is renamed over the target
8
+ * and is removed again if anything fails, which is what keeps a crash from
9
+ * leaving half a draft behind.
10
+ *
11
+ * Drafts are not a version history: saving the same path again replaces the
12
+ * file, and a draft is only meant to be read back by the tab that lost it.
13
+ *
14
+ * Nothing here expires on a timer. `sweep()` runs whenever a draft route is
15
+ * used, which is the only moment the directory matters, and it drops two kinds
16
+ * of garbage: drafts whose `savedAt` is older than {@link DRAFT_MAX_AGE_MS}, and
17
+ * orphan temp files from a process that died mid-write. A draft's file mtime is
18
+ * its `savedAt` (the file is written once), so a fresh file needs no read at all
19
+ * and only a stale one is parsed to confirm.
20
+ */
21
+ import { createHash, randomBytes } from 'node:crypto'
22
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
23
+ import { join, posix } from 'node:path'
24
+ import { canonicalRemotePath, isPlainRemotePath } from './file-ops.js'
25
+
26
+ /** Largest draft one request may carry. */
27
+ export const DRAFT_MAX_BYTES = 8 * 1024 * 1024
28
+ /** How long an untouched draft is kept. */
29
+ export const DRAFT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000
30
+ /** A temp file older than this can only be an orphan of a dead process. */
31
+ export const DRAFT_TEMP_MAX_AGE_MS = 60 * 60 * 1000
32
+ /** Directory name under the plugin's data directory. */
33
+ export const DRAFT_DIR_NAME = 'drafts'
34
+ /** Longest connection id kept in a draft record. */
35
+ const MAX_CONNECTION_ID = 128
36
+
37
+ export const DRAFT_INVALID_CODE = 'NOT_REMOTE_PATH'
38
+ export const DRAFT_NOT_TEXT_CODE = 'NOT_TEXT'
39
+ export const DRAFT_TOO_LARGE_CODE = 'TOO_LARGE'
40
+
41
+ function refuse(code, message) {
42
+ return { ok: false, code, message }
43
+ }
44
+
45
+ /** The file one draft lives in: stable, and free of path separators. */
46
+ export function draftFileName(connectionId, path) {
47
+ const digest = createHash('sha256').update(`${connectionId}\u0000${path}`).digest('hex')
48
+ return `${digest.slice(0, 32)}.json`
49
+ }
50
+
51
+ /**
52
+ * Validate the path a draft is filed under.
53
+ *
54
+ * The same rules as the editor's read/write: absolute POSIX, no `..`, no `//`,
55
+ * something left to name.
56
+ *
57
+ * @param {unknown} value
58
+ * @returns {{ ok: true, path: string } | { ok: false, code: string, message: string }}
59
+ */
60
+ export function parseDraftPath(value) {
61
+ if (!isPlainRemotePath(value)) return refuse(DRAFT_INVALID_CODE, 'A remote POSIX file path is required.')
62
+ const path = canonicalRemotePath(value)
63
+ if (posix.basename(path) === '') return refuse(DRAFT_INVALID_CODE, 'Cannot keep a draft for that path.')
64
+ return { ok: true, path }
65
+ }
66
+
67
+ /**
68
+ * Validate a draft write.
69
+ *
70
+ * @param {unknown} body parsed JSON body
71
+ * @returns {{ ok: true, draft: { connectionId: string, path: string, content: string, baseMtime: number | null } } | { ok: false, code: string, message: string }}
72
+ */
73
+ export function parseDraftWrite(body) {
74
+ const source = body !== null && typeof body === 'object' ? body : {}
75
+ const target = parseDraftPath(source.path)
76
+ if (target.ok !== true) return target
77
+ if (typeof source.connectionId === 'string' && source.connectionId.length > MAX_CONNECTION_ID) {
78
+ return refuse(DRAFT_INVALID_CODE, 'That connection id is not addressable.')
79
+ }
80
+ if (typeof source.content !== 'string') return refuse(DRAFT_NOT_TEXT_CODE, 'Content must be a string.')
81
+ if (Buffer.byteLength(source.content, 'utf8') > DRAFT_MAX_BYTES) {
82
+ return refuse(DRAFT_TOO_LARGE_CODE, `A draft is limited to ${Math.round(DRAFT_MAX_BYTES / 1024 / 1024)} MB.`)
83
+ }
84
+ const baseMtime = typeof source.baseMtime === 'number' && Number.isFinite(source.baseMtime)
85
+ ? Math.round(source.baseMtime)
86
+ : null
87
+ return {
88
+ ok: true,
89
+ draft: {
90
+ connectionId: typeof source.connectionId === 'string' ? source.connectionId : '',
91
+ path: target.path,
92
+ content: source.content,
93
+ baseMtime,
94
+ },
95
+ }
96
+ }
97
+
98
+ /** Read one draft file, or null when it is missing or unreadable. */
99
+ function readDraftFile(file) {
100
+ let text
101
+ try {
102
+ text = readFileSync(file, 'utf8')
103
+ } catch {
104
+ return null
105
+ }
106
+ try {
107
+ const parsed = JSON.parse(text)
108
+ if (parsed === null || typeof parsed !== 'object') return null
109
+ if (typeof parsed.path !== 'string' || typeof parsed.content !== 'string') return null
110
+ return {
111
+ connectionId: typeof parsed.connectionId === 'string' ? parsed.connectionId : '',
112
+ path: parsed.path,
113
+ content: parsed.content,
114
+ baseMtime: typeof parsed.baseMtime === 'number' && Number.isFinite(parsed.baseMtime) ? parsed.baseMtime : null,
115
+ savedAt: Number.isFinite(Number(parsed.savedAt)) ? Number(parsed.savedAt) : 0,
116
+ }
117
+ } catch {
118
+ return null
119
+ }
120
+ }
121
+
122
+ /**
123
+ * The draft directory, resolved once per API server.
124
+ *
125
+ * A store without a directory (no data dir configured) is simply unavailable:
126
+ * every route answers 500 rather than pretending a draft was kept.
127
+ */
128
+ export class DraftStore {
129
+ #dir
130
+ #now
131
+
132
+ /**
133
+ * @param {object} options
134
+ * @param {string | null} options.dir absolute path of the drafts directory
135
+ * @param {() => number} [options.now] clock, injectable for tests
136
+ */
137
+ constructor({ dir, now = () => Date.now() }) {
138
+ this.#dir = typeof dir === 'string' && dir.length > 0 ? dir : null
139
+ this.#now = now
140
+ }
141
+
142
+ get available() {
143
+ return this.#dir !== null
144
+ }
145
+
146
+ get dir() {
147
+ return this.#dir
148
+ }
149
+
150
+ #file(connectionId, path) {
151
+ return join(this.#dir, draftFileName(connectionId, path))
152
+ }
153
+
154
+ #ensureDir() {
155
+ mkdirSync(this.#dir, { recursive: true })
156
+ }
157
+
158
+ /**
159
+ * Drop what has aged out: drafts past their keep-by date, and temp files an
160
+ * interrupted write left behind. Safe to call on every request.
161
+ *
162
+ * @returns {{ expired: number, orphans: number }}
163
+ */
164
+ sweep() {
165
+ const result = { expired: 0, orphans: 0 }
166
+ if (this.#dir === null || !existsSync(this.#dir)) return result
167
+ const now = this.#now()
168
+ let entries
169
+ try {
170
+ entries = readdirSync(this.#dir, { withFileTypes: true })
171
+ } catch {
172
+ return result
173
+ }
174
+ for (const entry of entries) {
175
+ if (!entry.isFile()) continue
176
+ const file = join(this.#dir, entry.name)
177
+ let stat
178
+ try {
179
+ stat = statSync(file)
180
+ } catch {
181
+ continue
182
+ }
183
+ if (entry.name.endsWith('.json')) {
184
+ if (now - stat.mtimeMs <= DRAFT_MAX_AGE_MS) continue
185
+ const draft = readDraftFile(file)
186
+ // An unreadable file is left alone: it is not this sweep's business.
187
+ if (draft === null) continue
188
+ if (now - draft.savedAt > DRAFT_MAX_AGE_MS) {
189
+ try {
190
+ unlinkSync(file)
191
+ result.expired += 1
192
+ } catch {
193
+ /* something else removed it; nothing to do */
194
+ }
195
+ }
196
+ continue
197
+ }
198
+ if (entry.name.includes('.tmp-') && now - stat.mtimeMs > DRAFT_TEMP_MAX_AGE_MS) {
199
+ try {
200
+ unlinkSync(file)
201
+ result.orphans += 1
202
+ } catch {
203
+ /* already gone */
204
+ }
205
+ }
206
+ }
207
+ return result
208
+ }
209
+
210
+ /**
211
+ * Keep the newest buffer for one path. Writes a temp file and renames it into
212
+ * place, so a reader never sees half a draft.
213
+ */
214
+ save({ connectionId, path, content, baseMtime }) {
215
+ const savedAt = this.#now()
216
+ const file = this.#file(connectionId, path)
217
+ const temp = `${file}.tmp-${process.pid.toString(36)}-${randomBytes(4).toString('hex')}`
218
+ const payload = JSON.stringify({ connectionId, path, content, baseMtime, savedAt })
219
+ this.#ensureDir()
220
+ try {
221
+ writeFileSync(temp, payload, 'utf8')
222
+ renameSync(temp, file)
223
+ } catch (error) {
224
+ try {
225
+ unlinkSync(temp)
226
+ } catch {
227
+ /* the temp file was never created, or is already gone */
228
+ }
229
+ throw error
230
+ }
231
+ return { savedAt }
232
+ }
233
+
234
+ /** The newest draft for one path, or null when there is none. */
235
+ read({ connectionId, path }) {
236
+ if (this.#dir === null) return null
237
+ const draft = readDraftFile(this.#file(connectionId, path))
238
+ if (draft === null) return null
239
+ return { path: draft.path, content: draft.content, baseMtime: draft.baseMtime, savedAt: draft.savedAt }
240
+ }
241
+
242
+ /** Drop one draft. Removing what is not there is a success. */
243
+ remove({ connectionId, path }) {
244
+ if (this.#dir === null) return false
245
+ try {
246
+ unlinkSync(this.#file(connectionId, path))
247
+ return true
248
+ } catch {
249
+ return false
250
+ }
251
+ }
252
+
253
+ /** Metadata of every draft, newest first. The content stays on disk. */
254
+ list() {
255
+ if (this.#dir === null || !existsSync(this.#dir)) return []
256
+ const rows = []
257
+ let entries
258
+ try {
259
+ entries = readdirSync(this.#dir, { withFileTypes: true })
260
+ } catch {
261
+ return []
262
+ }
263
+ for (const entry of entries) {
264
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue
265
+ const draft = readDraftFile(join(this.#dir, entry.name))
266
+ if (draft === null) continue
267
+ rows.push({
268
+ connectionId: draft.connectionId,
269
+ path: draft.path,
270
+ savedAt: draft.savedAt,
271
+ bytes: Buffer.byteLength(draft.content, 'utf8'),
272
+ })
273
+ }
274
+ return rows.sort((a, b) => b.savedAt - a.savedAt)
275
+ }
276
+
277
+ /** Drop every draft, temp files included. */
278
+ clear() {
279
+ if (this.#dir === null || !existsSync(this.#dir)) return 0
280
+ let removed = 0
281
+ let entries
282
+ try {
283
+ entries = readdirSync(this.#dir, { withFileTypes: true })
284
+ } catch {
285
+ return 0
286
+ }
287
+ for (const entry of entries) {
288
+ if (!entry.isFile()) continue
289
+ if (!entry.name.endsWith('.json') && !entry.name.includes('.tmp-')) continue
290
+ try {
291
+ unlinkSync(join(this.#dir, entry.name))
292
+ if (entry.name.endsWith('.json')) removed += 1
293
+ } catch {
294
+ /* already gone */
295
+ }
296
+ }
297
+ return removed
298
+ }
299
+ }