Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
Use .plexo partial files until downloads complete
Anmol Kapild7dc40523990
diff --git a/README.md b/README.mdindex e209529..36463c2 100644--- a/README.md+++ b/README.md@@ -157,9 +157,7 @@ Work distribution is dynamically proportional to each interface's real-time throEach worker writes its assigned byte range at its final offset in one staging file beside the chosen destination. Workers use separate file handles and explicit byte positions, so non-overlapping ranges can be written in parallel.-Once every range is complete, Plexo flushes the staging file and renames it to the final filename in the same directory. There is no full-file assembly copy, so the destination needs approximately one file's worth of space.--The visible final filename is reserved as an empty placeholder while the download runs. It is only replaced after the staged file is complete.+While downloading, the folder contains `<filename>.plexo` and no empty file under the final name. Once every range is complete, Plexo flushes the partial file, publishes the final name without overwriting an existing file, and removes the `.plexo` name. There is no full-file assembly copy, so the destination needs approximately one file's worth of space.---diff --git a/e2e/blockProgress.spec.ts b/e2e/blockProgress.spec.tsindex e21ad38..8df518a 100644--- a/e2e/blockProgress.spec.ts+++ b/e2e/blockProgress.spec.ts@@ -5,6 +5,7 @@ import { expect, test } from '@playwright/test'import fc from 'fast-check'import { advanceBlock, retractBlock } from '../src/main/download/blockProgress'import { DownloadFile } from '../src/main/download/downloadFile'+import { reserveDestinationPath } from '../src/main/download/paths'import type { BlockState } from '../src/shared/types'// K. What a block's byte counts mean when two attempts race for it, and how range writes land@@ -86,16 +87,41 @@ test.describe('destination-side staging file', () => {const bytes = (from: number, to: number): Buffer =>Buffer.from(Array.from({ length: to - from }, (_, i) => (from + i) % 251))+ test('only the .plexo file is visible until completion, and it reserves the name', async () => {+ const first = await reserveDestinationPath(dir, 'result.bin')+ const second = await reserveDestinationPath(dir, 'result.bin')+ expect(first).toBe(join(dir, 'result.bin'))+ expect(second).toBe(join(dir, 'result (1).bin'))+ expect(await readFile(`${first}.plexo`)).toHaveLength(0)+ expect(await readFile(`${second}.plexo`)).toHaveLength(0)+ await expect(readFile(first)).rejects.toMatchObject({ code: 'ENOENT' })+ await expect(readFile(second)).rejects.toMatchObject({ code: 'ENOENT' })+ })+test('out-of-order ranges and a hedge overwrite produce one exact file', async () => {const destination = join(dir, 'result.bin')- await writeFile(destination, '')- const file = new DownloadFile(destination, 'test-id')- await file.create()+ const file = new DownloadFile(`${destination}.plexo`)+ await writeFile(file.path, '')await file.writeBuffers(500, [bytes(500, LENGTH)])await file.writeBuffers(0, [bytes(0, 600)])await file.writeBuffers(400, [bytes(400, LENGTH)])expect(await file.read(390, 20)).toEqual(bytes(390, 410))- await file.publish(LENGTH)+ expect(await readFile(file.path)).toEqual(bytes(0, LENGTH))+ expect(await file.publish(destination, LENGTH, async () => {})).toBe(destination)+ await file.discard()expect(await readFile(destination)).toEqual(bytes(0, LENGTH))})++ test('publishing does not replace a final file created during the download', async () => {+ const destination = join(dir, 'result.bin')+ const file = new DownloadFile(`${destination}.plexo`)+ await writeFile(file.path, bytes(0, LENGTH))+ await writeFile(destination, 'someone else owns this name')++ const published = await file.publish(destination, LENGTH, async () => {})+ expect(published).toBe(join(dir, 'result (1).bin'))+ expect(await readFile(destination, 'utf-8')).toBe('someone else owns this name')+ expect(await readFile(published)).toEqual(bytes(0, LENGTH))+ await file.discard()+ })})diff --git a/e2e/download.spec.ts b/e2e/download.spec.tsindex 6138840..7bdaf87 100644--- a/e2e/download.spec.ts+++ b/e2e/download.spec.ts@@ -140,6 +140,32 @@ test.describe('file names @smoke', () => {expect(sha256(await readFile(one.destinationPath))).toBe(first.sha256)})+ test('a file appearing under the final name mid-download is not overwritten', async ({+ plexo,+ serve+ }) => {+ const { existsSync } = await import('node:fs')+ const { readFile, writeFile } = await import('node:fs/promises')+ const origin = await serve({ size: 16 * BLOCK })+ const reached = origin.hold(8 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 1 })+ await reached+ const pending = (await plexo.current())!+ expect(existsSync(`${pending.destinationPath}.plexo`)).toBe(true)+ expect(existsSync(pending.destinationPath)).toBe(false)++ await writeFile(pending.destinationPath, 'another application created this file')+ // The fixture's stray-file check should ignore the deliberate external file.+ plexo.tracked.get(id)!.destBefore.push(pending.fileName)+ origin.release()++ const done = await plexo.waitForStatus('completed')+ expect(done.fileName).toBe('test (1).bin')+ expect(await readFile(pending.destinationPath, 'utf-8')).toBe(+ 'another application created this file'+ )+ })+test('a malformed %-escape in the URL path still downloads', async ({ plexo, serve }) => {const origin = await serve({ size: 2 * BLOCK })await plexo.start(origin.url('/files/100%25%E0%A4%A.bin'), origin.sha256)diff --git a/e2e/fixtures.ts b/e2e/fixtures.tsindex fa050c4..2547dff 100644--- a/e2e/fixtures.ts+++ b/e2e/fixtures.ts@@ -366,7 +366,7 @@ export async function checkFinalState(app: PlexoApp): Promise<void> {expectedAdded)- const stagingPath = join(tracked.destinationDir, `.plexo-${state.id}.part`)+ const stagingPath = `${state.destinationPath}.plexo`await expect.poll(() => existsSync(stagingPath), { message: 'staging file cleaned up', timeout: 5000 }).toBe(false)diff --git a/e2e/recovery.spec.ts b/e2e/recovery.spec.tsindex a570a53..a8636f3 100644--- a/e2e/recovery.spec.ts+++ b/e2e/recovery.spec.ts@@ -136,12 +136,12 @@ test.describe('persisted state on disk @smoke', () => {test('staging file deleted while the app was closed → reports lost progress', async ({plexo,- serve,- dirs+ serve}) => {- const { id } = await pausedDownload(plexo, serve)+ await pausedDownload(plexo, serve)+ const partial = `${(await plexo.current())!.destinationPath}.plexo`await plexo.quit()- await rm(join(dirs.dest, `.plexo-${id}.part`))+ await rm(partial)await plexo.launch()expect((await plexo.current())?.status).toBe('error')expect((await plexo.current())?.error).toMatch(/partial download file is missing/)@@ -149,8 +149,7 @@ test.describe('persisted state on disk @smoke', () => {test('a staging file cut short while the app was closed is fetched again', async ({plexo,- serve,- dirs+ serve}) => {// What a power cut can do: the manifest says a block is done, but its data never all// reached the disk.@@ -158,7 +157,7 @@ test.describe('persisted state on disk @smoke', () => {const state = (await plexo.current())!const done = state.blocks!.find((block) => block.status === 'completed')!await plexo.quit()- const staging = join(dirs.dest, `.plexo-${id}.part`)+ const staging = `${state.destinationPath}.plexo`await truncate(staging, done.rangeStart + 1000)await plexo.launch()diff --git a/e2e/sim.spec.ts b/e2e/sim.spec.tsindex 9305fa5..c9548e8 100644--- a/e2e/sim.spec.ts+++ b/e2e/sim.spec.ts@@ -94,8 +94,9 @@ test.describe('simulated downloads @smoke', () => {source.sha)await plexo.waitUntil((state) => state.bytesDownloaded > 0)- const staging = join(dirs.dest, `.plexo-${id}.part`)+ const staging = join(dirs.dest, 'source-5.bin.plexo')expect(existsSync(staging)).toBe(true)+ expect(existsSync(join(dirs.dest, 'source-5.bin'))).toBe(false)expect(existsSync(join(dirs.userData, 'downloads', id, 'parts'))).toBe(false)await plexo.waitForStatus('completed', 30_000)expect(existsSync(staging)).toBe(false)@@ -122,7 +123,7 @@ test.describe('simulated downloads @smoke', () => {source.sha)await plexo.waitUntil((state) => state.bytesDownloaded > 0)- const staging = join(dirs.dest, `.plexo-${id}.part`)+ const staging = join(dirs.dest, 'source-2.bin.plexo')await plexo.api.pauseDownload(id)expect((await plexo.current())?.status).toBe('paused')expect(existsSync(staging)).toBe(true)diff --git a/src/main/download/downloadFile.ts b/src/main/download/downloadFile.tsindex f607bf3..16d5fef 100644--- a/src/main/download/downloadFile.ts+++ b/src/main/download/downloadFile.ts@@ -1,24 +1,11 @@import { createWriteStream, type WriteStream } from 'node:fs'-import { open, rename, rm, stat } from 'node:fs/promises'-import { dirname, join } from 'node:path'+import { link, lstat, open, rm, stat } from 'node:fs/promises'+import { basename, dirname, extname, join } from 'node:path'/** The only large file owned by a download. It lives beside the final file so publishing it* requires no copy and never needs a second file's worth of disk space. */export class DownloadFile {- readonly path: string-- constructor(- readonly destinationPath: string,- id: string- ) {- // Keep the component short even when the final filename is near the filesystem limit.- this.path = join(dirname(destinationPath), `.plexo-${id}.part`)- }-- async create(): Promise<void> {- const handle = await open(this.path, 'wx+')- await handle.close()- }+ constructor(readonly path: string) {}/** Every writer has its own descriptor and explicit offset. Never use append mode here. */writer(position: number): WriteStream {@@ -67,12 +54,55 @@ export class DownloadFile {return (await stat(this.path)).size}- async publish(expectedBytes: number): Promise<void> {+ async publish(+ destinationPath: string,+ expectedBytes: number,+ beforeAttempt: (candidate: string) => Promise<void>+ ): Promise<string> {if (expectedBytes > 0 && (await this.size()) !== expectedBytes) {throw new Error('Download file size does not match the expected size')}await this.sync()- await rename(this.path, this.destinationPath)+ const extension = extname(destinationPath)+ const stem = basename(destinationPath, extension)+ const directory = dirname(destinationPath)+ for (let index = 0; index < 10_000; index += 1) {+ const suffix = index === 0 ? '' : ` (${index})`+ if (Buffer.byteLength(`${suffix}${extension}`) >= 255) {+ throw new Error('The file extension is too long')+ }+ const candidateCharacters = Array.from(stem)+ while (Buffer.byteLength(`${candidateCharacters.join('')}${suffix}${extension}`) > 255) {+ candidateCharacters.pop()+ }+ const candidateStem = candidateCharacters.join('')+ const candidate = join(directory, `${candidateStem}${suffix}${extension}`)+ if (candidate !== destinationPath) {+ const partialExists = await lstat(`${candidate}.plexo`).then(+ () => true,+ (error: NodeJS.ErrnoException) => {+ if (error.code === 'ENOENT') return false+ throw error+ }+ )+ if (partialExists) continue+ }+ await beforeAttempt(candidate)+ try {+ // Hard-linking is an atomic, no-overwrite publication on the same volume.+ // Removing the partial name afterwards frees no extra file-sized space.+ await link(this.path, candidate)+ return candidate+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code+ if (code === 'EEXIST') continue+ if (code === 'ENOTSUP' || code === 'EOPNOTSUPP' || code === 'ENOSYS') {+ throw new Error('This destination does not support safe one-copy finalization')+ }+ throw error+ }+ }+ throw new Error('Could not find an unused file name for this download')}async discard(): Promise<void> {diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 2997a09..24f9ca3 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -107,6 +107,8 @@ interface SpeedSample {interface DownloadRuntime {state: DownloadState+ publicationPath?: string+ publicationIdentity?: { dev: number; ino: number }requestPayload: StartDownloadRequestactiveInterfaces: NetworkInterfaceInfo[]chunkRuntimes: Map<number, ChunkRuntime>@@ -136,9 +138,12 @@ interface DownloadRuntime {}interface PersistedDownload {- version: 3+ version: 4savedAt: numberstate: DownloadState+ partialPath: string+ publicationPath?: string+ publicationIdentity?: { dev: number; ino: number }requestPayload: StartDownloadRequestactiveInterfaces: NetworkInterfaceInfo[]}@@ -326,7 +331,7 @@ export class DownloadManager {const persisted = JSON.parse(await readFile(this.manifestPath(id), 'utf-8')) as PersistedDownload- if (persisted.version !== 3 || persisted.state.id !== id || !persisted.state.blocks)+ if (persisted.version !== 4 || persisted.state.id !== id || !persisted.state.blocks)returnconst state = persisted.state@@ -353,28 +358,38 @@ export class DownloadManager {if (block.status === 'downloading') block.status = 'pending'}- const file = new DownloadFile(state.destinationPath, id)+ const file = new DownloadFile(persisted.partialPath)if (state.status === 'paused') {const size = await file.size().catch(() => -1)- if (size < 0) {- const publishedSize = await stat(state.destinationPath).then(- (entry) => entry.size,- () => -1- )- const expected = state.totalBytes || state.bytesDownloaded- if (- blocks.every((block) => block.status === 'completed') &&- publishedSize === expected- ) {- state.status = 'completed'- state.error = undefined- state.completedAt ??= persisted.savedAt- } else {- state.status = 'error'- state.error =- 'The partial download file is missing. Remove this download and start again.'- if (publishedSize === 0) await rm(state.destinationPath, { force: true })- }+ const publishedPath = persisted.publicationPath ?? state.destinationPath+ const published = await stat(publishedPath).catch(() => null)+ const publishedSize = published?.size ?? -1+ const expected = state.totalBytes || state.bytesDownloaded+ const sameFile =+ !!published &&+ (size >= 0+ ? await stat(file.path)+ .then(+ (partial) => partial.dev === published.dev && partial.ino === published.ino+ )+ .catch(() => false)+ : persisted.publicationIdentity?.dev === published.dev &&+ persisted.publicationIdentity?.ino === published.ino)+ if (+ blocks.every((block) => block.status === 'completed') &&+ publishedSize === expected &&+ sameFile+ ) {+ state.status = 'completed'+ state.destinationPath = publishedPath+ state.fileName = basename(publishedPath)+ state.error = undefined+ state.completedAt ??= persisted.savedAt+ if (size >= 0) await file.discard()+ } else if (size < 0) {+ state.status = 'error'+ state.error =+ 'The partial download file is missing. Remove this download and start again.'} else {for (const block of blocks) {const length = block.rangeEnd === null ? 0 : block.rangeEnd - block.rangeStart + 1@@ -393,6 +408,8 @@ export class DownloadManager {restored.push({state,+ publicationPath: persisted.publicationPath,+ publicationIdentity: persisted.publicationIdentity,requestPayload: persisted.requestPayload,activeInterfaces: persisted.activeInterfaces,chunkRuntimes: new Map(),@@ -424,9 +441,22 @@ export class DownloadManager {restored.sort((a, b) => b.state.startedAt - a.state.startedAt)const [current, ...orphans] = restored- await Promise.all(orphans.map((runtime) => this.removePersistedDownload(runtime)))+ await Promise.all(+ orphans.map((runtime) =>+ this.removePersistedDownload(runtime, runtime.file.path !== current?.file.path)+ )+ )if (current) {+ if (current.state.status === 'completed' && current.publicationIdentity) {+ const published = await stat(current.state.destinationPath).catch(() => null)+ if (+ published?.dev === current.publicationIdentity.dev &&+ published.ino === current.publicationIdentity.ino+ ) {+ await current.file.discard().catch(() => {})+ }+ }this.runtimes.set(current.state.id, current)await this.persistNow(current)}@@ -545,13 +575,7 @@ export class DownloadManager {)const id = randomUUID()- const file = new DownloadFile(destinationPath, id)- try {- await file.create()- } catch (error) {- await rm(destinationPath, { force: true })- throw error- }+ const file = new DownloadFile(`${destinationPath}.plexo`)// The UI caps how many cells it renders separately (see BlockGrid), by bucketing these// blocks rather than by shrinking their count here.@@ -807,7 +831,6 @@ export class DownloadManager {await runtime.runPromiseawait runtime.file.discard()unregisterSimSession(runtime.requestPayload.url)- await this.discardUnfinishedDestination(runtime)await this.removePersistedDownload(runtime)}@@ -890,7 +913,6 @@ export class DownloadManager {this.pushUpdate(runtime)await runtime.file.discard()unregisterSimSession(runtime.requestPayload.url)- await this.discardUnfinishedDestination(runtime)}return}@@ -901,10 +923,23 @@ export class DownloadManager {throw new Error('Download is incomplete — refusing to publish the file')}await this.persistNow(runtime)- await runtime.file.publish(runtime.state.totalBytes)+ const publishedPath = await runtime.file.publish(+ runtime.state.destinationPath,+ runtime.state.totalBytes,+ async (candidate) => {+ runtime.publicationPath = candidate+ const partial = await stat(runtime.file.path)+ runtime.publicationIdentity = { dev: partial.dev, ino: partial.ino }+ await this.persistNow(runtime, true)+ }+ )+ runtime.state.destinationPath = publishedPath+ runtime.state.fileName = basename(publishedPath)runtime.state.status = 'completed'runtime.state.completedAt = Date.now()runtime.state.bytesDownloaded = runtime.state.totalBytes || runtime.state.bytesDownloaded+ await this.persistNow(runtime)+ await runtime.file.discard().catch(() => {})this.notify('Download Complete', `${runtime.state.fileName} has finished downloading.`)} catch (error) {runtime.state.status = 'error'@@ -914,9 +949,8 @@ export class DownloadManager {runtime.publishing = falsethis.pushUpdate(runtime)- if (runtime.state.status !== 'completed') await runtime.file.discard()- unregisterSimSession(runtime.requestPayload.url)- await this.discardUnfinishedDestination(runtime)+ // Publication failures keep the complete partial file so Resume can try again.+ if (runtime.state.status === 'completed') unregisterSimSession(runtime.requestPayload.url)}/**@@ -1679,21 +1713,6 @@ export class DownloadManager {window.webContents.send(IpcChannels.downloadUpdated, structuredClone(runtime.state))}- /**- * Releases the placeholder file reserved at start when the download won't be- * filling it in, so its name is free for the next attempt. Only ever removes- * a path this download created and never finished writing — a completed- * download keeps its file.- */- private async discardUnfinishedDestination(runtime: DownloadRuntime): Promise<void> {- if (runtime.state.status === 'completed') return- try {- await rm(runtime.state.destinationPath, { force: true })- } catch {- // Best-effort — a stray empty file isn't worth failing the download over.- }- }-private schedulePersistence(runtime: DownloadRuntime): void {if (this.suspending || runtime.removed || runtime.persistenceTimer) returnruntime.persistenceTimer = setTimeout(() => {@@ -1702,14 +1721,14 @@ export class DownloadManager {}, CHECKPOINT_INTERVAL_MS)}- private persistNow(runtime: DownloadRuntime): Promise<void> {+ private persistNow(runtime: DownloadRuntime, required = false): Promise<void> {if (runtime.removed) return runtime.persistenceChainif (runtime.persistenceTimer) {clearTimeout(runtime.persistenceTimer)runtime.persistenceTimer = undefined}- runtime.persistenceChain = runtime.persistenceChain+ const operation = runtime.persistenceChain.catch(() => {}).then(async () => {if (runtime.removed) return@@ -1717,9 +1736,12 @@ export class DownloadManager {const path = this.manifestPath(runtime.state.id)const temporaryPath = `${path}.tmp`const persisted: PersistedDownload = {- version: 3,+ version: 4,savedAt: Date.now(),state: structuredClone(runtime.state),+ partialPath: runtime.file.path,+ publicationPath: runtime.publicationPath,+ publicationIdentity: runtime.publicationIdentity,requestPayload: runtime.requestPayload,activeInterfaces: runtime.activeInterfaces}@@ -1730,17 +1752,20 @@ export class DownloadManager {await writeFile(temporaryPath, JSON.stringify(persisted), 'utf-8')await rename(temporaryPath, path)})- .catch(() => {- // Progress persistence is best-effort; transfer errors are surfaced separately.- })- return runtime.persistenceChain+ runtime.persistenceChain = operation.catch(() => {+ // Routine progress checkpoints are best-effort. Publication intent is required.+ })+ return required ? operation : runtime.persistenceChain}- private async removePersistedDownload(runtime: DownloadRuntime): Promise<void> {+ private async removePersistedDownload(+ runtime: DownloadRuntime,+ discardPartial = true+ ): Promise<void> {runtime.removed = trueif (runtime.persistenceTimer) clearTimeout(runtime.persistenceTimer)await runtime.persistenceChain.catch(() => {})- await runtime.file.discard().catch(() => {})+ if (discardPartial) await runtime.file.discard().catch(() => {})await rm(this.downloadDir(runtime.state.id), { recursive: true, force: true })}}diff --git a/src/main/download/paths.ts b/src/main/download/paths.tsindex 83c2c27..6628e0d 100644--- a/src/main/download/paths.ts+++ b/src/main/download/paths.ts@@ -1,5 +1,5 @@import { app } from 'electron'-import { mkdir, open } from 'node:fs/promises'+import { lstat, mkdir, open, rm, stat } from 'node:fs/promises'import { basename, extname, join } from 'node:path'export function getDefaultDownloadsDir(): string {@@ -14,6 +14,16 @@ export function getHomeDir(): string {// (or if something outside the app is creating them as fast as we try).const MAX_NAME_ATTEMPTS = 10_000+async function pathExists(path: string): Promise<boolean> {+ try {+ await lstat(path)+ return true+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false+ throw error+ }+}+function sanitizeFileName(fileName: string): string {// A server-provided name is one component, never a path or NTFS data stream.let safe = fileName.replace(/[\\/]/g, '_').replace(/\p{Cc}/gu, '_')@@ -24,8 +34,6 @@ function sanitizeFileName(fileName: string): string {return !safe || /^\.+$/.test(safe) ? 'download' : safe}-import { stat } from 'node:fs/promises'-export async function ensureDirectory(directory: string): Promise<void> {try {await mkdir(directory, { recursive: true })@@ -40,31 +48,35 @@ export async function ensureDirectory(directory: string): Promise<void> {}/**- * Claims <directory>/<fileName>, or <directory>/<fileName> (1), (2), ... if it- * already exists, by creating an empty file at that path.- *- * Creating it is the point. A download's bytes go to a hidden staging file and only become- * visible under the final name at publication, so merely *checking* that a name is free- * leaves it free: two downloads of the same file name started minutes apart- * would both pick it, and the one that finished second would overwrite the- * first — or, if their publications overlapped, both would write into one file- * and neither would survive. An exclusive create is what makes the name ours.- *- * The caller owns the placeholder from here: it must be removed if the- * download doesn't end up producing a file.+ * Claims a download by exclusively creating <final name>.plexo. The final name+ * itself does not appear until the file is complete. An existing partial file+ * also claims its corresponding final name, including after a restart.*/export async function reserveDestinationPath(directory: string, fileName: string): Promise<string> {await ensureDirectory(directory)fileName = sanitizeFileName(fileName)const ext = extname(fileName)- const base = basename(fileName, ext)+ // Leave room for " (9999).plexo" within the usual 255-byte component limit.+ const suffixRoom = Buffer.byteLength(' (9999).plexo')+ const maxBaseBytes = 255 - suffixRoom - Buffer.byteLength(ext)+ if (maxBaseBytes <= 0) throw new Error('The file extension is too long')+ const baseCharacters = Array.from(basename(fileName, ext))+ while (Buffer.byteLength(baseCharacters.join('')) > maxBaseBytes) baseCharacters.pop()+ const base = baseCharacters.join('')for (let counter = 0; counter < MAX_NAME_ATTEMPTS; counter += 1) {const candidate =- counter === 0 ? join(directory, fileName) : join(directory, `${base} (${counter})${ext}`)+ counter === 0+ ? join(directory, `${base}${ext}`)+ : join(directory, `${base} (${counter})${ext}`)+ if (await pathExists(candidate)) continuetry {- const handle = await open(candidate, 'wx')+ const handle = await open(`${candidate}.plexo`, 'wx+')await handle.close()+ if (await pathExists(candidate)) {+ await rm(`${candidate}.plexo`)+ continue+ }return candidate} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error