{"version":3,"file":"main.cjs","sources":["../src/shared/internal/codec.ts","../src/shared/internal/helpers.ts","../src/shared/constants.ts","../src/shared/guards.ts","../src/shared/support.ts","../src/shared/internal/validations.ts","../src/async/internal/helpers.ts","../src/async/core/create.ts","../src/async/core/read.ts","../src/async/core/remove.ts","../src/async/core/stat.ts","../src/async/tmp.ts","../src/async/core/write.ts","../src/async/ext.ts","../src/async/archive/helpers.ts","../src/async/archive/unzip-stream.ts","../src/async/archive/unzip.ts","../src/async/archive/zip-stream.ts","../src/async/archive/zip.ts","../src/async/transfer/download.ts","../src/async/transfer/upload.ts","../src/sync/channel/state.ts","../src/sync/protocol.ts","../src/sync/ops.ts","../src/sync/channel/connect.ts","../src/sync/channel/listen.ts"],"sourcesContent":["/**\n * Text encoding/decoding utilities using cached TextEncoder/TextDecoder.\n *\n * @internal\n * @module\n */\n\nimport { Lazy } from 'happy-rusty';\n\n/**\n * Lazily initialized `TextEncoder` instance.\n * Created on first access via `force()`.\n */\nconst encoder = Lazy(() => new TextEncoder());\n\n/**\n * Lazily initialized `TextDecoder` instance.\n * Created on first access via `force()`.\n */\nconst decoder = Lazy(() => new TextDecoder());\n\n/**\n * Encodes a string to a UTF-8 `Uint8Array`.\n *\n * @param data - The string to encode.\n * @returns A `Uint8Array` containing the encoded data.\n */\nexport function textEncode(data: string): Uint8Array<ArrayBuffer> {\n    return encoder.force().encode(data);\n}\n\n/**\n * Decodes binary data to a UTF-8 string.\n *\n * @param data - The binary data to decode.\n * @returns The decoded string.\n */\nexport function textDecode(data: AllowSharedBufferSource): string {\n    return decoder.force().decode(data);\n}","/**\n * Shared helper utilities for both async and sync APIs.\n *\n * @internal\n * @module\n */\n\n/**\n * Asynchronously reads a Blob's content as a Uint8Array.\n * Uses native `bytes()` method if available, otherwise falls back to `arrayBuffer()`.\n *\n * @param blob - The Blob to read.\n * @returns A promise that resolves to a Uint8Array containing the blob's binary data.\n */\nexport async function readBlobBytes(blob: Blob): Promise<Uint8Array<ArrayBuffer>> {\n    return typeof blob.bytes === 'function'\n        ? blob.bytes()\n        : new Uint8Array(await blob.arrayBuffer());\n}\n\n/**\n * Synchronously reads a Blob's content as a Uint8Array.\n * Uses FileReaderSync for synchronous binary data reading.\n *\n * **Note:** This function can only be used in Worker threads,\n * as `FileReaderSync` is not available in the main thread.\n *\n * @param blob - The Blob to read.\n * @returns A Uint8Array containing the blob's binary data.\n */\nexport function readBlobBytesSync(blob: Blob): Uint8Array<ArrayBuffer> {\n    const reader = new FileReaderSync();\n    return new Uint8Array(reader.readAsArrayBuffer(blob));\n}\n","export { ABORT_ERROR, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n\n/**\n * A constant representing the error thrown when a file or directory is not found.\n * Name of DOMException.NOT_FOUND_ERR.\n */\nexport const NOT_FOUND_ERROR = 'NotFoundError' as const;\n\n/**\n * Response body is empty (null), typically from 204/304 responses or HEAD requests.\n */\nexport const EMPTY_BODY_ERROR = 'EmptyBodyError' as const;\n\n/**\n * File content is empty (0 bytes).\n */\nexport const EMPTY_FILE_ERROR = 'EmptyFileError' as const;\n\n/**\n * Nothing to zip - empty directory with no entries.\n */\nexport const NOTHING_TO_ZIP_ERROR = 'NothingToZipError' as const;\n\n/**\n * A constant representing the root directory path.\n */\nexport const ROOT_DIR = '/' as const;\n\n/**\n * A constant representing the temporary directory path.\n */\nexport const TMP_DIR = '/tmp' as const;","import type { FileSystemDirectoryHandleLike, FileSystemFileHandleLike, FileSystemHandleLike } from './defines.ts';\n\n/**\n * Checks whether the given handle is a file handle.\n *\n * @param handle - The `FileSystemHandle` to check.\n * @returns `true` if the handle is a `FileSystemFileHandle`, otherwise `false`.\n * @since 1.0.0\n * @see {@link isDirectoryHandle} for checking directory handles\n * @see {@link isFileHandleLike} for sync handle-like objects\n * @see {@link stat} for getting handles from paths\n * @example\n * ```typescript\n * (await stat('/path/to/file'))\n *     .inspect(handle => isFileHandle(handle) && console.log('This is a file'));\n * ```\n */\nexport function isFileHandle(handle: FileSystemHandle): handle is FileSystemFileHandle {\n    return handle.kind === 'file';\n}\n\n/**\n * Checks whether the given handle is a directory handle.\n *\n * @param handle - The `FileSystemHandle` to check.\n * @returns `true` if the handle is a `FileSystemDirectoryHandle`, otherwise `false`.\n * @since 1.0.0\n * @see {@link isFileHandle} for checking file handles\n * @see {@link stat} for getting handles from paths\n * @example\n * ```typescript\n * (await stat('/path/to/dir'))\n *     .inspect(handle => isDirectoryHandle(handle) && console.log('This is a directory'));\n * ```\n */\nexport function isDirectoryHandle(handle: FileSystemHandle): handle is FileSystemDirectoryHandle {\n    return handle.kind === 'directory';\n}\n\n/**\n * Checks whether the given handle-like object represents a file.\n *\n * @param handle - The `FileSystemHandleLike` object to check.\n * @returns `true` if the handle-like object represents a file, otherwise `false`.\n * @since 1.1.0\n * @see {@link isFileHandle} for async file handles\n * @see {@link statSync} for getting sync handle-like objects\n * @example\n * ```typescript\n * statSync('/path/to/file')\n *     .inspect(handle => isFileHandleLike(handle) && console.log(`File size: ${ handle.size }`));\n * ```\n */\nexport function isFileHandleLike(handle: FileSystemHandleLike): handle is FileSystemFileHandleLike {\n    return handle.kind === 'file';\n}\n\n/**\n * Checks whether the given handle-like object represents a directory.\n *\n * @param handle - The `FileSystemHandleLike` object to check.\n * @returns `true` if the handle-like object represents a directory, otherwise `false`.\n * @since 2.0.0\n * @see {@link isDirectoryHandle} for async directory handles\n * @see {@link isFileHandleLike} for checking file handle-like objects\n * @see {@link statSync} for getting sync handle-like objects\n * @example\n * ```typescript\n * statSync('/path/to/dir')\n *     .inspect(handle => isDirectoryHandleLike(handle) && console.log('This is a directory'));\n *\n * // Filter directories from readDirSync results\n * readDirSync('/documents')\n *     .inspect(entries => {\n *         const dirs = entries.filter(e => isDirectoryHandleLike(e.handle));\n *         console.log('Directories:', dirs.map(d => d.path));\n *     });\n * ```\n */\nexport function isDirectoryHandleLike(handle: FileSystemHandleLike): handle is FileSystemDirectoryHandleLike {\n    return handle.kind === 'directory';\n}\n","/**\n * Checks if the Origin Private File System (OPFS) is supported in the current environment.\n * OPFS requires a secure context (HTTPS or localhost) and browser support.\n *\n * @returns `true` if OPFS is supported, `false` otherwise.\n * @since 1.0.0\n * @see {@link isSyncChannelSupported} for checking sync channel support\n * @example\n * ```typescript\n * if (isOPFSSupported()) {\n *     // Use OPFS APIs\n *     const result = await readFile('/path/to/file');\n * } else {\n *     console.warn('OPFS is not supported in this environment');\n * }\n * ```\n */\nexport function isOPFSSupported(): boolean {\n    return typeof navigator?.storage?.getDirectory === 'function';\n}\n\n/**\n * Checks if the SyncChannel (synchronous file system operations) is supported.\n * SyncChannel requires `SharedArrayBuffer` and `Atomics` which are only available\n * in secure contexts with proper COOP/COEP headers.\n *\n * **Required HTTP headers for cross-origin isolation:**\n * ```\n * Cross-Origin-Opener-Policy: same-origin\n * Cross-Origin-Embedder-Policy: require-corp\n * ```\n *\n * @returns `true` if SyncChannel is supported, `false` otherwise.\n * @since 2.0.0\n * @see {@link isOPFSSupported} for checking OPFS support\n * @example\n * ```typescript\n * if (isSyncChannelSupported()) {\n *     // Use sync APIs\n *     const result = await SyncChannel.connect(worker);\n *     const content = readFileSync('/path/to/file');\n * } else {\n *     console.warn('SyncChannel requires cross-origin isolation');\n * }\n * ```\n */\nexport function isSyncChannelSupported(): boolean {\n    return typeof SharedArrayBuffer === 'function' && typeof Atomics === 'object';\n}","/**\n * Internal shared validation functions for async and sync operations.\n * These functions return Result types instead of throwing exceptions.\n *\n * @internal\n * @module\n */\n\nimport { normalize } from '@std/path/posix';\nimport { Err, Ok, RESULT_VOID, type IOResult, type VoidIOResult } from 'happy-rusty';\nimport { ROOT_DIR, type ExistsOptions, type WriteFileContent, type WriteSyncFileContent } from '../mod.ts';\n\n/**\n * Validates that the provided path is an absolute path and normalizes it.\n * Returns a Result instead of throwing.\n *\n * @param path - The file path to validate.\n * @returns An `IOResult` containing the normalized absolute path, or an error.\n */\nexport function validateAbsolutePath(path: string): IOResult<string> {\n    if (typeof path !== 'string') {\n        return Err(new TypeError(`Path must be a string but received ${ typeof path }`));\n    }\n\n    if (path[0] !== ROOT_DIR) {\n        return Err(new Error(`Path must be absolute (start with '/'): '${ path }'`));\n    }\n\n    // Normalize and remove trailing slash except for root\n    const normalized = normalize(path);\n    const result = normalized.length > 1 && normalized[normalized.length - 1] === ROOT_DIR\n        ? normalized.slice(0, -1)\n        : normalized;\n\n    return Ok(result);\n}\n\n/**\n * Validates that the provided URL is valid and returns a URL object.\n * Supports relative URLs by using current location as base.\n * Returns a Result instead of throwing.\n *\n * @param url - The URL string or URL object to validate.\n * @returns An `IOResult` containing the URL object, or an error.\n */\nexport function validateUrl(url: string | URL): IOResult<URL> {\n    if (url instanceof URL) {\n        return Ok(url);\n    }\n\n    try {\n        return Ok(new URL(url, location.href));\n    } catch {\n        return Err(new TypeError(`Invalid URL: '${ url }'`));\n    }\n}\n\n/**\n * Validates that the provided ExistsOptions are valid.\n * `isDirectory` and `isFile` cannot both be `true`.\n *\n * @param options - The ExistsOptions to validate.\n * @returns A `VoidIOResult` indicating success, or an error if options are invalid.\n */\nexport function validateExistsOptions(options?: ExistsOptions): VoidIOResult {\n    const { isDirectory = false, isFile = false } = options ?? {};\n\n    return isDirectory && isFile\n        ? Err(new Error('isDirectory and isFile cannot both be true'))\n        : RESULT_VOID;\n}\n\n/**\n * Validates that the provided value is a valid Date for pruneTemp expiration.\n * Returns a Result instead of throwing.\n *\n * @param expired - The Date to validate.\n * @returns A `VoidIOResult` indicating success, or an error if not a valid Date instance, eg: `new Date('invalid')`.\n */\nexport function validateExpiredDate(expired: Date): VoidIOResult {\n    if (!(expired instanceof Date)) {\n        return Err(new TypeError(`Expired must be a Date but received ${ typeof expired }`));\n    }\n\n    return Number.isNaN(expired.getTime())\n        ? Err(new TypeError('Expired must be a valid Date'))\n        : RESULT_VOID;\n}\n\n/**\n * Validates that the provided content is a valid type for writeFile (async).\n * Supports: string, Blob, ArrayBuffer, TypedArray, ReadableStream<Uint8Array>.\n *\n * @param contents - The content to validate.\n * @returns A `VoidIOResult` indicating success, or an error if type is invalid.\n */\nexport function validateWriteFileContent(contents: WriteFileContent): VoidIOResult {\n    // Check for ReadableStream first (async only)\n    if (isBinaryReadableStream(contents)) {\n        return RESULT_VOID;\n    }\n\n    // Check for Blob (async only)\n    if (contents instanceof Blob) {\n        return RESULT_VOID;\n    }\n\n    // Check for sync-compatible types (string, ArrayBuffer, TypedArray)\n    if (isWriteSyncFileContent(contents)) {\n        return RESULT_VOID;\n    }\n\n    return Err(new TypeError('Invalid content type for writeFile. Expected string, Blob, ArrayBuffer, TypedArray, or ReadableStream'));\n}\n\n/**\n * Validates that the provided content is a valid type for writeFileSync (sync).\n * Supports: string, ArrayBuffer, TypedArray.\n * Note: Blob and ReadableStream are NOT supported in sync operations.\n *\n * @param contents - The content to validate.\n * @returns A `VoidIOResult` indicating success, or an error if type is invalid.\n */\nexport function validateWriteSyncFileContent(contents: WriteSyncFileContent): VoidIOResult {\n    if (!isWriteSyncFileContent(contents)) {\n        return Err(new TypeError('Invalid content type for writeFileSync. Expected string, ArrayBuffer, or TypedArray'));\n    }\n\n    return RESULT_VOID;\n}\n\n// #region Internal functions\n\n/**\n * Type guard for detecting binary ReadableStream input for file writing.\n *\n * @param x - The value to check.\n * @returns `true` if the value is a ReadableStream.\n */\nfunction isBinaryReadableStream(x: unknown): x is ReadableStream<Uint8Array<ArrayBuffer>> {\n    return typeof ReadableStream !== 'undefined' && x instanceof ReadableStream;\n}\n\n/**\n * Type guard for detecting valid sync file content types.\n * Supports: string, ArrayBuffer, ArrayBufferView (TypedArray/DataView).\n *\n * @param contents - The value to check.\n * @returns `true` if the value is a valid sync file content type.\n */\nfunction isWriteSyncFileContent(contents: unknown): contents is WriteSyncFileContent {\n    return typeof contents === 'string' ||\n        contents instanceof ArrayBuffer ||\n        ArrayBuffer.isView(contents);\n}\n\n// #endregion\n","/**\n * Internal helper utilities for async file operations.\n * These functions are not exported publicly.\n *\n * @internal\n * @module\n */\n\nimport type { FetchTask } from '@happy-ts/fetch-t';\nimport { basename, dirname, SEPARATOR } from '@std/path/posix';\nimport { LazyAsync, Ok, RESULT_VOID, tryAsyncResult, type AsyncIOResult, type AsyncVoidIOResult, type IOResult } from 'happy-rusty';\nimport { ABORT_ERROR, EMPTY_BODY_ERROR, EMPTY_FILE_ERROR, NOT_FOUND_ERROR, NOTHING_TO_ZIP_ERROR, ROOT_DIR } from '../../shared/mod.ts';\n\n// #region Internal Variables\n\n/**\n * Lazily initialized root directory handle of the file system.\n * Created on first access via `force()`.\n */\nconst fsRoot = LazyAsync(() => navigator.storage.getDirectory());\n\n// #endregion\n\n/**\n * Checks if the provided path is the root directory path.\n *\n * @param path - The path to check.\n * @returns `true` if the path equals `'/'`, otherwise `false`.\n */\nexport function isRootDir(path: string): boolean {\n    return path === ROOT_DIR;\n}\n\n/**\n * Retrieves a directory handle by traversing the path from root.\n *\n * Algorithm:\n * 1. Start from the OPFS root directory\n * 2. If path is `/`, return root immediately\n * 3. Split path by `/` separator and iterate through each segment\n * 4. For each segment, get or create the child directory handle\n * 5. Return error immediately if any segment fails\n *\n * @param dirPath - The absolute path of the directory to retrieve.\n * @param options - Optional parameters (e.g., `{ create: true }` to create intermediate directories).\n * @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemDirectoryHandle`.\n */\nexport async function getDirHandle(dirPath: string, options?: FileSystemGetDirectoryOptions): AsyncIOResult<FileSystemDirectoryHandle> {\n    // Start from root\n    let dirHandle = fsRoot.isInitialized()\n        ? fsRoot.get().unwrap()\n        : await fsRoot.force();\n\n    if (isRootDir(dirPath)) {\n        // Root is already a handle, no traversal needed\n        return Ok(dirHandle);\n    } else {\n        // NOTE: Empty else branch is intentional to fix V8 coverage tracking.\n        // Without explicit else, V8 incorrectly marks code after early return as uncovered.\n    }\n\n    // Traverse path from root\n    // Iterate through each path segment\n    // Path is already normalized by validateAbsolutePath, no empty segments\n    // Remove leading '/' and start traversing\n    for (const childDirName of dirPath.slice(1).split(SEPARATOR)) {\n        // Get or create child directory\n        const dirHandleRes = await getChildDirHandle(dirHandle, childDirName, options);\n        if (dirHandleRes.isErr()) {\n            // Stop traversal on error\n            return dirHandleRes;\n        }\n\n        dirHandle = dirHandleRes.unwrap();\n    }\n\n    return Ok(dirHandle);\n}\n\n/**\n * Gets the directory handle for the parent directory of the given path.\n *\n * @param path - The absolute path whose parent directory handle is to be retrieved.\n * @param options - Optional parameters (e.g., `{ create: true }` to create intermediate directories).\n * @returns A promise that resolves to an `AsyncIOResult` containing the parent `FileSystemDirectoryHandle`.\n */\nexport function getParentDirHandle(path: string, options?: FileSystemGetDirectoryOptions): AsyncIOResult<FileSystemDirectoryHandle> {\n    return getDirHandle(dirname(path), options);\n}\n\n/**\n * Retrieves a file handle given a file path.\n *\n * @param filePath - The absolute path of the file to retrieve.\n * @param options - Optional parameters (e.g., `{ create: true }` to create the file if not exists).\n * @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemFileHandle`.\n */\nexport async function getFileHandle(filePath: string, options?: FileSystemGetFileOptions): AsyncIOResult<FileSystemFileHandle> {\n    const dirHandleRes = await getParentDirHandle(filePath, options);\n\n    return dirHandleRes.andThenAsync(dirHandle => {\n        const fileName = basename(filePath);\n        return getChildFileHandle(dirHandle, fileName, options);\n    });\n}\n\n/**\n * Checks whether the error is a `NotFoundError`.\n *\n * @param err - The error to check.\n * @returns `true` if the error's name is `'NotFoundError'`, otherwise `false`.\n */\nexport function isNotFoundError(err: Error): boolean {\n    return err.name === NOT_FOUND_ERROR;\n}\n\n/**\n * Aggregates multiple async void I/O results into a single result.\n * Waits for all tasks to complete, then returns the first error encountered,\n * or a void success result if all tasks succeed.\n *\n * @param tasks - The list of async void I/O result promises to aggregate.\n * @returns A promise that resolves to the first error result, or `RESULT_VOID` if all tasks succeed.\n */\nexport async function aggregateResults(tasks: AsyncVoidIOResult[]): AsyncVoidIOResult {\n    if (tasks.length === 0) {\n        return RESULT_VOID;\n    }\n\n    const allRes = await Promise.all(tasks);\n    return allRes.find(x => x.isErr()) ?? RESULT_VOID;\n}\n\n/**\n * Creates an `AbortError` instance.\n * Used to signal that an operation was aborted.\n *\n * @returns An `Error` object with the name set to `'AbortError'`.\n */\nexport function createAbortError(): Error {\n    const error = new Error('Operation was aborted');\n    error.name = ABORT_ERROR;\n\n    return error;\n}\n\n/**\n * Creates an `EmptyBodyError` instance.\n * Used to signal that a response body is empty (null).\n *\n * @returns An `Error` object with the name set to `'EmptyBodyError'`.\n */\nexport function createEmptyBodyError(): Error {\n    const error = new Error('Response body is empty');\n    error.name = EMPTY_BODY_ERROR;\n\n    return error;\n}\n\n/**\n * Creates an `EmptyFileError` instance.\n * Used to signal that a file content is empty (0 bytes).\n *\n * @returns An `Error` object with the name set to `'EmptyFileError'`.\n */\nexport function createEmptyFileError(): Error {\n    const error = new Error('File content is empty');\n    error.name = EMPTY_FILE_ERROR;\n\n    return error;\n}\n\n/**\n * Creates a `NothingToZipError` instance.\n * Used when attempting to zip an empty directory with preserveRoot=false.\n *\n * @returns An `Error` object with the name set to `'NothingToZipError'`.\n */\nexport function createNothingToZipError(): Error {\n    const error = new Error('Nothing to zip');\n    error.name = NOTHING_TO_ZIP_ERROR;\n\n    return error;\n}\n\n/**\n * Creates a failed FetchTask that immediately resolves with an error.\n * Used when validation fails before making the actual fetch request.\n *\n * @param errResult - The error result to return.\n * @returns A FetchTask that resolves with the error.\n */\nexport function createFailedFetchTask<T>(errResult: IOResult<unknown>): FetchTask<T> {\n    return {\n        abort(): void { /* noop */ },\n        get aborted(): boolean { return false; },\n        get result() { return Promise.resolve(errResult.asErr<T>()); },\n    };\n}\n\n/**\n * Marks all parent directories of a path as non-empty.\n * Used to optimize directory creation by skipping directories that will be\n * implicitly created when writing files.\n *\n * @param path - The relative file path.\n * @param nonEmptyDirs - Set to track non-empty directories.\n */\nexport function markParentDirsNonEmpty(\n    path: string,\n    nonEmptyDirs: Set<string>,\n): void {\n    let slashIndex = path.lastIndexOf(SEPARATOR);\n    while (slashIndex > 0) {\n        const parent = path.slice(0, slashIndex);\n        if (nonEmptyDirs.has(parent)) break;\n        nonEmptyDirs.add(parent);\n        slashIndex = path.lastIndexOf(SEPARATOR, slashIndex - 1);\n    }\n}\n\n/**\n * Removes a file or directory with cross-browser compatibility.\n * Accepts either a handle or a name string. When a handle is provided and\n * `handle.remove()` is supported (Chrome/Edge), uses native removal.\n * Otherwise falls back to `parentDirHandle.removeEntry()`.\n *\n * For root directory removal on Firefox/Safari (where `handle.remove()` is not supported),\n * iterates through all children and removes them individually.\n *\n * @param handleOrName - The handle to remove, or the name of the entry.\n * @param parentDirHandle - The parent directory handle.\n * @param options - Optional remove options (e.g., `{ recursive: true }`).\n * @returns A promise that resolves when the entry is removed.\n */\nexport async function removeHandle(\n    handleOrName: FileSystemHandle | string,\n    parentDirHandle: FileSystemDirectoryHandle,\n    options?: FileSystemRemoveOptions,\n): Promise<void> {\n    if (typeof handleOrName === 'string') {\n        // Name string: use removeEntry directly\n        return parentDirHandle.removeEntry(handleOrName, options);\n    }\n\n    const removableHandle = handleOrName as RemovableHandle;\n\n    if (typeof removableHandle.remove === 'function') {\n        // Chrome/Edge: use native handle.remove()\n        return removableHandle.remove(options);\n    }\n\n    // Firefox/Safari: fallback to removeEntry()\n    // Special case: root directory has empty name, cannot use removeEntry\n    // Instead, iterate and remove all children\n    if (!handleOrName.name) {\n        const dirHandle = handleOrName as FileSystemDirectoryHandle;\n        const tasks: Promise<void>[] = [];\n\n        for await (const childName of dirHandle.keys()) {\n            tasks.push(dirHandle.removeEntry(childName, options));\n        }\n\n        if (tasks.length > 0) {\n            await Promise.all(tasks);\n        }\n    } else {\n        return parentDirHandle.removeEntry(handleOrName.name, options);\n    }\n}\n\n/**\n * Result of peeking a stream's first chunk.\n */\nexport interface PeekStreamResult<T> {\n    /** Whether the stream is empty (no data). */\n    isEmpty: boolean;\n    /** The reconstructed stream with first chunk prepended. Only valid if not empty. */\n    stream: ReadableStream<T>;\n}\n\n/**\n * Peeks the first chunk of a ReadableStream to check if it's empty.\n * Returns the original stream reconstructed with the peeked chunk prepended.\n *\n * This enables true streaming while detecting empty streams before processing.\n *\n * @param source - The source ReadableStream to peek.\n * @returns A promise resolving to an `AsyncIOResult` containing PeekStreamResult with isEmpty flag and reconstructed stream.\n */\nexport async function peekStream<T>(source: ReadableStream<T>): AsyncIOResult<PeekStreamResult<T>> {\n    const reader = source.getReader();\n\n    const firstRes = await tryAsyncResult(reader.read());\n    if (firstRes.isErr()) {\n        reader.releaseLock();\n        return firstRes.asErr();\n    }\n\n    const first = firstRes.unwrap();\n\n    if (first.done) {\n        reader.releaseLock();\n        // Return a new empty stream since the original is already consumed\n        return Ok({\n            isEmpty: true,\n            stream: new ReadableStream<T>({\n                start(controller) {\n                    controller.close();\n                },\n            }),\n        });\n    }\n\n    // Reconstruct stream: first chunk + remaining data\n    const stream = new ReadableStream<T>({\n        async start(controller) {\n            controller.enqueue(first.value);\n        },\n        async pull(controller) {\n            try {\n                const { done, value } = await reader.read();\n                if (done) {\n                    reader.releaseLock();\n                    controller.close();\n                } else {\n                    controller.enqueue(value);\n                }\n            } catch (err) {\n                reader.releaseLock();\n                controller.error(err);\n            }\n        },\n        async cancel(reason) {\n            try {\n                await reader.cancel(reason);\n            } finally {\n                reader.releaseLock();\n            }\n        },\n    });\n\n    return Ok({\n        isEmpty: false,\n        stream,\n    });\n}\n\n/**\n * Moves a file handle to a new path, creating parent directories if needed.\n * This is a higher-level operation that handles path resolution and directory creation.\n *\n * @param fileHandle - The file handle to move.\n * @param destFilePath - The destination absolute file path.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n */\nexport async function moveFileHandle(fileHandle: FileSystemFileHandle, destFilePath: string): AsyncVoidIOResult {\n    const dirRes = await getParentDirHandle(destFilePath, {\n        create: true,\n    });\n\n    return dirRes.andTryAsync(destDirHandle => {\n        const destName = basename(destFilePath);\n        return (fileHandle as unknown as MovableHandle).move(destDirHandle, destName);\n    });\n}\n\n// #region Internal Types\n\n/**\n * Extended FileSystemHandle interface with optional remove method.\n * The remove() method is not supported in Firefox/iOS Safari.\n */\ninterface RemovableHandle extends FileSystemHandle {\n    remove?(options?: FileSystemRemoveOptions): Promise<void>;\n}\n\n/**\n * Extended FileSystemHandle interface with move method.\n * The move() method is not yet in TypeScript's lib.dom.d.ts.\n * @see https://github.com/mdn/browser-compat-data/issues/20341\n */\ninterface MovableHandle extends FileSystemHandle {\n    move(destination: FileSystemDirectoryHandle, name: string): Promise<void>;\n}\n\n// #endregion\n\n// #region Internal Functions\n\n/**\n * Asynchronously obtains a handle to a child directory from the given parent directory handle.\n *\n * @param dirHandle - The handle to the parent directory.\n * @param childDirName - The name of the child directory to retrieve.\n * @param options - Optional parameters (e.g., `{ create: true }` to create if not exists).\n * @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemDirectoryHandle`.\n */\nasync function getChildDirHandle(dirHandle: FileSystemDirectoryHandle, childDirName: string, options?: FileSystemGetDirectoryOptions): AsyncIOResult<FileSystemDirectoryHandle> {\n    const handleRes = await tryAsyncResult<FileSystemDirectoryHandle, DOMException>(dirHandle.getDirectoryHandle(childDirName, options));\n    return handleRes.mapErr(err => {\n        const error = new Error(`${ err.name }: ${ err.message } When get child directory '${ childDirName }' from directory '${ dirHandle.name || ROOT_DIR }'`);\n        error.name = err.name;\n        return error;\n    });\n}\n\n/**\n * Retrieves a file handle for a child file within a directory.\n *\n * @param dirHandle - The directory handle to search within.\n * @param childFileName - The name of the file to retrieve.\n * @param options - Optional parameters (e.g., `{ create: true }` to create if not exists).\n * @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemFileHandle`.\n */\nasync function getChildFileHandle(dirHandle: FileSystemDirectoryHandle, childFileName: string, options?: FileSystemGetFileOptions): AsyncIOResult<FileSystemFileHandle> {\n    const handleRes = await tryAsyncResult<FileSystemFileHandle, DOMException>(dirHandle.getFileHandle(childFileName, options));\n    return handleRes.mapErr(err => {\n        const error = new Error(`${ err.name }: ${ err.message } When get child file '${ childFileName }' from directory '${ dirHandle.name || ROOT_DIR }'`);\n        error.name = err.name;\n        return error;\n    });\n}\n\n// #endregion\n","import { RESULT_VOID, type AsyncVoidIOResult } from 'happy-rusty';\nimport { validateAbsolutePath } from '../../shared/internal/mod.ts';\nimport { getDirHandle, getFileHandle } from '../internal/mod.ts';\n\n/**\n * Creates a new empty file at the specified path, similar to the `touch` command.\n * If the file already exists, this operation succeeds without modifying it.\n * Parent directories are created automatically if they don't exist.\n *\n * **Note:** For temporary files, use {@link mkTemp} instead, which provides\n * automatic unique naming and integrates with {@link pruneTemp} for cleanup.\n *\n * @param filePath - The absolute path of the file to create.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.7.0\n * @see {@link createFileSync} for synchronous version\n * @see {@link mkTemp} for creating temporary files\n * @see {@link writeFile} for creating files with content\n * @example\n * ```typescript\n * (await createFile('/path/to/file.txt'))\n *     .inspect(() => console.log('File created'));\n * ```\n */\nexport async function createFile(filePath: string): AsyncVoidIOResult {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    const handleRes = await getFileHandle(filePath, {\n        create: true,\n    });\n\n    return handleRes.and(RESULT_VOID);\n}\n\n/**\n * Creates a new directory at the specified path, similar to `mkdir -p`.\n * Creates all necessary parent directories if they don't exist.\n *\n * **Note:** For temporary directories, use {@link mkTemp} with `{ isDirectory: true }` instead,\n * which provides automatic unique naming and integrates with temporary file management.\n *\n * @param dirPath - The absolute path where the directory will be created.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.0.0\n * @see {@link mkdirSync} for synchronous version\n * @see {@link emptyDir} for creating or emptying a directory\n * @see {@link mkTemp} for creating temporary directories\n * @example\n * ```typescript\n * (await mkdir('/path/to/new/directory'))\n *     .inspect(() => console.log('Directory created'));\n * ```\n */\nexport async function mkdir(dirPath: string): AsyncVoidIOResult {\n    const dirPathRes = validateAbsolutePath(dirPath);\n    if (dirPathRes.isErr()) return dirPathRes.asErr();\n    dirPath = dirPathRes.unwrap();\n\n    const handleRes = await getDirHandle(dirPath, {\n        create: true,\n    });\n\n    return handleRes.and(RESULT_VOID);\n}\n","import { join } from '@std/path/posix';\nimport { Err, Ok, type AsyncIOResult } from 'happy-rusty';\nimport { readBlobBytes, textDecode, validateAbsolutePath } from '../../shared/internal/mod.ts';\nimport { isDirectoryHandle, type DirEntry, type ReadDirOptions, type ReadFileContent, type ReadOptions } from '../../shared/mod.ts';\nimport { createAbortError, getDirHandle, getFileHandle } from '../internal/mod.ts';\n/**\n * Reads the contents of a directory at the specified path.\n *\n * @param dirPath - The path of the directory to read.\n * @param options - Options of readdir.\n * @returns A promise that resolves to an `AsyncIOResult` containing an async iterable iterator over the entries of the directory.\n * @since 1.0.0\n * @see {@link readDirSync} for synchronous version\n * @example\n * ```typescript\n * // List directory contents\n * (await readDir('/documents'))\n *     .inspect(async entries => {\n *         for await (const entry of entries) {\n *             console.log(entry.path, entry.handle.kind);\n *         }\n *     });\n *\n * // List recursively\n * await readDir('/documents', { recursive: true });\n * ```\n */\nexport async function readDir(dirPath: string, options?: ReadDirOptions): AsyncIOResult<AsyncIterableIterator<DirEntry>> {\n    const dirPathRes = validateAbsolutePath(dirPath);\n    if (dirPathRes.isErr()) return dirPathRes.asErr();\n    dirPath = dirPathRes.unwrap();\n\n    const dirHandleRes = await getDirHandle(dirPath);\n    if (dirHandleRes.isErr()) {\n        return dirHandleRes.asErr();\n    }\n\n    // Check if aborted after getting handle\n    if (options?.signal?.aborted) {\n        const { reason } = options.signal;\n        return Err(reason instanceof Error ? reason : createAbortError());\n    }\n\n    async function* read(dirHandle: FileSystemDirectoryHandle, relativePath?: string): AsyncIterableIterator<DirEntry> {\n        if (options?.signal?.aborted) {\n            return;\n        }\n\n        for await (const [name, handle] of dirHandle.entries()) {\n            // Check if aborted before yielding each entry\n            if (options?.signal?.aborted) {\n                return;\n            }\n\n            const path = relativePath ? join(relativePath, name) : name;\n            yield {\n                path,\n                handle,\n            };\n\n            if (options?.recursive && isDirectoryHandle(handle)) {\n                yield* read(handle, path);\n            }\n        }\n    }\n\n    return Ok(read(dirHandleRes.unwrap()));\n}\n\n/**\n * Reads the content of a file at the specified path as a File.\n *\n * @param filePath - The path of the file to read.\n * @param options - Read options specifying the 'blob' encoding.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a File.\n * @since 1.0.0\n * @see {@link readFileSync} for synchronous version\n * @see {@link readBlobFile} convenience wrapper\n * @example\n * ```typescript\n * (await readFile('/path/to/file.txt', { encoding: 'blob' }))\n *     .inspect(file => console.log(file.name, file.size, file.type));\n * ```\n */\nexport function readFile(filePath: string, options: ReadOptions & {\n    encoding: 'blob';\n}): AsyncIOResult<File>;\n\n/**\n * Reads the content of a file at the specified path as a string.\n *\n * @param filePath - The path of the file to read.\n * @param options - Read options specifying the 'utf8' encoding.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a string.\n * @since 1.0.0\n * @see {@link readFileSync} for synchronous version\n * @see {@link readTextFile} convenience wrapper\n * @example\n * ```typescript\n * (await readFile('/path/to/file.txt', { encoding: 'utf8' }))\n *     .inspect(content => console.log(content));\n * ```\n */\nexport function readFile(filePath: string, options: ReadOptions & {\n    encoding: 'utf8';\n}): AsyncIOResult<string>;\n\n/**\n * Reads the content of a file at the specified path as a readable stream.\n * Useful for processing large files without loading them entirely into memory.\n *\n * @param filePath - The path of the file to read.\n * @param options - Read options specifying the 'stream' encoding.\n * @returns A promise that resolves to an `AsyncIOResult` containing a `ReadableStream<Uint8Array>`.\n * @since 1.0.0\n * @see {@link readFileSync} for synchronous version (bytes only)\n * @example\n * ```typescript\n * (await readFile('/path/to/large-file.bin', { encoding: 'stream' }))\n *     .inspect(async stream => {\n *         const reader = stream.getReader();\n *         while (true) {\n *             const { done, value } = await reader.read();\n *             if (done) break;\n *             console.log('Received chunk:', value.length, 'bytes');\n *         }\n *     });\n * ```\n */\nexport function readFile(filePath: string, options: ReadOptions & {\n    encoding: 'stream';\n}): AsyncIOResult<ReadableStream<Uint8Array<ArrayBuffer>>>;\n\n/**\n * Reads the content of a file at the specified path as a Uint8Array (default).\n *\n * @param filePath - The path of the file to read.\n * @param options - Optional read options. Defaults to 'bytes' encoding.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a Uint8Array.\n * @since 1.0.0\n * @see {@link readFileSync} for synchronous version\n * @example\n * ```typescript\n * (await readFile('/path/to/file.bin'))\n *     .inspect(bytes => console.log('First byte:', bytes[0]));\n * ```\n */\nexport function readFile(filePath: string, options?: ReadOptions & {\n    encoding?: 'bytes';\n}): AsyncIOResult<Uint8Array<ArrayBuffer>>;\n\n/**\n * Reads the content of a file at the specified path with the specified options.\n * This overload accepts any ReadOptions and returns the union of all possible content types.\n * Useful when the encoding is determined at runtime.\n *\n * @param filePath - The path of the file to read.\n * @param options - Optional read options.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content.\n * @since 1.0.0\n * @see {@link readFileSync} for synchronous version\n * @example\n * ```typescript\n * // When encoding is dynamic\n * const encoding = getUserPreference(); // 'utf8' | 'bytes' | ...\n * (await readFile('/path/to/file.txt', { encoding }))\n *     .inspect(content => {\n *         // content type is ReadFileContent (union type)\n *         if (typeof content === 'string') {\n *             console.log('Text:', content);\n *         } else if (content instanceof Uint8Array) {\n *             console.log('Bytes:', content.length);\n *         }\n *     });\n * ```\n */\nexport function readFile(filePath: string, options?: ReadOptions): AsyncIOResult<ReadFileContent>;\n\n/**\n * Reads the content of a file at the specified path with the specified options.\n *\n * @template T The type of the content to read from the file.\n * @param filePath - The path of the file to read.\n * @param options - Optional read options.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content.\n */\nexport async function readFile(filePath: string, options?: ReadOptions): AsyncIOResult<ReadFileContent> {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    const fileHandleRes = await getFileHandle(filePath);\n\n    return fileHandleRes.andTryAsync(async fileHandle => {\n        const encoding = options?.encoding;\n\n        // Prefer sync access in Worker for better performance\n        // Only for encodings that don't require File object or streaming\n        return encoding !== 'blob' && encoding !== 'stream' && typeof fileHandle.createSyncAccessHandle === 'function'\n            ? readViaSyncAccess(fileHandle, encoding)\n            // Main thread fallback or blob/stream encoding\n            : readViaFile(fileHandle, encoding);\n    });\n}\n\n/**\n * Reads file content using the Worker's FileSystemSyncAccessHandle API.\n * More performant than File-based reading in Worker context.\n */\nasync function readViaSyncAccess(\n    fileHandle: FileSystemFileHandle,\n    encoding?: 'bytes' | 'utf8',\n): Promise<Uint8Array<ArrayBuffer> | string> {\n    const accessHandle = await fileHandle.createSyncAccessHandle();\n\n    try {\n        const size = accessHandle.getSize();\n        const bytes = new Uint8Array(size);\n        accessHandle.read(bytes, { at: 0 });\n\n        if (encoding === 'utf8') {\n            return textDecode(bytes);\n        }\n        // 'bytes' or undefined (default)\n        return bytes;\n    } finally {\n        accessHandle.close();\n    }\n}\n\n/**\n * Reads file content using the File API (main thread strategy).\n */\nasync function readViaFile(\n    fileHandle: FileSystemFileHandle,\n    encoding?: 'bytes' | 'utf8' | 'blob' | 'stream',\n): Promise<ReadFileContent> {\n    const file = await fileHandle.getFile();\n\n    switch (encoding) {\n        case 'blob': {\n            return file;\n        }\n        case 'utf8': {\n            return file.text();\n        }\n        case 'stream': {\n            return file.stream();\n        }\n        default: {\n            // 'bytes' or undefined (default)\n            return readBlobBytes(file);\n        }\n    }\n}\n","import { basename } from '@std/path/posix';\nimport { Err, RESULT_VOID, type AsyncVoidIOResult } from 'happy-rusty';\nimport { validateAbsolutePath } from '../../shared/internal/mod.ts';\nimport { getParentDirHandle, isNotFoundError, isRootDir, removeHandle } from '../internal/mod.ts';\n\n/**\n * Removes a file or directory at the specified path, similar to `rm -rf`.\n * If the path doesn't exist, the operation succeeds silently.\n *\n * @param path - The absolute path of the file or directory to remove.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.0.0\n * @see {@link removeSync} for synchronous version\n * @see {@link emptyDir} for emptying a directory without removing it\n * @see {@link deleteTemp} for removing the temporary directory\n * @example\n * ```typescript\n * (await remove('/path/to/file-or-directory'))\n *     .inspect(() => console.log('Removed successfully'));\n * ```\n */\nexport async function remove(path: string): AsyncVoidIOResult {\n    const pathRes = validateAbsolutePath(path);\n    if (pathRes.isErr()) return pathRes.asErr();\n    path = pathRes.unwrap();\n\n    const parentDirHandleRes = await getParentDirHandle(path);\n\n    const removeRes = await parentDirHandleRes.andTryAsync(parentDirHandle => {\n        // For root, parentDirHandle is the root itself\n        // For non-root, use basename as the entry name\n        const handleOrName = isRootDir(path) ? parentDirHandle : basename(path);\n        return removeHandle(handleOrName, parentDirHandle, {\n            recursive: true,\n        });\n    });\n\n    return removeRes.orElse(err => {\n        // not found as success\n        return isNotFoundError(err) ? RESULT_VOID : Err(err);\n    });\n}\n","import { basename } from '@std/path/posix';\nimport { tryAsyncResult, type AsyncIOResult } from 'happy-rusty';\nimport { validateAbsolutePath } from '../../shared/internal/mod.ts';\nimport { getParentDirHandle, isRootDir } from '../internal/mod.ts';\n\n/**\n * Retrieves the `FileSystemHandle` for a file or directory at the specified path.\n * Can be used to check the type (file or directory) and access metadata.\n *\n * @param path - The absolute path of the file or directory.\n * @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemHandle`.\n * @since 1.0.0\n * @see {@link statSync} for synchronous version\n * @see {@link exists} for checking existence without getting the handle\n * @see {@link isFileHandle} for checking handle type\n * @see {@link isDirectoryHandle} for checking handle type\n * @example\n * ```typescript\n * (await stat('/path/to/entry'))\n *     .inspect(handle => console.log(`Kind: ${ handle.kind }, Name: ${ handle.name }`));\n * ```\n */\nexport async function stat(path: string): AsyncIOResult<FileSystemHandle> {\n    const pathRes = validateAbsolutePath(path);\n    if (pathRes.isErr()) return pathRes.asErr();\n    path = pathRes.unwrap();\n\n    const dirHandleRes = await getParentDirHandle(path);\n    if (isRootDir(path)) {\n        // root\n        return dirHandleRes;\n    }\n\n    return dirHandleRes.andThenAsync(async dirHandle => {\n        // Try to get the handle directly instead of iterating\n        // First try as file, then as directory\n        const childName = basename(path);\n        let findRes = await tryAsyncResult<FileSystemHandle, DOMException>(dirHandle.getFileHandle(childName));\n        if (findRes.isOk()) {\n            return findRes;\n        }\n\n        // Not a file, try as directory\n        findRes = await tryAsyncResult<FileSystemHandle, DOMException>(dirHandle.getDirectoryHandle(childName));\n\n        return findRes.mapErr(err => {\n            const error = new Error(`${ err.name }: '${ childName }' does not exist. Full path is '${ path }'`);\n            error.name = err.name;\n            return error;\n        });\n    });\n}\n","import { join, SEPARATOR } from '@std/path/posix';\nimport { Ok, type AsyncIOResult, type AsyncVoidIOResult } from 'happy-rusty';\nimport { validateExpiredDate } from '../shared/internal/mod.ts';\nimport { isFileHandle, TMP_DIR, type TempOptions } from '../shared/mod.ts';\nimport { createFile, mkdir, remove } from './core/mod.ts';\nimport { getDirHandle, removeHandle } from './internal/mod.ts';\n\n/**\n * Generates a unique temporary file or directory path without creating it.\n * Uses `crypto.randomUUID()` to ensure uniqueness.\n *\n * @param options - Options for generating the temporary path.\n * @returns The generated temporary path string.\n * @since 1.7.0\n * @see {@link mkTemp} for creating the temporary file/directory\n * @see {@link isTempPath} for checking if a path is temporary\n * @example\n * ```typescript\n * generateTempPath();                           // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000'\n * generateTempPath({ basename: 'cache' });      // '/tmp/cache-550e8400-e29b-41d4-a716-446655440000'\n * generateTempPath({ extname: '.txt' });        // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000.txt'\n * generateTempPath({ isDirectory: true });      // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000'\n * ```\n */\nexport function generateTempPath(options?: TempOptions): string {\n    const {\n        isDirectory = false,\n        basename = 'tmp',\n        extname = '',\n    } = options ?? {};\n\n    const base = basename ? `${ basename }-` : '';\n    const ext = isDirectory ? '' : extname;\n\n    // use uuid to generate a unique name\n    return join(TMP_DIR, base + crypto.randomUUID() + ext);\n}\n\n/**\n * Checks whether the path is a temporary path (under `/tmp`).\n *\n * @param path - The path to check.\n * @returns `true` if the path starts with `/tmp/`, otherwise `false`.\n * @since 1.7.2\n * @see {@link generateTempPath} for generating temporary paths\n * @see {@link TMP_DIR} for the temporary directory constant\n * @example\n * ```typescript\n * isTempPath('/tmp/file.txt');  // true\n * isTempPath('/data/file.txt'); // false\n * ```\n */\nexport function isTempPath(path: string): boolean {\n    return path.startsWith(TMP_DIR + SEPARATOR);\n}\n\n/**\n * Creates a temporary file or directory in the `/tmp` directory.\n * Uses `crypto.randomUUID()` to generate a unique name.\n *\n * @param options - Options for creating the temporary path.\n * @returns A promise that resolves to an `AsyncIOResult` containing the created path.\n * @since 1.7.0\n * @see {@link generateTempPath} for generating paths without creating\n * @see {@link deleteTemp} for removing the entire temp directory\n * @see {@link pruneTemp} for removing expired temp files\n * @example\n * ```typescript\n * // Create a temporary file\n * (await mkTemp())\n *     .inspect(path => console.log(path)); // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000'\n *\n * // Create a temporary directory\n * await mkTemp({ isDirectory: true });\n *\n * // Create with custom basename and extension\n * await mkTemp({ basename: 'cache', extname: '.json' });\n * ```\n */\nexport async function mkTemp(options?: TempOptions): AsyncIOResult<string> {\n    const path = generateTempPath(options);\n    const { isDirectory = false } = options ?? {};\n\n    const res = await (isDirectory ? mkdir : createFile)(path);\n\n    return res.and(Ok(path));\n}\n\n/**\n * Deletes the entire temporary directory (`/tmp`) and all its contents.\n *\n * **Warning:** When writing a `ReadableStream` to a new file, `writeFile` uses a temporary file\n * in `/tmp` before moving it to the target path. Calling `deleteTemp()` during such operations\n * may cause the write to fail. Ensure no stream writes are in progress before calling this function.\n *\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.7.0\n * @see {@link pruneTemp} for selective cleanup\n * @see {@link remove} for general file/directory removal\n * @example\n * ```typescript\n * (await deleteTemp())\n *     .inspect(() => console.log('Temporary directory deleted'));\n * ```\n */\nexport function deleteTemp(): AsyncVoidIOResult {\n    return remove(TMP_DIR);\n}\n\n/**\n * Removes expired files from the temporary directory.\n * Only removes direct children files whose `lastModified` time is before the specified date.\n *\n * **Note:** This function only removes files directly under `/tmp`, not subdirectories or their contents.\n * Use `deleteTemp()` to remove the entire temporary directory including all nested content.\n *\n * @param expired - Files modified before this date will be deleted.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.7.0\n * @see {@link deleteTemp} for removing all temp files\n * @see {@link mkTemp} for creating temp files\n * @example\n * ```typescript\n * // Remove files older than 24 hours\n * const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);\n * const result = await pruneTemp(yesterday);\n * ```\n */\nexport async function pruneTemp(expired: Date): AsyncVoidIOResult {\n    const expiredRes = validateExpiredDate(expired);\n    if (expiredRes.isErr()) return expiredRes;\n\n    // Get TMP_DIR handle to iterate and reuse for removal\n    const tmpDirHandleRes = await getDirHandle(TMP_DIR);\n\n    return tmpDirHandleRes.andTryAsync(async tmpDirHandle => {\n        const expiredTime = expired.getTime();\n        const tasks: Promise<void>[] = [];\n\n        // Only process direct children (no recursive), since mkTemp only creates top-level items\n        for await (const handle of tmpDirHandle.values()) {\n            if (!isFileHandle(handle)) {\n                continue;\n            }\n\n            tasks.push((async () => {\n                const file = await handle.getFile();\n                if (file.lastModified <= expiredTime) {\n                    return removeHandle(handle, tmpDirHandle);\n                }\n            })());\n        }\n\n        if (tasks.length > 0) {\n            await Promise.all(tasks);\n        }\n    });\n}","import { tryAsyncResult, type AsyncIOResult, type AsyncVoidIOResult } from 'happy-rusty';\nimport { readBlobBytesSync, textEncode, validateAbsolutePath, validateWriteFileContent } from '../../shared/internal/mod.ts';\nimport type { WriteFileContent, WriteOptions } from '../../shared/mod.ts';\nimport { getFileHandle, isNotFoundError, moveFileHandle } from '../internal/mod.ts';\nimport { generateTempPath } from '../tmp.ts';\nimport { remove } from './remove.ts';\n\n/**\n * Writes content to a file at the specified path.\n * Creates the file and parent directories if they don't exist (unless `create: false`).\n *\n * When writing a `ReadableStream` to a **new file**, the stream is first written to a temporary\n * file in `/tmp`, then moved to the target path upon success. This prevents leaving incomplete\n * files if the stream is interrupted. For existing files, writes are performed directly since\n * OPFS's transactional writes preserve the original content on failure.\n *\n * @param filePath - The absolute path of the file to write to.\n * @param contents - The content to write (string, ArrayBuffer, TypedArray, Blob, or ReadableStream<Uint8Array>).\n * @param options - Optional write options.\n * @param options.create - Whether to create the file if it doesn't exist. Default: `true`.\n * @param options.append - Whether to append to the file instead of overwriting. Default: `false`.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.0.0\n * @see {@link writeFileSync} for synchronous version\n * @see {@link appendFile} for appending to files\n * @see {@link writeJsonFile} for writing JSON data\n * @example\n * ```typescript\n * // Write string content\n * await writeFile('/path/to/file.txt', 'Hello, World!');\n *\n * // Write binary content\n * await writeFile('/path/to/file.bin', new Uint8Array([1, 2, 3]));\n *\n * // Append to existing file\n * await writeFile('/path/to/file.txt', '\\nMore content', { append: true });\n * ```\n */\nexport async function writeFile(filePath: string, contents: WriteFileContent, options?: WriteOptions): AsyncVoidIOResult {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    // Validate content type at entry point to prevent silent failures\n    const contentRes = validateWriteFileContent(contents);\n    if (contentRes.isErr()) return contentRes.asErr();\n\n    // For stream content, use temp file strategy when creating new files\n    if (isBinaryReadableStream(contents)) {\n        return writeStreamToFile(filePath, contents, options);\n    }\n\n    const fileHandleRes = await getWriteFileHandle(filePath, options);\n\n    return fileHandleRes.andTryAsync(fileHandle => {\n        const { append = false } = options ?? {};\n\n        // Prefer sync access in Worker for better performance\n        if (typeof fileHandle.createSyncAccessHandle === 'function') {\n            return writeDataViaSyncAccess(fileHandle, contents, append);\n        }\n\n        // Main thread fallback\n        return writeDataViaWritable(fileHandle, contents, append);\n    });\n}\n\n/**\n * Opens a file and returns a writable stream for writing contents.\n * Useful for writing large files without loading them entirely into memory.\n * The caller is responsible for closing the stream when done.\n *\n * @param filePath - The absolute path of the file to write.\n * @param options - Optional write options.\n * @returns A promise that resolves to an `AsyncIOResult` containing a `FileSystemWritableFileStream`.\n * @since 1.0.0\n * @see {@link writeFile} for general file writing\n * @example\n * ```typescript\n * (await openWritableFileStream('/path/to/large-file.bin'))\n *     .inspect(async stream => {\n *         try {\n *             await stream.write(new Uint8Array([1, 2, 3]));\n *             await stream.write(new Uint8Array([4, 5, 6]));\n *         } finally {\n *             await stream.close();\n *         }\n *     });\n * ```\n */\nexport async function openWritableFileStream(filePath: string, options?: WriteOptions): AsyncIOResult<FileSystemWritableFileStream> {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    const fileHandleRes = await getWriteFileHandle(filePath, options);\n\n    return fileHandleRes.andTryAsync(async fileHandle => {\n        const { append = false } = options ?? {};\n\n        const writable = await fileHandle.createWritable({\n            keepExistingData: append,\n        });\n\n        // If appending, seek to end\n        if (append) {\n            try {\n                const { size } = await fileHandle.getFile();\n                await writable.seek(size);\n            } catch (err) {\n                await writable.close();\n                throw err;\n            }\n        }\n\n        return writable;\n    });\n}\n\n/**\n * Gets a file handle for writing, with optional creation.\n */\nfunction getWriteFileHandle(filePath: string, options?: WriteOptions): AsyncIOResult<FileSystemFileHandle> {\n    const { create = true } = options ?? {};\n    return getFileHandle(filePath, { create });\n}\n\n/**\n * Type guard for detecting binary ReadableStream input for file writing.\n */\nfunction isBinaryReadableStream(x: unknown): x is ReadableStream<Uint8Array<ArrayBuffer>> {\n    return typeof ReadableStream !== 'undefined' && x instanceof ReadableStream;\n}\n\n/**\n * Writes a ReadableStream to a file with atomic semantics for new files.\n *\n * Strategy:\n * - If target file exists: write directly (OPFS transactional writes preserve original on failure)\n * - If target file doesn't exist: write to temp file first, then move to target on success\n *\n * This prevents leaving incomplete/empty files when stream is interrupted during new file creation.\n *\n * Assumes filePath is already validated.\n */\nasync function writeStreamToFile(\n    filePath: string,\n    stream: ReadableStream<Uint8Array<ArrayBuffer>>,\n    options?: WriteOptions,\n): AsyncVoidIOResult {\n    const { create = true, append = false } = options ?? {};\n\n    // Check if target file already exists\n    const existHandleRes = await getFileHandle(filePath, { create: false });\n\n    if (existHandleRes.isOk()) {\n        // File exists: write directly (transactional protection)\n        return writeStreamToHandle(existHandleRes.unwrap(), stream, append);\n    }\n\n    // File doesn't exist or unexpected error - return error if not creating or not a NotFoundError\n    if (!create || !isNotFoundError(existHandleRes.unwrapErr())) {\n        return existHandleRes.asErr();\n    }\n\n    // New file: use temp file strategy\n    const tempPath = generateTempPath();\n    const tempHandleRes = await getFileHandle(tempPath, { create: true });\n    if (tempHandleRes.isErr()) {\n        return tempHandleRes.asErr();\n    }\n\n    const tempHandle = tempHandleRes.unwrap();\n    const writeRes = await writeStreamToHandle(tempHandle, stream, false);\n\n    if (writeRes.isErr()) {\n        // Clean up temp file on failure\n        await remove(tempPath);\n        return writeRes;\n    }\n\n    // Move temp file to target path (this creates parent directories if needed)\n    const moveRes = await moveFileHandle(tempHandle, filePath);\n    if (moveRes.isErr()) {\n        // Clean up temp file\n        await remove(tempPath);\n    }\n\n    return moveRes;\n}\n\n/**\n * Writes a stream to a file handle using the appropriate API.\n */\nasync function writeStreamToHandle(\n    fileHandle: FileSystemFileHandle,\n    stream: ReadableStream<Uint8Array<ArrayBuffer>>,\n    append: boolean,\n): AsyncVoidIOResult {\n    return tryAsyncResult(() => {\n        // Prefer sync access in Worker for better performance\n        if (typeof fileHandle.createSyncAccessHandle === 'function') {\n            return writeStreamViaSyncAccess(fileHandle, stream, append);\n        }\n        // Main thread fallback\n        return writeStreamViaWritable(fileHandle, stream, append);\n    });\n}\n\n/**\n * Writes a ReadableStream to a file using the main thread's FileSystemWritableFileStream API.\n */\nasync function writeStreamViaWritable(\n    fileHandle: FileSystemFileHandle,\n    stream: ReadableStream<Uint8Array<ArrayBuffer>>,\n    append: boolean,\n): Promise<void> {\n    const writable = await fileHandle.createWritable({\n        keepExistingData: append,\n    });\n\n    if (append) {\n        const { size } = await fileHandle.getFile();\n        await writable.seek(size);\n    }\n\n    return stream.pipeTo(writable);\n}\n\n/**\n * Writes non-stream data to a file using the main thread's FileSystemWritableFileStream API.\n */\nasync function writeDataViaWritable(\n    fileHandle: FileSystemFileHandle,\n    contents: Exclude<WriteFileContent, ReadableStream>,\n    append: boolean,\n): Promise<void> {\n    const writable = await fileHandle.createWritable({\n        keepExistingData: append,\n    });\n\n    try {\n        const params: WriteParams = {\n            type: 'write',\n            data: contents,\n        };\n\n        if (append) {\n            const { size } = await fileHandle.getFile();\n            params.position = size;\n        }\n\n        return writable.write(params);\n    } finally {\n        await writable.close();\n    }\n}\n\n/**\n * Writes a ReadableStream to a file using the Worker's FileSystemSyncAccessHandle API.\n */\nasync function writeStreamViaSyncAccess(\n    fileHandle: FileSystemFileHandle,\n    stream: ReadableStream<Uint8Array<ArrayBuffer>>,\n    append: boolean,\n): Promise<void> {\n    const accessHandle = await fileHandle.createSyncAccessHandle();\n\n    try {\n        if (!append) {\n            accessHandle.truncate(0);\n        }\n\n        let position = append ? accessHandle.getSize() : 0;\n\n        for await (const chunk of stream) {\n            position = writeBytesWithRetry(accessHandle, chunk, position);\n        }\n    } finally {\n        accessHandle.close();\n    }\n}\n\n/**\n * Writes non-stream data to a file using the Worker's FileSystemSyncAccessHandle API.\n */\nasync function writeDataViaSyncAccess(\n    fileHandle: FileSystemFileHandle,\n    contents: Exclude<WriteFileContent, ReadableStream>,\n    append: boolean,\n): Promise<void> {\n    const accessHandle = await fileHandle.createSyncAccessHandle();\n\n    try {\n        // Always write as Uint8Array to avoid copying buffer.\n        let bytes: Uint8Array<ArrayBuffer>;\n        if (typeof contents === 'string') {\n            bytes = textEncode(contents);\n        } else if (contents instanceof Blob) {\n            bytes = readBlobBytesSync(contents);\n        } else if (contents instanceof ArrayBuffer) {\n            bytes = new Uint8Array(contents);\n        } else if (contents instanceof Uint8Array) {\n            bytes = contents as Uint8Array<ArrayBuffer>;\n        } else {\n            bytes = new Uint8Array(contents.buffer, contents.byteOffset, contents.byteLength);\n        }\n\n        if (!append) {\n            accessHandle.truncate(0);\n        }\n\n        const position = append ? accessHandle.getSize() : 0;\n        writeBytesWithRetry(accessHandle, bytes, position);\n    } finally {\n        accessHandle.close();\n    }\n}\n\n/**\n * Writes bytes to a FileSystemSyncAccessHandle with retry logic for partial writes.\n * Returns the final position after writing.\n */\nfunction writeBytesWithRetry(\n    accessHandle: FileSystemSyncAccessHandle,\n    bytes: Uint8Array<ArrayBuffer>,\n    position: number,\n): number {\n    let remaining = bytes;\n    let currentPosition = position;\n\n    while (remaining.byteLength > 0) {\n        const written = accessHandle.write(remaining, {\n            at: currentPosition,\n        });\n\n        currentPosition += written;\n\n        if (written >= remaining.byteLength) {\n            break;\n        }\n\n        // Create a new Uint8Array for the remaining part without copying buffer.\n        remaining = remaining.subarray(written);\n    }\n\n    return currentPosition;\n}\n","import { join, SEPARATOR } from '@std/path/posix';\nimport { Err, RESULT_FALSE, RESULT_VOID, tryAsyncResult, tryResult, type AsyncIOResult, type AsyncVoidIOResult } from 'happy-rusty';\nimport { validateAbsolutePath, validateExistsOptions } from '../shared/internal/mod.ts';\nimport { isDirectoryHandle, isFileHandle, type AppendOptions, type CopyOptions, type ExistsOptions, type MoveOptions, type WriteFileContent } from '../shared/mod.ts';\nimport { mkdir, readDir, readFile, remove, stat, writeFile } from './core/mod.ts';\nimport { aggregateResults, isNotFoundError, isRootDir, markParentDirsNonEmpty, moveFileHandle } from './internal/mod.ts';\n\n/**\n * Appends content to a file at the specified path.\n * Creates the file if it doesn't exist (unless `create: false` is specified).\n *\n * @param filePath - The absolute path of the file to append to.\n * @param contents - The content to append (string, ArrayBuffer, TypedArray, or Blob).\n * @param options - Optional append options.\n * @param options.create - Whether to create the file if it doesn't exist. Default: `true`.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.0.0\n * @see {@link writeFile} with `append: true` option\n * @example\n * ```typescript\n * // Append to file, create if doesn't exist (default behavior)\n * await appendFile('/path/to/log.txt', 'New log entry\\n');\n *\n * // Append only if file exists, fail if it doesn't\n * await appendFile('/path/to/log.txt', 'New log entry\\n', { create: false });\n * ```\n */\nexport function appendFile(filePath: string, contents: WriteFileContent, options?: AppendOptions): AsyncVoidIOResult {\n    return writeFile(filePath, contents, {\n        append: true,\n        create: options?.create,\n    });\n}\n\n/**\n * Copies a file or directory from one location to another, similar to `cp -r`.\n * Both source and destination must be of the same type (both files or both directories).\n *\n * @param srcPath - The absolute source path.\n * @param destPath - The absolute destination path.\n * @param options - Optional copy options.\n * @param options.overwrite - Whether to overwrite existing files. Default: `true`.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.7.0\n * @see {@link move} for moving instead of copying\n * @example\n * ```typescript\n * // Copy a file\n * await copy('/src/file.txt', '/dest/file.txt');\n *\n * // Copy a directory\n * await copy('/src/folder', '/dest/folder');\n *\n * // Copy without overwriting existing files\n * await copy('/src', '/dest', { overwrite: false });\n * ```\n */\nexport function copy(srcPath: string, destPath: string, options?: CopyOptions): AsyncVoidIOResult {\n    return mkDestFromSrc(srcPath, destPath, copyFileHandle, 'copy', options?.overwrite);\n}\n\n/**\n * Empties all contents of a directory at the specified path.\n * If the directory doesn't exist, it will be created.\n *\n * @param dirPath - The absolute path of the directory to empty.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.0.9\n * @see {@link mkdir} for creating directories\n * @see {@link remove} for removing directories\n * @example\n * ```typescript\n * await emptyDir('/path/to/directory');\n * ```\n */\nexport async function emptyDir(dirPath: string): AsyncVoidIOResult {\n    // For root directory, remove() clears all contents\n    if (isRootDir(dirPath)) {\n        return remove(dirPath);\n    }\n\n    // Check if path is a directory\n    const statRes = await stat(dirPath);\n    if (statRes.isErr()) {\n        // Create if not exist\n        return isNotFoundError(statRes.unwrapErr())\n            ? mkdir(dirPath)\n            : statRes.asErr();\n    }\n\n    if (isFileHandle(statRes.unwrap())) {\n        return Err(new Error(`Path '${ dirPath }' is not a directory`));\n    }\n\n    // Remove and recreate directory (OPFS has no metadata to preserve)\n    const removeRes = await remove(dirPath);\n    return removeRes.andThenAsync(() => mkdir(dirPath));\n}\n\n/**\n * Checks whether a file or directory exists at the specified path.\n *\n * @param path - The absolute path to check.\n * @param options - Optional existence options. Set `isDirectory: true` to check for directory,\n *                  or `isFile: true` to check for file. Cannot set both to `true`.\n * @returns A promise that resolves to an `AsyncIOResult<boolean>` indicating existence.\n * @since 1.0.0\n * @see {@link existsSync} for synchronous version\n * @see {@link stat} for getting the handle\n * @example\n * ```typescript\n * // Check if path exists (file or directory)\n * const exists = await exists('/path/to/entry');\n *\n * // Check if path exists and is a file\n * const isFile = await exists('/path/to/file', { isFile: true });\n *\n * // Check if path exists and is a directory\n * const isDir = await exists('/path/to/dir', { isDirectory: true });\n * ```\n */\nexport async function exists(path: string, options?: ExistsOptions): AsyncIOResult<boolean> {\n    const optionsRes = validateExistsOptions(options);\n    if (optionsRes.isErr()) return optionsRes.asErr();\n\n    const statRes = await stat(path);\n\n    return statRes.map(handle => {\n        const { isDirectory = false, isFile = false } = options ?? {};\n        const notExist =\n            (isDirectory && isFileHandle(handle))\n            || (isFile && isDirectoryHandle(handle));\n        return !notExist;\n    }).orElse(err => {\n        return isNotFoundError(err) ? RESULT_FALSE : statRes.asErr();\n    });\n}\n\n/**\n * Moves a file or directory from one location to another.\n * Both source and destination must be of the same type (both files or both directories).\n *\n * @param srcPath - The absolute source path.\n * @param destPath - The absolute destination path.\n * @param options - Optional move options.\n * @param options.overwrite - Whether to overwrite existing files. Default: `true`.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.8.0\n * @see {@link copy} for copying instead of moving\n * @example\n * ```typescript\n * // Move/rename a file\n * await move('/old/path/file.txt', '/new/path/file.txt');\n *\n * // Move a directory\n * await move('/old/folder', '/new/folder');\n * ```\n */\nexport async function move(srcPath: string, destPath: string, options?: MoveOptions): AsyncVoidIOResult {\n    const mkRes = await mkDestFromSrc(srcPath, destPath, moveFileHandle, 'move', options?.overwrite);\n    return mkRes.andThenAsync(() => remove(srcPath));\n}\n\n/**\n * Reads the content of a file as a `File` object (Blob with name).\n *\n * @param filePath - The absolute path of the file to read.\n * @returns A promise that resolves to an `AsyncIOResult` containing the `File` object.\n * @since 1.0.0\n * @see {@link readFile} with `encoding: 'blob'`\n * @see {@link uploadFile} for uploading files\n * @example\n * ```typescript\n * (await readBlobFile('/path/to/file.txt'))\n *     .inspect(file => console.log(file.name, file.size, file.type));\n * ```\n */\nexport function readBlobFile(filePath: string): AsyncIOResult<File> {\n    return readFile(filePath, {\n        encoding: 'blob',\n    });\n}\n\n/**\n * Reads a JSON file and parses its content.\n *\n * @template T - The expected type of the parsed JSON object.\n * @param filePath - The path of the JSON file to read.\n * @returns A promise that resolves to an `AsyncIOResult` containing the parsed JSON object.\n * @since 1.8.4\n * @see {@link writeJsonFile} for the reverse operation\n * @see {@link readTextFile} for reading raw text\n * @example\n * ```typescript\n * interface Config {\n *     name: string;\n *     version: number;\n * }\n * (await readJsonFile<Config>('/config.json'))\n *     .inspect(config => console.log(config.name));\n * ```\n */\nexport async function readJsonFile<T>(filePath: string): AsyncIOResult<T> {\n    const readRes = await readTextFile(filePath);\n    return readRes.andThen(text => tryResult<T, Error, [string]>(JSON.parse, text));\n}\n\n/**\n * Reads a file as a UTF-8 string.\n *\n * @param filePath - The absolute path of the file to read.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a string.\n * @since 1.0.0\n * @see {@link readFile} with `encoding: 'utf8'`\n * @see {@link readJsonFile} for reading JSON files\n * @example\n * ```typescript\n * (await readTextFile('/path/to/file.txt'))\n *     .inspect(content => console.log(content));\n * ```\n */\nexport function readTextFile(filePath: string): AsyncIOResult<string> {\n    return readFile(filePath, {\n        encoding: 'utf8',\n    });\n}\n\n/**\n * Writes an object to a file as JSON.\n *\n * @template T - The type of the object to write.\n * @param filePath - The absolute path of the file to write.\n * @param data - The object to serialize and write.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n * @since 1.0.0\n * @see {@link readJsonFile} for the reverse operation\n * @see {@link writeFile} for writing raw content\n * @example\n * ```typescript\n * const config = { name: 'app', version: 1 };\n * (await writeJsonFile('/config.json', config))\n *     .inspect(() => console.log('Config saved'));\n * ```\n */\nexport function writeJsonFile<T>(filePath: string, data: T): AsyncVoidIOResult {\n    const result = tryResult(JSON.stringify, data);\n    return result.andThenAsync(text => writeFile(filePath, text));\n}\n\n// #region Internal Types\n\n/**\n * Handler function type for processing source file to destination.\n *\n * @param srcFileHandle - The source file handle to process.\n * @param destFilePath - The destination file path.\n */\ntype HandleSrcFileToDest = (srcFileHandle: FileSystemFileHandle, destFilePath: string) => AsyncVoidIOResult;\n\n// #endregion\n\n// #region Internal Functions\n\n/**\n * Copies a file handle to a new path by reading and writing the file content.\n *\n * @param fileHandle - The file handle to copy.\n * @param destFilePath - The destination absolute path for the file.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n */\nasync function copyFileHandle(fileHandle: FileSystemFileHandle, destFilePath: string): AsyncVoidIOResult {\n    const fileRes = await tryAsyncResult(fileHandle.getFile());\n    return fileRes.andThenAsync(file => writeFile(destFilePath, file));\n}\n\n/**\n * Internal helper that copies or moves a file/directory from source to destination.\n *\n * Algorithm:\n * 1. Verify source exists via stat()\n * 2. Check if destination exists and validate type compatibility (file-to-file or dir-to-dir)\n * 3. For files: directly apply handler (copy or move)\n * 4. For directories: recursively process all entries in parallel\n * 5. Respect overwrite flag - skip if dest exists and overwrite=false\n *\n * @param srcPath - The source file/directory path.\n * @param destPath - The destination file/directory path.\n * @param handler - The function to handle file transfer (copy or move).\n * @param opName - The operation name for error messages ('copy' or 'move').\n * @param overwrite - Whether to overwrite existing files. Default: `true`.\n * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure.\n */\nasync function mkDestFromSrc(\n    srcPath: string,\n    destPath: string,\n    handler: HandleSrcFileToDest,\n    opName: 'copy' | 'move',\n    overwrite = true,\n): AsyncVoidIOResult {\n    const srcPathRes = validateAbsolutePath(srcPath);\n    if (srcPathRes.isErr()) return srcPathRes.asErr();\n    srcPath = srcPathRes.unwrap();\n\n    const destPathRes = validateAbsolutePath(destPath);\n    if (destPathRes.isErr()) return destPathRes.asErr();\n    destPath = destPathRes.unwrap();\n\n    // Prevent copying/moving a directory into itself\n    // For root directory, any destPath is a subdirectory\n    if (isRootDir(srcPath) || destPath.startsWith(srcPath + SEPARATOR) || destPath === srcPath) {\n        return Err(new Error(`Cannot ${ opName } '${ srcPath }' into itself '${ destPath }'`));\n    }\n\n    const statRes = await stat(srcPath);\n    if (statRes.isErr()) {\n        return statRes.asErr();\n    }\n\n    const srcHandle = statRes.unwrap();\n    // Track whether destination already exists (needed for overwrite logic)\n    let destExists = false;\n\n    const destHandleRes = await stat(destPath);\n    if (destHandleRes.isErr()) {\n        // Destination doesn't exist - that's OK unless it's an unexpected error\n        if (!isNotFoundError(destHandleRes.unwrapErr())) {\n            return destHandleRes.asErr();\n        }\n    } else {\n        destExists = true;\n        // Validate type compatibility: both must be files OR both must be directories\n        const destHandle = destHandleRes.unwrap();\n        if (\n            !(isFileHandle(srcHandle) && isFileHandle(destHandle))\n            && !(isDirectoryHandle(srcHandle) && isDirectoryHandle(destHandle))\n        ) {\n            return Err(new Error(`Source '${ srcPath }' and destination '${ destPath }' must both be files or both be directories`));\n        }\n    }\n\n    // Handle file source: apply handler directly\n    if (isFileHandle(srcHandle)) {\n        return (overwrite || !destExists) ? await handler(srcHandle, destPath) : RESULT_VOID;\n    }\n\n    // Handle directory source: recursively process all entries\n    const readDirRes = await readDir(srcPath, {\n        recursive: true,\n    });\n    if (readDirRes.isErr()) {\n        return readDirRes.asErr();\n    }\n\n    // Collect all tasks for parallel execution\n    const tasks: AsyncVoidIOResult[] = [];\n    const dirs: string[] = [];\n    const nonEmptyDirs = new Set<string>();\n\n    try {\n        for await (const { path, handle } of readDirRes.unwrap()) {\n            if (isFileHandle(handle)) {\n                const newFilePath = join(destPath, path);\n\n                // Wrap file processing in an async IIFE for parallel execution\n                tasks.push((async () => {\n                    let newPathExists = false;\n\n                    if (destExists) {\n                    // Destination dir exists, need to check each file individually\n                        const existsRes = await exists(newFilePath);\n                        if (existsRes.isErr()) {\n                            return existsRes.asErr();\n                        }\n\n                        newPathExists = existsRes.unwrap();\n                    }\n\n                    return overwrite || !newPathExists ? handler(handle, newFilePath) : RESULT_VOID;\n                })());\n\n                // Mark all parent directories as non-empty\n                markParentDirsNonEmpty(path, nonEmptyDirs);\n            } else {\n                dirs.push(path);\n            }\n        }\n    } catch (e) {\n        return Err(e as Error);\n    }\n\n    // Only create truly empty directories\n    for (const dir of dirs) {\n        if (!nonEmptyDirs.has(dir)) {\n            tasks.push(mkdir(join(destPath, dir)));\n        }\n    }\n\n    // Handle empty source directory case\n    if (tasks.length === 0 && !destExists) {\n        return mkdir(destPath);\n    }\n\n    // Wait for all tasks and return first error if any\n    return aggregateResults(tasks);\n}\n\n// #endregion\n","/**\n * Internal helper utilities for archive operations.\n *\n * @internal\n * @module\n */\n\nimport { Err, type AsyncIOResult } from 'happy-rusty';\nimport { validateAbsolutePath } from '../../shared/internal/mod.ts';\nimport { exists } from '../ext.ts';\n\n/**\n * Empty bytes constant, used for directory entries in zip or empty file content.\n */\nexport const EMPTY_BYTES: Uint8Array<ArrayBuffer> = new Uint8Array(0);\n\n/**\n * Validates that destDir is an absolute path and is not an existing file.\n * If destDir doesn't exist, that's fine (it will be created).\n * If destDir exists and is a directory, that's fine.\n * If destDir exists and is a file, return an error.\n *\n * @param destDir - The destination directory path to validate.\n * @returns An `AsyncIOResult` containing the normalized path, or an error.\n */\nexport async function validateDestDir(destDir: string): AsyncIOResult<string> {\n    const pathRes = validateAbsolutePath(destDir);\n    if (pathRes.isErr()) return pathRes;\n    destDir = pathRes.unwrap();\n\n    const existsRes = await exists(destDir, { isFile: true });\n\n    return existsRes.andThen(isFile => {\n        return isFile\n            ? Err(new Error(`Path '${ destDir }' is not a directory`))\n            : pathRes;\n    });\n}\n","import { fetchT } from '@happy-ts/fetch-t';\nimport { join, SEPARATOR } from '@std/path/posix';\nimport { AsyncUnzipInflate, Unzip, UnzipPassThrough, type UnzipFile } from 'fflate/browser';\nimport { Err, type AsyncIOResult, type AsyncVoidIOResult } from 'happy-rusty';\nimport { validateUrl } from '../../shared/internal/mod.ts';\nimport type { UnzipFromUrlRequestInit } from '../../shared/mod.ts';\nimport { mkdir, readFile, writeFile } from '../core/mod.ts';\nimport { aggregateResults, createEmptyBodyError, createEmptyFileError, markParentDirsNonEmpty } from '../internal/mod.ts';\nimport { EMPTY_BYTES, validateDestDir } from './helpers.ts';\n\n/**\n * Unzip a zip file to a directory using streaming decompression.\n * Equivalent to `unzip -o <zipFilePath> -d <destDir>`\n *\n * This function processes the zip file incrementally, minimizing memory usage.\n * Recommended for large files (>10MB). For small files, consider using {@link unzip} instead.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend.\n *\n * @param zipFilePath - Zip file path.\n * @param destDir - The directory to unzip to.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped.\n * @since 2.0.0\n * @see {@link unzip} for batch version (faster for small files)\n * @see {@link zipStream} for the reverse operation\n * @example\n * ```typescript\n * (await unzipStream('/downloads/large-archive.zip', '/extracted'))\n *     .inspect(() => console.log('Unzipped successfully'));\n * ```\n */\nexport async function unzipStream(zipFilePath: string, destDir: string): AsyncVoidIOResult {\n    return unzipStreamWith(\n        () => readFile(zipFilePath, { encoding: 'stream' }),\n        destDir,\n        createEmptyFileError,\n    );\n}\n\n/**\n * Unzip a remote zip file to a directory using streaming decompression.\n * Equivalent to `unzip -o <zipFilePath> -d <destDir>`\n *\n * This function processes the zip file incrementally, minimizing memory usage.\n * Recommended for large files (>10MB). For small files, consider using {@link unzipFromUrl} instead.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend.\n *\n * This API is built on `@happy-ts/fetch-t` for downloading the zip file.\n * `options` supports `timeout` and `onProgress` options.\n *\n * @param zipFileUrl - Zip file url.\n * @param destDir - The directory to unzip to.\n * @param requestInit - Optional request options.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped.\n * @since 2.0.0\n * @see {@link unzipFromUrl} for batch version (faster for small files)\n * @see {@link zipStreamFromUrl} for the reverse operation\n * @example\n * ```typescript\n * (await unzipStreamFromUrl('https://example.com/large-archive.zip', '/extracted'))\n *     .inspect(() => console.log('Remote zip file unzipped successfully'));\n *\n * // With timeout\n * (await unzipStreamFromUrl('https://example.com/archive.zip', '/extracted', { timeout: 30000 }))\n *     .inspect(() => console.log('Remote zip file unzipped successfully'));\n * ```\n */\nexport async function unzipStreamFromUrl(zipFileUrl: string | URL, destDir: string, requestInit?: UnzipFromUrlRequestInit): AsyncVoidIOResult {\n    const zipFileUrlRes = validateUrl(zipFileUrl);\n    if (zipFileUrlRes.isErr()) return zipFileUrlRes.asErr();\n    zipFileUrl = zipFileUrlRes.unwrap();\n\n    return unzipStreamWith(\n        () => fetchT(zipFileUrl, {\n            redirect: 'follow',\n            ...requestInit,\n            responseType: 'stream',\n            abortable: false,\n        }),\n        destDir,\n        createEmptyBodyError,\n    );\n}\n\n// #region Internal Functions\n\n/**\n * Common streaming unzip implementation for both local and remote sources.\n * @param getStream - Function to get the readable stream.\n * @param destDir - Destination directory path.\n * @param createEmptyError - Function to create error for empty data.\n */\nasync function unzipStreamWith(\n    getStream: () => AsyncIOResult<ReadableStream<Uint8Array<ArrayBuffer>> | null>,\n    destDir: string,\n    createEmptyError: () => Error,\n): AsyncVoidIOResult {\n    const destDirRes = await validateDestDir(destDir);\n    if (destDirRes.isErr()) return destDirRes.asErr();\n    destDir = destDirRes.unwrap();\n\n    const streamRes = await getStream();\n    if (streamRes.isErr()) return streamRes.asErr();\n    const stream = streamRes.unwrap();\n\n    // stream can be null for 204/304 responses\n    if (!stream) {\n        return Err(createEmptyError());\n    }\n\n    return streamUnzipTo(stream, destDir, createEmptyError);\n}\n\n/**\n * Stream unzip from a ReadableStream to destination directory.\n * Uses fflate's streaming Unzip API to minimize memory usage.\n *\n * @param stream - The readable stream containing zip data.\n * @param destDir - Destination directory path.\n * @param createEmptyError - Function to create error for empty data.\n */\nasync function streamUnzipTo(\n    stream: ReadableStream<Uint8Array<ArrayBuffer>>,\n    destDir: string,\n    createEmptyError: () => Error,\n): AsyncVoidIOResult {\n    // Track directories and files for proper handling\n    const tasks: AsyncVoidIOResult[] = [];\n    const dirs: string[] = [];\n    const nonEmptyDirs = new Set<string>();\n    let hasData = false;\n\n    const unzipper = new Unzip();\n    // Register decompression handlers\n    unzipper.register(UnzipPassThrough); // For stored (uncompressed) files\n    unzipper.register(AsyncUnzipInflate); // For deflated files\n\n    unzipper.onfile = file => {\n        const path = file.name;\n\n        if (path.at(-1) === SEPARATOR) {\n            // Directory entry - collect for later creation\n            dirs.push(path.slice(0, -1));\n        } else {\n            // Create a promise for this file's extraction\n            tasks.push(extractFile(file, join(destDir, path)));\n            // File entry - mark parent directories as non-empty\n            markParentDirsNonEmpty(path, nonEmptyDirs);\n        }\n    };\n\n    try {\n        for await (const chunk of stream) {\n            hasData = true;\n            unzipper.push(chunk, false);\n        }\n        // Signal end of stream\n        unzipper.push(EMPTY_BYTES, true);\n    } catch (err) {\n        return Err(err as Error);\n    }\n\n    // Empty stream check\n    if (!hasData) {\n        return Err(createEmptyError());\n    }\n\n    // Add empty directory creation tasks\n    for (const dir of dirs) {\n        if (!nonEmptyDirs.has(dir)) {\n            tasks.push(mkdir(join(destDir, dir)));\n        }\n    }\n\n    return aggregateResults(tasks);\n}\n\n/**\n * Extract a single file from the unzip stream using streaming write.\n *\n * @param file - The UnzipFile object from fflate.\n * @param destPath - The destination path for this file.\n */\nfunction extractFile(file: UnzipFile, destPath: string): AsyncVoidIOResult {\n    // Convert UnzipFile to ReadableStream\n    const stream = new ReadableStream<Uint8Array<ArrayBuffer>>({\n        start(controller) {\n            file.ondata = (err, data, final) => {\n                if (err) {\n                    controller.error(err);\n                    return;\n                }\n\n                controller.enqueue(data as Uint8Array<ArrayBuffer>);\n\n                if (final) {\n                    controller.close();\n                }\n            };\n\n            file.start();\n        },\n    });\n\n    return writeFile(destPath, stream);\n}\n\n// #endregion\n","import { fetchT } from '@happy-ts/fetch-t';\nimport { join, SEPARATOR } from '@std/path/posix';\nimport { unzip as decompress } from 'fflate/browser';\nimport { Err, type AsyncIOResult, type AsyncVoidIOResult, type VoidIOResult } from 'happy-rusty';\nimport { Future } from 'tiny-future';\nimport { validateUrl } from '../../shared/internal/mod.ts';\nimport type { UnzipFromUrlRequestInit } from '../../shared/mod.ts';\nimport { mkdir, readFile, writeFile } from '../core/mod.ts';\nimport { aggregateResults, createEmptyBodyError, createEmptyFileError, markParentDirsNonEmpty } from '../internal/mod.ts';\nimport { validateDestDir } from './helpers.ts';\n\n/**\n * Unzip a zip file to a directory using batch decompression.\n * Equivalent to `unzip -o <zipFilePath> -d <destDir>`\n *\n * This function loads the entire zip file into memory before decompression.\n * Faster for small files (<5MB). For large files, consider using {@link unzipStream} instead.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend.\n *\n * @param zipFilePath - Zip file path.\n * @param destDir - The directory to unzip to.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped.\n * @since 1.6.0\n * @see {@link unzipSync} for synchronous version\n * @see {@link unzipStream} for streaming version (better for large files)\n * @see {@link zip} for the reverse operation\n * @example\n * ```typescript\n * (await unzip('/downloads/archive.zip', '/extracted'))\n *     .inspect(() => console.log('Unzipped successfully'));\n * ```\n */\nexport async function unzip(zipFilePath: string, destDir: string): AsyncVoidIOResult {\n    return unzipWith(\n        () => readFile(zipFilePath),\n        destDir,\n        createEmptyFileError,\n    );\n}\n\n/**\n * Unzip a remote zip file to a directory using batch decompression.\n * Equivalent to `unzip -o <zipFilePath> -d <destDir>`\n *\n * This function loads the entire zip file into memory before decompression.\n * Faster for small files (<5MB). For large files, consider using {@link unzipStreamFromUrl} instead.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend.\n *\n * This API is built on `@happy-ts/fetch-t` for downloading the zip file.\n * `options` supports `timeout` and `onProgress` options.\n *\n * @param zipFileUrl - Zip file url.\n * @param destDir - The directory to unzip to.\n * @param requestInit - Optional request options.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped.\n * @since 1.7.0\n * @see {@link unzipStreamFromUrl} for streaming version (better for large files)\n * @see {@link zipFromUrl} for the reverse operation\n * @example\n * ```typescript\n * (await unzipFromUrl('https://example.com/archive.zip', '/extracted'))\n *     .inspect(() => console.log('Remote zip file unzipped successfully'));\n *\n * // With timeout\n * (await unzipFromUrl('https://example.com/archive.zip', '/extracted', { timeout: 5000 }))\n *     .inspect(() => console.log('Remote zip file unzipped successfully'));\n * ```\n */\nexport async function unzipFromUrl(zipFileUrl: string | URL, destDir: string, requestInit?: UnzipFromUrlRequestInit): AsyncVoidIOResult {\n    const zipFileUrlRes = validateUrl(zipFileUrl);\n    if (zipFileUrlRes.isErr()) return zipFileUrlRes.asErr();\n    zipFileUrl = zipFileUrlRes.unwrap();\n\n    return unzipWith(\n        () => fetchT(zipFileUrl, {\n            redirect: 'follow',\n            ...requestInit,\n            responseType: 'bytes',\n            abortable: false,\n        }),\n        destDir,\n        createEmptyBodyError,\n    );\n}\n\n// #region Internal Functions\n\n/**\n * Common unzip implementation for both local and remote sources.\n * @param getBytes - Function to get zip data.\n * @param destDir - Destination directory path.\n * @param createEmptyError - Function to create error for empty data.\n */\nasync function unzipWith(\n    getBytes: () => AsyncIOResult<Uint8Array<ArrayBuffer>>,\n    destDir: string,\n    createEmptyError: () => Error,\n): AsyncVoidIOResult {\n    const destDirRes = await validateDestDir(destDir);\n    if (destDirRes.isErr()) return destDirRes.asErr();\n    destDir = destDirRes.unwrap();\n\n    const bytesRes = await getBytes();\n\n    return bytesRes.andThenAsync(bytes => {\n        return bytes.byteLength === 0\n            ? Err(createEmptyError())\n            : batchUnzipTo(bytes, destDir);\n    });\n}\n\n/**\n * Unzip a buffer then write to the destination directory.\n * @param bytes - Zipped Uint8Array.\n * @param destDir - Destination directory path.\n */\nfunction batchUnzipTo(bytes: Uint8Array<ArrayBuffer>, destDir: string): AsyncVoidIOResult {\n    const future = new Future<VoidIOResult>();\n\n    decompress(bytes, async (err, unzipped) => {\n        if (err) {\n            future.resolve(Err(err));\n            return;\n        }\n\n        // Collect all tasks for parallel execution\n        const tasks: AsyncVoidIOResult[] = [];\n        const dirs: string[] = [];\n        const nonEmptyDirs = new Set<string>();\n\n        for (const path in unzipped) {\n            if (path.at(-1) === SEPARATOR) {\n                // Collect directory entries without trailing slash\n                dirs.push(path.slice(0, -1));\n            } else {\n                // File entry - writeFile will create parent directories automatically\n                tasks.push(writeFile(join(destDir, path), unzipped[path] as Uint8Array<ArrayBuffer>));\n                // Mark all parent directories as non-empty\n                markParentDirsNonEmpty(path, nonEmptyDirs);\n            }\n        }\n\n        // Only create truly empty directories\n        for (const dir of dirs) {\n            if (!nonEmptyDirs.has(dir)) {\n                tasks.push(mkdir(join(destDir, dir)));\n            }\n        }\n\n        future.resolve(aggregateResults(tasks));\n    });\n\n    return future.promise;\n}\n\n// #endregion\n","import { fetchT } from '@happy-ts/fetch-t';\nimport { basename, join, SEPARATOR } from '@std/path/posix';\nimport { Zip, ZipDeflate, ZipPassThrough, zipSync } from 'fflate/browser';\nimport { Err, tryAsyncResult, type AsyncVoidIOResult } from 'happy-rusty';\nimport { validateAbsolutePath, validateUrl } from '../../shared/internal/mod.ts';\nimport { isFileHandle, type DirEntry, type ZipFromUrlRequestInit, type ZipOptions } from '../../shared/mod.ts';\nimport { readDir, stat, writeFile } from '../core/mod.ts';\nimport { createEmptyBodyError, createNothingToZipError, peekStream } from '../internal/mod.ts';\nimport { EMPTY_BYTES } from './helpers.ts';\n\n/**\n * Zip a file or directory using streaming compression.\n * Equivalent to `zip -r <zipFilePath> <sourcePath>`.\n *\n * This function processes files sequentially with streaming read/write,\n * minimizing memory usage. Recommended for large directories or files.\n * For better speed with small files, consider using {@link zip} instead.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.\n *\n * @param sourcePath - The path to be zipped.\n * @param zipFilePath - The path to the zip file.\n * @param options - Options of zip.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped.\n * @since 2.0.0\n * @see {@link zip} for batch version (faster for small files)\n * @see {@link unzipStream} for the reverse operation\n * @example\n * ```typescript\n * // Stream zip a large directory\n * (await zipStream('/large-documents', '/backups/documents.zip'))\n *     .inspect(() => console.log('Directory zipped successfully'));\n * ```\n */\nexport async function zipStream(sourcePath: string, zipFilePath: string, options?: ZipOptions): AsyncVoidIOResult {\n    const zipFilePathRes = validateAbsolutePath(zipFilePath);\n    if (zipFilePathRes.isErr()) return zipFilePathRes.asErr();\n    zipFilePath = zipFilePathRes.unwrap();\n\n    const statRes = await stat(sourcePath);\n    if (statRes.isErr()) return statRes.asErr();\n\n    const sourceHandle = statRes.unwrap();\n    const sourceName = basename(sourcePath);\n\n    if (isFileHandle(sourceHandle)) {\n        // Single file - stream read and compress\n        return streamZipFile(sourceHandle, sourceName, zipFilePath);\n    }\n\n    // Directory - stream compress entries directly\n    const readDirRes = await readDir(sourcePath, { recursive: true });\n    if (readDirRes.isErr()) return readDirRes.asErr();\n\n    const { preserveRoot = true } = options ?? {};\n    const entries = readDirRes.unwrap();\n\n    // Peek first entry to check if directory is empty\n    const firstRes = await tryAsyncResult(entries.next());\n    if (firstRes.isErr()) return firstRes.asErr();\n\n    const first = firstRes.unwrap();\n    if (first.done && !preserveRoot) {\n        // Empty directory with preserveRoot=false - nothing to zip\n        // Matches zip command: `zip -r archive.zip .` in empty dir returns \"Nothing to do!\"\n        return Err(createNothingToZipError());\n    }\n\n    return streamZipEntries(\n        first,\n        entries,\n        sourceName,\n        zipFilePath,\n        preserveRoot,\n    );\n}\n\n/**\n * Zip a remote file using streaming compression.\n *\n * This function downloads and compresses the file in a streaming manner,\n * minimizing memory usage. Recommended for large remote files.\n * For small files, consider using {@link zipFromUrl} instead.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.\n *\n * This API is built on `@happy-ts/fetch-t` for downloading the source.\n * `requestInit` supports `timeout`, `onProgress`, and `filename` via {@link ZipFromUrlRequestInit}.\n *\n * @param sourceUrl - The url to be zipped.\n * @param zipFilePath - The path to the zip file.\n * @param requestInit - Optional request initialization parameters.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped.\n * @since 2.0.0\n * @see {@link zipFromUrl} for batch version (faster for small files)\n * @see {@link unzipStreamFromUrl} for the reverse operation\n * @example\n * ```typescript\n * // Stream zip a large remote file\n * (await zipStreamFromUrl('https://example.com/large-file.bin', '/backups/file.zip'))\n *     .inspect(() => console.log('Remote file zipped successfully'));\n * ```\n */\nexport async function zipStreamFromUrl(sourceUrl: string | URL, zipFilePath: string, requestInit?: ZipFromUrlRequestInit): AsyncVoidIOResult {\n    const sourceUrlRes = validateUrl(sourceUrl);\n    if (sourceUrlRes.isErr()) return sourceUrlRes.asErr();\n    sourceUrl = sourceUrlRes.unwrap();\n\n    const zipFilePathRes = validateAbsolutePath(zipFilePath);\n    if (zipFilePathRes.isErr()) return zipFilePathRes.asErr();\n    zipFilePath = zipFilePathRes.unwrap();\n\n    // Fetch as stream for true streaming\n    const fetchRes = await fetchT(sourceUrl, {\n        redirect: 'follow',\n        ...requestInit,\n        responseType: 'stream',\n        abortable: false,\n    });\n\n    if (fetchRes.isErr()) return fetchRes.asErr();\n\n    const stream = fetchRes.unwrap();\n    const { filename, keepEmptyBody = false } = requestInit ?? {};\n    // Use provided filename, or basename of pathname, or 'file' as fallback\n    const sourceName = filename ?? (sourceUrl.pathname !== SEPARATOR ? basename(sourceUrl.pathname) : 'file');\n\n    // Handle null stream (204/304 responses or HEAD requests)\n    if (!stream) {\n        return keepEmptyBody\n            ? zipEmptyFile(sourceName, zipFilePath)\n            : Err(createEmptyBodyError());\n    }\n\n    // Peek first chunk to check for empty body\n    const peekRes = await peekStream(stream);\n    if (peekRes.isErr()) return peekRes.asErr();\n\n    const peek = peekRes.unwrap();\n\n    if (peek.isEmpty) {\n        return keepEmptyBody\n            ? zipEmptyFile(sourceName, zipFilePath)\n            : Err(createEmptyBodyError());\n    }\n\n    return streamZipFromStream(peek.stream, sourceName, zipFilePath);\n}\n\n// #region Internal Functions\n\n/**\n * Create a Zip instance with callback that pipes to controller.\n */\nfunction createZip(controller: ReadableStreamDefaultController<Uint8Array<ArrayBuffer>>): Zip {\n    return new Zip((err, chunk, final) => {\n        if (err) {\n            controller.error(err);\n            return;\n        }\n\n        controller.enqueue(chunk as Uint8Array<ArrayBuffer>);\n\n        if (final) {\n            controller.close();\n        }\n    });\n}\n\n/**\n * Add an empty entry (directory or empty file) to zip.\n */\nfunction addEmptyEntry(zip: Zip, entryName: string): void {\n    const entry = new ZipPassThrough(entryName);\n    zip.add(entry);\n    entry.push(EMPTY_BYTES, true);\n}\n\n/**\n * Stream zip a single file handle.\n */\nasync function streamZipFile(fileHandle: FileSystemFileHandle, entryName: string, zipFilePath: string): AsyncVoidIOResult {\n    const fileRes = await tryAsyncResult(fileHandle.getFile());\n\n    return fileRes.andThenAsync(file => {\n        return file.size === 0\n            ? zipEmptyFile(entryName, zipFilePath)\n            : streamZipFromStream(file.stream(), entryName, zipFilePath);\n    });\n}\n\n/**\n * Stream zip from a ReadableStream source.\n */\nfunction streamZipFromStream(\n    sourceStream: ReadableStream<Uint8Array<ArrayBuffer>>,\n    entryName: string,\n    zipFilePath: string,\n): AsyncVoidIOResult {\n    const zipStream = new ReadableStream<Uint8Array<ArrayBuffer>>({\n        async start(controller) {\n            const zip = createZip(controller);\n            const entry = new ZipDeflate(entryName);\n            zip.add(entry);\n\n            try {\n                for await (const chunk of sourceStream) {\n                    entry.push(chunk, false);\n                }\n                entry.push(EMPTY_BYTES, true);\n                zip.end();\n            } catch (err) {\n                controller.error(err);\n            }\n        },\n    });\n\n    return writeFile(zipFilePath, zipStream);\n}\n\n/**\n * Create a zip with an empty file entry.\n *\n * This is preferred over streaming for empty files/bodies to avoid creating\n * unnecessary ReadableStream, Zip, and ZipDeflate instances.\n */\nfunction zipEmptyFile(entryName: string, zipFilePath: string): AsyncVoidIOResult {\n    const data = zipSync({\n        [entryName]: EMPTY_BYTES,\n    }) as Uint8Array<ArrayBuffer>;\n    return writeFile(zipFilePath, data);\n}\n\n/**\n * Stream zip multiple directory entries sequentially.\n */\nfunction streamZipEntries(\n    first: IteratorResult<DirEntry>,\n    rest: AsyncIterableIterator<DirEntry>,\n    sourceName: string,\n    zipFilePath: string,\n    preserveRoot: boolean,\n): AsyncVoidIOResult {\n    const zipStream = new ReadableStream<Uint8Array<ArrayBuffer>>({\n        async start(controller) {\n            const zip = createZip(controller);\n\n            // Add root directory entry first\n            if (preserveRoot) {\n                addEmptyEntry(zip, sourceName + SEPARATOR);\n            }\n\n            // Helper to process a single entry\n            const processEntry = async ({ path, handle }: DirEntry): Promise<void> => {\n                const entryName = preserveRoot ? join(sourceName, path) : path;\n\n                // Directory entry\n                if (!isFileHandle(handle)) {\n                    addEmptyEntry(zip, entryName + SEPARATOR);\n                    return;\n                }\n\n                // File entry - stream read and compress\n                const file = await handle.getFile();\n                const entry = new ZipDeflate(entryName);\n                zip.add(entry);\n\n                for await (const chunk of file.stream()) {\n                    entry.push(chunk, false);\n                }\n                entry.push(EMPTY_BYTES, true);\n            };\n\n            try {\n                // Process peeked first entry\n                if (!first.done) {\n                    await processEntry(first.value);\n                }\n\n                // Process remaining entries\n                for await (const dirEntry of rest) {\n                    await processEntry(dirEntry);\n                }\n\n                zip.end();\n            } catch (err) {\n                controller.error(err);\n            }\n        },\n    });\n\n    return writeFile(zipFilePath, zipStream);\n}\n\n// #endregion\n","import { fetchT } from '@happy-ts/fetch-t';\nimport { basename, join, SEPARATOR } from '@std/path/posix';\nimport { zip as compress, type AsyncZippable } from 'fflate/browser';\nimport { Err, Ok, tryAsyncResult, type AsyncIOResult, type AsyncVoidIOResult, type IOResult, type VoidIOResult } from 'happy-rusty';\nimport { Future } from 'tiny-future';\nimport { readBlobBytes, readBlobBytesSync, validateAbsolutePath, validateUrl } from '../../shared/internal/mod.ts';\nimport { isFileHandle, type ZipFromUrlRequestInit, type ZipOptions } from '../../shared/mod.ts';\nimport { readDir, stat, writeFile } from '../core/mod.ts';\nimport { createEmptyBodyError, createNothingToZipError } from '../internal/mod.ts';\nimport { EMPTY_BYTES } from './helpers.ts';\n\n/**\n * Zip a file or directory and write to a zip file.\n * Equivalent to `zip -r <zipFilePath> <sourcePath>`.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.\n * @param sourcePath - The path to be zipped.\n * @param zipFilePath - The path to the zip file.\n * @param options - Options of zip.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped.\n * @since 1.6.0\n * @see {@link zipSync} for synchronous version\n * @see {@link zipStream} for streaming version (better for large files)\n * @see {@link unzip} for the reverse operation\n * @example\n * ```typescript\n * // Zip a directory to a file\n * (await zip('/documents', '/backups/documents.zip'))\n *     .inspect(() => console.log('Directory zipped successfully'));\n * ```\n */\nexport function zip(sourcePath: string, zipFilePath: string, options?: ZipOptions): AsyncVoidIOResult;\n\n/**\n * Zip a file or directory and return the zip file data.\n * Equivalent to `zip -r <zipFilePath> <sourcePath>`.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.\n * @param sourcePath - The path to be zipped.\n * @param options - Options of zip.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped.\n * @since 1.6.0\n * @see {@link zipSync} for synchronous version\n * @see {@link zipStream} for streaming version (better for large files)\n * @see {@link unzip} for the reverse operation\n * @example\n * ```typescript\n * // Zip a directory and get the data\n * (await zip('/documents'))\n *     .inspect(zipData => console.log(`Zip size: ${ zipData.byteLength } bytes`));\n * ```\n */\nexport function zip(sourcePath: string, options?: ZipOptions): AsyncIOResult<Uint8Array<ArrayBuffer>>;\nexport async function zip(sourcePath: string, zipFilePath?: string | ZipOptions, options?: ZipOptions): Promise<ZipIOResult> {\n    if (typeof zipFilePath === 'string') {\n        const zipFilePathRes = validateAbsolutePath(zipFilePath);\n        if (zipFilePathRes.isErr()) return zipFilePathRes.asErr() as ZipIOResult;\n        zipFilePath = zipFilePathRes.unwrap();\n    } else {\n        options = zipFilePath;\n        zipFilePath = undefined;\n    }\n\n    const statRes = await stat(sourcePath);\n    if (statRes.isErr()) {\n        return statRes.asErr() as ZipIOResult;\n    }\n\n    const handle = statRes.unwrap();\n    const sourceName = basename(sourcePath);\n    const zippable: AsyncZippable = {};\n\n    if (isFileHandle(handle)) {\n        // file\n        const dataRes = await getFileDataByHandle(handle);\n        if (dataRes.isErr()) {\n            return dataRes.asErr() as ZipIOResult;\n        }\n        zippable[sourceName] = dataRes.unwrap();\n    } else {\n        // directory\n        const readDirRes = await readDir(sourcePath, {\n            recursive: true,\n        });\n        if (readDirRes.isErr()) {\n            return readDirRes.asErr() as ZipIOResult;\n        }\n\n        // default to preserve root\n        const { preserveRoot = true } = options ?? {};\n        const tasks: AsyncIOResult<{\n            entryName: string;\n            data: Uint8Array<ArrayBuffer>;\n        }>[] = [];\n\n        // Add root directory entry\n        if (preserveRoot) {\n            zippable[sourceName + SEPARATOR] = EMPTY_BYTES;\n        }\n\n        try {\n            for await (const { path, handle } of readDirRes.unwrap()) {\n                const entryName = preserveRoot ? join(sourceName, path) : path;\n\n                if (isFileHandle(handle)) {\n                    // file\n                    tasks.push((async () => {\n                        const dataRes = await getFileDataByHandle(handle);\n                        return dataRes.map(data => ({\n                            entryName,\n                            data,\n                        }));\n                    })());\n                } else {\n                    // directory - add entry with trailing slash and empty content\n                    zippable[entryName + SEPARATOR] = EMPTY_BYTES;\n                }\n            }\n        } catch (e) {\n            return Err(e as Error) as ZipIOResult;\n        }\n\n        if (tasks.length > 0) {\n            const results = await Promise.all(tasks);\n            for (const res of results) {\n                if (res.isErr()) {\n                    return res.asErr() as ZipIOResult;\n                }\n                const { entryName, data } = res.unwrap();\n                zippable[entryName] = data;\n            }\n        }\n    }\n\n    // Nothing to zip - matches standard zip command behavior\n    if (Object.keys(zippable).length === 0) {\n        return Err(createNothingToZipError()) as ZipIOResult;\n    }\n\n    return zipTo(zippable, zipFilePath);\n}\n\n/**\n * Zip a remote file and write to a zip file.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.\n *\n * This API is built on `@happy-ts/fetch-t` for downloading the source.\n * `requestInit` supports `timeout`, `onProgress`, and `filename` via {@link ZipFromUrlRequestInit}.\n *\n * @param sourceUrl - The url to be zipped.\n * @param zipFilePath - The path to the zip file.\n * @param requestInit - Optional request initialization parameters.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped.\n * @since 1.7.0\n * @see {@link zipStreamFromUrl} for streaming version (better for large files)\n * @see {@link unzipFromUrl} for the reverse operation\n * @example\n * ```typescript\n * // Zip a remote file to a local zip file\n * (await zipFromUrl('https://example.com/file.txt', '/backups/file.zip'))\n *     .inspect(() => console.log('Remote file zipped successfully'));\n * ```\n */\nexport function zipFromUrl(sourceUrl: string | URL, zipFilePath: string, requestInit?: ZipFromUrlRequestInit): AsyncVoidIOResult;\n\n/**\n * Zip a remote file and return the zip file data.\n *\n * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.\n *\n * This API is built on `@happy-ts/fetch-t` for downloading the source.\n * `requestInit` supports `timeout`, `onProgress`, and `filename` via {@link ZipFromUrlRequestInit}.\n *\n * @param sourceUrl - The url to be zipped.\n * @param requestInit - Optional request initialization parameters.\n * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped.\n * @since 1.7.0\n * @see {@link zipStreamFromUrl} for streaming version (better for large files)\n * @see {@link unzipFromUrl} for the reverse operation\n * @example\n * ```typescript\n * // Zip a remote file and get the data\n * (await zipFromUrl('https://example.com/file.txt'))\n *     .inspect(zipData => console.log(`Zip size: ${ zipData.byteLength } bytes`));\n * ```\n */\nexport function zipFromUrl(sourceUrl: string | URL, requestInit?: ZipFromUrlRequestInit): AsyncIOResult<Uint8Array<ArrayBuffer>>;\nexport async function zipFromUrl(sourceUrl: string | URL, zipFilePath?: string | ZipFromUrlRequestInit, requestInit?: ZipFromUrlRequestInit): Promise<ZipIOResult> {\n    const sourceUrlRes = validateUrl(sourceUrl);\n    if (sourceUrlRes.isErr()) return sourceUrlRes.asErr() as ZipIOResult;\n    sourceUrl = sourceUrlRes.unwrap();\n\n    if (typeof zipFilePath === 'string') {\n        const zipFilePathRes = validateAbsolutePath(zipFilePath);\n        if (zipFilePathRes.isErr()) return zipFilePathRes.asErr() as ZipIOResult;\n        zipFilePath = zipFilePathRes.unwrap();\n    } else {\n        requestInit = zipFilePath;\n        zipFilePath = undefined;\n    }\n\n    const fetchRes = await fetchT(sourceUrl, {\n        redirect: 'follow',\n        ...requestInit,\n        responseType: 'bytes',\n        abortable: false,\n    });\n\n    if (fetchRes.isErr()) {\n        return fetchRes.asErr() as ZipIOResult;\n    }\n\n    const bytes = fetchRes.unwrap();\n\n    const { filename, keepEmptyBody = false } = requestInit ?? {};\n\n    // body can be null for 204/304 responses or HEAD requests\n    if (!keepEmptyBody && bytes.byteLength === 0) {\n        return Err(createEmptyBodyError()) as ZipIOResult;\n    }\n\n    // Use provided filename, or basename of pathname, or 'file' as fallback\n    const sourceName = filename ?? (sourceUrl.pathname !== SEPARATOR ? basename(sourceUrl.pathname) : 'file');\n\n    return zipTo({\n        [sourceName]: bytes,\n    }, zipFilePath);\n}\n\n// #region Internal Types\n\n/**\n * Result type for zip operation.\n */\ntype ZipIOResult = IOResult<Uint8Array<ArrayBuffer>> | VoidIOResult;\n\n// #endregion\n\n// #region Internal Functions\n\n/**\n * Zip data and optionally write to the target path.\n * @param zippable - Zippable data.\n * @param zipFilePath - Target zip file path. If provided, writes to file; otherwise returns bytes.\n */\nfunction zipTo(zippable: AsyncZippable, zipFilePath?: string): Promise<ZipIOResult> {\n    const future = new Future<ZipIOResult>();\n\n    compress(zippable, {\n        consume: true,\n    }, async (err, bytesLike) => {\n        if (err) {\n            future.resolve(Err(err) as ZipIOResult);\n            return;\n        }\n\n        const bytes = bytesLike as Uint8Array<ArrayBuffer>;\n        // whether to write to file\n        if (zipFilePath) {\n            future.resolve(writeFile(zipFilePath, bytes));\n        } else {\n            future.resolve(Ok(bytes));\n        }\n    });\n\n    return future.promise;\n}\n\n/**\n * Reads the binary data from a file handle.\n * Uses FileReaderSync in Worker context for better performance,\n * falls back to async readBlobBytes in main thread.\n *\n * @param fileHandle - The `FileSystemFileHandle` to read from.\n * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a `Uint8Array`.\n */\nfunction getFileDataByHandle(fileHandle: FileSystemFileHandle): AsyncIOResult<Uint8Array<ArrayBuffer>> {\n    return tryAsyncResult(async () => {\n        const file = await fileHandle.getFile();\n        // Use sync read in Worker context, async in main thread\n        return typeof FileReaderSync === 'function'\n            ? readBlobBytesSync(file)\n            : readBlobBytes(file);\n    });\n}\n\n// #endregion\n","import { fetchT, type FetchResult, type FetchTask } from '@happy-ts/fetch-t';\nimport { extname } from '@std/path/posix';\nimport { Err, Ok } from 'happy-rusty';\nimport { validateAbsolutePath, validateUrl } from '../../shared/internal/mod.ts';\nimport type { DownloadFileTempResponse, DownloadRequestInit } from '../../shared/mod.ts';\nimport { createFile, writeFile } from '../core/mod.ts';\nimport { createEmptyBodyError, createFailedFetchTask, peekStream } from '../internal/mod.ts';\nimport { generateTempPath } from '../tmp.ts';\n\n/**\n * Downloads a file from a URL and saves it to a temporary file.\n * The returned response will contain the temporary file path.\n *\n * This API is built on `@happy-ts/fetch-t`.\n * - Supports `timeout` and `onProgress` via {@link DownloadRequestInit}\n * - Supports `keepEmptyBody` to allow saving empty responses\n * - Returns an abortable {@link FetchTask}\n *\n * @param fileUrl - The URL of the file to download.\n * @param requestInit - Optional request initialization parameters.\n * @returns A task that can be aborted and contains the result of the download.\n * @since 1.0.4\n * @see {@link uploadFile} for the reverse operation\n * @see {@link unzipFromUrl} for downloading and extracting zip files\n * @example\n * ```typescript\n * // Download to a temporary file\n * const task = downloadFile('https://example.com/file.pdf');\n * (await task.result)\n *     .inspect(({ tempFilePath }) => console.log(`File downloaded to: ${ tempFilePath }`));\n * ```\n */\nexport function downloadFile(fileUrl: string | URL, requestInit?: DownloadRequestInit): FetchTask<DownloadFileTempResponse>;\n\n/**\n * Downloads a file from a URL and saves it to the specified path.\n *\n * @param fileUrl - The URL of the file to download.\n * @param filePath - The path where the downloaded file will be saved.\n * @param requestInit - Optional request initialization parameters.\n * @returns A task that can be aborted and contains the result of the download.\n * @since 1.0.4\n * @see {@link uploadFile} for the reverse operation\n * @see {@link unzipFromUrl} for downloading and extracting zip files\n * @example\n * ```typescript\n * // Download to a specific path\n * const task = downloadFile('https://example.com/file.pdf', '/downloads/file.pdf');\n * (await task.result)\n *     .inspect(() => console.log('File downloaded successfully'));\n *\n * // Abort the download\n * task.abort();\n * ```\n */\nexport function downloadFile(fileUrl: string | URL, filePath: string, requestInit?: DownloadRequestInit): FetchTask<Response>;\nexport function downloadFile(fileUrl: string | URL, filePath?: string | DownloadRequestInit, requestInit?: DownloadRequestInit): FetchTask<Response | DownloadFileTempResponse> {\n    type T = FetchResult<Response | DownloadFileTempResponse>;\n\n    const fileUrlRes = validateUrl(fileUrl);\n    if (fileUrlRes.isErr()) return createFailedFetchTask(fileUrlRes);\n    fileUrl = fileUrlRes.unwrap();\n\n    let saveToTemp = false;\n\n    if (typeof filePath === 'string') {\n        const filePathRes = validateAbsolutePath(filePath);\n        if (filePathRes.isErr()) return createFailedFetchTask(filePathRes);\n        filePath = filePathRes.unwrap();\n    } else {\n        requestInit = filePath;\n        // save to a temporary file, preserve the extension from URL\n        filePath = generateTempPath({\n            extname: extname(fileUrl.pathname),\n        });\n        saveToTemp = true;\n    }\n\n    const fetchTask = fetchT(fileUrl, {\n        redirect: 'follow',\n        ...requestInit,\n        abortable: true,\n    });\n\n    const result = (async (): T => {\n        const responseRes = await fetchTask.result;\n\n        return responseRes.andThenAsync(async rawResponse => {\n            function okResult() {\n                return Ok(\n                    saveToTemp\n                        ? {\n                            tempFilePath: filePath as string,\n                            rawResponse,\n                        } satisfies DownloadFileTempResponse\n                        : rawResponse,\n                );\n            }\n\n            // Handle empty body: return error or create empty file\n            async function handleEmptyBody() {\n                const { keepEmptyBody = false } = requestInit ?? {};\n\n                if (!keepEmptyBody) {\n                    return Err(createEmptyBodyError());\n                }\n\n                const createRes = await createFile(filePath as string);\n                return createRes.and(okResult());\n            }\n\n            // Use peek approach for true streaming while detecting empty body\n            // Note: browsers don't conform to spec (body should be null for 204/HEAD responses)\n            // See: https://developer.mozilla.org/en-US/docs/Web/API/Response/body\n            const { body } = rawResponse;\n\n            // body is null - treat as empty\n            if (!body) {\n                return handleEmptyBody();\n            }\n\n            // Peek first chunk to detect empty stream\n            const peekRes = await peekStream(body);\n            if (peekRes.isErr()) return peekRes.asErr();\n\n            const peek = peekRes.unwrap();\n            if (peek.isEmpty) {\n                return handleEmptyBody();\n            }\n\n            // True streaming write with reconstructed stream\n            const writeRes = await writeFile(filePath, peek.stream);\n\n            return writeRes.and(okResult());\n        });\n    })();\n\n    return {\n        // FetchTask.abort() accepts `any` for the reason parameter to match\n        // the native AbortController.abort(reason?: any) signature\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        abort(reason?: any): void {\n            fetchTask.abort(reason);\n        },\n\n        get aborted(): boolean {\n            return fetchTask.aborted;\n        },\n\n        get result(): T {\n            return result;\n        },\n    };\n}","import { fetchT, type FetchResult, type FetchTask } from '@happy-ts/fetch-t';\nimport { basename } from '@std/path/posix';\nimport { Err } from 'happy-rusty';\nimport { validateAbsolutePath, validateUrl } from '../../shared/internal/mod.ts';\nimport type { UploadRequestInit } from '../../shared/mod.ts';\nimport { readBlobFile } from '../ext.ts';\nimport { createAbortError, createFailedFetchTask } from '../internal/mod.ts';\n\n/**\n * Uploads a file from the specified path to a URL.\n *\n * This API is built on `@happy-ts/fetch-t`.\n * - Supports `timeout` and `onProgress` via {@link UploadRequestInit}\n * - Returns an abortable {@link FetchTask}\n *\n * @param filePath - The path of the file to upload.\n * @param uploadUrl - The URL where the file will be uploaded.\n * @param requestInit - Optional request initialization parameters.\n * @returns A task that can be aborted and contains the result of the upload.\n * @since 1.0.6\n * @see {@link downloadFile} for the reverse operation\n * @see {@link readBlobFile} for reading file as Blob before upload\n * @example\n * ```typescript\n * const task = uploadFile('/documents/report.pdf', 'https://example.com/upload');\n * (await task.result)\n *     .inspect(() => console.log('File uploaded successfully'));\n *\n * // Abort the upload\n * task.abort();\n * ```\n */\nexport function uploadFile(filePath: string, uploadUrl: string | URL, requestInit?: UploadRequestInit): FetchTask<Response> {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return createFailedFetchTask(filePathRes);\n    filePath = filePathRes.unwrap();\n\n    const uploadUrlRes = validateUrl(uploadUrl);\n    if (uploadUrlRes.isErr()) return createFailedFetchTask(uploadUrlRes);\n    uploadUrl = uploadUrlRes.unwrap();\n\n    let aborted = false;\n    let fetchTask: FetchTask<Response>;\n\n    const result = (async (): FetchResult<Response> => {\n        const fileRes = await readBlobFile(filePath);\n\n        return fileRes.andThenAsync(async file => {\n            // maybe aborted\n            if (aborted) {\n                return Err(createAbortError());\n            }\n\n            const {\n                // default file name\n                filename = basename(filePath),\n                ...rest\n            } = requestInit ?? {};\n\n            const formData = new FormData();\n            formData.append(filename, file, filename);\n\n            fetchTask = fetchT(uploadUrl, {\n                method: 'POST',\n                ...rest,\n                abortable: true,\n                body: formData,\n            });\n\n            return fetchTask.result;\n        });\n    })();\n\n    return {\n        // FetchTask.abort() accepts `any` for the reason parameter to match\n        // the native AbortController.abort(reason?: any) signature\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        abort(reason?: any): void {\n            aborted = true;\n            fetchTask?.abort(reason);\n        },\n\n        get aborted(): boolean {\n            return aborted;\n        },\n\n        get result(): FetchResult<Response> {\n            return result;\n        },\n    };\n}","/**\n * Internal shared state for sync channel.\n * This module is not exported publicly.\n *\n * @internal\n */\n\nimport type { SyncMessenger } from '../protocol.ts';\n\n/**\n * State for sync channel.\n * - 'idle': Not initialized, can call connectSyncChannel or attachSyncChannel\n * - 'connecting': Connection in progress (only during connectSyncChannel)\n * - 'ready': Ready to use, messenger is available\n */\nexport type SyncChannelState = 'idle' | 'connecting' | 'ready';\n\n/**\n * Current state of the sync channel.\n */\nlet syncChannelState: SyncChannelState = 'idle';\n\n/**\n * Messenger instance for sync communication.\n * Only available when syncChannelState is 'ready'.\n */\nlet messenger: SyncMessenger | null = null;\n\n/**\n * Global timeout for synchronous I/O operations in milliseconds.\n */\nlet globalSyncOpTimeout = 1000;\n\n/**\n * Gets the current sync channel state.\n */\nexport function getSyncChannelState(): SyncChannelState {\n    return syncChannelState;\n}\n\n/**\n * Sets the sync channel state.\n */\nexport function setSyncChannelState(state: SyncChannelState): void {\n    syncChannelState = state;\n}\n\n/**\n * Gets the messenger instance.\n */\nexport function getMessenger(): SyncMessenger | null {\n    return messenger;\n}\n\n/**\n * Sets the messenger instance and marks the channel as ready.\n */\nexport function setMessenger(m: SyncMessenger): void {\n    messenger = m;\n    syncChannelState = 'ready';\n}\n\n/**\n * Gets the global sync operation timeout.\n */\nexport function getGlobalSyncOpTimeout(): number {\n    return globalSyncOpTimeout;\n}\n\n/**\n * Sets the global sync operation timeout.\n */\nexport function setGlobalSyncOpTimeout(timeout: number): void {\n    globalSyncOpTimeout = timeout;\n}\n","/**\n * Binary protocol for synchronous communication between main thread and worker.\n * Uses SharedArrayBuffer with lock-based synchronization via Atomics.\n *\n * @internal\n * @module\n */\n\nimport { textDecode, textEncode } from '../shared/internal/mod.ts';\n\n// #region Internal Variables\n\n/**\n * Payload type markers for binary protocol.\n */\nconst PayloadType = {\n    /**\n     * Pure JSON payload, no binary data.\n     * Format: [type: 1B][json bytes]\n     */\n    JSON: 0,\n    /**\n     * JSON payload with separate binary data field.\n     * Binary data is stored separately to avoid JSON serialization overhead.\n     * Format: [type: 1B][json length: 4B][json bytes][binary bytes]\n     */\n    BINARY_JSON: 1,\n} as const;\n\n// #endregion\n\n/**\n * Operations that can be called from main thread to worker thread.\n * Each value corresponds to a specific file system operation.\n */\nexport const WorkerOp = {\n    // core\n    createFile: 0,\n    mkdir: 1,\n    move: 2,\n    readDir: 3,\n    readFile: 4,\n    remove: 5,\n    stat: 6,\n    writeFile: 7,\n    // ext\n    copy: 8,\n    emptyDir: 9,\n    exists: 10,\n    deleteTemp: 11,\n    mkTemp: 12,\n    pruneTemp: 13,\n    readBlobFile: 14,\n    unzip: 15,\n    zip: 16,\n} as const;\n\n/**\n * Worker operation type.\n */\nexport type WorkerOp = typeof WorkerOp[keyof typeof WorkerOp];\n\n/**\n * Main thread lock index in the Int32Array view of SharedArrayBuffer.\n * Used to synchronize main thread state.\n */\nexport const MAIN_LOCK_INDEX = 0;\n\n/**\n * Worker thread lock index in the Int32Array view of SharedArrayBuffer.\n * Used to synchronize worker thread state.\n */\nexport const WORKER_LOCK_INDEX = 1;\n\n/**\n * Data length index in the Int32Array view of SharedArrayBuffer.\n * Stores the byte length of the current payload.\n */\nexport const DATA_INDEX = 2;\n\n/**\n * Main thread locked value (waiting for response).\n */\nexport const MAIN_LOCKED = 1;\n\n/**\n * Main thread unlocked value (response ready or idle).\n * This is the default/initial state.\n */\nexport const MAIN_UNLOCKED = 0;\n\n/**\n * Worker thread unlocked value (request ready to process).\n * Intentionally equals MAIN_LOCKED to simplify state machine.\n */\nexport const WORKER_UNLOCKED = MAIN_LOCKED;\n\n/**\n * Encodes data to a binary buffer for cross-thread communication.\n * Uses JSON serialization with optional binary data separation.\n *\n * If the last element of the array is a Uint8Array, it is stored separately\n * to avoid JSON serialization overhead (which would convert to number[]).\n *\n * All requests/responses use array format: `[op, ...args]` or `[error, result]`.\n *\n * @param value - The array data to encode.\n * @returns A `Uint8Array` containing the encoded payload.\n */\nexport function encodePayload(value: unknown[]): Uint8Array<ArrayBuffer> {\n    const lastItem = value[value.length - 1];\n\n    // If the last element is a Uint8Array, store it separately\n    if (lastItem instanceof Uint8Array) {\n        // BINARY_JSON format: [type: 1B][json length: 4B][json bytes][binary bytes]\n        const jsonValue = value.slice(0, -1);\n        const json = textEncode(JSON.stringify(jsonValue));\n        const result = new Uint8Array(1 + 4 + json.byteLength + lastItem.byteLength);\n        result[0] = PayloadType.BINARY_JSON;\n        new DataView(result.buffer).setUint32(1, json.byteLength);\n        result.set(json, 5);\n        result.set(lastItem, 5 + json.byteLength);\n        return result;\n    }\n\n    // JSON format: [type: 1B][json bytes]\n    const json = textEncode(JSON.stringify(value));\n    const result = new Uint8Array(1 + json.byteLength);\n    result[0] = PayloadType.JSON;\n    result.set(json, 1);\n    return result;\n}\n\n/**\n * Decodes binary payload back to its original structure.\n * Reverses the `encodePayload` operation.\n *\n * For BINARY_JSON payloads, the binary data is restored as the last element.\n *\n * All requests/responses use array format: `[op, ...args]` or `[error, result]`.\n *\n * @template T - The expected type of the decoded data (must be an array type).\n * @param payload - The binary payload from SharedArrayBuffer to decode.\n * @returns The decoded array with Uint8Array<ArrayBuffer> restored as the last element if applicable.\n */\nexport function decodePayload<T extends unknown[]>(payload: Uint8Array<SharedArrayBuffer>): T {\n    const type = payload[0];\n\n    if (type === PayloadType.BINARY_JSON) {\n        // BINARY_JSON format: [type: 1B][json length: 4B][json bytes][binary bytes]\n        const jsonLen = new DataView(payload.buffer, payload.byteOffset + 1, 4).getUint32(0);\n        // Use slice() for both json and data:\n        // 1. TextDecoder cannot accept SharedArrayBuffer views (browser security restriction)\n        // 2. Returned data needs its own ArrayBuffer (caller may access .buffer property)\n        const json = payload.slice(5, 5 + jsonLen);\n        const data = payload.slice(5 + jsonLen);\n        const parsed: unknown[] = JSON.parse(textDecode(json));\n\n        // Restore binary data as the last element\n        parsed.push(data);\n\n        return parsed as T;\n    }\n\n    // JSON format: [type: 1B][json bytes]\n    // Use slice() because TextDecoder cannot accept SharedArrayBuffer views\n    return JSON.parse(textDecode(payload.slice(1)));\n}\n\n/**\n * Messenger for synchronous communication between main thread and worker thread.\n * Inspired by [memfs](https://github.com/streamich/memfs/blob/master/src/fsa-to-node/worker/SyncMessenger.ts).\n *\n * Uses a `SharedArrayBuffer` with lock-based synchronization via `Atomics`.\n *\n * Buffer Layout (all values are Int32 at 4-byte boundaries):\n * ```\n * Offset  Size    Field           Description\n * ------  ----    -----           -----------\n * 0       4       MAIN_LOCK       Main thread state (0=unlocked/ready, 1=locked/waiting)\n * 4       4       WORKER_LOCK     Worker thread state (0=locked/idle, 1=unlocked/processing)\n * 8       4       DATA_LENGTH     Length of payload data in bytes\n * 12      4       RESERVED        Reserved for future use\n * 16+     var     PAYLOAD         Actual request/response binary data\n * ```\n *\n * Communication Flow:\n * 1. Main thread writes request to PAYLOAD, sets DATA_LENGTH\n * 2. Main thread sets MAIN_LOCK=1 (locked), WORKER_LOCK=1 (unlocked)\n * 3. Worker sees WORKER_LOCK=1, reads request, processes it\n * 4. Worker writes response to PAYLOAD, sets DATA_LENGTH\n * 5. Worker sets WORKER_LOCK=0 (locked), MAIN_LOCK=0 (unlocked)\n * 6. Main thread sees MAIN_LOCK=0, reads response\n *\n * @example\n * ```typescript\n * // Create messenger with 1MB buffer\n * const sab = new SharedArrayBuffer(1024 * 1024);\n * const messenger = new SyncMessenger(sab);\n * ```\n */\nexport class SyncMessenger {\n    /**\n     * Header size in bytes: 4 Int32 values = 16 bytes.\n     * Payload data starts after this offset.\n     */\n    private static readonly HEADER_LENGTH = 4 * 4;\n\n    /**\n     * Int32 view for atomic lock operations.\n     * Layout: [MAIN_LOCK, WORKER_LOCK, DATA_LENGTH, RESERVED]\n     */\n    readonly i32a: Int32Array;\n\n    /**\n     * Maximum payload size in bytes.\n     * Calculated as: total buffer size - header length.\n     * Requests/responses exceeding this limit will fail.\n     */\n    readonly maxDataLength: number;\n\n    /**\n     * Uint8 view for reading/writing binary payload.\n     * Payload starts after the header.\n     */\n    private readonly u8a: Uint8Array<SharedArrayBuffer>;\n\n    /**\n     * Creates a new SyncMessenger instance.\n     *\n     * @param sab - The SharedArrayBuffer to use for cross-thread communication.\n     *              Must be created in the main thread and transferred to the worker.\n     */\n    constructor(sab: SharedArrayBuffer) {\n        this.i32a = new Int32Array(sab);\n        this.u8a = new Uint8Array(sab);\n        this.maxDataLength = sab.byteLength - SyncMessenger.HEADER_LENGTH;\n    }\n\n    /**\n     * Writes payload data to the buffer after the header.\n     *\n     * @param data - The payload data to write.\n     */\n    setPayload(data: Uint8Array): void {\n        this.u8a.set(data, SyncMessenger.HEADER_LENGTH);\n    }\n\n    /**\n     * Reads payload data from the buffer as a view.\n     *\n     * Note: Returns a subarray (view) of the SharedArrayBuffer.\n     * Caller must use slice() if they need to pass data to TextDecoder\n     * or return data to user code that may access .buffer property.\n     *\n     * @param length - The number of bytes to read.\n     * @returns A view into the SharedArrayBuffer payload region.\n     */\n    getPayload(length: number): Uint8Array<SharedArrayBuffer> {\n        return this.u8a.subarray(SyncMessenger.HEADER_LENGTH, SyncMessenger.HEADER_LENGTH + length);\n    }\n}","/**\n * Synchronous file system operations for main thread.\n * Uses SharedArrayBuffer to communicate with worker thread.\n *\n * @module\n */\n\nimport { Err, Ok, tryResult, type IOResult, type VoidIOResult } from 'happy-rusty';\nimport { textDecode, textEncode, validateAbsolutePath, validateExistsOptions, validateExpiredDate, validateWriteSyncFileContent } from '../shared/internal/mod.ts';\nimport { TIMEOUT_ERROR, type AppendOptions, type CopyOptions, type DirEntryLike, type ExistsOptions, type FileSystemHandleLike, type MoveOptions, type ReadDirSyncOptions, type ReadSyncFileContent, type ReadSyncOptions, type TempOptions, type WriteOptions, type WriteSyncFileContent, type ZipOptions } from '../shared/mod.ts';\nimport { getGlobalSyncOpTimeout, getMessenger, getSyncChannelState } from './channel/state.ts';\nimport type { ErrorLike, FileMetadata } from './defines.ts';\nimport { DATA_INDEX, decodePayload, encodePayload, MAIN_LOCK_INDEX, MAIN_LOCKED, MAIN_UNLOCKED, WORKER_LOCK_INDEX, WORKER_UNLOCKED, WorkerOp, type SyncMessenger } from './protocol.ts';\n\n/**\n * Synchronous version of `createFile`.\n * Creates a new empty file at the specified path.\n *\n * @param filePath - The absolute path of the file to create.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link createFile} for the async version.\n * @since 1.7.0\n * @example\n * ```typescript\n * createFileSync('/path/to/file.txt')\n *     .inspect(() => console.log('File created'));\n * ```\n */\nexport function createFileSync(filePath: string): VoidIOResult {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.createFile, filePath);\n}\n\n/**\n * Synchronous version of `mkdir`.\n * Creates a directory at the specified path, including any necessary parent directories.\n *\n * @param dirPath - The absolute path of the directory to create.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link mkdir} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * mkdirSync('/path/to/directory')\n *     .inspect(() => console.log('Directory created'));\n * ```\n */\nexport function mkdirSync(dirPath: string): VoidIOResult {\n    const dirPathRes = validateAbsolutePath(dirPath);\n    if (dirPathRes.isErr()) return dirPathRes.asErr();\n    dirPath = dirPathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.mkdir, dirPath);\n}\n\n/**\n * Synchronous version of `move`.\n * Moves a file or directory from one location to another.\n *\n * @param srcPath - The source path.\n * @param destPath - The destination path.\n * @param options - Optional move options.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link move} for the async version.\n * @since 1.8.0\n * @example\n * ```typescript\n * moveSync('/old/path/file.txt', '/new/path/file.txt')\n *     .inspect(() => console.log('File moved'));\n * ```\n */\nexport function moveSync(srcPath: string, destPath: string, options?: MoveOptions): VoidIOResult {\n    const srcPathRes = validateAbsolutePath(srcPath);\n    if (srcPathRes.isErr()) return srcPathRes.asErr();\n    srcPath = srcPathRes.unwrap();\n\n    const destPathRes = validateAbsolutePath(destPath);\n    if (destPathRes.isErr()) return destPathRes.asErr();\n    destPath = destPathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.move, srcPath, destPath, options);\n}\n\n/**\n * Synchronous version of `readDir`.\n * Reads the contents of a directory.\n *\n * **Note:** Returns `DirEntryLike[]` instead of `AsyncIterableIterator<DirEntry>` because:\n * 1. Sync API cannot return async iterators\n * 2. Native `FileSystemHandle` objects cannot be serialized across threads;\n *    `DirEntryLike` uses `FileSystemHandleLike` which is JSON-serializable\n *\n * @param dirPath - The absolute path of the directory to read.\n * @param options - Optional read options (e.g., recursive).\n * @returns An `IOResult` containing an array of directory entries.\n * @see {@link readDir} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * readDirSync('/documents')\n *     .inspect(entries => entries.forEach(e => console.log(e.path, e.handle.kind)));\n * ```\n */\nexport function readDirSync(dirPath: string, options?: ReadDirSyncOptions): IOResult<DirEntryLike[]> {\n    const dirPathRes = validateAbsolutePath(dirPath);\n    if (dirPathRes.isErr()) return dirPathRes.asErr();\n    dirPath = dirPathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.readDir, dirPath, options);\n}\n\n/**\n * Synchronous version of `readFile`.\n * Reads the content of a file as a `File` object (blob encoding).\n *\n * @param filePath - The absolute path of the file to read.\n * @param options - Read options with 'blob' encoding.\n * @returns An `IOResult` containing a `File` object.\n * @since 1.1.0\n * @example\n * ```typescript\n * readFileSync('/path/to/file.txt', { encoding: 'blob' })\n *     .inspect(file => console.log(file.name, file.size));\n * ```\n */\nexport function readFileSync(filePath: string, options: ReadSyncOptions & {\n    encoding: 'blob';\n}): IOResult<File>;\n/**\n * Synchronous version of `readFile`.\n * Reads the content of a file as a string (utf8 encoding).\n *\n * @param filePath - The absolute path of the file to read.\n * @param options - Read options with 'utf8' encoding.\n * @returns An `IOResult` containing the file content as a string.\n * @since 1.1.0\n * @example\n * ```typescript\n * readFileSync('/path/to/file.txt', { encoding: 'utf8' })\n *     .inspect(content => console.log(content));\n * ```\n */\nexport function readFileSync(filePath: string, options: ReadSyncOptions & {\n    encoding: 'utf8';\n}): IOResult<string>;\n/**\n * Synchronous version of `readFile`.\n * Reads the content of a file as a Uint8Array (default).\n *\n * @param filePath - The absolute path of the file to read.\n * @param options - Optional read options. Defaults to 'bytes' encoding.\n * @returns An `IOResult` containing the file content as a Uint8Array.\n * @since 1.1.0\n * @example\n * ```typescript\n * readFileSync('/path/to/file.bin')\n *     .inspect(bytes => console.log('First byte:', bytes[0]));\n * ```\n */\nexport function readFileSync(filePath: string, options?: ReadSyncOptions & {\n    encoding?: 'bytes';\n}): IOResult<Uint8Array<ArrayBuffer>>;\n/**\n * Synchronous version of `readFile`.\n * Reads the content of a file with the specified options.\n * This overload accepts any ReadOptions and returns the union of all possible content types.\n * Useful when the encoding is determined at runtime.\n *\n * @param filePath - The absolute path of the file to read.\n * @param options - Optional read options.\n * @returns An `IOResult` containing the file content.\n * @see {@link readFile} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * // When encoding is dynamic\n * const encoding = getUserPreference(); // 'utf8' | 'bytes' | ...\n * readFileSync('/path/to/file.txt', { encoding })\n *     .inspect(content => {\n *         // content type is ReadSyncFileContent (union type)\n *         if (typeof content === 'string') {\n *             console.log('Text:', content);\n *         } else if (content instanceof Uint8Array) {\n *             console.log('Bytes:', content.length);\n *         }\n *     });\n * ```\n */\nexport function readFileSync(filePath: string, options?: ReadSyncOptions): IOResult<ReadSyncFileContent>;\n/**\n * Synchronous version of `readFile`.\n * Reads the content of a file with the specified encoding.\n *\n * @param filePath - The absolute path of the file to read.\n * @param options - Optional read options.\n * @returns An `IOResult` containing the file content.\n * @see {@link readFile} for the async version.\n */\nexport function readFileSync(filePath: string, options?: ReadSyncOptions): IOResult<ReadSyncFileContent> {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    const encoding = options?.encoding;\n\n    // blob encoding: use readBlobFile for File object with metadata\n    if (encoding === 'blob') {\n        // Response is [metadata, Uint8Array] from binary protocol\n        const readRes = callWorkerOp<[FileMetadata, Uint8Array<ArrayBuffer>]>(WorkerOp.readBlobFile, filePath);\n        return readRes.map(([metadata, data]) => deserializeFile(metadata, data));\n    }\n\n    // bytes/utf8: always request bytes encoding from worker\n    // This avoids double encoding/decoding for utf8 (string -> bytes -> string)\n    const readRes = callWorkerOp<Uint8Array<ArrayBuffer>>(WorkerOp.readFile, filePath);\n    return readRes.map(bytes => {\n        if (encoding === 'utf8') {\n            return textDecode(bytes);\n        }\n        // 'bytes' or undefined (default)\n        return bytes;\n    });\n}\n\n/**\n * Synchronous version of `remove`.\n * Removes a file or directory at the specified path.\n *\n * @param path - The absolute path of the file or directory to remove.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link remove} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * removeSync('/path/to/file-or-directory')\n *     .inspect(() => console.log('Removed successfully'));\n * ```\n */\nexport function removeSync(path: string): VoidIOResult {\n    const pathRes = validateAbsolutePath(path);\n    if (pathRes.isErr()) return pathRes.asErr();\n    path = pathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.remove, path);\n}\n\n/**\n * Synchronous version of `stat`.\n * Retrieves metadata about a file or directory.\n *\n * **Note:** Returns `FileSystemHandleLike` instead of `FileSystemHandle` because\n * native `FileSystemHandle` objects cannot be serialized across threads.\n * `FileSystemHandleLike` is a plain object with `name` and `kind` properties.\n * For file entries, it also includes `size`, `type`, and `lastModified` -\n * use `isFileHandleLike()` to check and narrow the type.\n *\n * @param path - The absolute path to get status for.\n * @returns An `IOResult` containing a `FileSystemHandleLike` object.\n * @see {@link stat} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * statSync('/path/to/entry')\n *     .inspect(handle => console.log(`Kind: ${ handle.kind }, Name: ${ handle.name }`));\n * ```\n */\nexport function statSync(path: string): IOResult<FileSystemHandleLike> {\n    const pathRes = validateAbsolutePath(path);\n    if (pathRes.isErr()) return pathRes.asErr();\n    path = pathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.stat, path);\n}\n\n/**\n * Synchronous version of `writeFile`.\n * Writes content to a file at the specified path.\n *\n * @param filePath - The absolute path of the file to write.\n * @param contents - The content to write (ArrayBuffer, TypedArray, or string).\n * @param options - Optional write options.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link writeFile} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * // Write string content\n * writeFileSync('/path/to/file.txt', 'Hello, World!');\n *\n * // Write binary content\n * writeFileSync('/path/to/file.bin', new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function writeFileSync(filePath: string, contents: WriteSyncFileContent, options?: WriteOptions): VoidIOResult {\n    const filePathRes = validateAbsolutePath(filePath);\n    if (filePathRes.isErr()) return filePathRes.asErr();\n    filePath = filePathRes.unwrap();\n\n    // Validate content type at entry point to prevent silent failures\n    const contentRes = validateWriteSyncFileContent(contents);\n    if (contentRes.isErr()) return contentRes.asErr();\n\n    // Put Uint8Array as the last argument for binary protocol\n    return callWorkerOp(WorkerOp.writeFile, filePath, options, serializeWriteContents(contents));\n}\n\n/**\n * Synchronous version of `appendFile`.\n * Appends content to a file at the specified path.\n *\n * @param filePath - The absolute path of the file to append to.\n * @param contents - The content to append (ArrayBuffer, TypedArray, or string).\n * @param options - Optional append options.\n * @param options.create - Whether to create the file if it doesn't exist. Default: `true`.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link appendFile} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * // Append to file, create if doesn't exist (default behavior)\n * appendFileSync('/path/to/log.txt', 'New log entry\\n');\n *\n * // Append only if file exists, fail if it doesn't\n * appendFileSync('/path/to/log.txt', 'New log entry\\n', { create: false });\n * ```\n */\nexport function appendFileSync(filePath: string, contents: WriteSyncFileContent, options?: AppendOptions): VoidIOResult {\n    return writeFileSync(filePath, contents, {\n        append: true,\n        create: options?.create,\n    });\n}\n\n/**\n * Synchronous version of `copy`.\n * Copies a file or directory from one location to another.\n *\n * @param srcPath - The source path.\n * @param destPath - The destination path.\n * @param options - Optional copy options.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link copy} for the async version.\n * @since 1.7.0\n * @example\n * ```typescript\n * // Copy a file\n * copySync('/src/file.txt', '/dest/file.txt');\n *\n * // Copy without overwriting\n * copySync('/src', '/dest', { overwrite: false });\n * ```\n */\nexport function copySync(srcPath: string, destPath: string, options?: CopyOptions): VoidIOResult {\n    const srcPathRes = validateAbsolutePath(srcPath);\n    if (srcPathRes.isErr()) return srcPathRes.asErr();\n    srcPath = srcPathRes.unwrap();\n\n    const destPathRes = validateAbsolutePath(destPath);\n    if (destPathRes.isErr()) return destPathRes.asErr();\n    destPath = destPathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.copy, srcPath, destPath, options);\n}\n\n/**\n * Synchronous version of `emptyDir`.\n * Removes all contents of a directory.\n *\n * @param dirPath - The absolute path of the directory to empty.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link emptyDir} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * emptyDirSync('/path/to/directory');\n * ```\n */\nexport function emptyDirSync(dirPath: string): VoidIOResult {\n    const dirPathRes = validateAbsolutePath(dirPath);\n    if (dirPathRes.isErr()) return dirPathRes.asErr();\n    dirPath = dirPathRes.unwrap();\n\n    return callWorkerOp(WorkerOp.emptyDir, dirPath);\n}\n\n/**\n * Synchronous version of `exists`.\n * Checks whether a file or directory exists at the specified path.\n *\n * @param path - The absolute path to check.\n * @param options - Optional existence options (e.g., isDirectory, isFile).\n * @returns An `IOResult` containing `true` if exists, `false` otherwise.\n * @see {@link exists} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * existsSync('/path/to/file')\n *     .inspect(exists => exists && console.log('File exists'));\n * ```\n */\nexport function existsSync(path: string, options?: ExistsOptions): IOResult<boolean> {\n    const pathRes = validateAbsolutePath(path);\n    if (pathRes.isErr()) return pathRes.asErr();\n    path = pathRes.unwrap();\n\n    const optionsRes = validateExistsOptions(options);\n    if (optionsRes.isErr()) return optionsRes.asErr();\n\n    return callWorkerOp(WorkerOp.exists, path, options);\n}\n\n/**\n * Synchronous version of `deleteTemp`.\n * Deletes the temporary directory and all its contents.\n *\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link deleteTemp} for the async version.\n * @since 1.7.0\n * @example\n * ```typescript\n * deleteTempSync();\n * ```\n */\nexport function deleteTempSync(): VoidIOResult {\n    return callWorkerOp(WorkerOp.deleteTemp);\n}\n\n/**\n * Synchronous version of `mkTemp`.\n * Creates a temporary file or directory.\n *\n * @param options - Optional temp options (e.g., isDirectory, basename, extname).\n * @returns An `IOResult` containing the temporary path.\n * @see {@link mkTemp} for the async version.\n * @since 1.7.0\n * @example\n * ```typescript\n * mkTempSync({ extname: '.txt' })\n *     .inspect(path => console.log('Temp file:', path));\n * ```\n */\nexport function mkTempSync(options?: TempOptions): IOResult<string> {\n    return callWorkerOp(WorkerOp.mkTemp, options);\n}\n\n/**\n * Synchronous version of `pruneTemp`.\n * Removes expired files from the temporary directory.\n *\n * @param expired - Files with lastModified before this date will be removed.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link pruneTemp} for the async version.\n * @since 1.7.0\n * @example\n * ```typescript\n * // Remove files older than 24 hours\n * const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);\n * pruneTempSync(yesterday);\n * ```\n */\nexport function pruneTempSync(expired: Date): VoidIOResult {\n    const expiredRes = validateExpiredDate(expired);\n    if (expiredRes.isErr()) return expiredRes;\n\n    return callWorkerOp(WorkerOp.pruneTemp, expired);\n}\n\n/**\n * Synchronous version of `readBlobFile`.\n * Reads a file as a `File` object.\n *\n * @param filePath - The absolute path of the file to read.\n * @returns An `IOResult` containing a `File` object.\n * @see {@link readBlobFile} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * readBlobFileSync('/path/to/file.txt')\n *     .inspect(file => console.log(file.name, file.size, file.type));\n * ```\n */\nexport function readBlobFileSync(filePath: string): IOResult<File> {\n    return readFileSync(filePath, {\n        encoding: 'blob',\n    });\n}\n\n/**\n * Synchronous version of `readJsonFile`.\n * Reads and parses a JSON file.\n *\n * @template T - The expected type of the parsed JSON.\n * @param filePath - The absolute path of the JSON file to read.\n * @returns An `IOResult` containing the parsed JSON object.\n * @see {@link readJsonFile} for the async version.\n * @since 1.8.4\n * @example\n * ```typescript\n * interface Config { name: string; version: number }\n * readJsonFileSync<Config>('/config.json')\n *     .inspect(config => console.log(config.name));\n * ```\n */\nexport function readJsonFileSync<T>(filePath: string): IOResult<T> {\n    return readTextFileSync(filePath).andThen(contents => {\n        return tryResult<T, Error, [string]>(JSON.parse, contents);\n    });\n}\n\n/**\n * Synchronous version of `readTextFile`.\n * Reads a file as a UTF-8 string.\n *\n * @param filePath - The absolute path of the file to read.\n * @returns An `IOResult` containing the file content as a string.\n * @see {@link readTextFile} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * readTextFileSync('/path/to/file.txt')\n *     .inspect(content => console.log(content));\n * ```\n */\nexport function readTextFileSync(filePath: string): IOResult<string> {\n    return readFileSync(filePath, {\n        encoding: 'utf8',\n    });\n}\n\n/**\n * Synchronous version of `writeJsonFile`.\n * Writes an object to a file as JSON.\n *\n * @template T - The type of the object to write.\n * @param filePath - The absolute path of the file to write.\n * @param data - The object to serialize and write.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link writeJsonFile} for the async version.\n * @since 1.1.0\n * @example\n * ```typescript\n * const config = { name: 'app', version: 1 };\n * writeJsonFileSync('/config.json', config);\n * ```\n */\nexport function writeJsonFileSync<T>(filePath: string, data: T): VoidIOResult {\n    return tryResult(JSON.stringify, data)\n        .andThen(text => writeFileSync(filePath, text));\n}\n\n/**\n * Synchronous version of `unzip`.\n * Extracts a zip file to a directory.\n *\n * @param zipFilePath - The path to the zip file.\n * @param destDir - The directory to unzip to.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link unzip} for the async version.\n * @since 1.6.0\n * @example\n * ```typescript\n * unzipSync('/downloads/archive.zip', '/extracted');\n * ```\n */\nexport function unzipSync(zipFilePath: string, destDir: string): VoidIOResult {\n    const zipFilePathRes = validateAbsolutePath(zipFilePath);\n    if (zipFilePathRes.isErr()) return zipFilePathRes.asErr();\n    zipFilePath = zipFilePathRes.unwrap();\n\n    const destDirRes = validateAbsolutePath(destDir);\n    if (destDirRes.isErr()) return destDirRes.asErr();\n    destDir = destDirRes.unwrap();\n\n    return callWorkerOp(WorkerOp.unzip, zipFilePath, destDir);\n}\n\n/**\n * Synchronous version of `zip`.\n * Zips a file or directory and writes to a zip file.\n *\n * @param sourcePath - The path to zip.\n * @param zipFilePath - The destination zip file path.\n * @param options - Optional zip options.\n * @returns A `VoidIOResult` indicating success or failure.\n * @see {@link zip} for the async version.\n * @since 1.6.0\n * @example\n * ```typescript\n * zipSync('/documents', '/backups/documents.zip');\n * ```\n */\nexport function zipSync(sourcePath: string, zipFilePath: string, options?: ZipOptions): VoidIOResult;\n/**\n * Synchronous version of `zip`.\n * Zips a file or directory and returns the zip data.\n *\n * @param sourcePath - The path to zip.\n * @param options - Optional zip options.\n * @returns An `IOResult` containing the zip data as `Uint8Array`.\n * @see {@link zip} for the async version.\n * @since 1.6.0\n * @example\n * ```typescript\n * zipSync('/documents')\n *     .inspect(data => console.log('Zip size:', data.byteLength));\n * ```\n */\nexport function zipSync(sourcePath: string, options?: ZipOptions): IOResult<Uint8Array<ArrayBuffer>>;\n/**\n * Synchronous version of `zip`.\n * Zips a file or directory.\n *\n * @param sourcePath - The path to zip.\n * @param zipFilePath - Optional destination zip file path or options.\n * @param options - Optional zip options.\n * @returns An `IOResult` containing the result.\n * @see {@link zip} for the async version.\n * @since 1.6.0\n */\nexport function zipSync(sourcePath: string, zipFilePath?: string | ZipOptions, options?: ZipOptions): IOResult<Uint8Array<ArrayBuffer> | void> {\n    const sourcePathRes = validateAbsolutePath(sourcePath);\n    if (sourcePathRes.isErr()) return sourcePathRes.asErr();\n    sourcePath = sourcePathRes.unwrap();\n\n    // If zipFilePath is a string path, validate it too\n    if (typeof zipFilePath === 'string') {\n        const zipFilePathRes = validateAbsolutePath(zipFilePath);\n        if (zipFilePathRes.isErr()) return zipFilePathRes.asErr();\n        zipFilePath = zipFilePathRes.unwrap();\n    }\n\n    // Result is Uint8Array directly as the last element from binary protocol, or undefined for void result\n    return callWorkerOp(WorkerOp.zip, sourcePath, zipFilePath, options);\n}\n\n// #region Internal Functions\n\n/**\n * Deserializes an `ErrorLike` object back to an `Error` instance.\n *\n * @param error - The `ErrorLike` object to deserialize.\n * @returns An `Error` instance with the same name and message.\n */\nfunction deserializeError(error: ErrorLike): Error {\n    const err = new Error(error.message);\n    err.name = error.name;\n\n    return err;\n}\n\n/**\n * Deserializes file metadata and binary data to a `File` instance.\n * Binary data is now received as the last element from the binary protocol.\n *\n * @param metadata - The file metadata (name, type, lastModified).\n * @param data - The binary data as Uint8Array.\n * @returns A `File` instance with the given properties.\n */\nfunction deserializeFile(metadata: FileMetadata, data: Uint8Array<ArrayBuffer>): File {\n    return new File([data], metadata.name, {\n        type: metadata.type,\n        lastModified: metadata.lastModified,\n    });\n}\n\n/**\n * Serializes write contents to Uint8Array for binary protocol transport.\n * All content types are converted to Uint8Array for efficient binary transfer.\n *\n * @param contents - The content to serialize (ArrayBuffer, TypedArray, or string).\n * @returns Uint8Array containing the binary data.\n */\nfunction serializeWriteContents(contents: WriteSyncFileContent): Uint8Array<ArrayBuffer> {\n    if (contents instanceof Uint8Array) {\n        return contents as Uint8Array<ArrayBuffer>;\n    }\n    if (contents instanceof ArrayBuffer) {\n        return new Uint8Array(contents);\n    }\n    if (ArrayBuffer.isView(contents)) {\n        // Other TypedArray -> Uint8Array (handle potential byteOffset)\n        return new Uint8Array(contents.buffer, contents.byteOffset, contents.byteLength);\n    }\n    // String -> Uint8Array via TextEncoder\n    return textEncode(contents);\n}\n\n/**\n * Blocks execution until a condition is met or timeout occurs.\n * Uses busy-waiting, which is necessary for synchronous operations.\n *\n * @param condition - A function that returns `true` when the wait should end.\n * @returns A `VoidIOResult` - `Ok` if condition met, `Err` with TimeoutError if timed out.\n */\nfunction sleepUntil(condition: () => boolean): VoidIOResult {\n    const timeout = getGlobalSyncOpTimeout();\n    const start = performance.now();\n    while (!condition()) {\n        if (performance.now() - start > timeout) {\n            const error = new Error('Operation timed out');\n            error.name = TIMEOUT_ERROR;\n\n            return Err(error);\n        }\n    }\n\n    return Ok();\n}\n\n/**\n * Sends a synchronous request from main thread to worker and waits for response.\n * This function blocks the main thread until the worker responds.\n *\n * Communication Protocol:\n * 1. Lock main thread (set MAIN_LOCKED) to signal we're waiting\n * 2. Write request data and length to SharedArrayBuffer\n * 3. Wake worker by setting WORKER_UNLOCKED\n * 4. Busy-wait until worker signals completion (MAIN_UNLOCKED)\n * 5. Read response from SharedArrayBuffer\n *\n * @param messenger - The `SyncMessenger` instance for communication.\n * @param data - The request data as a `Uint8Array`.\n * @returns An `IOResult` containing the response data, or an error if the request is too large or times out.\n */\nfunction callWorkerFromMain(messenger: SyncMessenger, data: Uint8Array<ArrayBuffer>): IOResult<Uint8Array<SharedArrayBuffer>> {\n    const { i32a, maxDataLength } = messenger;\n    const requestLength = data.byteLength;\n\n    // check whether request is too large\n    if (requestLength > maxDataLength) {\n        return Err(new RangeError(`Request is too large: ${ requestLength } > ${ maxDataLength }. Consider increasing the size of SharedArrayBuffer`));\n    }\n\n    // Lock main thread - signal that we're waiting for a response\n    Atomics.store(i32a, MAIN_LOCK_INDEX, MAIN_LOCKED);\n\n    // Write payload: store length and data to SharedArrayBuffer\n    i32a[DATA_INDEX] = requestLength;\n    messenger.setPayload(data);\n\n    // Wake up worker by setting it to UNLOCKED\n    // Note: Atomics.notify() may not work reliably cross-thread, using store + busy-wait instead\n    // Atomics.notify(i32a, WORKER_LOCK_INDEX); // this may not work\n    Atomics.store(i32a, WORKER_LOCK_INDEX, WORKER_UNLOCKED);\n\n    // Busy-wait for worker to finish processing and unlock main thread\n    const waitResult = sleepUntil(() => Atomics.load(i32a, MAIN_LOCK_INDEX) === MAIN_UNLOCKED);\n    if (waitResult.isErr()) {\n        return waitResult.asErr();\n    }\n\n    // Worker has finished - read response data\n    const responseLength = i32a[DATA_INDEX];\n    const response = messenger.getPayload(responseLength);\n\n    return Ok(response);\n}\n\n/**\n * Calls a worker I/O operation synchronously.\n * Serializes the request, sends to worker, and deserializes the response.\n *\n * @template T - The expected return type.\n * @param op - The I/O operation enum value from `WorkerOp`.\n * @param args - Arguments to pass to the operation.\n * @returns The I/O operation result wrapped in `IOResult<T>`.\n */\nfunction callWorkerOp<T>(op: WorkerOp, ...args: unknown[]): IOResult<T> {\n    if (getSyncChannelState() !== 'ready') {\n        return Err(new Error('Sync channel not connected'));\n    }\n\n    const messenger = getMessenger() as SyncMessenger;\n\n    // Serialize request: [operation, ...arguments]\n    const request = [op, ...args];\n    const requestData = encodePayload(request);\n\n    return callWorkerFromMain(messenger, requestData)\n        .andThen(response => {\n            // Deserialize response: [error, result] or [error] if failed\n            // For binary protocol, if result contains Uint8Array, it's the last element\n            const decodedResponse = decodePayload<[Error, ...unknown[]]>(response);\n            const err = decodedResponse[0];\n            if (err) {\n                return Err(deserializeError(err));\n            }\n            // For single result, return decodedResponse[1]\n            // For multi-value result (like readBlobFile), return all elements after error\n            if (decodedResponse.length === 2) {\n                return Ok(decodedResponse[1] as T);\n            }\n            // Multi-value result: return slice from index 1\n            return Ok(decodedResponse.slice(1) as T);\n        });\n}\n\n// #endregion\n","/**\n * SyncChannel connection APIs.\n * Provides functions for connecting, attaching, and checking sync channel status.\n *\n * @module\n */\n\nimport { Err, Ok, RESULT_VOID, type AsyncIOResult, type VoidIOResult } from 'happy-rusty';\nimport { Future } from 'tiny-future';\nimport type { AttachSyncChannelOptions, ConnectSyncChannelOptions } from '../../shared/mod.ts';\nimport { SyncMessenger } from '../protocol.ts';\nimport { getSyncChannelState, setGlobalSyncOpTimeout, setMessenger, setSyncChannelState } from './state.ts';\n\n// #region Internal Variables\n\n/**\n * Default size of SharedArrayBuffer in bytes (1MB).\n */\nconst DEFAULT_BUFFER_LENGTH = 1024 * 1024;\n\n/**\n * Minimum required buffer size in bytes.\n * 16 bytes header + ~131 bytes for largest error response = 147 bytes.\n * Using 256 (power of 2) for better memory alignment.\n */\nconst MIN_BUFFER_LENGTH = 256;\n\n/**\n * Default timeout for sync operations in milliseconds.\n */\nconst DEFAULT_OP_TIMEOUT = 1000;\n\n// #endregion\n\n/**\n * Connects to a worker and establishes a sync channel for synchronous file system operations.\n * Must be called before using any sync API functions.\n *\n * @param worker - The worker to communicate with. Can be a `Worker` instance, a `URL`, or a URL string.\n * @param options - Optional configuration options for the sync channel.\n * @returns A promise that resolves with an `AsyncIOResult` containing the `SharedArrayBuffer` when the worker is ready.\n *          The returned buffer can be shared with other contexts (e.g., iframes) via `postMessage`.\n * @since 1.1.0\n * @example\n * ```typescript\n * // Connect to worker and get SharedArrayBuffer\n * const result = await SyncChannel.connect(\n *     new URL('./worker.js', import.meta.url),\n *     { sharedBufferLength: 1024 * 1024, opTimeout: 5000 }\n * );\n * result.inspect(sharedBuffer => {\n *     // Share with iframe\n *     iframe.contentWindow.postMessage({ sharedBuffer }, '*');\n * });\n * ```\n */\nexport async function connectSyncChannel(worker: Worker | URL | string, options?: ConnectSyncChannelOptions): AsyncIOResult<SharedArrayBuffer> {\n    const state = getSyncChannelState();\n    if (state === 'ready') {\n        return Err(new Error('Sync channel already connected'));\n    }\n    if (state === 'connecting') {\n        return Err(new Error('Sync channel is connecting'));\n    }\n\n    const {\n        sharedBufferLength = DEFAULT_BUFFER_LENGTH,\n        opTimeout = DEFAULT_OP_TIMEOUT,\n    } = options ?? {};\n\n    // check parameters\n    if (!(worker instanceof Worker || worker instanceof URL || (typeof worker === 'string' && worker))) {\n        return Err(new TypeError('worker must be a Worker, URL, or non-empty string'));\n    }\n    if (!(sharedBufferLength >= MIN_BUFFER_LENGTH && sharedBufferLength % 4 === 0)) {\n        return Err(new TypeError('sharedBufferLength must be at least 256 and a multiple of 4'));\n    }\n    if (!(Number.isInteger(opTimeout) && opTimeout > 0)) {\n        return Err(new TypeError('opTimeout must be a positive integer'));\n    }\n\n    // May throw if worker url is invalid\n    let workerAdapter: Worker;\n    try {\n        workerAdapter = worker instanceof Worker\n            ? worker\n            : new Worker(worker);\n    } catch (e) {\n        return Err(e as Error);\n    }\n\n    // Set state after all validations pass\n    setSyncChannelState('connecting');\n    setGlobalSyncOpTimeout(opTimeout);\n\n    const sab = new SharedArrayBuffer(sharedBufferLength);\n    const channel = new MessageChannel();\n\n    const future = new Future<SharedArrayBuffer>();\n\n    // Use MessageChannel for isolated communication\n    // port1 stays in main thread, port2 is transferred to worker\n    channel.port1.onmessage = (): void => {\n        setMessenger(new SyncMessenger(sab));\n        future.resolve(sab);\n    };\n\n    workerAdapter.postMessage({ port: channel.port2, sab }, [channel.port2]);\n\n    return Ok(await future.promise);\n}\n\n/**\n * Checks if the sync channel is ready to use.\n *\n * @returns `true` if ready, `false` otherwise.\n * @since 1.11.0\n * @example\n * ```typescript\n * if (!SyncChannel.isReady()) {\n *     await SyncChannel.connect(new URL('./worker.js', import.meta.url));\n * }\n * ```\n */\nexport function isSyncChannelReady(): boolean {\n    return getSyncChannelState() === 'ready';\n}\n\n/**\n * Attaches to an existing `SharedArrayBuffer` for synchronous file system operations.\n * Used to share a sync channel connection with other contexts (e.g., iframes).\n *\n * After calling this function, sync APIs (e.g., `readFileSync`, `writeFileSync`)\n * can be used in the current context without calling `connect`.\n *\n * @param sharedBuffer - The `SharedArrayBuffer` received from another context.\n * @param options - Optional configuration options.\n * @returns A `VoidIOResult` indicating success or failure.\n * @since 1.8.5\n * @example\n * ```typescript\n * // In iframe: receive SharedArrayBuffer from main page\n * window.addEventListener('message', (event) => {\n *     if (event.data.sharedBuffer) {\n *         const result = SyncChannel.attach(event.data.sharedBuffer, { opTimeout: 5000 });\n *         if (result.isOk()) {\n *             // Now sync APIs can be used\n *             const fileResult = readTextFileSync('/data/file.txt');\n *         }\n *     }\n * });\n * ```\n */\nexport function attachSyncChannel(sharedBuffer: SharedArrayBuffer, options?: AttachSyncChannelOptions): VoidIOResult {\n    const state = getSyncChannelState();\n    if (state === 'connecting') {\n        return Err(new Error('Cannot attach: sync channel is connecting'));\n    }\n\n    if (!(sharedBuffer instanceof SharedArrayBuffer)) {\n        return Err(new TypeError('sharedBuffer must be a SharedArrayBuffer'));\n    }\n\n    const { opTimeout = DEFAULT_OP_TIMEOUT } = options ?? {};\n    if (!(Number.isInteger(opTimeout) && opTimeout > 0)) {\n        return Err(new TypeError('opTimeout must be a positive integer'));\n    }\n\n    setGlobalSyncOpTimeout(opTimeout);\n    setMessenger(new SyncMessenger(sharedBuffer));\n\n    return RESULT_VOID;\n}\n","import { Err, RESULT_VOID, type AsyncIOResult, type VoidIOResult } from 'happy-rusty';\nimport {\n    copy, createFile,\n    deleteTemp,\n    emptyDir, exists,\n    mkdir, mkTemp, move,\n    pruneTemp,\n    readBlobFile, readDir, readFile, remove,\n    stat,\n    unzip,\n    writeFile,\n    zip,\n} from '../../async/mod.ts';\nimport { readBlobBytesSync } from '../../shared/internal/mod.ts';\nimport { isFileHandle, type DirEntry, type DirEntryLike, type FileSystemDirectoryHandleLike, type FileSystemFileHandleLike, type FileSystemHandleLike } from '../../shared/mod.ts';\nimport type { ErrorLike, FileMetadata } from '../defines.ts';\nimport { DATA_INDEX, decodePayload, encodePayload, MAIN_LOCK_INDEX, MAIN_UNLOCKED, SyncMessenger, WORKER_LOCK_INDEX, WORKER_UNLOCKED, WorkerOp } from '../protocol.ts';\n\n// #region Internal Variables\n\n/**\n * Worker thread locked value.\n * Default.\n */\nconst WORKER_LOCKED = MAIN_UNLOCKED;\n\n/**\n * Mapping of async operation enums to their corresponding OPFS functions.\n * Used by the worker loop to dispatch operations from the main thread.\n *\n * Key: `WorkerOp` value\n * Value: The async function to execute\n */\nconst opHandlers = {\n    [WorkerOp.createFile]: createFile,\n    [WorkerOp.mkdir]: mkdir,\n    [WorkerOp.move]: move,\n    [WorkerOp.readDir]: readDir,\n    [WorkerOp.readFile]: readFile,\n    [WorkerOp.remove]: remove,\n    [WorkerOp.stat]: stat,\n    [WorkerOp.writeFile]: writeFile,\n    [WorkerOp.copy]: copy,\n    [WorkerOp.emptyDir]: emptyDir,\n    [WorkerOp.exists]: exists,\n    [WorkerOp.deleteTemp]: deleteTemp,\n    [WorkerOp.mkTemp]: mkTemp,\n    [WorkerOp.pruneTemp]: pruneTemp,\n    [WorkerOp.readBlobFile]: readBlobFile,\n    [WorkerOp.unzip]: unzip,\n    [WorkerOp.zip]: zip,\n};\n\n/**\n * Cache the messenger instance.\n */\nlet messenger: SyncMessenger;\n\n/**\n * Flag to track if listenSyncChannel has been called.\n * Used to prevent multiple event listeners from being registered.\n */\nlet isListening = false;\n\n// #endregion\n\n/**\n * Starts listening for sync channel requests in a Web Worker.\n * Waits for a SharedArrayBuffer from the main thread and begins processing requests.\n *\n * @returns A `VoidIOResult` indicating success or failure.\n * @since 1.1.0\n * @example\n * ```typescript\n * // In worker.js\n * import { SyncChannel } from 'happy-opfs';\n * const result = SyncChannel.listen();\n * if (result.isErr()) {\n *     console.error('Failed to start listening:', result.unwrapErr());\n * }\n * ```\n */\nexport function listenSyncChannel(): VoidIOResult {\n    if (!isWorkerRuntime()) {\n        return Err(new Error('listenSyncChannel can only be called in Worker'));\n    }\n    if (isListening) {\n        return Err(new Error('Sync channel already listening'));\n    }\n\n    isListening = true;\n\n    const messageHandler = (event: MessageEvent<unknown>): void => {\n        const { data } = event;\n\n        // Ignore messages that are not SyncChannelInitMessage\n        if (!isSyncChannelInitMessage(data)) {\n            return;\n        }\n\n        // Remove listener after receiving valid init message\n        removeEventListener('message', messageHandler);\n\n        const { port, sab } = data;\n\n        messenger = new SyncMessenger(sab);\n\n        // Notify main thread that worker is ready via dedicated MessagePort\n        port.postMessage(null);\n\n        // Start waiting for requests\n        runWorkerLoop();\n    };\n\n    addEventListener('message', messageHandler);\n\n    return RESULT_VOID;\n}\n\n// #region Internal Types\n\n/**\n * Message sent from main thread to worker to initialize sync channel.\n * Uses MessageChannel for isolated communication.\n */\ninterface SyncChannelInitMessage {\n    /**\n     * MessagePort for dedicated communication back to main thread.\n     */\n    port: MessagePort;\n    /**\n     * SharedArrayBuffer for cross-thread synchronous communication.\n     */\n    sab: SharedArrayBuffer;\n}\n\n// #endregion\n\n// #region Internal Functions\n\n/**\n * Checks whether the code is running in a Web Worker context.\n */\nfunction isWorkerRuntime(): boolean {\n    return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;\n}\n\n/**\n * Type guard to check if a message is a SyncChannelInitMessage.\n * @param data - The message data to check.\n * @returns `true` if the message is a valid SyncChannelInitMessage.\n */\nfunction isSyncChannelInitMessage(data: unknown): data is SyncChannelInitMessage {\n    if (data == null || typeof data !== 'object') {\n        return false;\n    }\n\n    const message = data as SyncChannelInitMessage;\n    return message.port instanceof MessagePort && message.sab instanceof SharedArrayBuffer;\n}\n\n/**\n * Serializes a `FileSystemHandle` to a plain object for cross-thread communication.\n *\n * @param handle - `FileSystemHandle` object.\n * @returns Serializable version of FileSystemHandle that is FileSystemHandleLike.\n */\nasync function serializeFileSystemHandle(handle: FileSystemHandle): Promise<FileSystemHandleLike> {\n    const { name } = handle;\n\n    if (isFileHandle(handle)) {\n        const file = await handle.getFile();\n        const { size, lastModified, type } = file;\n\n        const fileHandle: FileSystemFileHandleLike = {\n            name,\n            kind: 'file',\n            type,\n            size,\n            lastModified,\n        };\n\n        return fileHandle;\n    }\n\n    const handleLike: FileSystemDirectoryHandleLike = {\n        name,\n        kind: 'directory',\n    };\n\n    return handleLike;\n}\n\n/**\n * Serializes an `Error` object to a plain object for cross-thread communication.\n *\n * @param error - The `Error` object to serialize, or `null`.\n * @returns A serializable `ErrorLike` object, or `null` if input is `null`.\n */\nfunction serializeError(error: Error | null): ErrorLike | null {\n    return error ? {\n        name: error.name,\n        message: error.message,\n    } : error;\n}\n\n/**\n * Handles incoming requests from main thread and sends responses.\n * This function runs in the worker thread and processes one request.\n *\n * @param messenger - The `SyncMessenger` instance for communication.\n * @param transfer - Async function that processes request data and returns response data.\n */\nasync function respondToMainFromWorker(messenger: SyncMessenger, transfer: (data: Uint8Array<SharedArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>>): Promise<void> {\n    const { i32a, maxDataLength } = messenger;\n\n    // Busy-wait until main thread signals a request is ready\n    // Using busy-wait instead of Atomics.wait() because Atomics.notify() may not work reliably cross-thread\n    while (true) {\n        if (Atomics.load(i32a, WORKER_LOCK_INDEX) === WORKER_UNLOCKED) {\n            break;\n        }\n    }\n\n    // payload and length\n    const requestLength = i32a[DATA_INDEX];\n    const data = messenger.getPayload(requestLength);\n\n    // call async I/O operation\n    let response = await transfer(data);\n\n    // check whether response is too large\n    if (response.byteLength > maxDataLength) {\n        const message = `Response is too large: ${ response.byteLength } > ${ maxDataLength }. Consider increasing the size of SharedArrayBuffer`;\n\n        // Error response is guaranteed to fit since bufferLength >= 256 bytes\n        // and error response is ~147 bytes (16 header + 131 payload)\n        response = encodePayload([{\n            name: 'RangeError',\n            message,\n        }]);\n    }\n\n    // write response data\n    i32a[DATA_INDEX] = response.byteLength;\n    messenger.setPayload(response);\n\n    // lock worker thread\n    Atomics.store(i32a, WORKER_LOCK_INDEX, WORKER_LOCKED);\n\n    // wakeup main thread\n    Atomics.store(i32a, MAIN_LOCK_INDEX, MAIN_UNLOCKED);\n}\n\n/**\n * Deserializes request arguments based on operation type.\n * Binary data is received as the last element from the binary protocol.\n *\n * @param op - The operation type.\n * @param args - The arguments to deserialize.\n */\nfunction deserializeArgs(op: WorkerOp, args: unknown[]): void {\n    switch (op) {\n        case WorkerOp.writeFile: {\n            // Request format: [filePath, options?, Uint8Array]\n            // Expected args: [filePath, Uint8Array, options?]\n            // Move Uint8Array from last position to second position\n            const data = args.pop();\n            const options = args[1];\n            args[1] = data;\n            args[2] = options;\n            break;\n        }\n        case WorkerOp.readFile: {\n            // Always use bytes encoding (default) - adapter handles encoding conversion\n            // This avoids double encoding/decoding for utf8 (string -> bytes -> string)\n            args.length = 1;\n            break;\n        }\n        case WorkerOp.pruneTemp: {\n            // Date was serialized as ISO string, reconstruct Date object\n            args[0] = new Date(args[0] as Date);\n            break;\n        }\n        // Other operations need no deserialization\n    }\n}\n\n/**\n * Serializes a readDir result (async iterator) to an array of DirEntryLike.\n * Uses parallel processing for better performance since getFile() involves disk I/O.\n *\n * @param iterator - The async iterator from readDir.\n * @returns Promise resolving to array of serializable directory entries.\n */\nasync function serializeReadDirResult(iterator: AsyncIterableIterator<DirEntry>): Promise<DirEntryLike[]> {\n    // Collect and serialize handles in parallel - getFile() involves disk I/O\n    const tasks: Promise<DirEntryLike>[] = [];\n\n    for await (const { path, handle } of iterator) {\n        tasks.push((async () => ({\n            path,\n            handle: await serializeFileSystemHandle(handle),\n        }))());\n    }\n\n    return Promise.all(tasks);\n}\n\n/**\n * Serializes readBlobFile result to [metadata, Uint8Array] for binary protocol.\n *\n * @param file - The File object from readBlobFile.\n * @returns Array of [metadata, bytes] to be spread into response.\n */\nfunction serializeReadBlobFileResult(file: File): [FileMetadata, Uint8Array<ArrayBuffer>] {\n    const metadata: FileMetadata = {\n        name: file.name,\n        type: file.type,\n        lastModified: file.lastModified,\n    };\n    return [metadata, readBlobBytesSync(file)];\n}\n\n/**\n * Processes a single request from the main thread.\n *\n * @param data - The encoded request data.\n * @returns The encoded response data.\n */\nasync function processRequest(data: Uint8Array<SharedArrayBuffer>): Promise<Uint8Array<ArrayBuffer>> {\n    try {\n        // Decode the request: [operation, ...arguments]\n        const [op, ...args] = decodePayload<[WorkerOp, ...Parameters<typeof opHandlers[WorkerOp]>]>(data);\n\n        deserializeArgs(op, args);\n\n        const handle = opHandlers[op] as (...args: unknown[]) => AsyncIOResult<unknown>;\n        const res = await handle(...args);\n\n        if (res.isErr()) {\n            // Operation failed - encode error only: [serializedError]\n            return encodePayload([serializeError(res.unwrapErr())]);\n        }\n\n        const result = res.unwrap();\n        // Build response array: [null (no error), ...serialized result]\n        const response: [null, ...unknown[]] = [null];\n\n        // Serialize result based on operation type\n        switch (op) {\n            case WorkerOp.stat: {\n                response.push(await serializeFileSystemHandle(result as FileSystemHandle));\n                break;\n            }\n            case WorkerOp.readDir: {\n                response.push(await serializeReadDirResult(result as AsyncIterableIterator<DirEntry>));\n                break;\n            }\n            case WorkerOp.readBlobFile: {\n                response.push(...serializeReadBlobFileResult(result as File));\n                break;\n            }\n            default: {\n                // Result is void, boolean, string, or Uint8Array\n                response.push(result);\n            }\n        }\n\n        return encodePayload(response);\n    } catch (e) {\n        return encodePayload([serializeError(e as Error)]);\n    }\n}\n\n/**\n * Main loop that continuously processes requests from the main thread.\n * Runs indefinitely until the worker is terminated.\n */\nasync function runWorkerLoop(): Promise<void> {\n    // No try-catch needed:\n    // - processRequest catches all exceptions and returns encoded error response\n    // - respondToMainFromWorker never throws (error response always fits in buffer >= 256 bytes)\n    while (true) {\n        await respondToMainFromWorker(messenger, processRequest);\n    }\n}\n\n// #endregion\n"],"names":["Lazy","Err","normalize","Ok","RESULT_VOID","isBinaryReadableStream","LazyAsync","SEPARATOR","dirname","basename","ABORT_ERROR","tryAsyncResult","join","RESULT_FALSE","tryResult","fetchT","Unzip","UnzipPassThrough","AsyncUnzipInflate","Future","decompress","Zip","ZipPassThrough","zipStream","ZipDeflate","zipSync","handle","compress","extname","messenger","json","result","readRes","TIMEOUT_ERROR"],"mappings":";;;;;;;;;;AAaA,MAAM,OAAA,GAAUA,eAAA,CAAK,MAAM,IAAI,aAAa,CAAA;AAM5C,MAAM,OAAA,GAAUA,eAAA,CAAK,MAAM,IAAI,aAAa,CAAA;AAQrC,SAAS,WAAW,IAAA,EAAuC;AAC9D,EAAA,OAAO,OAAA,CAAQ,KAAA,EAAM,CAAE,MAAA,CAAO,IAAI,CAAA;AACtC;AAQO,SAAS,WAAW,IAAA,EAAuC;AAC9D,EAAA,OAAO,OAAA,CAAQ,KAAA,EAAM,CAAE,MAAA,CA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