dsh-harness-toolbox 1.6.4 → 1.8.8

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/src/gh.js CHANGED
@@ -4,6 +4,7 @@ import { pipeline } from 'node:stream/promises'
4
4
  import { basename, dirname, join } from 'node:path'
5
5
  import { spawn } from 'node:child_process'
6
6
  import { proxyEnv } from './publish.js'
7
+ import { moveIntoPlace } from './swap.js'
7
8
 
8
9
  /**
9
10
  * GitHub CLI (`gh`) management, merged in from `homerdsh-workbench`. The
@@ -11,8 +12,10 @@ import { proxyEnv } from './publish.js'
11
12
  * plugin can install a pinned managed copy, find one already on PATH, and run
12
13
  * the `gh auth login --web` device flow from the settings page.
13
14
  *
14
- * State lives in the plugin directory so it survives profile rebuilds:
15
- * `<DSH home>/compression-tiers/gh/{bin,download,src}`.
15
+ * The first argument of every file-touching export is the shared download root
16
+ * (`settings.toolsPath`, see `src/tools-path.js`), not the DSH home: the
17
+ * managed copy lives in `<toolsPath>/gh/{bin,download,src}` next to the managed
18
+ * ffmpeg, so both tools move together.
16
19
  */
17
20
 
18
21
  /**
@@ -44,12 +47,13 @@ const GH_ASSETS = {
44
47
  'linux-arm64': { file: `gh_${GH_VERSION}_linux_arm64.tar.gz`, kind: 'tar.gz' },
45
48
  }
46
49
 
47
- export function ghRoot(home) {
48
- return join(home, 'compression-tiers', 'gh')
50
+ /** `<toolsPath>/gh`: the managed component's own directory. */
51
+ export function ghRoot(root) {
52
+ return join(root, 'gh')
49
53
  }
50
54
 
51
- export function ghBinDir(home) {
52
- return join(ghRoot(home), 'bin')
55
+ export function ghBinDir(root) {
56
+ return join(ghRoot(root), 'bin')
53
57
  }
54
58
 
55
59
  export function ghBinaryName(platform = process.platform) {
@@ -63,12 +67,12 @@ export function ghAsset(platform = process.platform, arch = process.arch) {
63
67
  return { ...asset, url: `${GH_RELEASE}/${asset.file}` }
64
68
  }
65
69
 
66
- function downloadDir(home) {
67
- return join(ghRoot(home), 'download')
70
+ function downloadDir(root) {
71
+ return join(ghRoot(root), 'download')
68
72
  }
69
73
 
70
- function partPath(home, asset) {
71
- return join(downloadDir(home), `${asset.file}.part`)
74
+ function partPath(root, asset) {
75
+ return join(downloadDir(root), `${asset.file}.part`)
72
76
  }
73
77
 
74
78
  /** Find an executable on PATH without spawning it. */
@@ -89,33 +93,38 @@ export function systemGh(platform = process.platform, envPath = process.env.PATH
89
93
  }
90
94
 
91
95
  /** The managed binary, then a system one, then null. */
92
- export function resolveGh(home, platform = process.platform, envPath = process.env.PATH) {
93
- const managed = join(ghBinDir(home), ghBinaryName(platform))
96
+ export function resolveGh(root, platform = process.platform, envPath = process.env.PATH) {
97
+ const managed = join(ghBinDir(root), ghBinaryName(platform))
94
98
  if (existsSync(managed)) return managed
95
99
  return systemGh(platform, envPath)
96
100
  }
97
101
 
98
- /** Live progress for the running download, keyed by home. */
102
+ /** Live progress for the running download, keyed by the shared tools root. */
99
103
  const jobs = new Map()
100
104
 
101
- function jobKey(home) {
102
- return home
105
+ function jobKey(root) {
106
+ return root
107
+ }
108
+
109
+ /** Whether a managed install is in flight; migration refuses to move a live job. */
110
+ export function ghDownloadRunning(root) {
111
+ return jobs.get(jobKey(root))?.running === true
103
112
  }
104
113
 
105
114
  /**
106
115
  * Everything the settings panel needs about the managed component: how far a
107
116
  * download got, whether a binary is installed, and what PATH already offers.
108
117
  */
109
- export function ghStatus(home, { platform = process.platform, arch = process.arch, envPath = process.env.PATH } = {}) {
118
+ export function ghStatus(root, { platform = process.platform, arch = process.arch, envPath = process.env.PATH } = {}) {
110
119
  const asset = ghAsset(platform, arch)
111
- const job = jobs.get(jobKey(home))
112
- const bin = join(ghBinDir(home), ghBinaryName(platform))
120
+ const job = jobs.get(jobKey(root))
121
+ const bin = join(ghBinDir(root), ghBinaryName(platform))
113
122
  const hasBinary = existsSync(bin)
114
123
  // A failed job keeps the component "not installed" even if a binary is still
115
124
  // on disk: the panel then offers a retry instead of a broken install.
116
125
  const installed = hasBinary && !job?.error
117
126
  const systemPath = installed ? null : systemGh(platform, envPath)
118
- const partBytes = asset && existsSync(partPath(home, asset)) ? statSync(partPath(home, asset)).size : 0
127
+ const partBytes = asset && existsSync(partPath(root, asset)) ? statSync(partPath(root, asset)).size : 0
119
128
  let state = 'missing'
120
129
  if (job?.running) state = 'downloading'
121
130
  else if (installed) state = 'installed'
@@ -143,7 +152,7 @@ export function ghStatus(home, { platform = process.platform, arch = process.arc
143
152
  total,
144
153
  percent: total ? Math.min(100, Math.round((received / total) * 100)) : null,
145
154
  error: job?.error || null,
146
- installDir: ghRoot(home),
155
+ installDir: ghRoot(root),
147
156
  }
148
157
  }
149
158
 
@@ -157,12 +166,58 @@ async function fetchKeepingRange(url, headers, signal, fetchImpl, hops = 0) {
157
166
  return response
158
167
  }
159
168
 
169
+ /** Defaults for {@link downloadWithResume}'s automatic retries. */
170
+ const DOWNLOAD_RETRIES = 3
171
+ const DOWNLOAD_RETRY_DELAY_MS = 1500
172
+
173
+ /** HTTP statuses that are worth another attempt; other 4xx answers are final. */
174
+ const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504])
175
+
176
+ /** Socket / fetch error codes a retry can plausibly fix. */
177
+ const RETRYABLE_CODE = new Set([
178
+ 'ECONNRESET', 'ECONNREFUSED', 'ECONNABORTED', 'EPIPE', 'ETIMEDOUT', 'ENETUNREACH',
179
+ 'ENETDOWN', 'EHOSTUNREACH', 'ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_SOCKET',
180
+ 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT',
181
+ ])
182
+
160
183
  /**
161
- * Download with HTTP `Range` resume: an interrupted run keeps its `.part`
162
- * file and the next attempt continues from its byte offset. A `416` means the
163
- * partial file belongs to another version, so it is dropped and refetched.
184
+ * Whether the failure is a dropped connection rather than a real answer: a 404
185
+ * or an aborted signal will fail exactly the same way next time, so retrying it
186
+ * only delays the error the page has to show.
187
+ */
188
+ function isRetryableDownloadError(error, signal) {
189
+ if (!error || signal?.aborted) return false
190
+ if (error.name === 'AbortError') return false
191
+ if (typeof error.status === 'number') return RETRYABLE_STATUS.has(error.status)
192
+ if (RETRYABLE_CODE.has(String(error.code || ''))) return true
193
+ return /fetch failed|socket hang up|other side closed|premature|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN/i.test(String(error.message || ''))
194
+ }
195
+
196
+ /** `setTimeout` that rejects as soon as the download is aborted. */
197
+ function waitForRetry(delayMs, signal) {
198
+ return new Promise((resolve, reject) => {
199
+ const abortError = () => (signal.reason instanceof Error ? signal.reason : new Error('download aborted'))
200
+ if (signal?.aborted) {
201
+ reject(abortError())
202
+ return
203
+ }
204
+ const timer = setTimeout(() => {
205
+ signal?.removeEventListener?.('abort', onAbort)
206
+ resolve()
207
+ }, delayMs)
208
+ function onAbort() {
209
+ clearTimeout(timer)
210
+ reject(abortError())
211
+ }
212
+ signal?.addEventListener?.('abort', onAbort, { once: true })
213
+ })
214
+ }
215
+
216
+ /**
217
+ * One download attempt. The `.part` file is the resume point, so a previous
218
+ * attempt's bytes are counted from disk every time this runs.
164
219
  */
165
- export async function downloadWithResume({ url, partPath: target, fetchImpl = fetch, onProgress, signal }) {
220
+ async function downloadAttempt({ url, partPath: target, fetchImpl, onProgress, signal }) {
166
221
  mkdirSync(dirname(target), { recursive: true })
167
222
  let existing = existsSync(target) ? statSync(target).size : 0
168
223
  const request = (resume) => fetchKeepingRange(
@@ -178,7 +233,9 @@ export async function downloadWithResume({ url, partPath: target, fetchImpl = fe
178
233
  response = await request(false)
179
234
  }
180
235
  if (response.status !== 200 && response.status !== 206) {
181
- throw new Error(`download failed HTTP ${response.status}`)
236
+ const error = new Error(`download failed HTTP ${response.status}`)
237
+ error.status = response.status
238
+ throw error
182
239
  }
183
240
  const restart = response.status === 200
184
241
  const contentRange = response.headers.get('content-range') || ''
@@ -201,6 +258,46 @@ export async function downloadWithResume({ url, partPath: target, fetchImpl = fe
201
258
  return { received, total, resumedFrom: restart ? 0 : existing }
202
259
  }
203
260
 
261
+ /**
262
+ * Download with HTTP `Range` resume: an interrupted run keeps its `.part`
263
+ * file and the next attempt continues from its byte offset. A `416` means the
264
+ * partial file belongs to another version, so it is dropped and refetched.
265
+ *
266
+ * A dropped connection is retried automatically (`retries` extra attempts with
267
+ * an exponential backoff) and every retry resumes from the `.part` file, so a
268
+ * flaky link costs seconds instead of the whole archive. Answers that will not
269
+ * change (404 and friends) and an aborted signal fail at once — the page then
270
+ * offers 「继续下载」 on the kept `.part` file.
271
+ */
272
+ export async function downloadWithResume({
273
+ url,
274
+ partPath: target,
275
+ fetchImpl = fetch,
276
+ onProgress,
277
+ onRetry,
278
+ signal,
279
+ retries = DOWNLOAD_RETRIES,
280
+ retryDelayMs = DOWNLOAD_RETRY_DELAY_MS,
281
+ }) {
282
+ let attempts = 0
283
+ for (;;) {
284
+ attempts += 1
285
+ try {
286
+ return await downloadAttempt({ url, partPath: target, fetchImpl, onProgress, signal })
287
+ } catch (error) {
288
+ if (attempts > retries || !isRetryableDownloadError(error, signal)) {
289
+ if (attempts > 1 && error instanceof Error) {
290
+ error.message = `${error.message} (gave up after ${attempts} attempts)`
291
+ }
292
+ throw error
293
+ }
294
+ const delayMs = retryDelayMs * 2 ** (attempts - 1)
295
+ onRetry?.({ attempt: attempts, retries, delayMs, error })
296
+ await waitForRetry(delayMs, signal)
297
+ }
298
+ }
299
+ }
300
+
204
301
  /** Run a command with a deadline, capturing both streams; shared with the ffmpeg manager. */
205
302
  export function runCommand(command, args, { timeoutMs = COMMAND_TIMEOUT_MS, env = process.env } = {}) {
206
303
  return new Promise((resolve) => {
@@ -276,10 +373,10 @@ export function findBinary(dir, name) {
276
373
  return null
277
374
  }
278
375
 
279
- function pruneDownload(home) {
280
- const staging = join(ghRoot(home), 'src')
376
+ function pruneDownload(root) {
377
+ const staging = join(ghRoot(root), 'src')
281
378
  if (existsSync(staging)) rmSync(staging, { recursive: true, force: true })
282
- if (existsSync(downloadDir(home))) rmSync(downloadDir(home), { recursive: true, force: true })
379
+ if (existsSync(downloadDir(root))) rmSync(downloadDir(root), { recursive: true, force: true })
283
380
  }
284
381
 
285
382
  function stagedPath(destination) {
@@ -323,9 +420,9 @@ async function installBinary(temp, final, platform) {
323
420
  }
324
421
  if (existsSync(final)) {
325
422
  backup = `${final}.old-${process.pid}-${Date.now()}`
326
- renameSync(final, backup)
423
+ await moveIntoPlace(final, backup)
327
424
  }
328
- renameSync(temp, final)
425
+ await moveIntoPlace(temp, final)
329
426
  installed = true
330
427
  const check = await runCommand(final, ['--version'], { timeoutMs: VERIFY_TIMEOUT_MS })
331
428
  if (check.code !== 0) {
@@ -346,7 +443,7 @@ async function installBinary(temp, final, platform) {
346
443
  // Keep restoring the older copy even if the new file is locked.
347
444
  }
348
445
  try {
349
- if (backup && existsSync(backup)) renameSync(backup, final)
446
+ if (backup && existsSync(backup)) await moveIntoPlace(backup, final)
350
447
  } catch {
351
448
  // Best effort; the caller still reports the install error.
352
449
  }
@@ -363,14 +460,14 @@ async function installBinary(temp, final, platform) {
363
460
  * Start the managed download in the background and return the current status
364
461
  * immediately: the panel polls {@link ghStatus} for progress and the outcome.
365
462
  */
366
- export function startGhDownload(home, { platform = process.platform, arch = process.arch } = {}) {
463
+ export function startGhDownload(root, { platform = process.platform, arch = process.arch } = {}) {
367
464
  const asset = ghAsset(platform, arch)
368
465
  if (!asset) throw new Error(`GitHub CLI has no build for ${platform}/${arch}`)
369
- const current = jobs.get(jobKey(home))
370
- if (current?.running) return ghStatus(home, { platform, arch })
466
+ const current = jobs.get(jobKey(root))
467
+ if (current?.running) return ghStatus(root, { platform, arch })
371
468
  const job = { running: true, received: 0, total: null, error: null }
372
- jobs.set(jobKey(home), job)
373
- const target = partPath(home, asset)
469
+ jobs.set(jobKey(root), job)
470
+ const target = partPath(root, asset)
374
471
  // A stalled connection must not leave the job "downloading" forever.
375
472
  const controller = new AbortController()
376
473
  let timedOut = false
@@ -379,34 +476,39 @@ export function startGhDownload(home, { platform = process.platform, arch = proc
379
476
  controller.abort(new Error('download timed out after 10 minutes'))
380
477
  }, DOWNLOAD_TIMEOUT_MS)
381
478
  if (typeof timer.unref === 'function') timer.unref()
382
- downloadWithResume({
383
- url: asset.url,
384
- partPath: target,
385
- signal: controller.signal,
386
- onProgress: (progress) => {
387
- job.received = progress.received
388
- job.total = progress.total
389
- },
390
- }).then(async () => {
479
+ // A renamed archive only exists once a download finished, so retrying after a
480
+ // failed install (locked binary, probe failure) reuses it instead of pulling
481
+ // the whole release again.
482
+ const archivePath = join(downloadDir(root), asset.file)
483
+ const ready = existsSync(archivePath)
484
+ ? Promise.resolve()
485
+ : downloadWithResume({
486
+ url: asset.url,
487
+ partPath: target,
488
+ signal: controller.signal,
489
+ onProgress: (progress) => {
490
+ job.received = progress.received
491
+ job.total = progress.total
492
+ },
493
+ }).then(() => moveIntoPlace(target, archivePath))
494
+ ready.then(async () => {
391
495
  clearTimeout(timer)
392
- const archivePath = join(downloadDir(home), asset.file)
393
- renameSync(target, archivePath)
394
- const staging = join(ghRoot(home), 'src')
496
+ const staging = join(ghRoot(root), 'src')
395
497
  await extractArchive(archivePath, staging, asset.kind, platform)
396
498
  const binaryName = ghBinaryName(platform)
397
499
  const binary = findBinary(staging, binaryName)
398
500
  if (!binary) throw new Error(`archive did not contain ${binaryName}`)
399
- const binDir = ghBinDir(home)
501
+ const binDir = ghBinDir(root)
400
502
  mkdirSync(binDir, { recursive: true })
401
503
  const final = join(binDir, binaryName)
402
504
  const temp = stageBinary(binary, final, platform)
403
505
  await installBinary(temp, final, platform)
404
506
  try {
405
- pruneDownload(home)
507
+ pruneDownload(root)
406
508
  } catch {
407
509
  // Cleanup is best effort: a leftover archive must not fail the install.
408
510
  }
409
- prependGhPath(home, platform)
511
+ prependGhPath(root, platform)
410
512
  }).catch((error) => {
411
513
  job.error = timedOut
412
514
  ? 'download timed out after 10 minutes; the partial file was kept for resume'
@@ -415,15 +517,15 @@ export function startGhDownload(home, { platform = process.platform, arch = proc
415
517
  clearTimeout(timer)
416
518
  job.running = false
417
519
  })
418
- return ghStatus(home, { platform, arch })
520
+ return ghStatus(root, { platform, arch })
419
521
  }
420
522
 
421
523
  /**
422
524
  * Put the managed `bin` directory first on PATH so the official change-request
423
525
  * bundle finds the managed `gh`. Returns whether any managed binary exists.
424
526
  */
425
- export function prependGhPath(home, platform = process.platform) {
426
- const dir = ghBinDir(home)
527
+ export function prependGhPath(root, platform = process.platform) {
528
+ const dir = ghBinDir(root)
427
529
  if (!existsSync(join(dir, ghBinaryName(platform)))) return false
428
530
  const current = process.env.PATH || ''
429
531
  const separator = platform === 'win32' ? ';' : ':'
@@ -473,8 +575,8 @@ export function parseGhAuthJson(output) {
473
575
  * Private repositories need `repo`; a token without it fails at push time with a
474
576
  * bare 403, so the panel warns as soon as the state is read.
475
577
  */
476
- export async function ghAuthStatus(home, { platform = process.platform, arch = process.arch, envPath = process.env.PATH } = {}) {
477
- const gh = resolveGh(home, platform, envPath)
578
+ export async function ghAuthStatus(root, { platform = process.platform, arch = process.arch, envPath = process.env.PATH } = {}) {
579
+ const gh = resolveGh(root, platform, envPath)
478
580
  if (!gh) return { available: false, authenticated: false, account: null, scopes: [], missingRepoScope: false, path: null, version: null, detail: '', source: 'none' }
479
581
  const asJson = await runCommand(gh, ['auth', 'status', '--json', 'hosts'], { timeoutMs: VERIFY_TIMEOUT_MS })
480
582
  const version = await runCommand(gh, ['--version'], { timeoutMs: VERIFY_TIMEOUT_MS })
@@ -537,8 +639,8 @@ export function parseRepoList(output) {
537
639
  * `gh` inherits the proxy from the environment; a missing login is reported as
538
640
  * such instead of an empty list.
539
641
  */
540
- export async function listRepos(home, { limit = 100, proxy = null, platform = process.platform, envPath = process.env.PATH, env = process.env } = {}) {
541
- const gh = resolveGh(home, platform, envPath)
642
+ export async function listRepos(root, { limit = 100, proxy = null, platform = process.platform, envPath = process.env.PATH, env = process.env } = {}) {
643
+ const gh = resolveGh(root, platform, envPath)
542
644
  if (!gh) return { ok: false, error: 'gh-not-installed', repos: [], detail: '' }
543
645
  const result = await runCommand(gh, [
544
646
  'repo', 'list',
@@ -604,12 +706,12 @@ export function cancelGithubLogin() {
604
706
  * background: it prints the code, receives Enter so it opens the browser, then
605
707
  * polls GitHub. Callers poll {@link githubLoginStatus} for the outcome.
606
708
  */
607
- export function beginGithubLogin(home, { platform = process.platform, envPath = process.env.PATH } = {}) {
709
+ export function beginGithubLogin(root, { platform = process.platform, envPath = process.env.PATH } = {}) {
608
710
  const live = loginSession
609
711
  if (live && (live.state === 'starting' || live.state === 'waiting')) {
610
712
  return { started: false, reused: true, command: live.command, ...loginSnapshot() }
611
713
  }
612
- const gh = resolveGh(home, platform, envPath)
714
+ const gh = resolveGh(root, platform, envPath)
613
715
  if (!gh) throw new Error('GitHub CLI is not installed yet; download it first')
614
716
  const args = ['auth', 'login', '--web', '--hostname', 'github.com', '--git-protocol', 'https']
615
717
  const command = `"${gh}" ${args.join(' ')}`
@@ -144,8 +144,17 @@ export function attachCompactQueue(ctx, deps) {
144
144
  return
145
145
  }
146
146
  if (event.type === 'user/message') {
147
- if (job.state === 'running' && event.data && event.data.source && event.data.source.kind === 'user') {
147
+ const source = job && event.data && event.data.source ? event.data.source : null
148
+ if (source && source.kind === 'user') {
149
+ // The human took the turn: never compact under them, and never inject
150
+ // a "continue" message that would answer them out of order. A queued
151
+ // job is dropped here; a running one notices `userSpoke` and skips the
152
+ // resume after the compaction it already started.
148
153
  job.userSpoke = true
154
+ if (job.state === 'queued') {
155
+ jobs.delete(id)
156
+ trace('compact:user-took-over', { sessionId: id })
157
+ }
149
158
  }
150
159
  return
151
160
  }
package/src/push-flow.js CHANGED
@@ -13,9 +13,19 @@ import { detectProxy, pushRepo, repoSnapshot, scanSecrets } from './publish.js'
13
13
  * refused when an agent tries to publish it.
14
14
  */
15
15
 
16
+ /**
17
+ * The push target an online-repository binding implies: the `sessionRepos` map
18
+ * lives on the plugin settings themselves (not under `github`), so this reads
19
+ * the top-level object and tolerates a missing map.
20
+ */
21
+ export function sessionTarget(settings, sessionId) {
22
+ const repos = settings && settings.sessionRepos ? settings.sessionRepos : null
23
+ const name = repos && sessionId ? repos[sessionId] : ''
24
+ return name ? `https://github.com/${name}.git` : ''
25
+ }
26
+
16
27
  /** A path that could be a checkout: absolute and an existing directory. */
17
- export function isRepoDir(path) {
18
- if (typeof path !== 'string' || !path.trim()) return false
28
+ export function isRepoDir(path) { if (typeof path !== 'string' || !path.trim()) return false
19
29
  const value = path.trim()
20
30
  if (!isAbsolute(value)) return false
21
31
  try {
package/src/store.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileS
2
2
  import { join } from 'node:path'
3
3
  import { DEFAULT_LEVEL, compactLevel } from './levels.js'
4
4
  import { normalizeRoutes } from './routes.js'
5
+ import { normalizeToolsPath } from './tools-path.js'
5
6
 
6
7
  /**
7
8
  * Plugin-owned state. The selected tier and the optional per-route overrides
@@ -33,6 +34,9 @@ export function defaultSettings() {
33
34
  // Session id → `owner/name` of the online repository that session publishes
34
35
  // to. Bound from the session header; the file is the only place it lives.
35
36
  sessionRepos: {},
37
+ // Shared download root for the managed gh and ffmpeg installs. Empty means
38
+ // `<DSH home>/compression-tiers`, which is where earlier versions put them.
39
+ toolsPath: '',
36
40
  }
37
41
  }
38
42
 
@@ -76,6 +80,9 @@ export function normalizeSettings(value) {
76
80
  proxy: text(github.proxy, base.github.proxy),
77
81
  }
78
82
  next.sessionRepos = normalizeSessionRepos(next.sessionRepos)
83
+ // A relative or unparsable toolsPath would resolve against the process CWD;
84
+ // drop it so the shared root falls back to the default directory.
85
+ next.toolsPath = normalizeToolsPath(next.toolsPath)
79
86
  return next
80
87
  }
81
88
 
package/src/swap.js ADDED
@@ -0,0 +1,77 @@
1
+ import { cpSync, renameSync, rmSync } from 'node:fs'
2
+
3
+ /**
4
+ * Atomic-ish replacement of an installed tree.
5
+ *
6
+ * Windows refuses `rename()` on a directory while any file inside it is still
7
+ * open — an antivirus halfway through scanning a freshly written 110 MB
8
+ * `ffmpeg.exe`, or the child process that just answered `-version`, is enough —
9
+ * and it reports that as `EPERM`. The lock is short-lived, so the first answer
10
+ * is to retry with a backoff. If the lock outlives the retries, renaming is
11
+ * hopeless but *reading* is not, so the tree is copied into the free path
12
+ * instead: the install still finishes, it just costs a copy.
13
+ *
14
+ * Renaming onto an existing non-empty directory also fails (`EPERM` /
15
+ * `ENOTEMPTY` on Windows, `ENOTEMPTY` on POSIX), so callers keep the contract
16
+ * that `to` must be free; the copy fallback clears it first anyway.
17
+ */
18
+
19
+ /** Locks that clear on their own: retry before giving up on the rename. */
20
+ const LOCKED = new Set(['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY', 'EEXIST'])
21
+
22
+ /** Errors that will never survive a retry but are fine for a copy. */
23
+ const CROSS_DEVICE = new Set(['EXDEV'])
24
+
25
+ /** Whether a filesystem error is a transient lock rather than a real refusal. */
26
+ export function isLockedError(error) {
27
+ return Boolean(error) && LOCKED.has(String(error.code || ''))
28
+ }
29
+
30
+ /** Whether the destination lives on another volume, so only a copy can work. */
31
+ export function isCrossDeviceError(error) {
32
+ return Boolean(error) && CROSS_DEVICE.has(String(error.code || ''))
33
+ }
34
+
35
+ function sleep(ms) {
36
+ return new Promise((resolve) => setTimeout(resolve, ms))
37
+ }
38
+
39
+ /**
40
+ * Rename with a bounded exponential backoff for lock errors. Errors that a
41
+ * retry cannot fix (`ENOENT`, `ENOSPC`, `EXDEV`, …) are rethrown at once.
42
+ *
43
+ * @returns the attempt number that succeeded.
44
+ */
45
+ export async function renameWithRetry(from, to, { attempts = 7, delayMs = 200, rename = renameSync } = {}) {
46
+ let lastError = null
47
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
48
+ try {
49
+ rename(from, to)
50
+ return attempt
51
+ } catch (error) {
52
+ lastError = error
53
+ if (!isLockedError(error) || attempt === attempts) throw error
54
+ await sleep(delayMs * 2 ** (attempt - 1))
55
+ }
56
+ }
57
+ throw lastError
58
+ }
59
+
60
+ /**
61
+ * Put `from` at the free path `to`, renaming it there or — when the tree stays
62
+ * locked / lives on another volume — copying it there. The source is left in
63
+ * place on both paths; callers prune their own staging directories.
64
+ *
65
+ * @returns `{ how: 'rename' | 'copy', attempts }`.
66
+ */
67
+ export async function moveIntoPlace(from, to, { attempts, delayMs, rename = renameSync, copy = cpSync, remove = rmSync } = {}) {
68
+ try {
69
+ const how = await renameWithRetry(from, to, { attempts, delayMs, rename })
70
+ return { how: 'rename', attempts: how }
71
+ } catch (error) {
72
+ if (!isLockedError(error) && !isCrossDeviceError(error)) throw error
73
+ remove(to, { recursive: true, force: true })
74
+ copy(from, to, { recursive: true })
75
+ return { how: 'copy', attempts }
76
+ }
77
+ }