happy-opfs
Version:
A browser-compatible fs module inspired by the Deno fs and @std/fs APIs, based on OPFS implementation.
729 lines (712 loc) • 25.1 kB
TypeScript
import { FetchInit, FetchTask } from '@happy-ts/fetch-t';
export { ABORT_ERROR, TIMEOUT_ERROR } from '@happy-ts/fetch-t';
import { AsyncVoidIOResult, AsyncIOResult, VoidIOResult, IOResult } from 'happy-rusty';
/**
* Asserts that the provided path is an absolute path.
*
* @param path - The file path to validate.
* @throws Will throw an error if the path is not an absolute path.
*/
declare function assertAbsolutePath(path: string): void;
/**
* Asserts that the provided URL is a valid file URL.
*
* @param fileUrl - The file URL to validate.
* @throws Will throw an error if the URL is not a valid file URL.
*/
declare function assertFileUrl(fileUrl: string): void;
/**
* 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";
/**
* A constant representing the root directory path.
*/
declare const ROOT_DIR: "/";
/**
* A constant representing the current directory path.
*/
declare const CURRENT_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.
*/
type WriteFileContent = BufferSource | Blob | string;
/**
* Represents the possible content types that can be written synchronously to a file.
*/
type WriteSyncFileContent = BufferSource | string;
/**
* Represents the possible content types that can be read from a file.
*/
type ReadFileContent = ArrayBuffer | File | string;
/**
* Options for reading files with specified encoding.
*/
interface ReadOptions {
/**
* The encoding to use for reading the file's content.
* @defaultValue `'binary'`
*/
encoding?: FileEncoding;
}
/**
* 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 to determine the existence of a file or directory.
*/
interface ExistsOptions {
/**
* Whether to check for the existence of a directory.
* @defaultValue `false`
*/
isDirectory?: boolean;
/**
* Whether to check for the existence of a file.
* @defaultValue `false`
*/
isFile?: boolean;
}
/**
* Supported file encodings for reading and writing files.
*/
type FileEncoding = 'binary' | 'utf8' | 'blob';
/**
* fetch-t options for download and upload.
*/
type FsRequestInit = Omit<FetchInit, 'abortable' | 'responseType'>;
/**
* fetch-t request options for uploading files.
*/
interface UploadRequestInit extends FsRequestInit {
/**
* The filename to use when uploading the file.
*/
filename?: string;
}
/**
* Options for reading directories.
*/
interface ReadDirOptions {
/**
* Whether to recursively read the contents of directories.
*/
recursive: boolean;
}
/**
* An entry returned by `readDir`.
*/
interface ReadDirEntry {
/**
* The relative path of the entry from readDir the path parameter.
*/
path: string;
/**
* The handle of the entry.
*/
handle: FileSystemHandle;
}
/**
* An entry returned by `readDirSync`.
*/
interface ReadDirEntrySync {
/**
* The relative path of the entry from readDir the path parameter.
*/
path: string;
/**
* The handle of the entry.
*/
handle: FileSystemHandleLike;
}
/**
* A handle to a file or directory returned by `statSync`.
*/
interface FileSystemHandleLike {
/**
* The name of the entry.
*/
name: string;
/**
* The kind of the entry.
*/
kind: FileSystemHandleKind;
}
interface FileSystemFileHandleLike extends FileSystemHandleLike {
/**
* The type of the file.
*/
type: string;
/**
* The size of the file.
*/
size: number;
/**
* The last modified time of the file.
*/
lastModified: number;
}
/**
* Serializable version of Error.
*/
interface ErrorLike {
/**
* The name of the error.
*/
name: string;
/**
* The message of the error.
*/
message: string;
}
/**
* Serializable version of File.
*/
interface FileLike {
/**
* The name of the file.
*/
name: string;
/**
* The type of the file.
*/
type: string;
/**
* The last modified time of the file.
*/
lastModified: number;
/**
* The size of the file.
*/
size: number;
/**
* The binary data of the file.
*/
data: ArrayBuffer;
}
/**
* Setup options of `connectSyncAgent`.
*/
interface SyncAgentOptions {
/**
* The worker to communicate with.
*/
worker: Worker | URL | string;
/**
* The length of the buffer to use for communication.
*/
bufferLength?: number;
/**
* The timeout for operations.
*/
opTimeout?: number;
}
/**
* Options for `zip`.
*/
interface ZipOptions {
/**
* Whether to preserve the root directory in the zip file.
* @defaultValue `true`
*/
preserveRoot: boolean;
}
/**
* Options for `mkTemp`.
*/
interface 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;
/**
* The extension of the file.
* eg: `mktemp --suffix .txt`
*/
extname?: string;
}
/**
* Options for `copy`.
*/
interface CopyOptions {
/**
* Whether to overwrite the destination file if it already exists.
* @defaultValue `true`
*/
overwrite?: boolean;
}
/**
* Result of `downloadFile` when the file is saved to a temporary path.
*/
interface DownloadFileTempResponse {
/**
* The temporary path of the downloaded file to be saved.
*/
tempFilePath: string;
/**
* The raw response.
*/
rawResponse: Response;
}
/**
* Options for `move`.
*/
interface MoveOptions {
/**
* Whether to overwrite the destination file if it already exists.
* @defaultValue `true`
*/
overwrite?: boolean;
}
/**
* Creates a new file at the specified path same as `touch`.
*
* @param filePath - The path of the file to create.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the file was successfully created.
*/
declare function createFile(filePath: string): AsyncVoidIOResult;
/**
* Creates a new directory at the specified path same as `mkdir -p`.
*
* @param dirPath - The path where the new directory will be created.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the directory was successfully 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.
*/
declare function readDir(dirPath: string, options?: ReadDirOptions): AsyncIOResult<AsyncIterableIterator<ReadDirEntry>>;
/**
* 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.
*/
declare function readFile(filePath: string, options: ReadOptions & {
encoding: 'blob';
}): AsyncIOResult<File>;
/**
* 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.
*/
declare function readFile(filePath: string, options: ReadOptions & {
encoding: 'utf8';
}): AsyncIOResult<string>;
/**
* Reads the content of a file at the specified path as an ArrayBuffer by default.
*
* @param filePath - The path of the file to read.
* @param options - Read options specifying the 'binary' encoding.
* @returns A promise that resolves to an `AsyncIOResult` containing the file content as an ArrayBuffer.
*/
declare function readFile(filePath: string, options?: ReadOptions & {
encoding: 'binary';
}): AsyncIOResult<ArrayBuffer>;
/**
* Removes a file or directory at the specified path same as `rm -rf`.
*
* @param path - The path of the file or directory to remove.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the file or directory was successfully removed.
*/
declare function remove(path: string): AsyncVoidIOResult;
/**
* Retrieves the status of a file or directory at the specified path.
*
* @param path - The path of the file or directory to retrieve status for.
* @returns A promise that resolves to an `AsyncIOResult` containing the `FileSystemHandle`.
*/
declare function stat(path: string): AsyncIOResult<FileSystemHandle>;
/**
* Writes content to a file at the specified path.
*
* @param filePath - The path of the file to write to.
* @param contents - The content to write to the file.
* @param options - Optional write options.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the file was successfully written.
*/
declare function writeFile(filePath: string, contents: WriteFileContent, options?: WriteOptions): AsyncVoidIOResult;
/**
* Downloads a file from a URL and saves it to a temporary file.
* The returned response will contain the temporary file path.
*
* @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.
*/
declare function downloadFile(fileUrl: string, requestInit?: FsRequestInit): FetchTask<DownloadFileTempResponse>;
/**
* 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.
*/
declare function downloadFile(fileUrl: string, filePath: string, requestInit?: FsRequestInit): FetchTask<Response>;
/**
* Appends content to a file at the specified path.
*
* @param filePath - The path of the file to append to.
* @param contents - The content to append to the file.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the content was successfully appended.
*/
declare function appendFile(filePath: string, contents: WriteFileContent): AsyncVoidIOResult;
/**
* Copies a file or directory from one location to another same as `cp -r`.
*
* Both `srcPath` and `destPath` must both be a file or directory.
*
* @param srcPath - The source file/directory path.
* @param destPath - The destination file/directory path.
* @param options - The copy options.
* @returns A promise that resolves to an `AsyncVoidIOResult` indicating whether the file was successfully copied.
*/
declare function copy(srcPath: string, destPath: string, options?: CopyOptions): AsyncVoidIOResult;
/**
* Empties the contents of a directory at the specified path.
*
* @param dirPath - The path of the directory to empty.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the directory was successfully emptied.
*/
declare function emptyDir(dirPath: string): AsyncVoidIOResult;
/**
* Checks whether a file or directory exists at the specified path.
*
* @param path - The path of the file or directory to check for existence.
* @param options - Optional existence options.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the file or directory exists.
*/
declare function exists(path: string, options?: ExistsOptions): AsyncIOResult<boolean>;
/**
* Move a file or directory from an old path to a new path.
*
* @param srcPath - The current path of the file or directory.
* @param destPath - The new path of the file or directory.
* @param options - Options of move.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the file or directory was successfully moved.
*/
declare function move(srcPath: string, destPath: string, options?: MoveOptions): AsyncVoidIOResult;
/**
* Reads the content of a file at the specified path as a File.
*
* @param filePath - The path of the file to read.
* @returns A promise that resolves to an `AsyncIOResult` containing the file content as a File.
*/
declare function readBlobFile(filePath: string): AsyncIOResult<File>;
/**
* Reads the content of a file at the specified path as a string and returns it as a JSON object.
*
* @param filePath - The path of the file to read.
* @returns A promise that resolves to an `AsyncIOResult` containing the file content as a JSON object.
*/
declare function readJsonFile<T>(filePath: string): AsyncIOResult<T>;
/**
* Reads the content of a file at the specified path as a string.
*
* @param filePath - The path of the file to read.
* @returns A promise that resolves to an `AsyncIOResult` containing the file content as a string.
*/
declare function readTextFile(filePath: string): AsyncIOResult<string>;
/**
* Create a temporary file or directory.
*
* @param options - Options and flags.
* @returns A promise that resolves the result of the temporary file or directory path.
*/
declare function mkTemp(options?: TempOptions): AsyncIOResult<string>;
/**
* Delete the temporary directory and all its contents.
* @returns A promise that resolves to an `AsyncVoidIOResult` indicating whether the temporary directory was successfully deleted.
*/
declare function deleteTemp(): AsyncVoidIOResult;
/**
* Prune the temporary directory and delete all expired files.
* @param expired - The date to determine whether a file is expired.
* @returns A promise that resolves to an `AsyncVoidIOResult` indicating whether the temporary directory was successfully pruned.
*/
declare function pruneTemp(expired: Date): AsyncVoidIOResult;
/**
* Unzip a zip file to a directory.
* Equivalent to `unzip -o <zipFilePath> -d <targetPath>
*
* Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend.
* @param zipFilePath - Zip file path.
* @param targetPath - The directory to unzip to.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped.
*/
declare function unzip(zipFilePath: string, targetPath: string): AsyncVoidIOResult;
/**
* Unzip a remote zip file to a directory.
* Equivalent to `unzip -o <zipFilePath> -d <targetPath>
*
* Use [fflate](https://github.com/101arrowz/fflate) as the unzip backend.
* @param zipFileUrl - Zip file url.
* @param targetPath - The directory to unzip to.
* @param requestInit - Optional request initialization parameters.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the zip file was successfully unzipped.
*/
declare function unzipFromUrl(zipFileUrl: string, targetPath: string, requestInit?: FsRequestInit): AsyncVoidIOResult;
/**
* Uploads a file from the specified path to a URL.
*
* @param filePath - The path of the file to upload.
* @param fileUrl - The URL where the file will be uploaded.
* @param requestInit - Optional request initialization parameters.
* @returns A promise that resolves to an `AsyncIOResult` indicating whether the file was successfully uploaded.
*/
declare function uploadFile(filePath: string, fileUrl: string, requestInit?: UploadRequestInit): FetchTask<Response>;
/**
* Zip a file or directory and write to a zip file.
* Equivalent to `zip -r <zipFilePath> <targetPath>`.
*
* 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.
*/
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 <zipFilePath> <targetPath>`.
*
* 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.
*/
declare function zip(sourcePath: string, options?: ZipOptions): AsyncIOResult<Uint8Array>;
/**
* Zip a remote file and write to a zip file.
*
* Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.
* @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.
*/
declare function zipFromUrl(sourceUrl: string, zipFilePath: string, requestInit?: FsRequestInit): AsyncVoidIOResult;
/**
* Zip a remote file and return the zip file data.
*
* Use [fflate](https://github.com/101arrowz/fflate) as the zip backend.
* @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.
*/
declare function zipFromUrl(sourceUrl: string, requestInit?: FsRequestInit): AsyncIOResult<Uint8Array>;
/**
* Checks if the Origin Private File System (OPFS) is supported in the current environment.
*
* @returns A boolean indicating whether OPFS is supported.
*/
declare function isOPFSSupported(): boolean;
/**
* Generate a temporary path but not create it.
*
* @param options - Options and flags.
* @returns The temporary path.
*/
declare function generateTempPath(options?: TempOptions): string;
/**
* Check whether the path is a temporary path.
* @param path - The path to check.
* @returns `true` if the path is a temporary path otherwise `false`.
*/
declare function isTempPath(path: string): boolean;
/**
* Serialize a `FileSystemHandle` to plain object.
* @param handle - `FileSystemHandle` object.
* @returns Serializable version of FileSystemHandle that is FileSystemHandleLike.
*/
declare function toFileSystemHandleLike(handle: FileSystemHandle): Promise<FileSystemHandleLike>;
/**
* Whether the handle is a file.
* @param handle - The handle which is a FileSystemHandle.
* @returns `true` if the handle is a file, otherwise `false`.
*/
declare function isFileHandle(handle: FileSystemHandle): handle is FileSystemFileHandle;
/**
* Whether the handle is a directory.
* @param handle - The handle which is a FileSystemHandle.
* @returns `true` if the handle is a directory, otherwise `false`.
*/
declare function isDirectoryHandle(handle: FileSystemHandle): handle is FileSystemDirectoryHandle;
/**
* Whether the handle is a file-like.
* @param handle - The handle which is a FileSystemHandleLike.
* @returns `true` if the handle is a file, otherwise `false`.
*/
declare function isFileHandleLike(handle: FileSystemHandleLike): handle is FileSystemFileHandleLike;
/**
* Gets the data of a file handle.
* @param handle - The file handle.
* @returns A promise that resolves to the data of the file.
*/
declare function getFileDataByHandle(handle: FileSystemFileHandle): Promise<Uint8Array>;
/**
* Start worker agent.
* Listens to postMessage from main thread.
* Start runner loop.
*/
declare function startSyncAgent(): void;
/**
* Inspired by [memfs](https://github.com/streamich/memfs/blob/master/src/fsa-to-node/worker/SyncMessenger.ts).
*
* Used both in main thread and worker thread.
*/
declare class SyncMessenger {
readonly i32a: Int32Array;
readonly u8a: Uint8Array;
readonly headerLength: number;
readonly maxDataLength: number;
constructor(sab: SharedArrayBuffer);
}
/**
* Communicate with worker.
* @param options - SyncAgentOptions
* @returns
*/
declare function connectSyncAgent(options: SyncAgentOptions): Promise<void>;
/**
* Get messenger instance.
* Use `setSyncMessenger` to pass the messenger to other environments for sharing.
*
* @returns SyncMessenger instance.
*/
declare function getSyncMessenger(): SyncMessenger;
/**
* Set messenger instance.
* Use this method to share messenger with other environments.
*
* @param syncMessenger - SyncMessenger instance.
*/
declare function setSyncMessenger(syncMessenger: SyncMessenger): void;
/**
* Sync version of `createFile`.
*/
declare function createFileSync(filePath: string): VoidIOResult;
/**
* Sync version of `mkdir`.
*/
declare function mkdirSync(dirPath: string): VoidIOResult;
/**
* Sync version of `move`.
*/
declare function moveSync(srcPath: string, destPath: string, options?: MoveOptions): VoidIOResult;
/**
* Sync version of `readDir`.
*/
declare function readDirSync(dirPath: string, options?: ReadDirOptions): IOResult<ReadDirEntrySync[]>;
/**
* Sync version of `readFile`.
*/
declare function readFileSync(filePath: string, options: ReadOptions & {
encoding: 'blob';
}): IOResult<FileLike>;
declare function readFileSync(filePath: string, options: ReadOptions & {
encoding: 'utf8';
}): IOResult<string>;
declare function readFileSync(filePath: string, options?: ReadOptions & {
encoding: 'binary';
}): IOResult<ArrayBuffer>;
/**
* Sync version of `remove`.
*/
declare function removeSync(path: string): VoidIOResult;
/**
* Sync version of `stat`.
*/
declare function statSync(path: string): IOResult<FileSystemHandleLike>;
/**
* Sync version of `writeFile`.
*/
declare function writeFileSync(filePath: string, contents: WriteSyncFileContent, options?: WriteOptions): VoidIOResult;
/**
* Sync version of `appendFile`.
*/
declare function appendFileSync(filePath: string, contents: WriteSyncFileContent): VoidIOResult;
/**
* Sync version of `copy`.
*/
declare function copySync(srcPath: string, destPath: string, options?: CopyOptions): VoidIOResult;
/**
* Sync version of `emptyDir`.
*/
declare function emptyDirSync(dirPath: string): VoidIOResult;
/**
* Sync version of `exists`.
*/
declare function existsSync(path: string, options?: ExistsOptions): IOResult<boolean>;
/**
* Sync version of `deleteTemp`.
*/
declare function deleteTempSync(): VoidIOResult;
/**
* Sync version of `mkTemp`.
*/
declare function mkTempSync(options?: TempOptions): IOResult<string>;
/**
* Sync version of `pruneTemp`.
*/
declare function pruneTempSync(expired: Date): VoidIOResult;
/**
* Sync version of `readBlobFile`.
*/
declare function readBlobFileSync(filePath: string): IOResult<FileLike>;
/**
* Sync version of `readJsonFile`.
*/
declare function readJsonFileSync<T>(filePath: string): IOResult<T>;
/**
* Sync version of `readTextFile`.
*/
declare function readTextFileSync(filePath: string): IOResult<string>;
/**
* Sync version of `unzip`.
*/
declare function unzipSync(zipFilePath: string, targetPath: string): VoidIOResult;
/**
* Sync version of `zip`.
*/
declare function zipSync(sourcePath: string, zipFilePath: string, options?: ZipOptions): VoidIOResult;
/**
* Sync version of `zip`.
*/
declare function zipSync(sourcePath: string, options?: ZipOptions): IOResult<Uint8Array>;
export { CURRENT_DIR, NOT_FOUND_ERROR, ROOT_DIR, SyncMessenger, TMP_DIR, appendFile, appendFileSync, assertAbsolutePath, assertFileUrl, connectSyncAgent, copy, copySync, createFile, createFileSync, deleteTemp, deleteTempSync, downloadFile, emptyDir, emptyDirSync, exists, existsSync, generateTempPath, getFileDataByHandle, getSyncMessenger, isDirectoryHandle, isFileHandle, isFileHandleLike, isOPFSSupported, isTempPath, mkTemp, mkTempSync, mkdir, mkdirSync, move, moveSync, pruneTemp, pruneTempSync, readBlobFile, readBlobFileSync, readDir, readDirSync, readFile, readFileSync, readJsonFile, readJsonFileSync, readTextFile, readTextFileSync, remove, removeSync, setSyncMessenger, startSyncAgent, stat, statSync, toFileSystemHandleLike, unzip, unzipFromUrl, unzipSync, uploadFile, writeFile, writeFileSync, zip, zipFromUrl, zipSync };
export type { CopyOptions, DownloadFileTempResponse, ErrorLike, ExistsOptions, FileEncoding, FileLike, FileSystemFileHandleLike, FileSystemHandleLike, FsRequestInit, MoveOptions, ReadDirEntry, ReadDirEntrySync, ReadDirOptions, ReadFileContent, ReadOptions, SyncAgentOptions, TempOptions, UploadRequestInit, WriteFileContent, WriteOptions, WriteSyncFileContent, ZipOptions };
//# sourceMappingURL=types.d.ts.map