@synstack/fs
Version:
File system operations made easy
1,272 lines (1,265 loc) • 45.8 kB
TypeScript
import * as execa from 'execa';
import { TemplateExpression } from 'execa';
import { Enhanced } from '@synstack/enhance';
import * as _synstack_str from '@synstack/str';
import * as _synstack_path from '@synstack/path';
import { AnyPath } from '@synstack/path';
import { MdDoc } from '@synstack/markdown';
import { Pipeable } from '@synstack/pipe';
import { Xml } from '@synstack/xml';
import { ZodType, ZodTypeDef } from 'zod/v3';
import { ZodType as ZodType$1 } from 'zod/v4';
/**
* A type serializable to string
*/
type Stringable = {
toString(): string;
};
type ZodSchema<OUT = any, IN = any> = ZodType<OUT, ZodTypeDef, IN> | ZodType$1<OUT, IN>;
type TextEncoding = Exclude<BufferEncoding, "buffer">;
type WriteMode = "preserve" | "overwrite";
interface Base64Data {
type: "base64";
data: string;
mimeType: string;
}
/**
* A strongly-typed, chainable API for file system operations.
* Provides methods for reading, writing, and manipulating files with support for multiple formats.
*
* @typeParam TEncoding - The text encoding to use for file operations (default: 'utf-8')
* @typeParam TSchema - Optional Zod schema for validating JSON/YAML data
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* // Create a file instance
* const configFile = fsFile("./config.json")
* .schema(ConfigSchema)
* .read.json();
*
* // Write text with different encodings
* const logFile = fsFile("./log.txt")
* .write.text("Hello World");
* ```
*/
declare class FsFile<TEncoding extends TextEncoding = "utf-8", TSchema extends ZodSchema | undefined = undefined> extends Pipeable<FsFile<TEncoding, TSchema>, AnyPath> {
private readonly _path;
private readonly _encoding;
private readonly _schema?;
/**
* Create a new FsFile instance from a path, a list of paths to be resolved, or an existing FsFile instance.
* The resulting path will be an absolute path.
*
* @param paths - A path or an existing FsFile instance
* @returns A new FsFile instance with UTF-8 encoding
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const relativeFile = fsFile("./relative/path.txt");
* const existingFile = fsFile(fsFile("/path/to/existing.txt"));
* ```
*/
static from(this: void, arg: FsFile | AnyPath): FsFile<"utf-8", undefined>;
protected constructor(path: AnyPath, encoding?: TEncoding, schema?: TSchema);
/**
* Provide a validation schema for the file content. To be used with:
* - `.read.json`
* - `.write.json`
* - `.read.yaml`
* - `.write.yaml`
*/
/**
* Provide a validation schema for JSON/YAML operations.
* The schema will be used to validate data when reading or writing JSON/YAML files.
*
* @typeParam NewSchema - The Zod schema type for validation
* @param schema - A Zod schema to validate JSON/YAML data
* @returns A new FsFile instance with the schema attached
*
* ```typescript
* import { fsFile } from "@synstack/fs";
* import { z } from "zod";
*
* const ConfigSchema = z.object({
* port: z.number(),
* host: z.string()
* });
*
* const config = await fsFile("config.json")
* .schema(ConfigSchema)
* .read.json();
* // config is typed as { port: number, host: string }
* ```
*/
schema<NewSchema extends ZodSchema>(schema: NewSchema): FsFile<TEncoding, NewSchema>;
/**
* Get the path of the file.
*
* @returns The absolute path of the file
*/
valueOf(): AnyPath;
/**
* Get the current instance of the file.
* Used for type compatibility with Pipeable.
*
* @returns The current FsFile instance
*/
instanceOf(): FsFile<TEncoding, TSchema>;
/**
* Access the read operations for the file.
* Provides methods for reading file contents in various formats.
*
* @returns An FsFileRead instance with methods for reading the file
*
* ```typescript
* const content = await fsFile("data.txt").read.text();
* const json = await fsFile("config.json").read.json();
* const yaml = await fsFile("config.yml").read.yaml();
* ```
*/
get read(): FsFileRead<TEncoding, TSchema>;
/**
* Access the write operations for the file.
* Provides methods for writing content to the file in various formats.
*
* @returns An FsFileWrite instance with methods for writing to the file
*
* ```typescript
* await fsFile("data.txt").write.text("Hello");
* await fsFile("config.json").write.json({ hello: "world" });
* await fsFile("config.yml").write.yaml({ config: true });
* ```
*/
get write(): FsFileWrite<TEncoding, TSchema>;
/**
* Get the absolute path of the file.
*
* @returns The absolute path as a string
*/
get path(): string;
/**
* Get the absolute path of the directory containing the file.
*
* @returns The directory path as a string
*/
dirPath(): _synstack_path.AbsolutePath;
/**
* Get an FsDir instance representing the directory containing the file.
*
* @returns An FsDir instance for the parent directory
*
* ```typescript
* const file = fsFile("/path/to/file.txt");
* const parentDir = file.dir(); // FsDir for "/path/to"
* ```
*/
dir(): FsDir;
/**
* Get the name of the file including its extension.
*
* @returns The file name with extension
*
* ```typescript
* const file = fsFile("/path/to/document.txt");
* console.log(file.fileName()); // "document.txt"
* ```
*/
fileName(): string;
/**
* Get the extension of the file.
*
* @returns The file extension including the dot (e.g., ".txt")
*
* ```typescript
* const file = fsFile("/path/to/document.txt");
* console.log(file.fileExtension()); // ".txt"
* ```
*/
fileExtension(): string;
/**
* Get the name of the file without its extension.
*
* @returns The file name without extension
*
* ```typescript
* const file = fsFile("/path/to/document.txt");
* console.log(file.fileNameWithoutExtension()); // "document"
* ```
*/
fileNameWithoutExtension(): string;
/**
* Get the MIME type of the file based on its extension.
*
* @returns The MIME type string or null if it cannot be determined
*
* ```typescript
* const file = fsFile("/path/to/image.png");
* console.log(file.mimeType()); // "image/png"
* ```
*/
mimeType(): string | null;
/**
* Create a new FsFile instance with a path relative to this file's directory.
*
* @param relativePath - The relative path from this file's directory
* @returns A new FsFile instance for the target path
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const sourceFile = fsFile("/path/to/source.txt");
* const targetFile = sourceFile.toFile("../output/target.txt");
* // targetFile.path === "/path/output/target.txt"
* ```
*/
toFile(relativePath: string): FsFile<"utf-8", undefined>;
/**
* Create a new FsDir instance with a path relative to this file's directory.
*
* @param relativePath - The relative path from this file's directory
* @returns A new FsDir instance for the target directory
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const sourceFile = fsFile("/path/to/source.txt");
* const outputDir = sourceFile.toDir("../output");
* // outputDir.path === "/path/output"
* ```
*/
toDir(relativePath: string): FsDir;
/**
* Get the relative path from another file to this file
*
* ```ts
* import { fsFile } from "@synstack/fs";
*
* const file1 = fsFile("/path/to/file1.txt");
* const file2 = fsFile("/path/to-other/file2.txt");
*
* console.log(file1.relativePathFrom(file2)); // ../to/file1.txt
* ```
*/
relativePathFrom(dirOrFile: FsDir | FsFile): string;
/**
* Get the relative path to go from this file to another
*
* ```ts
* import { fsFile } from "@synstack/fs";
*
* const file1 = fsFile("/path/to/file1.txt");
* const file2 = fsFile("/path/to-other/file2.txt");
*
* console.log(file1.relativePathTo(file2)); // ../to-other/file2.txt
* ```
*/
relativePathTo(dirOrFileOrPath: FsDir | FsFile): string;
/**
* Check if the file is located within the specified directory.
*
* @param dirOrPath - The directory or path to check against
* @returns True if the file is in the directory, false otherwise
*
* ```typescript
* import { fsFile, fsDir } from "@synstack/fs";
*
* const sourceFile = fsFile("/path/to/file.txt");
* console.log(sourceFile.isInDir(fsDir("/path"))); // true
* console.log(sourceFile.isInDir(fsDir("/other"))); // false
* ```
*/
isInDir(dirOrPath: AnyPath | FsDir): boolean;
/**
* Delete the file from the file system.
* If the file doesn't exist, the operation is silently ignored.
*
* @returns A promise that resolves when the file is deleted
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const tempFile = fsFile("./temp.txt");
* await tempFile.write.text("temporary content");
* await tempFile.remove(); // File is deleted
* ```
*/
remove(): Promise<void>;
/**
* @deprecated Use {@link remove} instead.
*/
rm(): Promise<void>;
/**
* Delete the file from the file system synchronously.
* If the file doesn't exist, the operation is silently ignored.
*
* @synchronous
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const tempFile = fsFile("./temp.txt");
* tempFile.write.textSync("temporary content");
* tempFile.removeSync(); // File is deleted immediately
* ```
*/
removeSync(): void;
/**
* @deprecated Use {@link removeSync} instead.
*/
rmSync(): void;
/**
* Move the file to a new location.
*
* @param newPath - The new path for the file or an existing FsFile instance
* @returns A promise that resolves the new file
*/
move(newPath: FsFile | AnyPath): Promise<FsFile>;
/**
* Move the file to a new location synchronously.
*
* @param newPath - The new path for the file or an existing FsFile instance
* @returns The new file
*/
moveSync(newPath: FsFile | AnyPath): FsFile;
/**
* Check if the file exists in the file system.
*
* @returns A promise that resolves to true if the file exists, false otherwise
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const configFile = fsFile("./config.json");
* if (await configFile.exists()) {
* const config = await configFile.read.json();
* }
* ```
*/
exists(): Promise<boolean>;
/**
* Check if the file exists in the file system synchronously.
*
* @synchronous
* @returns True if the file exists, false otherwise
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const configFile = fsFile("./config.json");
* if (configFile.existsSync()) {
* const config = configFile.read.jsonSync();
* }
* ```
*/
existsSync(): boolean;
/**
* Get the creation date of the file.
*
* @returns A promise that resolves to the file's creation date
* @throws If the file doesn't exist or cannot be accessed
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const sourceFile = fsFile("./source.txt");
* const created = await sourceFile.creationDate();
* console.log(`File created on: ${created.toISOString()}`);
* ```
*/
creationDate(): Promise<Date>;
/**
* Get the creation date of the file synchronously.
*
* @synchronous
* @returns The file's creation date
* @throws If the file doesn't exist or cannot be accessed
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const sourceFile = fsFile("./source.txt");
* const created = sourceFile.creationDateSync();
* console.log(`File created on: ${created.toISOString()}`);
* ```
*/
creationDateSync(): Date;
/**
* Check if the file path matches any of the provided glob patterns.
*
* @param globs - One or more glob patterns to match against, either as separate arguments or an array
* @returns True if the file matches any pattern, false otherwise
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const sourceFile = fsFile("./src/components/Button.tsx");
* console.log(sourceFile.matchesGlobs("**\/*.tsx")); // true
* console.log(sourceFile.matchesGlobs(["*.css", "*.html"])); // false
* console.log(sourceFile.matchesGlobs("**\/*.ts", "**\/*.tsx")); // true
* ```
*/
matchesGlobs(...globs: Array<string> | [Array<string>]): boolean;
/**
* Capture parts of the file path using a glob pattern
*
* ```ts
* import { fsFile } from "@synstack/fs";
*
* const myFile = fsFile("/my-domain/my-sub-domain/features/feature-name.controller.ts");
* const res = myFile.globCapture("/(*)/(*)/features/(*).controller.ts");
* if (!res) throw new Error("File doesn't match glob pattern");
* console.log(res[1]); // my-domain
* console.log(res[2]); // my-sub-domain
* console.log(res[3]); // feature-name.controller.ts
* ```
*/
globCapture(globPattern: string): string[] | null;
}
declare class FsFileRead<ENCODING extends TextEncoding = "utf-8", SCHEMA extends ZodSchema | undefined = undefined> {
private readonly _path;
private readonly _encoding;
private readonly _schema?;
constructor(path: AnyPath, encoding: ENCODING, schema?: SCHEMA);
get path(): string;
/**
* Read the file contents as a string.
*
* @returns A promise that resolves to the file contents as a string
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* const content = await fsFile("data.txt").read.text();
* console.log(content); // "Hello, World!"
* ```
*/
text(): Promise<string>;
/**
* Read the file contents as a string synchronously.
*
* @synchronous
* @returns The file contents as a string
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* const content = fsFile("data.txt").read.textSync();
* console.log(content); // "Hello, World!"
* ```
*/
textSync(): string;
/**
* Read the file contents and return a chainable string instance.
* Used for further manipulation of the content using @synstack/str methods.
*
* @returns A promise that resolves to a chainable string instance
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* const content = await fsFile("data.txt").read.str();
* const lines = content
* .split("\n")
* .filter((line) => line.trim().length > 0);
* ```
*/
str(): Promise<_synstack_str.Str>;
/**
* Read the file contents and return a chainable string instance synchronously.
* Used for further manipulation of the content using @synstack/str methods.
*
* @synchronous
* @returns A chainable string instance
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* const content = fsFile("data.txt").read.strSync();
* const lines = content
* .split("\n")
* .filter((line) => line.trim().length > 0);
* ```
*/
strSync(): _synstack_str.Str;
/**
* Read and parse the file contents as JSON.
* If a schema is provided, the parsed data will be validated against it.
*
* @returns A promise that resolves to the parsed JSON data
* @throws If the file doesn't exist, cannot be read, or contains invalid JSON
* @throws If schema validation fails when a schema is provided
*
* ```typescript
* interface Config {
* port: number;
* host: string;
* }
*
* const config = await fsFile("config.json")
* .schema(ConfigSchema)
* .read.json();
* // config is automatically typed as the schema's output type
* ```
*/
json<OUT = SCHEMA extends ZodSchema<infer O> ? O : unknown>(): Promise<OUT>;
/**
* Read and parse the file contents as JSON synchronously.
* If a schema is provided, the parsed data will be validated against it.
*
* @synchronous
* @returns The parsed JSON data
* @throws If the file doesn't exist, cannot be read, or contains invalid JSON
* @throws If schema validation fails when a schema is provided
*
* ```typescript
* const config = fsFile("config.json")
* .schema(ConfigSchema)
* .read.jsonSync();
* // config is automatically typed as the schema's output type
* ```
*/
jsonSync<OUT = SCHEMA extends ZodSchema<infer O> ? O : unknown>(): OUT;
/**
* Read and parse the file contents as YAML.
* If a schema is provided, the parsed data will be validated against it.
*
* @typeParam T - The type of the parsed YAML data
* @returns A promise that resolves to the parsed YAML data
* @throws If the file doesn't exist, cannot be read, or contains invalid YAML
* @throws If schema validation fails when a schema is provided
*
* ```typescript
* interface Config {
* environment: string;
* settings: Record<string, unknown>;
* }
*
* const config = await fsFile("config.yml")
* .schema(ConfigSchema)
* .read.yaml();
* // config is automatically typed as the schema's output type
* ```
*/
yaml<OUT = SCHEMA extends ZodSchema<infer O> ? O : unknown>(): Promise<OUT>;
/**
* Read and parse the file contents as YAML synchronously.
* If a schema is provided, the parsed data will be validated against it.
*
* @typeParam T - The type of the parsed YAML data
* @synchronous
* @returns The parsed YAML data
* @throws If the file doesn't exist, cannot be read, or contains invalid YAML
* @throws If schema validation fails when a schema is provided
*
* ```typescript
* const config = fsFile("config.yml")
* .schema(ConfigSchema)
* .read.yamlSync();
* // config is automatically typed as the schema's output type
* ```
*/
yamlSync<OUT = SCHEMA extends ZodSchema<infer O> ? O : unknown>(): OUT;
/**
* Read and parse the file contents as XML using @synstack/xml.
* This parser is specifically designed for LLM-related XML processing.
*
* @typeParam T - The type of the parsed XML nodes array, must extend Array<Xml.Node>
* @returns A promise that resolves to the parsed XML nodes
* @throws If the file doesn't exist, cannot be read, or contains invalid XML
* @see {@link https://github.com/pAIrprogio/synscript/tree/main/packages/xml|@synstack/xml documentation}
*
* ```typescript
* interface XmlNode {
* tag: string;
* attributes: Record<string, string>;
* children: Array<XmlNode>;
* }
*
* const nodes = await fsFile("data.xml").read.xml<XmlNode[]>();
* console.log(nodes[0].tag); // "root"
* console.log(nodes[0].attributes.id); // "main"
* ```
*
* @remarks
* - Uses a non-spec-compliant XML parser tailored for LLM use cases
* - Optimized for simple XML structures commonly used in LLM responses
* - Does not support all XML features (see documentation for details)
*/
xml<T extends Array<Xml.Node>>(): Promise<T>;
/**
* Read and parse the file contents as XML synchronously using @synstack/xml.
* This parser is specifically designed for LLM-related XML processing.
*
* @typeParam T - The type of the parsed XML nodes array, must extend Array<Xml.Node>
* @synchronous
* @returns The parsed XML nodes
* @throws If the file doesn't exist, cannot be read, or contains invalid XML
* @see {@link https://github.com/pAIrprogio/synscript/tree/main/packages/xml|@synstack/xml documentation}
*
* ```typescript
* const nodes = fsFile("data.xml").read.xmlSync<XmlNode[]>();
* console.log(nodes[0].tag); // "root"
* console.log(nodes[0].attributes.id); // "main"
* ```
*
* @remarks
* - Uses a non-spec-compliant XML parser tailored for LLM use cases
* - Optimized for simple XML structures commonly used in LLM responses
* - Does not support all XML features (see documentation for details)
*/
xmlSync<T extends Array<Xml.Node>>(): T;
/**
* Read the file contents and encode them as a base64 string.
* Useful for handling binary data or preparing content for data URLs.
*
* @returns A promise that resolves to the file contents as a base64-encoded string
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* // Read and encode an image file
* const imageBase64 = await fsFile("image.png").read.base64();
* console.log(imageBase64); // "iVBORw0KGgoAAAANSUhEUgAA..."
*
* // Create a data URL for use in HTML/CSS
* const dataUrl = `data:image/png;base64,${imageBase64}`;
* ```
*/
base64(): Promise<string>;
/**
* Read the file contents and encode them as a base64 string synchronously.
* Useful for handling binary data or preparing content for data URLs.
*
* @synchronous
* @returns The file contents as a base64-encoded string
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* const imageBase64 = fsFile("image.png").read.base64Sync();
* const dataUrl = `data:image/png;base64,${imageBase64}`;
* ```
*/
base64Sync(): string;
/**
* Read the file contents and create a synstack-compatible Base64Data object.
* This format includes MIME type information along with the base64-encoded data.
*
* @param defaultMimeType - The MIME type to use if it cannot be determined from the file extension
* @returns A promise that resolves to a Base64Data object containing the encoded content and MIME type
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* // Read an image with automatic MIME type detection
* const imageData = await fsFile("image.png").read.base64Data();
* console.log(imageData);
* // {
* // type: "base64",
* // data: "iVBORw0KGgoAAAANSUhEUgAA...",
* // mimeType: "image/png"
* // }
*
* // Specify a custom MIME type for a binary file
* const data = await fsFile("custom.bin")
* .read.base64Data("application/custom");
* ```
*/
base64Data(defaultMimeType?: string): Promise<Base64Data>;
/**
* Read the file contents and create a synstack-compatible Base64Data object synchronously.
* This format includes MIME type information along with the base64-encoded data.
*
* @param defaultMimeType - The MIME type to use if it cannot be determined from the file extension
* @synchronous
* @returns A Base64Data object containing the encoded content and MIME type
* @throws If the file doesn't exist or cannot be read
*
* ```typescript
* const imageData = fsFile("image.png").read.base64DataSync();
* console.log(imageData);
* // {
* // type: "base64",
* // data: "iVBORw0KGgoAAAANSUhEUgAA...",
* // mimeType: "image/png"
* // }
* ```
*/
base64DataSync(defaultMimeType?: string): Base64Data;
/**
* Read the file contents and parse them as a markdown document.
* If a schema is provided, the header data will be validated before returning.
*
* @returns A promise that resolves to the markdown document
* @throws If the file doesn't exist, cannot be read, or contains invalid markdown
* @throws If schema validation fails when a schema is provided
*/
md<DATA_SHAPE = SCHEMA extends ZodSchema<infer O> ? O : unknown>(): Promise<MdDoc<DATA_SHAPE, DATA_SHAPE>>;
/**
* Read the file contents and parse them as a markdown document synchronously.
* If a schema is provided, the header data will be validated before returning.
*
* @synchronous
* @returns The markdown document
* @throws If the file doesn't exist, cannot be read, or contains invalid markdown
* @throws If schema validation fails when a schema is provided
*/
mdSync<DATA_SHAPE = SCHEMA extends ZodSchema<infer O> ? O : unknown>(): MdDoc<DATA_SHAPE, DATA_SHAPE>;
}
declare class FsFileWrite<TEncoding extends TextEncoding, TSchema extends ZodSchema | undefined = undefined> {
private readonly _path;
private readonly _encoding;
private readonly _schema?;
private readonly _mode;
constructor(path: AnyPath, encoding: TEncoding, mode?: WriteMode, schema?: TSchema);
/**
* Set the write mode of the file
* @argument preserve: If the file already exists, it will be left untouched
* @argument overwrite: If the file already exists, it will be overwritten
*/
mode<NewWriteMode extends WriteMode>(writeMode: NewWriteMode): FsFileWrite<TEncoding, TSchema>;
/**
* Write text content to a file asynchronously.
* Creates parent directories if they don't exist.
* Respects the write mode (overwrite/preserve) setting.
*
* @param content - The content to write, will be converted to string using toString()
* @returns A promise that resolves when the write operation is complete
* @throws If the write operation fails or if parent directory creation fails
*/
text(content: Stringable): Promise<void>;
/**
* Write text content to a file synchronously.
* Creates parent directories if they don't exist.
* Respects the write mode (overwrite/preserve) setting.
*
* @param content - The content to write, will be converted to string using toString()
* @synchronous
* @throws If the write operation fails or if parent directory creation fails
*/
textSync(content: Stringable): void;
/**
* Write data as JSON to a file asynchronously.
* The data will be serialized using JSON.stringify.
* If a schema is provided, the data will be validated before writing.
*
* @typeParam T - The type of data being written
* @param data - The data to write, must be JSON-serializable
* @returns A promise that resolves when the write operation is complete
* @throws If schema validation fails or if the write operation fails
*/
json<T>(data: TSchema extends ZodSchema<infer O> ? O : T): Promise<void>;
/**
* Write data as formatted JSON to a file asynchronously.
* The data will be serialized using JSON.stringify with pretty printing.
* If a schema is provided, the data will be validated before writing.
*
* @typeParam T - The type of data being written
* @param data - The data to write, must be JSON-serializable
* @returns A promise that resolves when the write operation is complete
* @throws If schema validation fails or if the write operation fails
*/
prettyJson<T>(data: TSchema extends ZodSchema<infer O> ? O : T): Promise<void>;
/**
* Write data as JSON to a file synchronously.
* The data will be serialized using JSON.stringify.
* If a schema is provided, the data will be validated before writing.
*
* @typeParam T - The type of data being written
* @param data - The data to write, must be JSON-serializable
* @synchronous
* @throws If schema validation fails or if the write operation fails
*/
jsonSync<T>(data: TSchema extends ZodSchema<infer O> ? O : T): void;
/**
* Write data as formatted JSON to a file synchronously.
* The data will be serialized using JSON.stringify with pretty printing.
* If a schema is provided, the data will be validated before writing.
*
* @typeParam T - The type of data being written
* @param data - The data to write, must be JSON-serializable
* @synchronous
* @throws If schema validation fails or if the write operation fails
*/
prettyJsonSync<T = unknown>(data: TSchema extends ZodSchema<infer O> ? O : T): void;
/**
* Write data as YAML to a file asynchronously.
* The data will be serialized using YAML.stringify.
* If a schema is provided, the data will be validated before writing.
*
* @typeParam T - The type of data being written
* @param data - The data to write, must be YAML-serializable
* @throws If schema validation fails or if the write operation fails
*/
yaml<T = unknown>(data: TSchema extends ZodSchema<infer O> ? O : T): Promise<void>;
/**
* Write data as YAML to a file synchronously.
* The data will be serialized using YAML.stringify.
* If a schema is provided, the data will be validated before writing.
*
* @typeParam T - The type of data being written
* @param data - The data to write, must be YAML-serializable
* @synchronous
* @throws If schema validation fails or if the write operation fails
*/
yamlSync<T = unknown>(data: TSchema extends ZodSchema<infer O> ? O : T): void;
/**
* Write base64-encoded data to a file asynchronously.
* Creates parent directories if they don't exist.
* Respects the write mode (overwrite/preserve) setting.
*
* @param data - The base64-encoded string to write
* @throws If the write operation fails or if parent directory creation fails
*/
base64(data: Stringable): Promise<void>;
/**
* Write base64-encoded data to a file synchronously.
* Creates parent directories if they don't exist.
* Respects the write mode (overwrite/preserve) setting.
*
* @param data - The base64-encoded string to write
* @synchronous
* @throws If the write operation fails or if parent directory creation fails
*/
base64Sync(data: Stringable): void;
/**
* Write a markdown document to a file asynchronously.
* The markdown document will be serialized using MdDoc.toMd.
* If a schema is provided, the data will be validated before writing.
*
* @param data - The markdown document to write
* @throws If schema validation fails or if the write operation fails
*/
md(data: MdDoc): Promise<void>;
/**
* Write a markdown document to a file synchronously.
* The markdown document will be serialized using MdDoc.toMd.
* If a schema is provided, the data will be validated before writing.
*
* @param data - The markdown document to write
* @throws If schema validation fails or if the write operation fails
* @synchronous
*/
mdSync(data: MdDoc): void;
}
/**
* Create a new FsFile instance from a path, a list of paths to be resolved, or an existing FsFile instance.
* The resulting path will be an absolute path.
*
* @param args - One or more path segments to join into a file path, or an existing FsFile instance
* @returns A new FsFile instance with UTF-8 encoding
*
* ```typescript
* import { fsFile } from "@synstack/fs";
*
* const relativeFile = fsFile("./relative/path.txt");
* const existingFile = fsFile(fsFile("/path/to/existing.txt"));
* ```
*/
declare const fsFile: typeof FsFile.from;
/**
* @deprecated Changed to avoid namespacing conflicts. Use {@link fsFile} instead
*/
declare const file: typeof FsFile.from;
/**
* Interface defining chainable methods for arrays of FsFile instances.
* @internal
*/
interface FsDirArrayMethods {
filter(this: FsDirArray, fn: (dir: FsDir) => boolean): FsDirArray;
toPaths(this: FsDirArray): Array<string>;
relativePathsFrom(this: FsDirArray, dir: FsDir | FsFile): Array<string>;
}
type FsDirArray = Enhanced<"dirs_array", Array<FsDir>, FsDirArrayMethods>;
/**
* Interface defining chainable methods for arrays of FsFile instances.
* @internal
*/
interface FsFileArrayMethods {
filter(this: FsFileArray, fn: (file: FsFile<any>) => boolean): FsFileArray;
filterGlobs(this: FsFileArray, ...patterns: Array<string> | [Array<string>]): FsFileArray;
filterMimeTypes(this: FsFileArray, ...mimeTypes: Array<string>): FsFileArray;
filterDir(this: FsFileArray, dir: FsDir): FsFileArray;
filterDir(this: FsFileArray, path: string): FsFileArray;
toPaths(this: FsFileArray): Array<string>;
relativePathsFrom(this: FsFileArray, dir: FsDir | FsFile): Array<string>;
}
type FsFileArray = Enhanced<"files_array", Array<FsFile<any>>, FsFileArrayMethods>;
/**
* Create a new FsFileArray instance with the provided files.
* @param files - An array of FsFile or paths
* @returns A new FsFileArray instance
*/
declare const fsFiles: (files: Array<FsFile<any> | AnyPath>) => FsFileArray;
/**
* @deprecated Changed to avoid namespacing conflicts. Use {@link fsFiles} instead
*/
declare const files: (files: Array<FsFile<any> | AnyPath>) => FsFileArray;
/**
* Create a new FsFileArray instance with the provided files relative to the cwd directory.
* @param dir - The cwd directory
* @param files - An array of relative paths from the cwd directory
* @returns A new FsFileArray instance
*/
declare const fsFilesFromDir: (dir: FsDir) => (files: Array<FsFile<any> | AnyPath>) => FsFileArray;
/**
* @deprecated Changed to match naming convention. Use {@link fsFilesFromDir} instead
*/
declare const filesFromDir: (dir: FsDir) => (files: Array<FsFile<any> | AnyPath>) => FsFileArray;
declare class FsDir extends Pipeable<FsDir> {
private readonly _path;
protected constructor(path: AnyPath);
/**
* Get the string representation of the directory path.
*
* @returns The absolute path of the directory as a string
*
* ```typescript
* const srcDir = fsDir("./src");
* console.log(srcDir.toString()); // "/absolute/path/to/src"
* ```
*/
toString(): AnyPath;
/**
* Get the primitive value of the directory path.
*
* @returns The absolute path of the directory
*/
valueOf(): AnyPath;
/**
* Get the current instance of the directory.
* Used for type compatibility with Pipeable.
*
* @returns The current FsDir instance
*/
instanceOf(): FsDir;
/**
* Get the absolute path of the directory.
*
* @returns The absolute path as a string
*
* ```typescript
* const srcDir = fsDir("./src");
* console.log(srcDir.path); // "/absolute/path/to/src"
* ```
*/
get path(): AnyPath;
/**
* Get the relative path from this directory to another file/directory
*
* @param dirOrfile - The other directory
* @returns The relative path as a string
*/
relativePathTo(dirOrfile: FsDir | FsFile): _synstack_path.RelativePath;
/**
* Get the relative path from another file/directory to this directory
*
* @param dirOrFile - The other directory
* @returns The relative path as a string
*/
relativePathFrom(dirOrFile: FsDir | FsFile): string;
/**
* Create a new directory instance with the provided path(s).
* Resolves relative paths to absolute paths.
*
* @param arg - A path or an existing FsDir instance
* @returns A new FsDir instance with the resolved path
*
* ```typescript
* // Create from absolute path
* const rootDir = fsDir("/path/to/project");
*
* // Create from relative path
* const srcDir = fsDir("./src");
*
* // Create from existing directory
* const existingDir = fsDir(fsDir("/path/to/existing"));
* ```
*/
static cwd(this: void, arg: FsDir | AnyPath): FsDir;
/**
* Create a new directory instance with a path relative to this directory.
*
* @alias {@link to}
* @param relativePath - The relative path to append to the current directory
* @returns A new FsDir instance representing the combined path
*
* ```typescript
* const projectDir = fsDir("/path/to/project");
*
* // Navigate to subdirectories
* const srcDir = projectDir.toDir("src");
* const testDir = projectDir.toDir("tests");
*
* // Navigate up and down
* const siblingDir = srcDir.toDir("../other");
* ```
*/
toDir(relativePath: string): FsDir;
/**
* Create a new directory instance with a path relative to this directory.
*
* @alias {@link toDir}
* @param relativePath - The relative path to append to the current directory
* @returns A new FsDir instance representing the combined path
*
* ```typescript
* const projectDir = fsDir("/path/to/project");
*
* // Navigate to subdirectories
* const srcDir = projectDir.to("src");
* const testDir = projectDir.to("tests");
*
* // Navigate up and down
* const siblingDir = srcDir.to("../other");
* ```
*/
to(relativePath: string): FsDir;
/**
* Create a new file instance with a path relative to this directory.
*
* @alias {@link file}
* @param relativePath - The relative path to the file from this directory
* @returns A new FsFile instance for the specified path
* @throws If an absolute path is provided
*
* ```typescript
* const srcDir = fsDir("./src");
*
* // Access files in the directory
* const configFile = srcDir.toFile("config.json");
* const deepFile = srcDir.toFile("components/Button.tsx");
*
* // Error: Cannot use absolute paths
* srcDir.toFile("/absolute/path"); // throws Error
* ```
*/
toFile(relativePath: string): FsFile<"utf-8", undefined>;
/**
* Create a new file instance with a path relative to this directory.
*
* @alias {@link toFile}
* @param relativePath - The relative path to the file from this directory
* @returns A new FsFile instance for the specified path
* @throws If an absolute path is provided
*
* ```typescript
* const srcDir = fsDir("./src");
*
* // Access files in the directory
* const configFile = srcDir.file("config.json");
* const deepFile = srcDir.file("components/Button.tsx");
*
* // Error: Cannot use absolute paths
* srcDir.file("/absolute/path"); // throws Error
* ```
*/
file(relativePath: string): FsFile<"utf-8", undefined>;
/**
* Get the name of the directory (last segment of the path).
*
* @returns The directory name without the full path
*
* ```typescript
* const srcDir = fsDir("/path/to/project/src");
* console.log(srcDir.name()); // "src"
* ```
*/
name(): string;
/**
* Check if the directory exists in the file system.
*
* @returns A promise that resolves to true if the directory exists, false otherwise
*
* ```typescript
* const configDir = fsDir("./config");
*
* if (await configDir.exists()) {
* // Directory exists, safe to use
* const files = await configDir.glob("*.json");
* } else {
* // Create the directory first
* await configDir.make();
* }
* ```
*/
exists(): Promise<boolean>;
/**
* Check if the directory exists in the file system synchronously.
*
* @synchronous
* @returns True if the directory exists, false otherwise
*
* ```typescript
* const configDir = fsDir("./config");
*
* if (configDir.existsSync()) {
* // Directory exists, safe to use
* const files = configDir.globSync("*.json");
* } else {
* // Create the directory first
* configDir.makeSync();
* }
* ```
*/
existsSync(): boolean;
/**
* Create the directory and any necessary parent directories.
*
* @returns A promise that resolves when the directory is created
*
* ```typescript
* const assetsDir = fsDir("./dist/assets/images");
*
* // Creates all necessary parent directories
* await assetsDir.make();
* ```
*/
make(): Promise<void>;
/**
* Create the directory and any necessary parent directories synchronously.
*
* @synchronous
*
* ```typescript
* const assetsDir = fsDir("./dist/assets/images");
*
* // Creates all necessary parent directories immediately
* assetsDir.makeSync();
* ```
*/
makeSync(): void;
/**
* Move the directory to a new location.
*
* @param newPath - The new path for the directory
* @returns A promise that resolves the new directory
*/
move(newPath: FsDir | AnyPath): Promise<FsDir>;
/**
* Move the directory to a new location synchronously.
*
* @param newPath - The new path for the directory
* @returns The new directory
*/
moveSync(newPath: FsDir | AnyPath): FsDir;
/**
* Remove the directory and all its contents recursively.
* If the directory doesn't exist, the operation is silently ignored.
*
* @returns A promise that resolves when the directory is removed
*
* ```typescript
* const tempDir = fsDir("./temp");
*
* // Remove directory and all contents
* await tempDir.rm();
* ```
*/
rm(): Promise<void>;
/**
* Remove the directory and all its contents recursively synchronously.
* If the directory doesn't exist, the operation is silently ignored.
*
* @synchronous
*
* ```typescript
* const tempDir = fsDir("./temp");
*
* // Remove directory and all contents immediately
* tempDir.rmSync();
* ```
*/
rmSync(): void;
/**
* Find files in the directory that match the specified glob patterns.
*
* @param patterns - One or more glob patterns to match against
* @returns A promise that resolves to an FsFileArray containing the matching files
*
* ```typescript
* const srcDir = fsDir("./src");
*
* // Find all TypeScript files
* const tsFiles = await srcDir.glob("**\/*.ts");
*
* // Find multiple file types
* const assets = await srcDir.glob("**\/*.{png,jpg,svg}");
*
* // Use array of patterns
* const configs = await srcDir.glob(["*.json", "*.yaml"]);
* ```
*/
glob(...patterns: Array<string> | [Array<string>]): Promise<FsFileArray>;
/**
* Find files in the directory that match the specified glob patterns synchronously.
*
* @param patterns - One or more glob patterns to match against
* @returns An FsFileArray containing the matching files
* @synchronous
*
* ```typescript
* const srcDir = fsDir("./src");
*
* // Find all TypeScript files synchronously
* const tsFiles = srcDir.globSync("**\/*.ts");
*
* // Find multiple file types
* const assets = srcDir.globSync("**\/*.{png,jpg,svg}");
* ```
*/
globSync(...patterns: Array<string> | [Array<string>]): FsFileArray;
/**
* Find folders in the directory that match the specified glob patterns.
*
* @param patterns - One or more glob patterns to match against
* @returns A promise that resolves to an FsDirArray containing the matching folders
*/
globDirs(...patterns: Array<string> | [Array<string>]): Promise<FsDirArray>;
/**
* Find folders in the directory that match the specified glob patterns synchronously.
*
* @param patterns - One or more glob patterns to match against
* @returns An FsDirArray containing the matching folders
* @synchronous
*/
globDirsSync(...patterns: Array<string> | [Array<string>]): FsDirArray;
/**
* Find files tracked by git in the directory.
*
* @returns A promise that resolves to an FsFileArray containing the git-tracked files
*
* ```typescript
* const projectDir = fsDir("./project");
*
* // Get all git-tracked files in the directory
* const trackedFiles = await projectDir.gitLs();
* ```
*/
gitLs(): Promise<FsFileArray>;
/**
* Execute a command in the directory.
*/
exec(template: TemplateStringsArray, ...args: Array<TemplateExpression>): Promise<execa.Result<{
cwd: string;
}>>;
}
/**
* Create a new directory instance with the provided path.
* Resolves relative paths to absolute paths.
*
* @param arg - A path or an existing FsDir instance
* @returns A new FsDir instance with the resolved path
*
* ```typescript
* // Create from absolute path
* const rootDir = fsDir("/path/to/project");
*
* // Create from relative path
* const srcDir = fsDir("./src");
*
* // Create from existing directory
* const existingDir = fsDir(fsDir("/path/to/existing"));
* ```
*/
declare const fsDir: typeof FsDir.cwd;
/**
* @deprecated Changed to avoid namespacing conflicts. Use {@link fsDir} instead
*/
declare const dir: typeof FsDir.cwd;
export { FsDir, FsFile, type FsFileArray, dir, file, files, filesFromDir, fsDir, fsFile, fsFiles, fsFilesFromDir };