import { AsyncVoidIOResult, AsyncIOResult, VoidIOResult, IOResult } from 'happy-rusty'; import { FetchInit, FetchTask } from '@happy-ts/fetch-t'; export { ABORT_ERROR, TIMEOUT_ERROR } from '@happy-ts/fetch-t'; /** * A constant representing the error thrown when a file or directory is not found. * Name of DOMException.NOT_FOUND_ERR. */ declare const NOT_FOUND_ERROR: "NotFoundError"; /** * Response body is empty (null), typically from 204/304 responses or HEAD requests. */ declare const EMPTY_BODY_ERROR: "EmptyBodyError"; /** * File content is empty (0 bytes). */ declare const EMPTY_FILE_ERROR: "EmptyFileError"; /** * Nothing to zip - empty directory with no entries. */ declare const NOTHING_TO_ZIP_ERROR: "NothingToZipError"; /** * A constant representing the root directory path. */ declare const ROOT_DIR: "/"; /** * A constant representing the temporary directory path. */ declare const TMP_DIR: "/tmp"; /** * Represents the possible content types that can be written to a file asynchronously. * Includes `BufferSource` (ArrayBuffer or TypedArray), `Blob`, `string`, or a binary `ReadableStream`. */ type WriteFileContent = BufferSource | Blob | string | ReadableStream>; /** * Represents the possible content types that can be written to a file synchronously. * Excludes `Blob` (requires async read) and `ReadableStream` (inherently async). */ type WriteSyncFileContent = Exclude>>; /** * Represents the possible content types that can be read from a file. * The actual type depends on the `encoding` option: * - `'bytes'` (default): `Uint8Array` * - `'utf8'`: `string` * - `'blob'`: `File` * - `'stream'`: `ReadableStream` */ type ReadFileContent = Uint8Array | File | string | ReadableStream>; /** * Represents the possible content types for synchronous file reads. * Excludes `ReadableStream` since it cannot be returned synchronously. */ type ReadSyncFileContent = Exclude>>; /** * Supported file encodings for reading files. * - `'bytes'` (default): Returns `Uint8Array` * - `'utf8'`: Returns decoded `string` * - `'blob'`: Returns `File` object with metadata * - `'stream'`: Returns `ReadableStream` for streaming reads */ type FileEncoding = 'bytes' | 'utf8' | 'blob' | 'stream'; /** * Supported file encodings for synchronous file reads. * Excludes `'stream'` since `ReadableStream` cannot be returned synchronously. */ type FileSyncEncoding = Exclude; /** * Options for reading files with specified encoding. */ interface ReadOptions { /** * The encoding to use for reading the file's content. * @defaultValue `'bytes'` */ encoding?: FileEncoding; } /** * Options for reading files synchronously. */ interface ReadSyncOptions { /** * The encoding to use for reading the file's content. * Excludes `'stream'` since `ReadableStream` cannot be returned synchronously. * @defaultValue `'bytes'` */ encoding?: FileSyncEncoding; } /** * Options for writing files, including flags for creation and appending. */ interface WriteOptions { /** * Whether to create the file if it does not exist. * @defaultValue `true` */ create?: boolean; /** * Whether to append to the file if it already exists. * @defaultValue `false` */ append?: boolean; } /** * Options for appending to files. */ interface AppendOptions { /** * Whether to create the file if it does not exist. * @defaultValue `true` */ create?: boolean; } /** * Options for reading directories synchronously. */ interface ReadDirSyncOptions { /** * Whether to recursively read the contents of subdirectories. * @defaultValue `false` */ recursive?: boolean; } /** * Options for reading directories. */ interface ReadDirOptions extends ReadDirSyncOptions { /** * An optional `AbortSignal` to abort the directory traversal. * When aborted, the iterator will stop yielding entries. */ signal?: AbortSignal; } /** * Options to determine the existence of a file or directory. * * The `isDirectory` and `isFile` options are mutually exclusive. * Setting both to `true` will result in a compile-time error (and runtime error as fallback). * * @example * ```typescript * // Check if path exists (any type) * await exists('/path'); * * // Check if path exists and is a directory * await exists('/path', { isDirectory: true }); * * // Check if path exists and is a file * await exists('/path', { isFile: true }); * ``` */ type ExistsOptions = { /** * Whether to check for the existence of a directory. * @defaultValue `false` */ isDirectory?: boolean; /** * Must be `false` or omitted when `isDirectory` is `true`. * @defaultValue `false` */ isFile?: false; } | { /** * Must be `false` or omitted when `isFile` is `true`. * @defaultValue `false` */ isDirectory?: false; /** * Whether to check for the existence of a file. * @defaultValue `false` */ isFile?: boolean; }; /** * Options for `copy`. */ interface CopyOptions { /** * Whether to overwrite the destination file if it already exists. * @defaultValue `true` */ overwrite?: boolean; } /** * Options for `move`. */ interface MoveOptions { /** * Whether to overwrite the destination file if it already exists. * @defaultValue `true` */ overwrite?: boolean; } /** * An entry returned by `readDir`. */ interface DirEntry { /** * The relative path of the entry from the `readDir` path parameter. * For non-recursive reads, this is just the entry name. * For recursive reads, this includes the subdirectory path. */ readonly path: string; /** * The `FileSystemHandle` of the entry. * Use `isFileHandle()` or `isDirectoryHandle()` to determine the type. */ readonly handle: FileSystemHandle; } /** * Serializable version of `DirEntry`. * * Unlike `DirEntry` which contains a native `FileSystemHandle`, this interface * uses `FileSystemHandleLike` which can be serialized to JSON for cross-thread * communication via `SharedArrayBuffer`. * * **Why this type exists:** * Native `FileSystemHandle` objects cannot be transferred between the main thread * and Web Workers through JSON serialization. This type provides a plain object * alternative that preserves the essential information. * * **When it's used:** * - Returned by `readDirSync()` in the sync API * - Internally used when worker sends directory entries back to main thread */ interface DirEntryLike { /** * The relative path of the entry from the `readDirSync` path parameter. */ readonly path: string; /** * The serializable handle-like object of the entry. * Use `isFileHandleLike()` to check if it's a file. */ readonly handle: FileSystemHandleLike; } /** * Serializable version of `FileSystemHandle`. * * Contains only the basic properties (`name`, `kind`) that identify a file system entry. * For file entries, use `FileSystemFileHandleLike` which includes additional metadata. * * **Why this type exists:** * Native `FileSystemHandle` is a browser API object with methods like `getFile()`, * `createWritable()`, etc. These methods and internal state cannot be serialized. * This type extracts only the serializable properties for cross-thread communication. * * **When it's used:** * - Returned by `statSync()` for directory entries * - Used as the `handle` property in `DirEntryLike` * - Internally converted from `FileSystemHandle` via `serializeFileSystemHandle()` */ interface FileSystemHandleLike { /** * The name of the file or directory. */ readonly name: string; /** * The kind of the entry: `'file'` or `'directory'`. */ readonly kind: FileSystemHandleKind; } /** * Serializable version of `FileSystemFileHandle` with file metadata. * * Extends `FileSystemHandleLike` with file-specific properties that are normally * obtained by calling `handle.getFile()` on a native `FileSystemFileHandle`. * * **Why this type exists:** * To provide file metadata (size, type, lastModified) without requiring async * operations. The native API requires `await handle.getFile()` to access these * properties, but this type pre-fetches and stores them. * * **When it's used:** * - Returned by `statSync()` for file entries * - Used in `DirEntryLike.handle` when the entry is a file * - Use `isFileHandleLike()` to narrow from `FileSystemHandleLike` */ interface FileSystemFileHandleLike extends FileSystemHandleLike { /** * The kind is always `'file'` for file handles. */ readonly kind: 'file'; /** * The MIME type of the file (e.g., `'text/plain'`, `'image/png'`). */ readonly type: string; /** * The size of the file in bytes. */ readonly size: number; /** * The last modified timestamp in milliseconds since Unix epoch. */ readonly lastModified: number; } /** * Serializable version of `FileSystemDirectoryHandle`. * * Contains only the basic properties (`name`, `kind`) that identify a directory entry. * This is effectively the same as `FileSystemHandleLike` but with a discriminated `kind`. * * **Why this type exists:** * Provides type safety when working with directory entries in sync APIs. * Use `isDirectoryHandleLike()` to narrow from `FileSystemHandleLike`. * * **When it's used:** * - Returned by `statSync()` for directory entries * - Used in `DirEntryLike.handle` when the entry is a directory */ interface FileSystemDirectoryHandleLike extends FileSystemHandleLike { /** * The kind is always `'directory'` for directory handles. */ readonly kind: 'directory'; } /** * Options for `mkTemp`. * * The `isDirectory` and `extname` options are mutually exclusive. * Setting both will result in a compile-time error; at runtime `extname` is ignored for directories. * * @example * ```typescript * // Create a temporary file * await mkTemp(); * * // Create a temporary directory * await mkTemp({ isDirectory: true }); * * // Create a temporary file with extension * await mkTemp({ extname: '.txt' }); * ``` */ type TempOptions = { /** * Whether to create a directory. * eg: `mktemp -d` * @defaultValue `false` */ isDirectory?: boolean; /** * The basename of the file or directory. * eg: `mktemp -t basename.XXX` * @defaultValue `tmp` */ basename?: string; /** * Must be omitted when `isDirectory` is `true`. */ extname?: never; } | { /** * Must be `false` or omitted when `extname` is provided. * @defaultValue `false` */ isDirectory?: false; /** * The basename of the file or directory. * eg: `mktemp -t basename.XXX` * @defaultValue `tmp` */ basename?: string; /** * The extension of the file. * eg: `mktemp --suffix .txt` */ extname?: string; }; /** * Options for `zip`. */ interface ZipOptions { /** * Whether to preserve the root directory name in the zip file structure. * - `true`: `/path/to/folder` → `folder/file1.txt`, `folder/file2.txt` * - `false`: `/path/to/folder` → `file1.txt`, `file2.txt` * @defaultValue `true` */ preserveRoot?: boolean; } /** * Request init options for network-related APIs. * * This type is based on `@happy-ts/fetch-t` and is used by: * - {@link downloadFile} * - {@link uploadFile} * - {@link zipFromUrl} * - {@link unzipFromUrl} * * It supports `timeout` and `onProgress` (see fetch-t docs for exact semantics). */ type FsRequestInit = Omit; /** * Request init options for {@link uploadFile}. */ interface UploadRequestInit extends FsRequestInit { /** * The filename to use when uploading the file. */ filename?: string; } /** * Request init options for {@link downloadFile}. */ interface DownloadRequestInit extends FsRequestInit { /** * Whether to keep empty response body (0 bytes) and save as an empty file. * - `true`: Empty response saves as an empty file * - `false`: Empty response returns an `EmptyBodyError` * @defaultValue `false` */ keepEmptyBody?: boolean; } /** * Request init options for {@link zipFromUrl}. */ interface ZipFromUrlRequestInit extends FsRequestInit { /** * The filename to use in the zip archive. * Defaults to the basename of the URL pathname, or 'file' if the pathname is '/'. */ filename?: string; /** * Whether to keep empty response body (0 bytes) and create a zip with an empty file entry. * - `true`: Empty response creates a zip with an empty file entry * - `false`: Empty response returns an `EmptyBodyError` * @defaultValue `false` */ keepEmptyBody?: boolean; } /** * Request init options for {@link unzipFromUrl} and {@link unzipStreamFromUrl}. */ type UnzipFromUrlRequestInit = FsRequestInit; /** * Result of {@link downloadFile} when the file is saved to a temporary path. */ interface DownloadFileTempResponse { /** * The temporary path of the downloaded file to be saved. */ readonly tempFilePath: string; /** * The raw response. */ readonly rawResponse: Response; } /** * Options for `SyncChannel.connect`. */ interface ConnectSyncChannelOptions { /** * The size of the `SharedArrayBuffer` in bytes. * Larger buffers can handle larger file operations but consume more memory. * Must be a multiple of 4 and at least 256 bytes. * @defaultValue `1048576` (1MB) */ sharedBufferLength?: number; /** * The timeout for each synchronous operation in milliseconds. * If an operation takes longer than this, a `TimeoutError` is thrown. * @defaultValue `1000` (1 second) */ opTimeout?: number; } /** * Options for `SyncChannel.attach`. */ interface AttachSyncChannelOptions { /** * The timeout for each synchronous operation in milliseconds. * If an operation takes longer than this, a `TimeoutError` is thrown. * @defaultValue `1000` (1 second) */ opTimeout?: number; } /** * Checks whether the given handle is a file handle. * * @param handle - The `FileSystemHandle` to check. * @returns `true` if the handle is a `FileSystemFileHandle`, otherwise `false`. * @since 1.0.0 * @see {@link isDirectoryHandle} for checking directory handles * @see {@link isFileHandleLike} for sync handle-like objects * @see {@link stat} for getting handles from paths * @example * ```typescript * (await stat('/path/to/file')) * .inspect(handle => isFileHandle(handle) && console.log('This is a file')); * ``` */ declare function isFileHandle(handle: FileSystemHandle): handle is FileSystemFileHandle; /** * Checks whether the given handle is a directory handle. * * @param handle - The `FileSystemHandle` to check. * @returns `true` if the handle is a `FileSystemDirectoryHandle`, otherwise `false`. * @since 1.0.0 * @see {@link isFileHandle} for checking file handles * @see {@link stat} for getting handles from paths * @example * ```typescript * (await stat('/path/to/dir')) * .inspect(handle => isDirectoryHandle(handle) && console.log('This is a directory')); * ``` */ declare function isDirectoryHandle(handle: FileSystemHandle): handle is FileSystemDirectoryHandle; /** * Checks whether the given handle-like object represents a file. * * @param handle - The `FileSystemHandleLike` object to check. * @returns `true` if the handle-like object represents a file, otherwise `false`. * @since 1.1.0 * @see {@link isFileHandle} for async file handles * @see {@link statSync} for getting sync handle-like objects * @example * ```typescript * statSync('/path/to/file') * .inspect(handle => isFileHandleLike(handle) && console.log(`File size: ${ handle.size }`)); * ``` */ declare function isFileHandleLike(handle: FileSystemHandleLike): handle is FileSystemFileHandleLike; /** * Checks whether the given handle-like object represents a directory. * * @param handle - The `FileSystemHandleLike` object to check. * @returns `true` if the handle-like object represents a directory, otherwise `false`. * @since 2.0.0 * @see {@link isDirectoryHandle} for async directory handles * @see {@link isFileHandleLike} for checking file handle-like objects * @see {@link statSync} for getting sync handle-like objects * @example * ```typescript * statSync('/path/to/dir') * .inspect(handle => isDirectoryHandleLike(handle) && console.log('This is a directory')); * * // Filter directories from readDirSync results * readDirSync('/documents') * .inspect(entries => { * const dirs = entries.filter(e => isDirectoryHandleLike(e.handle)); * console.log('Directories:', dirs.map(d => d.path)); * }); * ``` */ declare function isDirectoryHandleLike(handle: FileSystemHandleLike): handle is FileSystemDirectoryHandleLike; /** * Checks if the Origin Private File System (OPFS) is supported in the current environment. * OPFS requires a secure context (HTTPS or localhost) and browser support. * * @returns `true` if OPFS is supported, `false` otherwise. * @since 1.0.0 * @see {@link isSyncChannelSupported} for checking sync channel support * @example * ```typescript * if (isOPFSSupported()) { * // Use OPFS APIs * const result = await readFile('/path/to/file'); * } else { * console.warn('OPFS is not supported in this environment'); * } * ``` */ declare function isOPFSSupported(): boolean; /** * Checks if the SyncChannel (synchronous file system operations) is supported. * SyncChannel requires `SharedArrayBuffer` and `Atomics` which are only available * in secure contexts with proper COOP/COEP headers. * * **Required HTTP headers for cross-origin isolation:** * ``` * Cross-Origin-Opener-Policy: same-origin * Cross-Origin-Embedder-Policy: require-corp * ``` * * @returns `true` if SyncChannel is supported, `false` otherwise. * @since 2.0.0 * @see {@link isOPFSSupported} for checking OPFS support * @example * ```typescript * if (isSyncChannelSupported()) { * // Use sync APIs * const result = await SyncChannel.connect(worker); * const content = readFileSync('/path/to/file'); * } else { * console.warn('SyncChannel requires cross-origin isolation'); * } * ``` */ declare function isSyncChannelSupported(): boolean; /** * Unzip a zip file to a directory using streaming decompression. * Equivalent to `unzip -o -d ` * * This function processes the zip file incrementally, minimizing memory usage. * Recommended for large files (>10MB). For small files, consider using {@link unzip} instead. * * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend. * * @param zipFilePath - Zip file path. * @param destDir - The directory to unzip to. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped. * @since 2.0.0 * @see {@link unzip} for batch version (faster for small files) * @see {@link zipStream} for the reverse operation * @example * ```typescript * (await unzipStream('/downloads/large-archive.zip', '/extracted')) * .inspect(() => console.log('Unzipped successfully')); * ``` */ declare function unzipStream(zipFilePath: string, destDir: string): AsyncVoidIOResult; /** * Unzip a remote zip file to a directory using streaming decompression. * Equivalent to `unzip -o -d ` * * This function processes the zip file incrementally, minimizing memory usage. * Recommended for large files (>10MB). For small files, consider using {@link unzipFromUrl} instead. * * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend. * * This API is built on `@happy-ts/fetch-t` for downloading the zip file. * `options` supports `timeout` and `onProgress` options. * * @param zipFileUrl - Zip file url. * @param destDir - The directory to unzip to. * @param requestInit - Optional request options. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped. * @since 2.0.0 * @see {@link unzipFromUrl} for batch version (faster for small files) * @see {@link zipStreamFromUrl} for the reverse operation * @example * ```typescript * (await unzipStreamFromUrl('https://example.com/large-archive.zip', '/extracted')) * .inspect(() => console.log('Remote zip file unzipped successfully')); * * // With timeout * (await unzipStreamFromUrl('https://example.com/archive.zip', '/extracted', { timeout: 30000 })) * .inspect(() => console.log('Remote zip file unzipped successfully')); * ``` */ declare function unzipStreamFromUrl(zipFileUrl: string | URL, destDir: string, requestInit?: UnzipFromUrlRequestInit): AsyncVoidIOResult; /** * Unzip a zip file to a directory using batch decompression. * Equivalent to `unzip -o -d ` * * This function loads the entire zip file into memory before decompression. * Faster for small files (<5MB). For large files, consider using {@link unzipStream} instead. * * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend. * * @param zipFilePath - Zip file path. * @param destDir - The directory to unzip to. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped. * @since 1.6.0 * @see {@link unzipSync} for synchronous version * @see {@link unzipStream} for streaming version (better for large files) * @see {@link zip} for the reverse operation * @example * ```typescript * (await unzip('/downloads/archive.zip', '/extracted')) * .inspect(() => console.log('Unzipped successfully')); * ``` */ declare function unzip(zipFilePath: string, destDir: string): AsyncVoidIOResult; /** * Unzip a remote zip file to a directory using batch decompression. * Equivalent to `unzip -o -d ` * * This function loads the entire zip file into memory before decompression. * Faster for small files (<5MB). For large files, consider using {@link unzipStreamFromUrl} instead. * * Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend. * * This API is built on `@happy-ts/fetch-t` for downloading the zip file. * `options` supports `timeout` and `onProgress` options. * * @param zipFileUrl - Zip file url. * @param destDir - The directory to unzip to. * @param requestInit - Optional request options. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped. * @since 1.7.0 * @see {@link unzipStreamFromUrl} for streaming version (better for large files) * @see {@link zipFromUrl} for the reverse operation * @example * ```typescript * (await unzipFromUrl('https://example.com/archive.zip', '/extracted')) * .inspect(() => console.log('Remote zip file unzipped successfully')); * * // With timeout * (await unzipFromUrl('https://example.com/archive.zip', '/extracted', { timeout: 5000 })) * .inspect(() => console.log('Remote zip file unzipped successfully')); * ``` */ declare function unzipFromUrl(zipFileUrl: string | URL, destDir: string, requestInit?: UnzipFromUrlRequestInit): AsyncVoidIOResult; /** * Zip a file or directory using streaming compression. * Equivalent to `zip -r `. * * This function processes files sequentially with streaming read/write, * minimizing memory usage. Recommended for large directories or files. * For better speed with small files, consider using {@link zip} instead. * * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend. * * @param sourcePath - The path to be zipped. * @param zipFilePath - The path to the zip file. * @param options - Options of zip. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped. * @since 2.0.0 * @see {@link zip} for batch version (faster for small files) * @see {@link unzipStream} for the reverse operation * @example * ```typescript * // Stream zip a large directory * (await zipStream('/large-documents', '/backups/documents.zip')) * .inspect(() => console.log('Directory zipped successfully')); * ``` */ declare function zipStream(sourcePath: string, zipFilePath: string, options?: ZipOptions): AsyncVoidIOResult; /** * Zip a remote file using streaming compression. * * This function downloads and compresses the file in a streaming manner, * minimizing memory usage. Recommended for large remote files. * For small files, consider using {@link zipFromUrl} instead. * * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend. * * This API is built on `@happy-ts/fetch-t` for downloading the source. * `requestInit` supports `timeout`, `onProgress`, and `filename` via {@link ZipFromUrlRequestInit}. * * @param sourceUrl - The url to be zipped. * @param zipFilePath - The path to the zip file. * @param requestInit - Optional request initialization parameters. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped. * @since 2.0.0 * @see {@link zipFromUrl} for batch version (faster for small files) * @see {@link unzipStreamFromUrl} for the reverse operation * @example * ```typescript * // Stream zip a large remote file * (await zipStreamFromUrl('https://example.com/large-file.bin', '/backups/file.zip')) * .inspect(() => console.log('Remote file zipped successfully')); * ``` */ declare function zipStreamFromUrl(sourceUrl: string | URL, zipFilePath: string, requestInit?: ZipFromUrlRequestInit): AsyncVoidIOResult; /** * Zip a file or directory and write to a zip file. * Equivalent to `zip -r `. * * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend. * @param sourcePath - The path to be zipped. * @param zipFilePath - The path to the zip file. * @param options - Options of zip. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped. * @since 1.6.0 * @see {@link zipSync} for synchronous version * @see {@link zipStream} for streaming version (better for large files) * @see {@link unzip} for the reverse operation * @example * ```typescript * // Zip a directory to a file * (await zip('/documents', '/backups/documents.zip')) * .inspect(() => console.log('Directory zipped successfully')); * ``` */ declare function zip(sourcePath: string, zipFilePath: string, options?: ZipOptions): AsyncVoidIOResult; /** * Zip a file or directory and return the zip file data. * Equivalent to `zip -r `. * * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend. * @param sourcePath - The path to be zipped. * @param options - Options of zip. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped. * @since 1.6.0 * @see {@link zipSync} for synchronous version * @see {@link zipStream} for streaming version (better for large files) * @see {@link unzip} for the reverse operation * @example * ```typescript * // Zip a directory and get the data * (await zip('/documents')) * .inspect(zipData => console.log(`Zip size: ${ zipData.byteLength } bytes`)); * ``` */ declare function zip(sourcePath: string, options?: ZipOptions): AsyncIOResult>; /** * Zip a remote file and write to a zip file. * * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend. * * This API is built on `@happy-ts/fetch-t` for downloading the source. * `requestInit` supports `timeout`, `onProgress`, and `filename` via {@link ZipFromUrlRequestInit}. * * @param sourceUrl - The url to be zipped. * @param zipFilePath - The path to the zip file. * @param requestInit - Optional request initialization parameters. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped. * @since 1.7.0 * @see {@link zipStreamFromUrl} for streaming version (better for large files) * @see {@link unzipFromUrl} for the reverse operation * @example * ```typescript * // Zip a remote file to a local zip file * (await zipFromUrl('https://example.com/file.txt', '/backups/file.zip')) * .inspect(() => console.log('Remote file zipped successfully')); * ``` */ declare function zipFromUrl(sourceUrl: string | URL, zipFilePath: string, requestInit?: ZipFromUrlRequestInit): AsyncVoidIOResult; /** * Zip a remote file and return the zip file data. * * Use [fflate](https://github.com/101arrowz/fflate) as the zip backend. * * This API is built on `@happy-ts/fetch-t` for downloading the source. * `requestInit` supports `timeout`, `onProgress`, and `filename` via {@link ZipFromUrlRequestInit}. * * @param sourceUrl - The url to be zipped. * @param requestInit - Optional request initialization parameters. * @returns A promise that resolves to an `AsyncIOResult` indicating whether the source was successfully zipped. * @since 1.7.0 * @see {@link zipStreamFromUrl} for streaming version (better for large files) * @see {@link unzipFromUrl} for the reverse operation * @example * ```typescript * // Zip a remote file and get the data * (await zipFromUrl('https://example.com/file.txt')) * .inspect(zipData => console.log(`Zip size: ${ zipData.byteLength } bytes`)); * ``` */ declare function zipFromUrl(sourceUrl: string | URL, requestInit?: ZipFromUrlRequestInit): AsyncIOResult>; /** * Creates a new empty file at the specified path, similar to the `touch` command. * If the file already exists, this operation succeeds without modifying it. * Parent directories are created automatically if they don't exist. * * **Note:** For temporary files, use {@link mkTemp} instead, which provides * automatic unique naming and integrates with {@link pruneTemp} for cleanup. * * @param filePath - The absolute path of the file to create. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.7.0 * @see {@link createFileSync} for synchronous version * @see {@link mkTemp} for creating temporary files * @see {@link writeFile} for creating files with content * @example * ```typescript * (await createFile('/path/to/file.txt')) * .inspect(() => console.log('File created')); * ``` */ declare function createFile(filePath: string): AsyncVoidIOResult; /** * Creates a new directory at the specified path, similar to `mkdir -p`. * Creates all necessary parent directories if they don't exist. * * **Note:** For temporary directories, use {@link mkTemp} with `{ isDirectory: true }` instead, * which provides automatic unique naming and integrates with temporary file management. * * @param dirPath - The absolute path where the directory will be created. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.0.0 * @see {@link mkdirSync} for synchronous version * @see {@link emptyDir} for creating or emptying a directory * @see {@link mkTemp} for creating temporary directories * @example * ```typescript * (await mkdir('/path/to/new/directory')) * .inspect(() => console.log('Directory created')); * ``` */ declare function mkdir(dirPath: string): AsyncVoidIOResult; /** * Reads the contents of a directory at the specified path. * * @param dirPath - The path of the directory to read. * @param options - Options of readdir. * @returns A promise that resolves to an `AsyncIOResult` containing an async iterable iterator over the entries of the directory. * @since 1.0.0 * @see {@link readDirSync} for synchronous version * @example * ```typescript * // List directory contents * (await readDir('/documents')) * .inspect(async entries => { * for await (const entry of entries) { * console.log(entry.path, entry.handle.kind); * } * }); * * // List recursively * await readDir('/documents', { recursive: true }); * ``` */ declare function readDir(dirPath: string, options?: ReadDirOptions): AsyncIOResult>; /** * Reads the content of a file at the specified path as a File. * * @param filePath - The path of the file to read. * @param options - Read options specifying the 'blob' encoding. * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a File. * @since 1.0.0 * @see {@link readFileSync} for synchronous version * @see {@link readBlobFile} convenience wrapper * @example * ```typescript * (await readFile('/path/to/file.txt', { encoding: 'blob' })) * .inspect(file => console.log(file.name, file.size, file.type)); * ``` */ declare function readFile(filePath: string, options: ReadOptions & { encoding: 'blob'; }): AsyncIOResult; /** * Reads the content of a file at the specified path as a string. * * @param filePath - The path of the file to read. * @param options - Read options specifying the 'utf8' encoding. * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a string. * @since 1.0.0 * @see {@link readFileSync} for synchronous version * @see {@link readTextFile} convenience wrapper * @example * ```typescript * (await readFile('/path/to/file.txt', { encoding: 'utf8' })) * .inspect(content => console.log(content)); * ``` */ declare function readFile(filePath: string, options: ReadOptions & { encoding: 'utf8'; }): AsyncIOResult; /** * Reads the content of a file at the specified path as a readable stream. * Useful for processing large files without loading them entirely into memory. * * @param filePath - The path of the file to read. * @param options - Read options specifying the 'stream' encoding. * @returns A promise that resolves to an `AsyncIOResult` containing a `ReadableStream`. * @since 1.0.0 * @see {@link readFileSync} for synchronous version (bytes only) * @example * ```typescript * (await readFile('/path/to/large-file.bin', { encoding: 'stream' })) * .inspect(async stream => { * const reader = stream.getReader(); * while (true) { * const { done, value } = await reader.read(); * if (done) break; * console.log('Received chunk:', value.length, 'bytes'); * } * }); * ``` */ declare function readFile(filePath: string, options: ReadOptions & { encoding: 'stream'; }): AsyncIOResult>>; /** * Reads the content of a file at the specified path as a Uint8Array (default). * * @param filePath - The path of the file to read. * @param options - Optional read options. Defaults to 'bytes' encoding. * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a Uint8Array. * @since 1.0.0 * @see {@link readFileSync} for synchronous version * @example * ```typescript * (await readFile('/path/to/file.bin')) * .inspect(bytes => console.log('First byte:', bytes[0])); * ``` */ declare function readFile(filePath: string, options?: ReadOptions & { encoding?: 'bytes'; }): AsyncIOResult>; /** * Reads the content of a file at the specified path with the specified options. * This overload accepts any ReadOptions and returns the union of all possible content types. * Useful when the encoding is determined at runtime. * * @param filePath - The path of the file to read. * @param options - Optional read options. * @returns A promise that resolves to an `AsyncIOResult` containing the file content. * @since 1.0.0 * @see {@link readFileSync} for synchronous version * @example * ```typescript * // When encoding is dynamic * const encoding = getUserPreference(); // 'utf8' | 'bytes' | ... * (await readFile('/path/to/file.txt', { encoding })) * .inspect(content => { * // content type is ReadFileContent (union type) * if (typeof content === 'string') { * console.log('Text:', content); * } else if (content instanceof Uint8Array) { * console.log('Bytes:', content.length); * } * }); * ``` */ declare function readFile(filePath: string, options?: ReadOptions): AsyncIOResult; /** * Removes a file or directory at the specified path, similar to `rm -rf`. * If the path doesn't exist, the operation succeeds silently. * * @param path - The absolute path of the file or directory to remove. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.0.0 * @see {@link removeSync} for synchronous version * @see {@link emptyDir} for emptying a directory without removing it * @see {@link deleteTemp} for removing the temporary directory * @example * ```typescript * (await remove('/path/to/file-or-directory')) * .inspect(() => console.log('Removed successfully')); * ``` */ declare function remove(path: string): AsyncVoidIOResult; /** * Retrieves the `FileSystemHandle` for a file or directory at the specified path. * Can be used to check the type (file or directory) and access metadata. * * @param path - The absolute path of the file or directory. * @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemHandle`. * @since 1.0.0 * @see {@link statSync} for synchronous version * @see {@link exists} for checking existence without getting the handle * @see {@link isFileHandle} for checking handle type * @see {@link isDirectoryHandle} for checking handle type * @example * ```typescript * (await stat('/path/to/entry')) * .inspect(handle => console.log(`Kind: ${ handle.kind }, Name: ${ handle.name }`)); * ``` */ declare function stat(path: string): AsyncIOResult; /** * Writes content to a file at the specified path. * Creates the file and parent directories if they don't exist (unless `create: false`). * * When writing a `ReadableStream` to a **new file**, the stream is first written to a temporary * file in `/tmp`, then moved to the target path upon success. This prevents leaving incomplete * files if the stream is interrupted. For existing files, writes are performed directly since * OPFS's transactional writes preserve the original content on failure. * * @param filePath - The absolute path of the file to write to. * @param contents - The content to write (string, ArrayBuffer, TypedArray, Blob, or ReadableStream). * @param options - Optional write options. * @param options.create - Whether to create the file if it doesn't exist. Default: `true`. * @param options.append - Whether to append to the file instead of overwriting. Default: `false`. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.0.0 * @see {@link writeFileSync} for synchronous version * @see {@link appendFile} for appending to files * @see {@link writeJsonFile} for writing JSON data * @example * ```typescript * // Write string content * await writeFile('/path/to/file.txt', 'Hello, World!'); * * // Write binary content * await writeFile('/path/to/file.bin', new Uint8Array([1, 2, 3])); * * // Append to existing file * await writeFile('/path/to/file.txt', '\nMore content', { append: true }); * ``` */ declare function writeFile(filePath: string, contents: WriteFileContent, options?: WriteOptions): AsyncVoidIOResult; /** * Opens a file and returns a writable stream for writing contents. * Useful for writing large files without loading them entirely into memory. * The caller is responsible for closing the stream when done. * * @param filePath - The absolute path of the file to write. * @param options - Optional write options. * @returns A promise that resolves to an `AsyncIOResult` containing a `FileSystemWritableFileStream`. * @since 1.0.0 * @see {@link writeFile} for general file writing * @example * ```typescript * (await openWritableFileStream('/path/to/large-file.bin')) * .inspect(async stream => { * try { * await stream.write(new Uint8Array([1, 2, 3])); * await stream.write(new Uint8Array([4, 5, 6])); * } finally { * await stream.close(); * } * }); * ``` */ declare function openWritableFileStream(filePath: string, options?: WriteOptions): AsyncIOResult; /** * Appends content to a file at the specified path. * Creates the file if it doesn't exist (unless `create: false` is specified). * * @param filePath - The absolute path of the file to append to. * @param contents - The content to append (string, ArrayBuffer, TypedArray, or Blob). * @param options - Optional append options. * @param options.create - Whether to create the file if it doesn't exist. Default: `true`. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.0.0 * @see {@link writeFile} with `append: true` option * @example * ```typescript * // Append to file, create if doesn't exist (default behavior) * await appendFile('/path/to/log.txt', 'New log entry\n'); * * // Append only if file exists, fail if it doesn't * await appendFile('/path/to/log.txt', 'New log entry\n', { create: false }); * ``` */ declare function appendFile(filePath: string, contents: WriteFileContent, options?: AppendOptions): AsyncVoidIOResult; /** * Copies a file or directory from one location to another, similar to `cp -r`. * Both source and destination must be of the same type (both files or both directories). * * @param srcPath - The absolute source path. * @param destPath - The absolute destination path. * @param options - Optional copy options. * @param options.overwrite - Whether to overwrite existing files. Default: `true`. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.7.0 * @see {@link move} for moving instead of copying * @example * ```typescript * // Copy a file * await copy('/src/file.txt', '/dest/file.txt'); * * // Copy a directory * await copy('/src/folder', '/dest/folder'); * * // Copy without overwriting existing files * await copy('/src', '/dest', { overwrite: false }); * ``` */ declare function copy(srcPath: string, destPath: string, options?: CopyOptions): AsyncVoidIOResult; /** * Empties all contents of a directory at the specified path. * If the directory doesn't exist, it will be created. * * @param dirPath - The absolute path of the directory to empty. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.0.9 * @see {@link mkdir} for creating directories * @see {@link remove} for removing directories * @example * ```typescript * await emptyDir('/path/to/directory'); * ``` */ declare function emptyDir(dirPath: string): AsyncVoidIOResult; /** * Checks whether a file or directory exists at the specified path. * * @param path - The absolute path to check. * @param options - Optional existence options. Set `isDirectory: true` to check for directory, * or `isFile: true` to check for file. Cannot set both to `true`. * @returns A promise that resolves to an `AsyncIOResult` indicating existence. * @since 1.0.0 * @see {@link existsSync} for synchronous version * @see {@link stat} for getting the handle * @example * ```typescript * // Check if path exists (file or directory) * const exists = await exists('/path/to/entry'); * * // Check if path exists and is a file * const isFile = await exists('/path/to/file', { isFile: true }); * * // Check if path exists and is a directory * const isDir = await exists('/path/to/dir', { isDirectory: true }); * ``` */ declare function exists(path: string, options?: ExistsOptions): AsyncIOResult; /** * Moves a file or directory from one location to another. * Both source and destination must be of the same type (both files or both directories). * * @param srcPath - The absolute source path. * @param destPath - The absolute destination path. * @param options - Optional move options. * @param options.overwrite - Whether to overwrite existing files. Default: `true`. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.8.0 * @see {@link copy} for copying instead of moving * @example * ```typescript * // Move/rename a file * await move('/old/path/file.txt', '/new/path/file.txt'); * * // Move a directory * await move('/old/folder', '/new/folder'); * ``` */ declare function move(srcPath: string, destPath: string, options?: MoveOptions): AsyncVoidIOResult; /** * Reads the content of a file as a `File` object (Blob with name). * * @param filePath - The absolute path of the file to read. * @returns A promise that resolves to an `AsyncIOResult` containing the `File` object. * @since 1.0.0 * @see {@link readFile} with `encoding: 'blob'` * @see {@link uploadFile} for uploading files * @example * ```typescript * (await readBlobFile('/path/to/file.txt')) * .inspect(file => console.log(file.name, file.size, file.type)); * ``` */ declare function readBlobFile(filePath: string): AsyncIOResult; /** * Reads a JSON file and parses its content. * * @template T - The expected type of the parsed JSON object. * @param filePath - The path of the JSON file to read. * @returns A promise that resolves to an `AsyncIOResult` containing the parsed JSON object. * @since 1.8.4 * @see {@link writeJsonFile} for the reverse operation * @see {@link readTextFile} for reading raw text * @example * ```typescript * interface Config { * name: string; * version: number; * } * (await readJsonFile('/config.json')) * .inspect(config => console.log(config.name)); * ``` */ declare function readJsonFile(filePath: string): AsyncIOResult; /** * Reads a file as a UTF-8 string. * * @param filePath - The absolute path of the file to read. * @returns A promise that resolves to an `AsyncIOResult` containing the file content as a string. * @since 1.0.0 * @see {@link readFile} with `encoding: 'utf8'` * @see {@link readJsonFile} for reading JSON files * @example * ```typescript * (await readTextFile('/path/to/file.txt')) * .inspect(content => console.log(content)); * ``` */ declare function readTextFile(filePath: string): AsyncIOResult; /** * Writes an object to a file as JSON. * * @template T - The type of the object to write. * @param filePath - The absolute path of the file to write. * @param data - The object to serialize and write. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.0.0 * @see {@link readJsonFile} for the reverse operation * @see {@link writeFile} for writing raw content * @example * ```typescript * const config = { name: 'app', version: 1 }; * (await writeJsonFile('/config.json', config)) * .inspect(() => console.log('Config saved')); * ``` */ declare function writeJsonFile(filePath: string, data: T): AsyncVoidIOResult; /** * Generates a unique temporary file or directory path without creating it. * Uses `crypto.randomUUID()` to ensure uniqueness. * * @param options - Options for generating the temporary path. * @returns The generated temporary path string. * @since 1.7.0 * @see {@link mkTemp} for creating the temporary file/directory * @see {@link isTempPath} for checking if a path is temporary * @example * ```typescript * generateTempPath(); // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000' * generateTempPath({ basename: 'cache' }); // '/tmp/cache-550e8400-e29b-41d4-a716-446655440000' * generateTempPath({ extname: '.txt' }); // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000.txt' * generateTempPath({ isDirectory: true }); // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000' * ``` */ declare function generateTempPath(options?: TempOptions): string; /** * Checks whether the path is a temporary path (under `/tmp`). * * @param path - The path to check. * @returns `true` if the path starts with `/tmp/`, otherwise `false`. * @since 1.7.2 * @see {@link generateTempPath} for generating temporary paths * @see {@link TMP_DIR} for the temporary directory constant * @example * ```typescript * isTempPath('/tmp/file.txt'); // true * isTempPath('/data/file.txt'); // false * ``` */ declare function isTempPath(path: string): boolean; /** * Creates a temporary file or directory in the `/tmp` directory. * Uses `crypto.randomUUID()` to generate a unique name. * * @param options - Options for creating the temporary path. * @returns A promise that resolves to an `AsyncIOResult` containing the created path. * @since 1.7.0 * @see {@link generateTempPath} for generating paths without creating * @see {@link deleteTemp} for removing the entire temp directory * @see {@link pruneTemp} for removing expired temp files * @example * ```typescript * // Create a temporary file * (await mkTemp()) * .inspect(path => console.log(path)); // '/tmp/tmp-550e8400-e29b-41d4-a716-446655440000' * * // Create a temporary directory * await mkTemp({ isDirectory: true }); * * // Create with custom basename and extension * await mkTemp({ basename: 'cache', extname: '.json' }); * ``` */ declare function mkTemp(options?: TempOptions): AsyncIOResult; /** * Deletes the entire temporary directory (`/tmp`) and all its contents. * * **Warning:** When writing a `ReadableStream` to a new file, `writeFile` uses a temporary file * in `/tmp` before moving it to the target path. Calling `deleteTemp()` during such operations * may cause the write to fail. Ensure no stream writes are in progress before calling this function. * * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.7.0 * @see {@link pruneTemp} for selective cleanup * @see {@link remove} for general file/directory removal * @example * ```typescript * (await deleteTemp()) * .inspect(() => console.log('Temporary directory deleted')); * ``` */ declare function deleteTemp(): AsyncVoidIOResult; /** * Removes expired files from the temporary directory. * Only removes direct children files whose `lastModified` time is before the specified date. * * **Note:** This function only removes files directly under `/tmp`, not subdirectories or their contents. * Use `deleteTemp()` to remove the entire temporary directory including all nested content. * * @param expired - Files modified before this date will be deleted. * @returns A promise that resolves to an `AsyncVoidIOResult` indicating success or failure. * @since 1.7.0 * @see {@link deleteTemp} for removing all temp files * @see {@link mkTemp} for creating temp files * @example * ```typescript * // Remove files older than 24 hours * const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000); * const result = await pruneTemp(yesterday); * ``` */ declare function pruneTemp(expired: Date): AsyncVoidIOResult; /** * Downloads a file from a URL and saves it to a temporary file. * The returned response will contain the temporary file path. * * This API is built on `@happy-ts/fetch-t`. * - Supports `timeout` and `onProgress` via {@link DownloadRequestInit} * - Supports `keepEmptyBody` to allow saving empty responses * - Returns an abortable {@link FetchTask} * * @param fileUrl - The URL of the file to download. * @param requestInit - Optional request initialization parameters. * @returns A task that can be aborted and contains the result of the download. * @since 1.0.4 * @see {@link uploadFile} for the reverse operation * @see {@link unzipFromUrl} for downloading and extracting zip files * @example * ```typescript * // Download to a temporary file * const task = downloadFile('https://example.com/file.pdf'); * (await task.result) * .inspect(({ tempFilePath }) => console.log(`File downloaded to: ${ tempFilePath }`)); * ``` */ declare function downloadFile(fileUrl: string | URL, requestInit?: DownloadRequestInit): FetchTask; /** * Downloads a file from a URL and saves it to the specified path. * * @param fileUrl - The URL of the file to download. * @param filePath - The path where the downloaded file will be saved. * @param requestInit - Optional request initialization parameters. * @returns A task that can be aborted and contains the result of the download. * @since 1.0.4 * @see {@link uploadFile} for the reverse operation * @see {@link unzipFromUrl} for downloading and extracting zip files * @example * ```typescript * // Download to a specific path * const task = downloadFile('https://example.com/file.pdf', '/downloads/file.pdf'); * (await task.result) * .inspect(() => console.log('File downloaded successfully')); * * // Abort the download * task.abort(); * ``` */ declare function downloadFile(fileUrl: string | URL, filePath: string, requestInit?: DownloadRequestInit): FetchTask; /** * Uploads a file from the specified path to a URL. * * This API is built on `@happy-ts/fetch-t`. * - Supports `timeout` and `onProgress` via {@link UploadRequestInit} * - Returns an abortable {@link FetchTask} * * @param filePath - The path of the file to upload. * @param uploadUrl - The URL where the file will be uploaded. * @param requestInit - Optional request initialization parameters. * @returns A task that can be aborted and contains the result of the upload. * @since 1.0.6 * @see {@link downloadFile} for the reverse operation * @see {@link readBlobFile} for reading file as Blob before upload * @example * ```typescript * const task = uploadFile('/documents/report.pdf', 'https://example.com/upload'); * (await task.result) * .inspect(() => console.log('File uploaded successfully')); * * // Abort the upload * task.abort(); * ``` */ declare function uploadFile(filePath: string, uploadUrl: string | URL, requestInit?: UploadRequestInit): FetchTask; /** * Synchronous file system operations for main thread. * Uses SharedArrayBuffer to communicate with worker thread. * * @module */ /** * Synchronous version of `createFile`. * Creates a new empty file at the specified path. * * @param filePath - The absolute path of the file to create. * @returns A `VoidIOResult` indicating success or failure. * @see {@link createFile} for the async version. * @since 1.7.0 * @example * ```typescript * createFileSync('/path/to/file.txt') * .inspect(() => console.log('File created')); * ``` */ declare function createFileSync(filePath: string): VoidIOResult; /** * Synchronous version of `mkdir`. * Creates a directory at the specified path, including any necessary parent directories. * * @param dirPath - The absolute path of the directory to create. * @returns A `VoidIOResult` indicating success or failure. * @see {@link mkdir} for the async version. * @since 1.1.0 * @example * ```typescript * mkdirSync('/path/to/directory') * .inspect(() => console.log('Directory created')); * ``` */ declare function mkdirSync(dirPath: string): VoidIOResult; /** * Synchronous version of `move`. * Moves a file or directory from one location to another. * * @param srcPath - The source path. * @param destPath - The destination path. * @param options - Optional move options. * @returns A `VoidIOResult` indicating success or failure. * @see {@link move} for the async version. * @since 1.8.0 * @example * ```typescript * moveSync('/old/path/file.txt', '/new/path/file.txt') * .inspect(() => console.log('File moved')); * ``` */ declare function moveSync(srcPath: string, destPath: string, options?: MoveOptions): VoidIOResult; /** * Synchronous version of `readDir`. * Reads the contents of a directory. * * **Note:** Returns `DirEntryLike[]` instead of `AsyncIterableIterator` because: * 1. Sync API cannot return async iterators * 2. Native `FileSystemHandle` objects cannot be serialized across threads; * `DirEntryLike` uses `FileSystemHandleLike` which is JSON-serializable * * @param dirPath - The absolute path of the directory to read. * @param options - Optional read options (e.g., recursive). * @returns An `IOResult` containing an array of directory entries. * @see {@link readDir} for the async version. * @since 1.1.0 * @example * ```typescript * readDirSync('/documents') * .inspect(entries => entries.forEach(e => console.log(e.path, e.handle.kind))); * ``` */ declare function readDirSync(dirPath: string, options?: ReadDirSyncOptions): IOResult; /** * Synchronous version of `readFile`. * Reads the content of a file as a `File` object (blob encoding). * * @param filePath - The absolute path of the file to read. * @param options - Read options with 'blob' encoding. * @returns An `IOResult` containing a `File` object. * @since 1.1.0 * @example * ```typescript * readFileSync('/path/to/file.txt', { encoding: 'blob' }) * .inspect(file => console.log(file.name, file.size)); * ``` */ declare function readFileSync(filePath: string, options: ReadSyncOptions & { encoding: 'blob'; }): IOResult; /** * Synchronous version of `readFile`. * Reads the content of a file as a string (utf8 encoding). * * @param filePath - The absolute path of the file to read. * @param options - Read options with 'utf8' encoding. * @returns An `IOResult` containing the file content as a string. * @since 1.1.0 * @example * ```typescript * readFileSync('/path/to/file.txt', { encoding: 'utf8' }) * .inspect(content => console.log(content)); * ``` */ declare function readFileSync(filePath: string, options: ReadSyncOptions & { encoding: 'utf8'; }): IOResult; /** * Synchronous version of `readFile`. * Reads the content of a file as a Uint8Array (default). * * @param filePath - The absolute path of the file to read. * @param options - Optional read options. Defaults to 'bytes' encoding. * @returns An `IOResult` containing the file content as a Uint8Array. * @since 1.1.0 * @example * ```typescript * readFileSync('/path/to/file.bin') * .inspect(bytes => console.log('First byte:', bytes[0])); * ``` */ declare function readFileSync(filePath: string, options?: ReadSyncOptions & { encoding?: 'bytes'; }): IOResult>; /** * Synchronous version of `readFile`. * Reads the content of a file with the specified options. * This overload accepts any ReadOptions and returns the union of all possible content types. * Useful when the encoding is determined at runtime. * * @param filePath - The absolute path of the file to read. * @param options - Optional read options. * @returns An `IOResult` containing the file content. * @see {@link readFile} for the async version. * @since 1.1.0 * @example * ```typescript * // When encoding is dynamic * const encoding = getUserPreference(); // 'utf8' | 'bytes' | ... * readFileSync('/path/to/file.txt', { encoding }) * .inspect(content => { * // content type is ReadSyncFileContent (union type) * if (typeof content === 'string') { * console.log('Text:', content); * } else if (content instanceof Uint8Array) { * console.log('Bytes:', content.length); * } * }); * ``` */ declare function readFileSync(filePath: string, options?: ReadSyncOptions): IOResult; /** * Synchronous version of `remove`. * Removes a file or directory at the specified path. * * @param path - The absolute path of the file or directory to remove. * @returns A `VoidIOResult` indicating success or failure. * @see {@link remove} for the async version. * @since 1.1.0 * @example * ```typescript * removeSync('/path/to/file-or-directory') * .inspect(() => console.log('Removed successfully')); * ``` */ declare function removeSync(path: string): VoidIOResult; /** * Synchronous version of `stat`. * Retrieves metadata about a file or directory. * * **Note:** Returns `FileSystemHandleLike` instead of `FileSystemHandle` because * native `FileSystemHandle` objects cannot be serialized across threads. * `FileSystemHandleLike` is a plain object with `name` and `kind` properties. * For file entries, it also includes `size`, `type`, and `lastModified` - * use `isFileHandleLike()` to check and narrow the type. * * @param path - The absolute path to get status for. * @returns An `IOResult` containing a `FileSystemHandleLike` object. * @see {@link stat} for the async version. * @since 1.1.0 * @example * ```typescript * statSync('/path/to/entry') * .inspect(handle => console.log(`Kind: ${ handle.kind }, Name: ${ handle.name }`)); * ``` */ declare function statSync(path: string): IOResult; /** * Synchronous version of `writeFile`. * Writes content to a file at the specified path. * * @param filePath - The absolute path of the file to write. * @param contents - The content to write (ArrayBuffer, TypedArray, or string). * @param options - Optional write options. * @returns A `VoidIOResult` indicating success or failure. * @see {@link writeFile} for the async version. * @since 1.1.0 * @example * ```typescript * // Write string content * writeFileSync('/path/to/file.txt', 'Hello, World!'); * * // Write binary content * writeFileSync('/path/to/file.bin', new Uint8Array([1, 2, 3])); * ``` */ declare function writeFileSync(filePath: string, contents: WriteSyncFileContent, options?: WriteOptions): VoidIOResult; /** * Synchronous version of `appendFile`. * Appends content to a file at the specified path. * * @param filePath - The absolute path of the file to append to. * @param contents - The content to append (ArrayBuffer, TypedArray, or string). * @param options - Optional append options. * @param options.create - Whether to create the file if it doesn't exist. Default: `true`. * @returns A `VoidIOResult` indicating success or failure. * @see {@link appendFile} for the async version. * @since 1.1.0 * @example * ```typescript * // Append to file, create if doesn't exist (default behavior) * appendFileSync('/path/to/log.txt', 'New log entry\n'); * * // Append only if file exists, fail if it doesn't * appendFileSync('/path/to/log.txt', 'New log entry\n', { create: false }); * ``` */ declare function appendFileSync(filePath: string, contents: WriteSyncFileContent, options?: AppendOptions): VoidIOResult; /** * Synchronous version of `copy`. * Copies a file or directory from one location to another. * * @param srcPath - The source path. * @param destPath - The destination path. * @param options - Optional copy options. * @returns A `VoidIOResult` indicating success or failure. * @see {@link copy} for the async version. * @since 1.7.0 * @example * ```typescript * // Copy a file * copySync('/src/file.txt', '/dest/file.txt'); * * // Copy without overwriting * copySync('/src', '/dest', { overwrite: false }); * ``` */ declare function copySync(srcPath: string, destPath: string, options?: CopyOptions): VoidIOResult; /** * Synchronous version of `emptyDir`. * Removes all contents of a directory. * * @param dirPath - The absolute path of the directory to empty. * @returns A `VoidIOResult` indicating success or failure. * @see {@link emptyDir} for the async version. * @since 1.1.0 * @example * ```typescript * emptyDirSync('/path/to/directory'); * ``` */ declare function emptyDirSync(dirPath: string): VoidIOResult; /** * Synchronous version of `exists`. * Checks whether a file or directory exists at the specified path. * * @param path - The absolute path to check. * @param options - Optional existence options (e.g., isDirectory, isFile). * @returns An `IOResult` containing `true` if exists, `false` otherwise. * @see {@link exists} for the async version. * @since 1.1.0 * @example * ```typescript * existsSync('/path/to/file') * .inspect(exists => exists && console.log('File exists')); * ``` */ declare function existsSync(path: string, options?: ExistsOptions): IOResult; /** * Synchronous version of `deleteTemp`. * Deletes the temporary directory and all its contents. * * @returns A `VoidIOResult` indicating success or failure. * @see {@link deleteTemp} for the async version. * @since 1.7.0 * @example * ```typescript * deleteTempSync(); * ``` */ declare function deleteTempSync(): VoidIOResult; /** * Synchronous version of `mkTemp`. * Creates a temporary file or directory. * * @param options - Optional temp options (e.g., isDirectory, basename, extname). * @returns An `IOResult` containing the temporary path. * @see {@link mkTemp} for the async version. * @since 1.7.0 * @example * ```typescript * mkTempSync({ extname: '.txt' }) * .inspect(path => console.log('Temp file:', path)); * ``` */ declare function mkTempSync(options?: TempOptions): IOResult; /** * Synchronous version of `pruneTemp`. * Removes expired files from the temporary directory. * * @param expired - Files with lastModified before this date will be removed. * @returns A `VoidIOResult` indicating success or failure. * @see {@link pruneTemp} for the async version. * @since 1.7.0 * @example * ```typescript * // Remove files older than 24 hours * const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000); * pruneTempSync(yesterday); * ``` */ declare function pruneTempSync(expired: Date): VoidIOResult; /** * Synchronous version of `readBlobFile`. * Reads a file as a `File` object. * * @param filePath - The absolute path of the file to read. * @returns An `IOResult` containing a `File` object. * @see {@link readBlobFile} for the async version. * @since 1.1.0 * @example * ```typescript * readBlobFileSync('/path/to/file.txt') * .inspect(file => console.log(file.name, file.size, file.type)); * ``` */ declare function readBlobFileSync(filePath: string): IOResult; /** * Synchronous version of `readJsonFile`. * Reads and parses a JSON file. * * @template T - The expected type of the parsed JSON. * @param filePath - The absolute path of the JSON file to read. * @returns An `IOResult` containing the parsed JSON object. * @see {@link readJsonFile} for the async version. * @since 1.8.4 * @example * ```typescript * interface Config { name: string; version: number } * readJsonFileSync('/config.json') * .inspect(config => console.log(config.name)); * ``` */ declare function readJsonFileSync(filePath: string): IOResult; /** * Synchronous version of `readTextFile`. * Reads a file as a UTF-8 string. * * @param filePath - The absolute path of the file to read. * @returns An `IOResult` containing the file content as a string. * @see {@link readTextFile} for the async version. * @since 1.1.0 * @example * ```typescript * readTextFileSync('/path/to/file.txt') * .inspect(content => console.log(content)); * ``` */ declare function readTextFileSync(filePath: string): IOResult; /** * Synchronous version of `writeJsonFile`. * Writes an object to a file as JSON. * * @template T - The type of the object to write. * @param filePath - The absolute path of the file to write. * @param data - The object to serialize and write. * @returns A `VoidIOResult` indicating success or failure. * @see {@link writeJsonFile} for the async version. * @since 1.1.0 * @example * ```typescript * const config = { name: 'app', version: 1 }; * writeJsonFileSync('/config.json', config); * ``` */ declare function writeJsonFileSync(filePath: string, data: T): VoidIOResult; /** * Synchronous version of `unzip`. * Extracts a zip file to a directory. * * @param zipFilePath - The path to the zip file. * @param destDir - The directory to unzip to. * @returns A `VoidIOResult` indicating success or failure. * @see {@link unzip} for the async version. * @since 1.6.0 * @example * ```typescript * unzipSync('/downloads/archive.zip', '/extracted'); * ``` */ declare function unzipSync(zipFilePath: string, destDir: string): VoidIOResult; /** * Synchronous version of `zip`. * Zips a file or directory and writes to a zip file. * * @param sourcePath - The path to zip. * @param zipFilePath - The destination zip file path. * @param options - Optional zip options. * @returns A `VoidIOResult` indicating success or failure. * @see {@link zip} for the async version. * @since 1.6.0 * @example * ```typescript * zipSync('/documents', '/backups/documents.zip'); * ``` */ declare function zipSync(sourcePath: string, zipFilePath: string, options?: ZipOptions): VoidIOResult; /** * Synchronous version of `zip`. * Zips a file or directory and returns the zip data. * * @param sourcePath - The path to zip. * @param options - Optional zip options. * @returns An `IOResult` containing the zip data as `Uint8Array`. * @see {@link zip} for the async version. * @since 1.6.0 * @example * ```typescript * zipSync('/documents') * .inspect(data => console.log('Zip size:', data.byteLength)); * ``` */ declare function zipSync(sourcePath: string, options?: ZipOptions): IOResult>; /** * SyncChannel connection APIs. * Provides functions for connecting, attaching, and checking sync channel status. * * @module */ /** * Connects to a worker and establishes a sync channel for synchronous file system operations. * Must be called before using any sync API functions. * * @param worker - The worker to communicate with. Can be a `Worker` instance, a `URL`, or a URL string. * @param options - Optional configuration options for the sync channel. * @returns A promise that resolves with an `AsyncIOResult` containing the `SharedArrayBuffer` when the worker is ready. * The returned buffer can be shared with other contexts (e.g., iframes) via `postMessage`. * @since 1.1.0 * @example * ```typescript * // Connect to worker and get SharedArrayBuffer * const result = await SyncChannel.connect( * new URL('./worker.js', import.meta.url), * { sharedBufferLength: 1024 * 1024, opTimeout: 5000 } * ); * result.inspect(sharedBuffer => { * // Share with iframe * iframe.contentWindow.postMessage({ sharedBuffer }, '*'); * }); * ``` */ declare function connectSyncChannel(worker: Worker | URL | string, options?: ConnectSyncChannelOptions): AsyncIOResult; /** * Checks if the sync channel is ready to use. * * @returns `true` if ready, `false` otherwise. * @since 1.11.0 * @example * ```typescript * if (!SyncChannel.isReady()) { * await SyncChannel.connect(new URL('./worker.js', import.meta.url)); * } * ``` */ declare function isSyncChannelReady(): boolean; /** * Attaches to an existing `SharedArrayBuffer` for synchronous file system operations. * Used to share a sync channel connection with other contexts (e.g., iframes). * * After calling this function, sync APIs (e.g., `readFileSync`, `writeFileSync`) * can be used in the current context without calling `connect`. * * @param sharedBuffer - The `SharedArrayBuffer` received from another context. * @param options - Optional configuration options. * @returns A `VoidIOResult` indicating success or failure. * @since 1.8.5 * @example * ```typescript * // In iframe: receive SharedArrayBuffer from main page * window.addEventListener('message', (event) => { * if (event.data.sharedBuffer) { * const result = SyncChannel.attach(event.data.sharedBuffer, { opTimeout: 5000 }); * if (result.isOk()) { * // Now sync APIs can be used * const fileResult = readTextFileSync('/data/file.txt'); * } * } * }); * ``` */ declare function attachSyncChannel(sharedBuffer: SharedArrayBuffer, options?: AttachSyncChannelOptions): VoidIOResult; /** * Starts listening for sync channel requests in a Web Worker. * Waits for a SharedArrayBuffer from the main thread and begins processing requests. * * @returns A `VoidIOResult` indicating success or failure. * @since 1.1.0 * @example * ```typescript * // In worker.js * import { SyncChannel } from 'happy-opfs'; * const result = SyncChannel.listen(); * if (result.isErr()) { * console.error('Failed to start listening:', result.unwrapErr()); * } * ``` */ declare function listenSyncChannel(): VoidIOResult; /** * SyncChannel namespace exports. * Provides a clean API for managing sync channel lifecycle. * * @example * ```typescript * import { SyncChannel } from 'happy-opfs'; * * // Worker: start listening * SyncChannel.listen(); * * // Main thread: connect to worker * const result = await SyncChannel.connect(worker); * result.inspect(sharedBuffer => { * // Iframe: attach to existing channel * SyncChannel.attach(sharedBuffer); * }); * * // Check if ready * if (SyncChannel.isReady()) { ... } * ``` * * @module */ declare namespace mod { export { attachSyncChannel as attach, connectSyncChannel as connect, isSyncChannelReady as isReady, listenSyncChannel as listen, }; } export { EMPTY_BODY_ERROR, EMPTY_FILE_ERROR, NOTHING_TO_ZIP_ERROR, NOT_FOUND_ERROR, ROOT_DIR, mod as SyncChannel, TMP_DIR, appendFile, appendFileSync, copy, copySync, createFile, createFileSync, deleteTemp, deleteTempSync, downloadFile, emptyDir, emptyDirSync, exists, existsSync, generateTempPath, isDirectoryHandle, isDirectoryHandleLike, isFileHandle, isFileHandleLike, isOPFSSupported, isSyncChannelSupported, isTempPath, mkTemp, mkTempSync, mkdir, mkdirSync, move, moveSync, openWritableFileStream, pruneTemp, pruneTempSync, readBlobFile, readBlobFileSync, readDir, readDirSync, readFile, readFileSync, readJsonFile, readJsonFileSync, readTextFile, readTextFileSync, remove, removeSync, stat, statSync, unzip, unzipFromUrl, unzipStream, unzipStreamFromUrl, unzipSync, uploadFile, writeFile, writeFileSync, writeJsonFile, writeJsonFileSync, zip, zipFromUrl, zipStream, zipStreamFromUrl, zipSync }; export type { AppendOptions, AttachSyncChannelOptions, ConnectSyncChannelOptions, CopyOptions, DirEntry, DirEntryLike, DownloadFileTempResponse, DownloadRequestInit, ExistsOptions, FileEncoding, FileSyncEncoding, FileSystemDirectoryHandleLike, FileSystemFileHandleLike, FileSystemHandleLike, FsRequestInit, MoveOptions, ReadDirOptions, ReadDirSyncOptions, ReadFileContent, ReadOptions, ReadSyncFileContent, ReadSyncOptions, TempOptions, UnzipFromUrlRequestInit, UploadRequestInit, WriteFileContent, WriteOptions, WriteSyncFileContent, ZipFromUrlRequestInit, ZipOptions };