import { ABORT_ERROR, FetchInit, TIMEOUT_ERROR } from "@happy-ts/fetch-t"; //#region src/shared/constants.d.ts /** * A constant representing the error thrown when a file or directory is not found. * Name of DOMException.NOT_FOUND_ERR. * * @since 1.0.0 */ export declare const NOT_FOUND_ERROR: "NotFoundError"; /** * Response body is empty (null), typically from 204/304 responses or HEAD requests. * * @since 2.0.0 */ export declare const EMPTY_BODY_ERROR: "EmptyBodyError"; /** * File content is empty (0 bytes). * * @since 2.0.0 */ export declare const EMPTY_FILE_ERROR: "EmptyFileError"; /** * Nothing to zip - empty directory with no entries. * * @since 2.0.0 */ export declare const NOTHING_TO_ZIP_ERROR: "NothingToZipError"; /** * A constant representing the root directory path. * * @since 1.0.0 */ export declare const ROOT_DIR: "/"; /** * A constant representing the temporary directory path. * * @since 1.7.0 */ export declare const TMP_DIR: "/tmp"; //#endregion //#region src/shared/defines.d.ts /** * Represents the possible content types that can be written to a file asynchronously. * Includes `BufferSource` (ArrayBuffer or TypedArray), `Blob`, `string`, or a binary `ReadableStream`. * * @since 1.0.0 */ export 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). * * @since 1.7.0 */ export 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` * * @since 1.0.0 */ export type ReadFileContent = Uint8Array | File | string | ReadableStream>; /** * Represents the possible content types for synchronous file reads. * Excludes `ReadableStream` since it cannot be returned synchronously. * * @since 2.0.0 */ export 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 * * @since 1.0.0 */ export type FileEncoding = 'bytes' | 'utf8' | 'blob' | 'stream'; /** * Supported file encodings for synchronous file reads. * Excludes `'stream'` since `ReadableStream` cannot be returned synchronously. * * @since 2.0.0 */ export type FileSyncEncoding = Exclude; /** * Options for reading files with specified encoding. * * @since 1.0.0 */ export interface ReadOptions { /** * The encoding to use for reading the file's content. * @defaultValue `'bytes'` */ encoding?: FileEncoding; } /** * Options for reading files synchronously. * * @since 2.0.0 */ export 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. * * @since 1.0.0 */ export 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. * * @since 2.0.2 */ export interface AppendOptions { /** * Whether to create the file if it does not exist. * @defaultValue `true` */ create?: boolean; } /** * Options for reading directories synchronously. * * @since 2.0.0 */ export interface ReadDirSyncOptions { /** * Whether to recursively read the contents of subdirectories. * @defaultValue `false` */ recursive?: boolean; /** * Whether each file entry carries metadata (`type`, `size`, `lastModified`). * * Metadata costs one `getFile()` lookup per file on the worker side and makes the * response considerably larger, which matters when listing a large tree. With * `false` the entries only carry `path` and `kind` - read metadata with `statSync` * when you actually need it. * @defaultValue `true` * @since 2.3.0 */ withMetadata?: boolean; } /** * Options for reading directories. * * @since 1.0.18 */ export interface ReadDirOptions extends Omit { /** * 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). * * @since 1.0.0 * @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 }); * ``` */ export 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`. * * @since 1.7.0 */ export interface CopyOptions { /** * Whether to overwrite the destination file if it already exists. * * When `false`, existing entries are skipped while the rest of the source is * still copied (`cp -rn` style merge). * @defaultValue `true` */ overwrite?: boolean; } /** * Options for `move`. * * @since 1.8.2 */ export interface MoveOptions { /** * Whether to overwrite the destination file if it already exists. * * When `false`, the move is a no-op if the destination already exists * (`mv -n` style): both the destination and the source are left untouched. * @defaultValue `true` */ overwrite?: boolean; } /** * An entry returned by `readDir`. * * @since 1.12.0 */ export 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 * * @since 1.12.0 */ export 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; } /** * A directory entry without metadata, returned by `readDirSync` when called with * `{ withMetadata: false }`. * * It carries no handle-like object: listing a large tree this way skips one `getFile()` * lookup per file and keeps the response small, at the cost of a separate `statSync` * call when metadata is actually needed. * * @since 2.3.0 * @see {@link readDirSync} for the options that produce it * @example * ```typescript * readDirSync('/documents', { recursive: true, withMetadata: false }) * .inspect(entries => entries.forEach(entry => console.log(entry.path, entry.kind))); * ``` */ export interface DirEntrySlim { /** * The relative path of the entry from the `readDirSync` path parameter. */ readonly path: string; /** * The kind of the entry: `'file'` or `'directory'`. */ readonly kind: FileSystemHandleKind; } /** * 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()` * * @since 1.1.0 */ export 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` * * @since 1.3.0 */ export 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 * * @since 2.0.0 */ export 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. * * @since 1.7.0 * @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' }); * ``` */ export 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; }; /** * Compression level for zip operations, aligning with fflate's `DeflateOptions.level`. * * - `0`: No compression (store only) — best for already-compressed data (images, videos, archives) * - `1`: Fastest compression * - `6`: Default compression (balanced) * - `9`: Best compression (slowest) * * Higher values usually take disproportionately longer than the reduction in final size. * Binary data typically benefits more from higher levels than text data. * @since 2.1.0 */ export type ZipLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; /** * Options for `zip`. * * @since 1.6.0 */ export 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; /** * Compression level for the zip operation. * * - `0`: No compression (store only) — best for already-compressed data * - `1`: Fastest compression * - `6`: Default compression (balanced) * - `9`: Best compression (slowest) * * Aligns with fflate's `DeflateOptions.level`. * @defaultValue `6` * @since 2.1.0 * @example * ```typescript * // Store without compression (for already-compressed files like images/videos) * await zip('/photos', '/photos.zip', { level: 0 }); * * // Best compression (for text-heavy data, slower) * await zip('/documents', '/documents.zip', { level: 9 }); * ``` */ level?: ZipLevel; } /** * 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). * * @since 1.0.14 */ export type FsRequestInit = Omit; /** * Request init options for {@link uploadFile}. * * @since 1.0.17 */ export interface UploadRequestInit extends FsRequestInit { /** * The filename to use when uploading the file. */ filename?: string; } /** * Request init options for {@link downloadFile}. * * @since 2.0.0 */ export 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}. * * @since 2.0.0 */ export 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; /** * Compression level for the zip operation. * * - `0`: No compression (store only) — best for already-compressed data * - `1`: Fastest compression * - `6`: Default compression (balanced) * - `9`: Best compression (slowest) * * Aligns with fflate's `DeflateOptions.level`. * @defaultValue `6` * @since 2.1.0 */ level?: ZipLevel; } /** * Request init options for {@link unzipFromUrl} and {@link unzipStreamFromUrl}. * * @since 2.0.0 */ export type UnzipFromUrlRequestInit = FsRequestInit; /** * Result of {@link downloadFile} when the file is saved to a temporary path. * * @since 1.7.2 */ export 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`. * * @since 2.0.0 */ export 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; /** * The timeout in milliseconds for establishing the connection itself * (worker startup, script load, and `SyncChannel.listen()` readiness). * If the worker does not signal readiness within this time, a * `TimeoutError` is returned. Distinct from `opTimeout`, which governs * individual sync operations after the channel is ready. * @defaultValue `10000` (10 seconds) * @since 2.1.0 */ connectTimeout?: number; /** * How the worker is loaded when `worker` is a URL or a string. * * - `'classic'` (default): `new Worker(url)` * - `'module'`: `new Worker(url, { type: 'module' })`, required for worker scripts * that use `import`/`export` (i.e. most bundler output) * * Module workers need Chrome/Edge 80+, Firefox 114+, Safari 15+; build a classic * worker or pass your own `Worker` instance if you target older Firefox. * * Ignored when a `Worker` instance is passed, since it is already configured. * @defaultValue `'classic'` * @since 2.3.0 */ workerType?: WorkerType; } /** * Options for `SyncChannel.attach`. * * @since 2.0.0 */ export 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; } //#endregion //#region src/shared/guards.d.ts /** * 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')); * ``` */ export 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')); * ``` */ export 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 }`)); * ``` */ export 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)); * }); * ``` */ export declare function isDirectoryHandleLike(handle: FileSystemHandleLike): handle is FileSystemDirectoryHandleLike; //#endregion //#region src/shared/support.d.ts /** * 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'); * } * ``` */ export 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'); * } * ``` */ export declare function isSyncChannelSupported(): boolean; //#endregion //#region src/shared/tmp.d.ts /** * 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' * ``` */ export 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 * ``` */ export declare function isTempPath(path: string): boolean; //#endregion export { ABORT_ERROR, TIMEOUT_ERROR }; //# sourceMappingURL=shared.d.cts.map