@remotex-labs/xbuild
Version:
A versatile JavaScript and TypeScript toolchain build system
3,259 lines • 128 kB
TypeScript
/**
* This file was automatically generated by xBuild.
* DO NOT EDIT MANUALLY.
*/
import type { SourceService } from '@remotex-labs/xmap';
import { SourceService } from '@remotex-labs/xmap';
export type { BuildResult, OnLoadArgs, OnLoadResult, OnResolveArgs, OnResolveResult, PluginBuild } from 'esbuild';
import type { BuildResult } from 'esbuild';
import type { BuildOptions } from 'esbuild';
import type { IncomingMessage, ServerResponse } from 'http';
import type { Loader, OnLoadArgs, BuildResult, OnEndResult, PluginBuild, OnLoadResult, OnResolveArgs, OnResolveResult } from 'esbuild';
import type { Format } from 'esbuild';
import type { Argv } from 'yargs';
import type { ChildProcessWithoutNullStreams } from 'child_process';
import type { Loader, Metafile, OnLoadArgs, OnLoadResult } from 'esbuild';
import type { BuildOptions, BuildResult, Metafile } from 'esbuild';
import type { Message } from 'esbuild';
import type { Plugin } from 'esbuild';
import type { ParsedCommandLine, Diagnostic } from 'typescript';
import type { OutputFile } from 'typescript';
import type { FormatDiagnosticsHost } from 'typescript';
import type { CompilerOptions, IScriptSnapshot } from 'typescript';
import type { ParsedCommandLine, LanguageService } from 'typescript';
import type { Context } from 'vm';
#!/usr/bin/env node
/**
* Import will remove at compile time
*/
export {};
/**
* Imports
*/
/**
* Represents an error specific to the xBuild process.
*
* The `xBuildError` class extends the `BaseError` class to provide a custom error type for the xBuild system.
* It includes additional functionality to maintain stack trace information and assigns a specific name to
* the error, making it easier to identify and handle in different parts of the application.
*
* @augments BaseError
*/
declare class xBuildError extends BaseError {
/**
* Original error stack
*/
originalErrorStack: string | undefined;
/**
* Creates an instance of `xBuildError`.
*
* @param message - The error message that describes the error. This message is passed to the base class
* `BaseError` constructor and is used to provide context about the nature of the error.
* @param options - Optional configuration for the error. This can include additional properties or settings
* that customize the error's behavior.
*/
constructor(message: string, options?: ErrorOptions);
}
/**
* Import will remove at compile time
*/
/**
* A base class for custom errors with enhanced stack trace formatting and source code information.
*
* The `BaseError` class extends the native `Error` class, adding functionality to format the error stack
* trace and include details from a source map service. This is useful for debugging errors in compiled
* or transpiled code by providing clearer information about the source of the error.
*/
export declare abstract class BaseError extends Error {
readonly sourceMap?: SourceService | undefined;
callStacks: Array<NodeJS.CallSite>;
/**
* Creates a new instance of `BaseError`.
*
* This constructor initializes a new `BaseError` instance by setting the error message and formatting
* the stack trace using the provided source map information. It also ensures the stack trace is maintained
* correctly by using `Error.captureStackTrace` (if available). The default source map service is used if
* none is provided.
*
* @param message - A descriptive error message to be associated with the error.
* @param sourceMap - (Optional) The `SourceService` instance used to format and resolve the stack trace.
* If not provided, the default source map service (`defaultSourceService`) is used.
*/
protected constructor(message: string, sourceMap?: SourceService | undefined);
/**
* Reformats the error stack trace using source map information.
*
* This function enhances the original error stack trace by attempting to map each entry
* back to its original position in the source file using the provided source map service.
* If the source map information is not available, it returns the original stack trace.
*
* @param error - The original error with stack trace of the error.
* @returns The reformatted stack trace or the original stack trace if no mapping is available.
*/
protected reformatStack(error: ErrorType): string;
}
/**
* A custom error type that extends the native `Error` object by adding a `callStacks` property.
* This property contains an array of `NodeJS.CallSite` objects, representing the call stack details.
*/
/**
* Represents an enhanced error type that extends the built-in Error object.
* This type adds an optional property to store call stack information.
*
* @type ErrorType
*
* @extends Error
*
* @property callStacks - An optional array of call sites
* captured when the error was created. This can provide additional context
* regarding the call stack at the time of the error, useful for debugging.
*
* @example
* ```ts
* const myError: ErrorType = new Error("Something went wrong!");
* myError.callStacks = getCallStack(); // Assuming getCallStack captures call sites.
* console.error(myError);
* ```
*/
type ErrorType = Error & {
callStacks?: Array<NodeJS.CallSite>;
};
/**
* Represents the state of a stack trace, containing information about the error, associated code, and formatted error message.
*
* @interface StackTraceStateInterface
* @property error - The error object with attached `callStacks`.
* @property blockCode - The block of code (if any) related to the error, or `null` if unavailable.
* @property formattedError - A formatted string representing the error details.
*/
interface StackTraceStateInterface {
error: ErrorType & BaseError;
blockCode: null | string;
formattedError: string;
}
/**
* Represents detailed information about a specific frame in the call stack.
*
* @interface FrameDetailsInterface
* @property line - The line number where the frame occurred.
* @property column - The column number where the frame occurred.
* @property source - The source file path where the frame occurred.
* @property functionName - The name of the function being executed at this frame, or an empty string if not available.
*/
interface FrameDetailsInterface {
line: number;
column: number;
source: string;
functionName: string;
}
/**
* Import will remove at compile time
*/
declare const xBuildLazy: {
service: SourceService;
};
/**
* Prepares the error stack trace for display.
*
* This function overrides the default stack trace preparation to provide a custom format,
* including enhanced stack trace information and error details.
*
* @param error - The error object (Error or BaseError).
* @param stackEntries - The array of stack entries from the call stack.
* @returns The formatted stack trace as a string.
*/
declare function formatStackTrace(error: ErrorType & BaseError, stackEntries: Array<NodeJS.CallSite>): string;
/**
* An enumeration of ANSI color codes used for text formatting in the terminal.
*
* These colors can be used to format terminal output with various text colors,
* including different shades of gray, yellow, and orange, among others.
*
* Each color code starts with an ANSI escape sequence (`\u001B`), followed by the color code.
* The `Reset` option can be used to reset the terminal's text formatting back to the default.
*
* @example
* ```ts
* console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);
* ```
*/
declare const enum Colors {
Reset = "\u001B[0m",
Red = "\u001B[38;5;9m",
Gray = "\u001B[38;5;243m",
Cyan = "\u001B[38;5;81m",
DarkGray = "\u001B[38;5;238m",
LightCoral = "\u001B[38;5;203m",
LightOrange = "\u001B[38;5;215m",
OliveGreen = "\u001B[38;5;149m",
BurntOrange = "\u001B[38;5;208m",
LightGoldenrodYellow = "\u001B[38;5;221m",
LightYellow = "\u001B[38;5;230m",
CanaryYellow = "\u001B[38;5;227m",
DeepOrange = "\u001B[38;5;166m",
LightGray = "\u001B[38;5;252m",
BrightPink = "\u001B[38;5;197m"
}
/**
* Formats a message string with the specified ANSI color and optionally resets it after the message.
*
* This function applies an ANSI color code to the provided message,
* and then appends the reset code to ensure that the color formatting doesn't extend beyond the message.
* It's useful for outputting colored text in a terminal. If color formatting is not desired,
* the function can return the message unformatted.
*
* @param color - The ANSI color code to apply. This is used only if `activeColor` is true.
* @param msg - The message to be formatted with the specified color.
* @param activeColor - A boolean flag indicating whether color formatting should be applied. Default is `__ACTIVE_COLOR`.
*
* @returns A string with the specified color applied to the message,
* followed by a reset sequence if `activeColor` is true.
*
* @example
* ```ts
* const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');
* console.log(coloredMessage);
* ```
*
* @example
* ```ts
* const plainMessage = setColor(Colors.LightOrange, 'This is a light orange message', false);
* console.log(plainMessage); // Output will be without color formatting
* ```
*/
declare function setColor(color: Colors, msg: string, activeColor?: boolean): string;
/**
* Import will remove at compile time
*/
/**
* Imports
*/
/**
* A custom error class to handle errors occurring within a virtual machine (VM) execution context.
*
* The `VMRuntimeError` class extends the native `Error` class and enhances the error with
* source map information to map stack traces back to the original source. This is particularly
* useful when debugging errors from code executed in a `vm` or `evalmachine` environment.
*
* @param message - The error message describing the error.
* @param originalError - The original error object thrown from the VM execution.
* @param sourceMap - The `SourceService` providing source map data to link the error to its original source.
*
* @example
* ```ts
* try {
* vm.run(someCode);
* } catch (error) {
* throw new VMRuntimeError("VM execution failed", error, sourceMapService);
* }
* ```
*/
declare class VMRuntimeError extends BaseError {
/**
* The original error thrown during the VM execution.
*/
originalError: Error;
/**
* Original error stack
*/
originalErrorStack: string | undefined;
/**
* Creates a new VMRuntimeError instance.
*
* This constructor initializes a new `VMRuntimeError` object, extending the native `Error` class with
* additional information, including the original error and optional source map data. It also ensures that
* the stack trace is correctly captured and reformatted using the source map (if provided) to enhance
* debugging.
*
* @param originalError - The original error object that was thrown during the VM execution.
* @param sourceMap - (Optional) The source map service used to map the error stack trace to its original
* source code locations. If not provided, this will be `null`.
*
* @example
* ```ts
* try {
* vm.run(code);
* } catch (error) {
* throw new VMRuntimeError(error, sourceMapService);
* }
* ```
*/
constructor(originalError: ErrorType, sourceMap?: SourceService);
}
/**
* Exports
*/
/**
* Import will remove at compile time
*/
/**
* Imports
*/
import '@errors/stack.error';
import '@errors/uncaught.error';
/**
* Main run function that initiates the build process based on CLI arguments.
*
* This function parses the CLI arguments, configures the build settings, and executes
* the appropriate build tasks, including type checking, serving, or running in debug mode.
*
* @param argv - An array of strings representing the CLI arguments.
*
* @returns A promise that resolves when all build tasks are completed.
*
* @example
* ```ts
* await buildWithArgv(process.argv);
* ```
*/
declare function buildWithArgv(argv: Array<string>): Promise<void>;
/**
* Builds the project using a configuration file specified by its path.
*
* This function reads the configuration from the provided file path, processes it,
* and initiates the build tasks.
*
* @param configFilePath - The path to the configuration file to be used for the build.
*
* @returns A promise that resolves to an array of `BuildResult` objects once all build tasks are completed.
*
* @throws Error Throws an error if the configuration file does not exist or is invalid.
*
* @example
* ```ts
* const results = await buildWithPath('./config.ts');
* console.log('Build results:', results);
* ```
*/
declare function buildWithConfigPath(configFilePath: string): Promise<BuildResult[]>;
/**
* Builds the project based on the provided configuration object.
*
* This function processes the given configuration and executes the build tasks accordingly.
*
* @param config - A partial configuration object used to define the build settings.
*
* @returns A promise that resolves to an array of `BuildResult` objects once all build tasks are completed.
*
* @example
* ```ts
* const results = await build({ entryPoints: ['./src/index.ts'] });
* console.log('Build results:', results);
* ```
*/
declare function build(config: PartialDeepConfigurationsType): Promise<BuildResult[]>;
/**
* Import will remove at compile time
*/
/**
* Represents the format for specifying entry points in TypeScript declaration generation and esbuild configuration.
*
* This type allows for various formats to specify the entry points from which TypeScript declaration files should be generated.
* The supported formats are:
* - `Array<string>`: An array of file paths as strings. Each string represents a path to a TypeScript entry point file.
* For example: `['src/index.ts', 'src/utils.ts']`.
*
* - `Record<string, string>`: An object where each key-value pair represents an entry point.
* The key is used as the output file name (without extension), and the value is the file path to the TypeScript entry point.
* For example: `{ main: 'src/index.ts', utils: 'src/utils.ts' }`.
*
* - `Array<{ in: string, out: string }>`: An array of objects, where each object specifies an input file path (`in`)
* and an output file path (`out`). This format allows for specifying where each entry point file is located and
* where its corresponding declaration file should be output.
* For example: `[{ in: 'src/index.ts', out: 'dist/index.d.ts' }]`.
*
* The chosen format affects how the build system processes your entry points and generates output files.
*
* @example
* ```ts
* // Array of file paths
* const entryPoints1: EntryPointsType = ['src/index.ts', 'src/utils.ts'];
*
* // Object with named entry points
* const entryPoints2: EntryPointsType = {
* main: 'src/index.ts',
* utils: 'src/utils.ts'
* };
*
* // Array of objects with explicit input and output paths
* const entryPoints3: EntryPointsType = [
* { in: 'src/index.ts', out: 'dist/index.d.ts' },
* { in: 'src/utils.ts', out: 'dist/utils.d.ts' }
* ];
* ```
*
* When used with esbuild configuration, the format determines how output files are named and structured.
* When used for TypeScript declaration generation, it affects how declaration files are generated and organized.
*/
type EntryPointsType = (string | {
in: string;
out: string;
})[] | Record<string, string> | undefined;
/**
* Represents a deeply nested partial version of a given type `T`.
*
* This type utility allows for partial objects at any level of nesting.
* It recursively makes all properties optional and applies the same behavior to nested objects.
*
* **Example Usage:**
*
* ```ts
* interface User {
* name: string;
* address: {
* street: string;
* city: string;
* };
* }
*
* // PartialDeepType<User> will allow the following:
* const partialUser: PartialDeepType<User> = {
* name: 'Alice', // 'name' is optional
* address: {
* city: 'Wonderland' // 'street' is optional
* }
* };
* ```
*
* @template T - The type to be made partially optional and deeply nested.
*
* @typeParam T - The base type to apply the partial transformation.
*
* @example
* ```
* type MyPartial = PartialDeepType<{ a: number; b: { c: string; d: { e: boolean } } }>;
* // MyPartial will be equivalent to:
* // {
* // a?: number;
* // b?: {
* // c?: string;
* // d?: {
* // e?: boolean;
* // }
* // }
* // }
* ```
*/
type PartialDeepType<T> = {
[P in keyof T]?: T[P] extends object ? PartialDeepType<T[P]> : T[P];
};
/**
* Represents a module with its exports and an optional default export.
*
* This interface provides a structure to define and interact with the exports of a module.
* It includes both named and default exports, where default exports are of a specific type.
*
* @interface ModuleInterface
*
* @property exports - An object representing the exports of the module.
* The keys are strings that represent the names of the exports, and the values can be of any type.
*
* @property exports[key: string] - A dictionary where each key is a string representing the export name,
* and the associated value can be of any type.
*
* @property [exports.default] - An optional default export.
* The default export, if present, is of type `ConfigurationInterface`.
*/
interface ModuleInterface {
/**
* An object representing the exports of the module.
* The keys are strings representing export names, and the values can be of any type.
*
* @property default - An optional default export of type `ConfigurationInterface`.
*/
exports: {
[key: string]: unknown;
default?: ConfigurationInterface;
};
}
/**
* Configuration options for the serve the build.
*
* This object allows you to specify various settings related to the server,
* such as the port, host, SSL/TLS certificates, and request handling functions.
*
* @example
* ```ts
* const serverConfig = {
* serve: {
* active: true,
* port: 8080,
* host: 'localhost',
* keyfile: '/path/to/ssl/keyfile.pem',
* certfile: '/path/to/ssl/certfile.pem',
* onStart: () => {
* console.log('Server started');
* }
* onRequest: (req, res, next) => {
* console.log('Server request received');
* next();
* }
* }
* };
* ```
*
* @public
*/
interface ServeInterface {
port: number;
host: string;
active: boolean;
keyfile?: string;
certfile?: string;
onRequest?: (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
onStart?: () => void;
}
/**
* Defines the lifecycle HooksInterface used in the plugin system.
*
* This interface specifies the types for various HooksInterface that can be registered
* to customize the behavior of the build process. Each hook corresponds to a
* specific stage in the lifecycle of an esbuild operation.
*
* @interface HooksInterface
*
* @property onEnd - A hook function that is called after the build process completes.
* This allows for post-processing or cleanup tasks.
* @property onLoad - A hook function that is called when esbuild attempts to load a module.
* It can be used to modify the contents of the loaded module.
* @property onStart - A hook function that is called before the build process starts.
* This is useful for initialization tasks or logging.
* @property onResolve - A hook function that is called when esbuild attempts to resolve a module path.
* It can be used to customize module resolution behavior.
*
* @example
* ```ts
* const myHooks: HooksInterface = {
* onEnd: async (result) => {
* console.log('Build finished:', result);
* },
* onLoad: async (contents, loader, args) => {
* // Modify contents if necessary
* return { contents, loader };
* },
* onStart: async (build) => {
* console.log('Build started:', build);
* },
* onResolve: async (args) => {
* if (args.path === 'my-module') {
* return { path: './src/my-module.ts' };
* }
* return null;
* }
* };
* ```
*
* @see OnEndType
* @see OnLoadType
* @see OnStartType
* @see OnResolveType
*/
interface HooksInterface {
onEnd: OnEndType;
onLoad: OnLoadType;
onStart: OnStartType;
onSuccess: OnEndType;
onResolve: OnResolveType;
}
/**
* Represents the configuration options for the build and development process.
*
* This interface defines various settings that control how the application is built and run, including development mode,
* file watching, TypeScript declaration generation, error handling, TypeScript type checking, and esbuild bundler options.
*
* @example
* ```ts
* const config: ConfigurationInterface = {
* dev: true,
* watch: true,
* declaration: true,
* buildOnError: false,
* noTypeChecker: false,
* esbuild: {
* entryPoints: ['./src/index.ts'],
* bundle: true,
* minify: true,
* target: 'es2020'
* },
* hooks: {
* onStart: async (build) => {
* console.log('Build started');
* },
* onEnd: async (result) => {
* console.log('Build finished:', result);
* }
* }
* };
* ```
*
* In this example, the configuration sets the application to development mode with file watching enabled,
* generates TypeScript declaration files, continues building on TypeScript errors, and includes esbuild options for bundling and minification.
* Additionally, custom hooks are provided to log messages at the start and end of the build process.
*
* @public
* @category Configuration
*/
interface ConfigurationInterface {
/**
* Build and run entryPoint for development
*/
dev: boolean | Array<string>;
/**
* Enables watching for file changes during development.
*/
watch: boolean;
/**
* The directory where the generated `package.json` file will be saved,
* indicating the module type (`"commonjs"` or `"module"`).
*
* - If the format is `esm`, the `package.json` file will contain `"type": "module"`.
* - If the format is `cjs`, the `package.json` file will contain `"type": "commonjs"`.
*
* If this field is not set (`undefined`), the `package.json` file will be saved in the
* `outdir` specified in the esbuild configuration.
*
* Example:
*
* ```ts
* {
* esbuild: {
* outdir: 'dist',
* format: 'esm'
* },
* moduleTypeOutDir: 'custom/dist'
* }
* // This will create 'custom/dist/package.json' with the content: {"type": "module"}
*
* // If moduleTypeOutDir is not provided:
* {
* esbuild: {
* outdir: 'dist',
* format: 'cjs'
* }
* }
* // This will create 'dist/package.json' with the content: {"type": "commonjs"}
* ```
*/
moduleTypeOutDir?: string;
/**
* Generates TypeScript declaration files.
*/
declaration: boolean;
/**
* Bundle declaration file
*/
bundleDeclaration: boolean;
/**
* Overrides the output directory for TypeScript declaration files (.d.ts).
*
* If this option is not set, the output directory specified in the `outDir`
* field of your `tsconfig.json` will be used.
* This allows for custom control
* over where the declaration files are emitted, separate from the main
* output directory for compiled JavaScript files.
*
* @default The `outDir` from `tsconfig.json` will be used if this is not provided.
*/
declarationOutDir?: string;
/**
* Continues building even if TypeScript type errors are present.
*/
buildOnError: boolean;
/**
* Skips TypeScript type checking.
*/
noTypeChecker: boolean;
/**
* Options for the esbuild bundler.
*/
esbuild: BuildOptions;
/**
* Option for the serve the build over http/s
*/
serve: ServeInterface;
/**
* lifecycle hooks to customize the build process.
*
* This property allows you to provide implementations for various HooksInterface defined in the `HooksInterface` interface.
* Using `Partial<HooksInterface>` means you can specify only the HooksInterface you want to implement,
* while the others will default to `undefined`.
*/
hooks?: Partial<HooksInterface>;
/**
* A dictionary of define options for the build process.
*
* This property allows you to specify global constants that can be replaced during the build process.
* Each key-value pair in the `define` object represents a constant where the key is the name of the
* constant, and the value is the string to replace it with. This is particularly useful for feature flags,
* environment-specific configurations, or any other value that you may want to define at compile time.
*
* @example
* ```ts
* const config: ConfigurationInterface = {
* dev: true,
* define: {
* 'process.env.NODE_ENV': 'development',
* 'API_URL': 'https://api.example.com'
* }
* };
* ```
*
* In this example, the constants `process.env.NODE_ENV` and `API_URL` will be replaced with their
* corresponding values during the build, making it easy to manage different configurations across
* various environments.
*
* @public
*/
define: Record<string, unknown>;
/** Documentation: https://esbuild.github.io/api/#banner */
banner?: {
[type: string]: string | (() => string);
};
/** Documentation: https://esbuild.github.io/api/#footer */
footer?: {
[type: string]: string | (() => string);
};
}
interface ExportedConfigurationInterface extends ConfigurationInterface {
/**
* Options for the esbuild bundler.
*/
esbuild: Omit<BuildOptions, 'plugins' | 'define'>;
}
/**
* Type alias for a partial configuration object.
*
* This type represents a configuration where all properties of the
* `ConfigurationInterface` are optional. It allows for flexible configuration
* objects where only a subset of properties need to be specified.
*/
type xBuildConfig = PartialDeepType<ExportedConfigurationInterface>;
/**
* Represents a partially deep configuration type based on the `ConfigurationInterface`.
*
* This type is used to define configurations that may have some properties
* missing or undefined. It leverages the `PartialDeepType` utility type to allow
* for flexibility in configuration management.
*/
type PartialDeepConfigurationsType = PartialDeepType<ConfigurationInterface>;
/**
* Defines the possible types for configurations.
*
* This type can either be a single instance of `PartialDeepConfigurationsType`
* or an array of such instances. This flexibility allows for configurations
* to be specified as a single object or as multiple objects, enabling
* support for various build setups.
*
* @example
* ```ts
* // A single configuration object
* const config: ConfigurationsType = {
* esbuild: {
* bundle: true,
* outdir: 'dist'
* }
* };
* ```
*
* @example
* ```ts
* // An array of configuration objects
* const configs: ConfigurationsType = [
* {
* esbuild: {
* bundle: true,
* outdir: 'dist/esm'
* }
* },
* {
* esbuild: {
* bundle: false,
* outdir: 'dist/cjs',
* declaration: false,
* noTypeChecker: true
* }
* }
* ];
* ```
*/
type ConfigurationsType = PartialDeepConfigurationsType | Array<PartialDeepConfigurationsType>;
export {};
/**
* Import will remove at compile time
*/
/**
* Interface for the build state that users can modify.
*
* This interface allows users to store and manage any custom data related to the build process.
*
* @template T - The type of values that can be stored in the state.
*/
interface PluginsBuildStateInterface {
[key: string]: unknown;
}
/**
* A type that defines the possible return values of a plugin function.
*
* The function can return a Promise that resolves to `null` or `void`, or it can return `null` or `void` directly.
*/
type PluginResultType = Promise<null | void> | null | void;
/**
* Defines the signature of a function that is called at the end of the build process.
*
* @param result - The `BuildResult` object that contains information about the outcome of the build process.
* @param state - The current build state that users can modify.
* @returns A `PluginResultType`, which may include asynchronous operations.
*/
type OnEndType = (result: BuildResult, state: PluginsBuildStateInterface) => PluginResultType | OnEndResult | Promise<OnEndResult>;
/**
* Defines the signature of a function that is called at the start of the build process.
*
* @param build - The `PluginBuild` object that contains information about the build process and allows modifying build options.
* @param state - The current build state that users can modify.
* @returns A `PluginResultType`, which may include asynchronous operations.
*/
type OnStartType = (build: PluginBuild, state: PluginsBuildStateInterface) => PluginResultType | OnEndResult | Promise<OnEndResult>;
/**
* Defines the signature of a function that is called during the resolution of an import path.
*
* @param args - The `OnResolveArgs` object, containing information about the file being resolved, such as its path, importer, namespace, etc.
* @param state - The current build state that users can modify.
* @returns A `Promise` or a direct `OnResolveResult` which can modify the resolved path, or a `PluginResultType` for
* performing additional async tasks without altering resolution.
*/
type OnResolveType = (args: OnResolveArgs, state: PluginsBuildStateInterface) => Promise<OnResolveResult | PluginResultType> | OnResolveResult | PluginResultType;
/**
* Defines the signature of a function that is called when a file is loaded.
*
* @param content - The content of the file being loaded, as either a `string` or `Uint8Array`.
* @param loader - The type of loader used for the file, such as `js`, `ts`, `json`, or others. It can also be `undefined`.
* @param args - The `OnLoadArgs` object, containing information about the file being loaded, such as its path, namespace, etc.
* @param state - The current build state that users can modify.
* @returns A `Promise` or direct `OnLoadResult`, which can modify the file content and loader, or a `PluginResultType`
* for performing additional async tasks without altering the content.
*/
type OnLoadType = (content: string | Uint8Array, loader: Loader | undefined, args: OnLoadArgs, state: PluginsBuildStateInterface) => Promise<OnLoadResult | PluginResultType> | OnLoadResult | PluginResultType;
/**
* Import will remove at compile time
*/
/**
* Interface representing the command-line arguments for the build tool.
*
* @interface ArgvInterface
* @property typeCheck - Flag indicating if the tool should perform type checking only.
* @property node - Flag indicating if the build is intended for Node.js environment.
* @property file - The entry file(s) to build.
* @property dev - List of development-related options for the build.
* @property debug - List of debugging-related options for the build.
* @property serve - Flag indicating if an HTTP server should be started for the build folder.
* @property outdir - The output directory for the build files.
* @property declaration - Flag indicating if TypeScript declaration files should be generated.
* @property watch - Flag indicating if the build should watch for file changes.
* @property config - Path to the build configuration file (JavaScript or TypeScript).
* @property tsconfig - Path to the TypeScript configuration file to use.
* @property minify - Flag indicating if the code should be minified.
* @property bundle - Flag indicating if the code should be bundled.
* @property format - Defines the formats for the build output.
*/
interface ArgvInterface {
typeCheck: boolean;
node: boolean;
file: string;
dev: Array<string>;
debug: Array<string>;
serve: boolean;
outdir: string;
declaration: boolean;
watch: boolean;
config: string;
tsconfig: string;
minify: boolean;
bundle: boolean;
format: Format;
}
/**
* Handles uncaught exceptions in the Node.js process.
*
* This handler is triggered when an error is thrown that is not caught by any try-catch blocks.
* It captures such exceptions and logs them to the console. If the exception is an instance of `Error`,
* its string representation is logged. Otherwise, the raw error object is logged.
*
* This setup helps in debugging by ensuring that all uncaught exceptions are logged, providing visibility
* into errors that might otherwise go unnoticed.
*
* @example
* ```ts
* process.on('uncaughtException', (error) => {
* if (error instanceof Error) {
* console.error(error.toString());
* } else {
* console.error(error);
* }
* });
* ```
*
* @throws Will log uncaught exceptions to the console.
* Custom handling logic should be added if additional error handling or logging is required.
*/
export {};
/**
* Import will remove at compile time
*/
/**
* Parses command-line arguments into an `ArgvInterface` object using `yargs`.
*
* This function configures `yargs` to handle various build-related options for a JavaScript and TypeScript toolchain.
* It returns an object that adheres to the `ArgvInterface` structure based on the parsed arguments.
*
* @param argv - An array of command-line arguments (e.g., `process.argv`).
* @returns An object representing the parsed command-line arguments.
*
* @see {@link ArgvInterface} for the structure of the returned object.
*
* @example
* // Example usage:
* const args = argvParser(process.argv);
* console.log(args.file); // Output: the file to build
* console.log(args.dev); // Output: true or false based on the --dev flag
*/
declare function argvParser(argv: Array<string>): Argv<ArgvInterface>;
/**
* Import will remove at compile time
*/
/**
* Manages the build process for a TypeScript project using esbuild.
*
* The `BuildService` class orchestrates the build process, including TypeScript compilation, handling of build errors,
* and lifecycle management of the build. It can operate in various modes, such as watching for file changes or running
* in development mode. It also provides functionality for spawning development processes and processing entry points.
*
* @remarks
* - The build process can be configured using the provided `ConfigurationInterface`.
* - Errors related to TypeScript are handled separately and are not logged by default.
* - The class supports various build modes, including watch mode and development mode, and handles different scenarios
* based on the configuration.
*
* @public
* @category Services
*/
declare class BuildService {
private config;
/**
* Provides TypeScript-related functionality for the build process.
*/
readonly typescriptModule: TypescriptModule;
/**
* Keeps track of active development processes spawned during the build.
* This property holds an array of `ChildProcessWithoutNullStreams` instances that represent Node.js processes spawned
* for running development tasks. These processes are used to handle development builds or runtime tasks and are managed
* by the `BuildService` class to ensure they are properly started and stopped.
*
* @remarks
* - The array is populated when development processes are spawned, such as when specific development files are
* processed or when running in development mode.
* - The processes are terminated gracefully at the end of the build to avoid leaving orphaned processes running.
* - It is important to manage these processes correctly to avoid resource leaks and ensure proper cleanup.
*
* @see ChildProcessWithoutNullStreams
*/
private activePossess;
/**
* Plugin provider
*
* @private
*/
private pluginsProvider;
/**
* A mapping of output filenames to their corresponding source file paths.
*
* @remarks
* This property stores the entry points configuration for TypeScript compilation.
* - Keys represent the output filenames (with or without .d.ts extension)
* - Values represent the source file paths to use as entry points
*
* Used by declaration bundling operations to determine which files to process
* and how to name the resulting declaration outputs.
*
* @example
* ```ts
* // Example entryPoints structure
* {
* 'index': 'src/index.ts',
* 'components/button': 'src/components/button.ts'
* }
* ```
*
* @private
* @since 1.5.9
*/
private readonly entryPoints;
/**
* Initializes the build service with the provided configuration.
*
* The constructor configures the TypeScript provider, suppresses esbuild logging,
* sets up development modes, and registers the necessary plugins.
*
* Declaration files will be output based on the following order of precedence:
* 1. If `declarationOutDir` is set in the configuration, it will be used.
* 2. If `declarationOutDir` is not provided, it will use the `outDir` value from the tsconfig.
* 3. If neither of the above is available, it falls back to using the `outdir` specified in the esbuild configuration.
*
* @param config - The configuration object for the build process, including esbuild and TypeScript settings.
*/
constructor(config: ConfigurationInterface);
/**
* Executes the build process.
* This method performs the build and handles any errors that occur during the execution.
* If watching or development mode is enabled in the configuration, it starts watching for changes
* to automatically rebuild as needed.
* The method logs errors that are not related to TypeScript
* compilation issues.
*
* @returns A promise that resolves with a `BuildResult` when the build process is complete,
* or `undefined` if an error occurs during execution.
*
* @throws Error Throws an error if the build process encounters issues that are not related
* to TypeScript. Such errors are logged, but the method does not rethrow them.
*
* @example
* ```ts
* import { BuildService } from './build-service';
*
* const buildService = new BuildService(config);
* buildService.run().then(() => {
* console.log('Build process completed successfully.');
* }).catch((error) => {
* console.error('Build process failed:', error);
* });
* ```
*
* In this example, the `run` method is invoked to execute the build process. It handles both successful
* completion and logs any encountered errors, allowing the user to understand the outcome of the build.
*/
run(): Promise<BuildResult | void>;
/**
* Runs the build process in debug mode for the specified entry points.
* This method temporarily disables development and watch mode, initiates the build process, and spawns development processes
* for the specified entry points. If any errors occur during the build, they are handled appropriately.
*
* @param entryPoints - An array of entry point file names for which the development processes will be spawned.
* These entry points are matched against the build output files.
*
* @returns A `Promise<void>` that resolves when the build and process spawning have completed.
*
* @throws Handles any build-related errors using the `handleErrors` method.
*
* @remarks
* - The `config.dev` and `config.watch` settings are temporarily disabled to prevent development mode or file watching during the build.
* - The `build()` method is called to generate the necessary build outputs.
* - The `spawnDev` method is then invoked to spawn processes for the matching entry points.
* - If any errors occur during the build, they are caught and passed to the `handleErrors` method.
*
* @example
* ```ts
* const entryPoints = ['index', 'main'];
* await this.runDebug(entryPoints);
* ```
*
* In this example, the `runDebug` method runs the build process and spawns development processes for `index` and `main`.
*
* @public
*/
runDebug(entryPoints: Array<string>): Promise<void>;
/**
* Serves the project and watches for changes.
* This method starts the development server using the `ServerProvider`, builds the project using esbuild,
* and watches for file changes to automatically rebuild as needed. It initializes the server and invokes
* the build process, enabling continuous development mode.
*
* @returns A promise that resolves when the server is started and the build process is complete.
*
* @throws This method catches any errors thrown during the build process and handles them using the
* `handleErrors` method.
*
* @example
* ```ts
* const buildService = new BuildService(config);
* buildService.serve().then(() => {
* console.log('Server is running and watching for changes.');
* }).catch((error) => {
* console.error('Failed to start the server:', error);
* });
* ```
*
* In this example, the `serve` method starts the server and watches for changes. If an error occurs during
* the build or server startup, it is handled and logged.
*/
serve(): Promise<void>;
/**
* Executes a provided asynchronous callback function within a try-catch block.
* This method ensures that any errors thrown during the execution of the callback
* are properly handled and logged. If the error appears to be an `esbuild`-related
* `OnEndResult` error with an array of errors, it avoids redundant logging.
* Otherwise, it wraps the error in a `VMRuntimeError` and logs the stack trace.
*
* @template T - The return type of the callback function, allowing flexibility
* in the expected result type. Defaults to `BuildResult`.
*
* @param callback - A function that returns a `Promise<T>`, which is executed asynchronously.
* The callback is wrapped in error handling logic to catch and process any exceptions.
*
* @returns A `Promise<T | void>` that resolves with the result of the callback function if successful,
* or `void` if an error was thrown and handled. This allows for optional chaining on the return value.
*
* @throws This method does not throw explicitly but will log an error message if an exception is caught
* and is not an `esbuild`-related error. The error stack is logged via `VMRuntimeError` for non-esbuild errors.
*
* @example
* ```ts
* await execute(async () => {
* // Perform some asynchronous operation here
* return someResult;
* });
* ```
*/
private execute;
/**
* Configures the development mode by ensuring that `config.dev` is set properly.
*/
private configureDevelopmentMode;
/**
* Sets up the plugin's provider and registers the plugin HooksInterface.
*/
private setupPlugins;
/**
* Registers the plugin HooksInterface for start, end, and load events.
*
* @param paths - The resolved path aliases.
* @param rootDir - The root directory for resolving paths.
*/
private registerPluginHooks;
/**
* Generates a path alias object from the TypeScript provider's path options.
* This method processes the `paths` property from the TypeScript provider's options,
* which is expected to be an object where each key represents a path alias pattern,
* and the corresponding value is an array of paths. The method removes any wildcard
* characters (`*`) from both the keys and the first values of the arrays. It also
* resolves the paths relative to the specified `rootDir`, returning a simplified
* object that maps the cleaned keys to their respective paths.
*
* The resolved paths will be formatted to use a relative path notation.
*
* Example:
* Given the following paths:
* ```ts
* {
* '@core/*': ['src/core/*'],
* '@utils/*': ['src/utils/*']
* }
* ```
* And assuming `rootDir` is set to the base directory of your project, the method
* will return:
* ```ts
* {
* '@core/': './core/',
* '@utils/': './utils/'
* }
* ```
*
* @param rootDir - The root directory to resolve paths against.
* @returns An object mapping cleaned path aliases to their respective resolved paths.
*/
private generatePathAlias;
/**
* Handles errors during the build process.
* This method processes and logs errors that occur during the esbuild process. It specifically filters out
* errors related to TypeScript (`TypesError`) to prevent them from being logged, while logging all other errors
* to the console. The error object is assumed to contain a list of messages, each with detailed information.
*
* @param esbuildError - The error object returned by esbuild, which is expected to contain an array of
* error messages.
*
* @private
*
* @remarks
* - TypeScript errors (denoted as `TypesError`) are skipped and not logged.
* - Other errors are logged to the console with their text descriptions.
*
* @example
* ```ts
* try {
* await buildService.run();
* } catch (esbuildError) {
* buildService.handleErrors(esbuildError);
* }
* ```
*
* In this example, if an error occurs during the build process, the `handleErrors` method is used to
* process and log the errors.
*/
private handleErrors;
/**
* Injects a configuration object (banner or footer) into the `esbuild` options.
* This method will update the `esbuild` object by adding or modifying the `banner` or `footer`
* property based on the provided configuration.
* The function handles both static values
* and functions within the configuration.
*
* @param esbuild - The `esbuild` configuration object where the `banner` or `footer`
* should be injected or updated.
* @param object - The configuration object that contains the properties to inject.
* The properties can either be static values or functions.
* @param name - A string that determines whether the method modifies the `banner` or `footer`
* property of the `esbuild` object.
*
* @returns void - This method does not return any value.
* It modifies the `esbuild` object directly.
*
* @throws Error - If the `object` parameter is not provided, nothing is injected.
* No action will be taken if the specific `name` property (either
* 'banner' or 'footer') does not exist in the `esbuild` object.
*/
private injects;
/**
* Builds the project based on the configuration.
* Depending on the configuration, this method either uses esbuild's `context` for watching or `build` for a one-time build.
*
* @returns A promise that resolves with the build context or result.
*
* @private
*/
private build;
/**
* Manages development processes for specified entry points.*
* This method spawns development processes for each file in the metafile that matches any of the specified entry points.
* It enables features like source maps and optional debugging mode for each spawned process.
*
* @param meta - The metafile containing information about build outputs.
* This typically includes a mapping of output files and their dependencies.
* @param entryPoint - An array of entry point file names to match against the metafile outputs.
* Only files that match these entry points will have development processes spawned.
* @param debug - A boolean flag to enable debugging mode for spawned processes.
* If `true`, the processes will start in debug mode with the `--inspect-brk` option. Defaults to `false`.
*
* @returns void
*
* @remarks
* - Files that contain 'map' in their names (e.g., source map files) are ignored and no process is spawned for them.
* - For each matching file in the metafile outputs, a new development process is spawned using the `spawn` function.
* - The `activePossess` array tracks all spawned processes, allowing further management (e.g., termination).
*
* @example
* ```ts
* const meta = {
* outputs: {
* 'dist/index.js': { \/* ... *\/ },
* 'dist/index.js.map': { \/* ... *\/ }
* }
* };
* const entryPoints = ['index'];
*
* this.spawnDev(meta, entryPoints, true); // Spawns processes in debug mode
* ```
*
* @private
*/
private spawnDev;
/**
* Starts the build process and type checking.
* This method performs initial setup for the build and ensures that any child processes are terminated properly.
*
* @private
*/
private start;
/**
* Finalizes the build process and logs results.
* This method handles the end of the build process, logs build results, and processes development files if applicable.
*
* @private
*/
private end;
/**
* Processes and updates entry points based on project dependencies.
* This method analyzes the project's dependencies and adjusts entry points configuration as needed.
*
* @private
*/
private processEntryPoints;
}
/**
* Import will remove at compile time
*/
/**
* The `BuildStateInterface` extends the `PluginsBuildStateInterface` interface to include additional properties related to the build
* process, specifically for handling `ifdef` conditions and function removals in macros.
*
* @interface BuildStateInterface
*/
interface BuildStateInterface extends PluginsBuildStateInterface {
ifdef: Array<string>;
macros: {
removeFunctions: Set<string>;
};
}
/**
* Custom error class to represent type-related errors.
*
* This class extends the built-in `Error` class to provide more specific
* error handling for issues related to types. It can be used to distinguish
* errors that occur due to type mismatches or other type-related problems
* in your application.
*
* @example
* ```ts
* throw new TypesError('Invalid type encountered.');
* ```
*
* @augments Error
*/
declare class TypesError extends Error {
/**
* Creates an instance of `TypesError`.
*
* @param message - A human-readable message providing details about the error.
* @param options - Optional configuration for the error, such as a `cause` (ECMAScript 2022+).
*/
constructor(message?: string, options?: {
cause?: Error;
});
}
/**
* Import will remove at compile time
*/
/**
* Spawns a new Node.js process to execute the provided JavaScript file, with optional debugging support.
*
* This function creates a new Node.js process to run the specified JavaScript file with source map support enabled.
* It optionally starts the process in debug mode, which allows WebStorm or other debuggers to attach to the process.
* The output and error streams of the spawned process are captured and logged to the console.
*
* @param filePath - The path to the JavaScript file to execute.
* @param debug - A boolean flag to enable debugging. If `true`, the process will be started with the `--inspect-brk` option,
* which opens a debugger on `0.0.0.0:9229`, allowing external debuggers to attach.
*
* @returns A `ChildProcessWithoutNullStreams` object representing the spawned process.
* This object allows interaction with the process, including capturing its output and error streams.
*
* @remarks
* - The `--enable-source-maps` flag is used to enable source map support, which allows better debugging by mapping
* errors and stack traces to the original source code.
* - If `debug` is `true`, the `--inspect-brk=0.0.0.0:9229` flag is added, starting the process in debug mode and pausing
* execution until a debugger is attached.
* - The output (`stdout`) and error (`stderr`) streams of the spawned process are logged to the console.
* - The function returns a `ChildProcessWithoutNullStreams` object that can be used to interact with the spawned process,
* such as handling its termination or sending input.
*
* @throws Error Throws an error if the Node.js process fails to start or if there are issues with the provided file path.
*
* @example
* ```ts
* import { spawn } from '@services/process.service';
*
* // Run without debugging
* const process = spawn('./path/to/script.js', false);
*
* process.on('close', (code) => {
* console.log(`Process exited with code ${code}`);
* });
*
* // Run with debugging enabled
* const debugProcess = spawn('./path/to/script.js', true);
*
* debugProcess.on('close', (code) => {
* console.log(`Debug process exited with code ${code}`);
* });
* ```
*
* In these examples, the `spawn` function is used to execute a JavaScript file, once in normal mode and once with debugging enabled.
* The process's exit code is logged when the process completes.
*
* @public
* @category Services
*/
declare function spawn(filePath: string, debug?: boolean): ChildProcessWithoutNullStreams;
/**
* Import will remove at compile time
*/
/**
* The `collectFunctionNames` function analyzes the provided TypeScript code and collects the names of functions
* that should be removed based on specific conditions. The function searches for function declarations and variable
* declarations where the function name or variable is prefixed with `$$`, and adds these function names to the
* `removeFunctions` set in the provided `state` object.
*
* - **Input**:
* - `code`: A string containing the TypeScript code to be analyzed.
* - `state`: An object representing the current build state, specifically the `mocks` state, which includes
* a `removeFunctions` set that will hold the names of functions that need to be removed.
*
* - **Output**: The function does not return any value. Instead, it modifies the `removeFunctions` set inside the
* `state` object by adding function names that meet the criteria for removal.
*
* ## Error Handling:
* - The function does not explicitly handle errors. If invalid TypeScript code is provided, `ts.createSourceFile`
* may throw an error, which should be handled by the caller if necessary.
*
* @param code - The TypeScript code as a string that will be analyzed.
* @param state - The build state containing the `removeFunctions` set to store the names of functions to be removed.
* @returns `void` - The function modifies the `state` directly and does not return a value.
*/
declare function collectFunctionNames(code: string, state: BuildStateInterface['macros']): void;
/**
* The `collectDeclaredFunctions` function processes the provided `meta` metafile and reads each file's contents
* to find function declarations within preprocessor directives. It uses regular expressions to match `// ifdef` and
* `// endif` blocks in the code and collects the function names from the code inside the `ifdef` block, based on the
* `define` configuration in the `config` object. If the condition defined in the `ifdef` is not met (i.e., not defined
* in the `config.define`), the function names found inside the block will be collected and added to the `removeFunctions`
* set in the `state` object.
*
* - **Input**:
* - `meta`: The `Metafile` object that contains the input files. The keys are file paths, and the values contain
* metadata about those files.
* - `config`: The configuration object containing a `define` field, which is an object of conditions that may be used
* in the `ifdef` blocks. If a condition in an `ifdef` block is not defined in `config.define`, the functions in
* that block will be collected.
* - `state`: The build state, specifically the `mocks` state, which includes a `removeFunctions` set that stores
* function names to be removed.
*
* - **Output**: This function does not return a value. It modifies the `removeFunctions` set within the provided `state`
* object by adding the names of functions found inside unprocessed `ifdef` blocks.
*
* ## Error Handling:
* - If a file cannot be read due to a filesystem error, the function will throw an error.
* - If the provided `meta` or `config` is malformed, it may result in runtime errors. The caller should ensure valid input.
*
* @param meta - The `Metafile` object containing the list of input files and their metadata.
* @param config - The configuration object that defines conditions used in `ifdef` blocks.
* @param state - The build state containing the `removeFunctions` set to store function names to be removed.
* @returns `void` - The function modifies the `state` directly and does not return a value.
*/
declare function collectDeclaredFunctions(meta: Metafile, config: ConfigurationInterface, state: BuildStateInterface['macros']): Promise<void>;
/**
* The `parseMacros` function processes TypeScript or JavaScript files to transform macros defined within the content.
* It ensures that the build state is initialized if necessary, analyzes file dependencies, collects declared functions
* that are marked for removal, and applies transformations to the source code based on the macros.
* If the file's extension is not `.ts` or `.js`, the function returns `undefined`. Otherwise, it transforms the code
* and returns the result in the specified loader format.
*
* - **Input**:
* - `content`: The content of the file as a string or `Uint8Array` to be parsed.
* - `loader`: A string representing the loader type for transforming the code (e.g., `'ts'`, `'js'`).
* - `args`: The `OnLoadArgs` object containing metadata for the current loading process, including the file path.
* - `state`: The build state containing the `mocks` object, which includes a `removeFunctions` set that tracks
* functions to be removed.
* - `config`: The configuration object that defines how macros should be handled (e.g., conditions for macro processing).
*
* - **Output**: A `Promise` that resolves to an `OnLoadResult`, `PluginResultType`, or `undefined`. If the file is
* of type `.ts` or `.js`, the transformed code is returned in the specified loader format (e.g., `'ts'`). If the file
* extension is not recognized, the function returns `undefined`.
*
* ## Error Handling:
* - If the file path does not end with `.ts` or `.js`, the function returns `undefined`.
* - If `state.mocks` is not initialized, it will be set up by analyzing the file dependencies and collecting declared functions.
* - If any errors occur during the analysis, function collection, or transformation, the function may throw an error.
*
* @param content - The content of the file as a string or `Uint8Array` to be parsed.
* @param loader - The loader type for transforming the code (e.g., `'ts'` or `'js'`).
* @param args - The `OnLoadArgs` containing metadata, including the file path.
* @param state - The build state that includes `mocks` with the `removeFunctions` set.
* @param config - The configuration object defining how macros should be handled.
* @returns A `Promise` that resolves to the transformed code (`OnLoadResult` or `PluginResultType`), or `undefined`
* if the file is not of type `.ts` or `.js`.
*/
declare function parseMacros(content: string | Uint8Array, loader: Loader | undefined, args: OnLoadArgs, state: BuildStateInterface, config: ConfigurationInterface): Promise<OnLoadResult | PluginResultType | undefined>;
/**
* Import will remove at compile time
*/
/**
* Default build options for esbuild bundler in RemoteX framework.
*
* These options are used to configure how esbuild processes and bundles the TypeScript
* files for the RemoteX testing framework.
*
* @public
* @category Configuration
*/
declare const defaultBuildOptions: BuildOptions;
/**
* Extracts the source map from the provided data string and returns the modified code and source map separately.
*
* This function searches for the inline source map in the data string using a regular expression, removes the
* source map comment from the data string, and returns an object containing the code without the source map
* comment and the extracted source map.
*
* @param dataString - The string containing the transpiled code with an inline source map.
* @returns An object containing the modified code without the source map comment and the extracted source map.
* @throws Error -Throws an error if the source map URL is not found in the data string.
*
* @public
*/
declare function extractSourceMap(dataString: string): TranspileFileInterface;
/**
* Transpiles a TypeScript file and extracts the source map.
*
* This function uses esbuild to transpile the specified TypeScript file based on provided build options,
* and then extracts the source map from the transpiled code.
*
* @param filePath - The path to the TypeScript file to be transpiled.
* @param buildOptions - Optional build options to override the default build options.
* @returns A promise that resolves to an object containing the transpiled code and the extracted source map.
* @throws Error - Throws an error if the build process fails or the source map extraction fails.
*
* @public
* @category Services
*/
declare function transpileFile(filePath: string, buildOptions?: BuildOptions): Promise<TranspileFileInterface>;
/**
* The `analyzeDependencies` function analyzes the dependencies of a given entry point for a specified platform.
* It performs a bundling operation and generates a metafile that contains detailed information about the
* dependencies involved in the build process.
* This is typically used to inspect the external packages and modules
* that the entry point depends on.
*
* - **Input**:
* - `entryPoint`: A string or array of strings representing the entry points for the build.
* This defines the starting point(s) for the bundling process.
* - `platform`: An optional parameter that specifies the platform to target for the build.
* Default is `'browser'`.
*
* - **Output**: A `Promise` that resolves to an object containing:
* - The `BuildResult` from the bundling process.
* - A `metafile`, which contains detailed metadata about the build, including the dependencies analyzed.
*
* ## Example:
*
* ```ts
* const result = await analyzeDependencies(['src/index.ts']);
* console.log(result.metafile); // { inputs: { 'src/index.ts': { ... } }, outputs: { ... } }
*
* const nodeResult = await analyzeDependencies(['src/server.ts'], 'node');
* console.log(nodeResult.metafile); // { inputs: { 'src/server.ts': { ... } }, outputs: { ... } }
* ```
*
* @param entryPoint - The entry point(s) to be analyzed.
* @param platform - The target platform for the build.
* @returns A `Promise` that resolves to a `BuildResult` object along with a `metafile` containing dependency details.
* @throws Error If the build process fails for any reason.
*/
declare function analyzeDependencies(entryPoint: EntryPointsType, platform?: BuildOptions['platform']): Promise<BuildResult & {
metafile: Metafile;
}>;
/**
* Represents the result of transpiling a TypeScript file.
*
* This interface defines the structure of the output returned from a TypeScript transpilation process,
* including the transpiled JavaScript code and the associated source map.
*
* @property code - The transpiled JavaScript code generated from the TypeScript file.
* @property sourceMap - The source map associated with the transpiled JavaScript code.
*
* @remarks
* - The `code` property contains the JavaScript code after TypeScript transpilation.
* - The `sourceMap` property provides the source map that maps the transpiled JavaScript code back to the original TypeScript source.
* - The source map is useful for debugging as it allows developers to trace errors in the generated JavaScript back to the original TypeScript code.
*
* @example
* ```typescript
* import { TranspileFileInterface } from './TranspileFileInterface';
*
* const result: TranspileFileInterface = {
* code: 'console.log("Hello, world!");',
* sourceMap: 'version: 3\nfile: out.js\nsources: ["file.ts"]\n'
* };
*
* console.log(result.code); // Output: console.log("Hello, world!");
* console.log(result.sourceMap); // Output: version: 3\nfile: out.js\nsources: ["file.ts"]\n
* ```
*
* In this example, the `TranspileFileInterface` is used to represent the result of transpiling a TypeScript file.
* The `code` contains the JavaScript code, while the `sourceMap` provides the mapping information for debugging purposes.
*
* @public
* @category Interfaces
*/
interface TranspileFileInterface {
code: string;
sourceMap: string;
}
/**
* Import will remove at compile time
*/
/**
* Represents an error that occurs during the esbuild process.
*
* This class extends the base error class to provide specific error handling for esbuild-related issues.
* It captures the error message and maintains the proper stack trace, allowing for easier debugging
* and identification of errors that occur during the build process.
*
* @class esBuildError
* @extends BaseError
*/
declare class esBuildError extends BaseError {
originalErrorStack?: string;
/**
* Creates an instance of the EsbuildError class.
*
* @param message - An object containing the error message. The `text` property is used to initialize
* the base error class with a descriptive message about the error encountered during the esbuild process.
*/
constructor(message: Message);
/**
* Generates a formatted error message with highlighted code.
*
* @param message - An esbuild Message object containing error information.
* @returns A formatted string of the error message.
*/
private generateFormattedError;
/**
* Reads code from a file if it exists.
*
* @param path - The file path to read from.
* @returns Array of lines if file exists, otherwise null.
*/
private readCode;
/**
* Formats a code snippet with highlighted errors.
*
* @param code - Array of code lines.
* @param location - The error location within the file.
* @returns A formatted and highlighted code snippet string.
*/
private formatCodeSnippet;
/**
* Applies color to a given text if colors are enabled.
*
* @param color - The color code.
* @param text - The text to colorize.
* @returns The colorized text if colors are active, otherwise plain text.
*/
private applyColor;
}
/**
* Imports
*/
/**
* ASCII Logo and Version Information
*
* @remarks
* The `asciiLogo` constant stores an ASCII representation of the project logo
* that will be displayed in the banner. This banner is rendered in a formatted
* string in the `bannerComponent` function.
*
* The `cleanScreen` constant contains an ANSI escape code to clear the terminal screen.
*/
declare const asciiLogo = "\n ______ _ _ _\n | ___ \\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\ \\/ / ___ \\ | | | | |/ _` |\n > <| |_/ / |_| | | | (_| |\n/_/\\_\\____/ \\__,_|_|_|\\__,_|\n";
declare const cleanScreen = "\u001Bc";
/**
* Renders the banner with the ASCII logo and version information.
*
* This function constructs and returns a formatted banner string that includes an ASCII logo and the version number.
* The colors used for the ASCII logo and version number can be enabled or disabled based on the `activeColor` parameter.
* If color formatting is enabled, the ASCII logo will be rendered in burnt orange, and the version number will be in bright pink.
*
* @param activeColor - A boolean flag indicating whether ANSI color formatting should be applied. Default is `__ACTIVE_COLOR`.
*
* @returns A formatted string containing the ASCII logo, version number, and ANSI color codes if `activeColor` is `true`.
*
* @remarks
* The `bannerComponent` function clears the terminal screen, applies color formatting if enabled, and displays
* the ASCII logo and version number. The version number is retrieved from the global `__VERSION` variable, and
* the colors are reset after the text is rendered.
*
* @example
* ```ts
* console.log(bannerComponent());
* ```
*
* This will output the banner to the console with the ASCII logo, version, and colors.
*
* @example
* ```ts
* console.log(bannerComponent(false));
* ```
*
* This will output the banner to the console with the ASCII logo and version number without color formatting.
*
* @public
*/
declare function bannerComponent(activeColor?: boolean): string;
/**
* A formatted string prefix used for logging build-related messages.
* // todo optimize this
*/
declare function prefix(): string;
/**
* Import will remove at compile time
*/
/**
* Manages the HTTP or HTTPS server based on the provided configuration.
*
* The `ServerProvider` class initializes and starts either an HTTP or HTTPS server based on whether SSL certificates
* are provided. It handles incoming requests, serves static files, and lists directory contents with appropriate
* icons and colors.
*
* @class
*/
declare class ServerProvider {
/**
* Root dir to serve
*/
private readonly rootDir;
/**
* Indicates whether the server is configured to use HTTPS.
*/
private readonly isHttps;
/**
* The server configuration object, including SSL certificate paths and other settings.
*/
private readonly config;
/**
* Creates an instance of ServerProvider.
*
* @param config - The server configuration object, including port number, SSL certificate paths, and an optional request handler.
* @param dir - The root directory from which to serve files.
*
* @example
* ```ts
* import { ServerProvider } from './server-provider';
*
* const serverConfig = {
* port: 8080,
* keyfile: './path/to/keyfile',
* certfile: './path/to/certfile',
* onRequest: (req, res, next) => { /* custom request handling *\/ }
* };
* const provider = new ServerProvider(serverConfig, './public');
* provider.start();
* ```
*
* This example shows how to create an instance of `ServerProvider` and start the server.
*/
constructor(config: ServeInterface, dir: string);
/**
* Starts the server based on the configuration.
* If SSL certificates are provided and valid, an HTTPS server is started. Otherwise, an HTTP server is started.
*
* @example
* ```ts
* provider.start();
* ```
*
* This example demonstrates how to start the server. It will either start an HTTP or HTTPS server based on the configuration.
*/
start(): void;
/**
* Starts an HTTP server.
* This method creates an HTTP server that listens on the configured port and handles incoming requests.
*
* @example
* ```ts
* provider.startHttpServer();
* ```
*
* This example shows how the `startHttpServer` method is used internally to start an HTTP server.
*/
private startHttpServer;
/**
* Starts an HTTPS server.
*
* This method creates an HTTPS server with SSL/TLS certificates, listens on the configured port, and handles incoming requests.
*
* @example
* ```ts
* provider.startHttpsServer();
* ```
*
* This example shows how the `startHttpsServer` method is used internally to start an HTTPS server.
*/
private startHttpsServer;
/**
* Handles incoming requests.
*
* This method checks if a custom request handler is provided in the configuration. If so, it uses the custom handler.
* Otherwise, it delegates to the default request handler.
*
* @param req - The incoming request object.
* @param res - The response object.
* @param defaultHandler - The default handler functions to be called if no custom handler is provided.
*
* @example
* ```ts
* // This method is used internally to handle requests
* ```
*/
private handleRequest;
/**
* Returns the MIME type for a given file extension.
*
* This method maps file extensions to their corresponding MIME types.
*
* @param ext - The file extension.
* @returns The MIME type associated with the file extension.
*
* @example
* ```ts
* const mimeType = provider.getContentType('html');
* console.log(mimeType); // 'text/html'
* ```
*/
private getContentType;
/**
* Handles the default response for requests, serving files or directories.
*
* This method serves the content of files or directories. If the request is for a directory, it lists the contents with
* appropriate icons and colors.
*
* @param req - The incoming request object.
* @param res - The response object.
*
* @returns A promise that resolves when the response is sent.
*
* @throws Throws an error if the file or directory cannot be accessed.
*
* @example
* ```ts
* // This method is used internally to handle file and directory responses
* ```
*/
private defaultResponse;
/**
* promisifyStat the `fs.stat` method.
*
* Converts the `fs.stat` callback-based method to return a promise.
*
* @param path - The file or directory path.
* @returns A promise that resolves with the file statistics.
*
* @example
* ```ts
* const stats = await provider.promisifyStat('./path/to/file');
* console.log(stats.isFile()); // true or false
* ```
*/
private promisifyStat;
/**
* Handles directory listings.
*
* Reads the contents of a directory and generates an HTML response with file icons and colors.
*
* @param fullPath - The full path to the directory.
* @param requestPath - The request path for generating relative links.
* @param res - The response object.
*
* @example
* ```ts
* // This method is used internally to handle directory listings
* ```
*/
private handleDirectory;
/**
* Handles file responses.
*
* Reads and serves the content of a file.
*
* @param fullPath - The full path to the file.
* @param res - The response object.
*
* @example
* ```ts
* // This method is used internally to handle file responses
* ```
*/
private handleFile;
/**
* Sends a 404 Not Found response.
*
* @param res - The response object.
*
* @example
* ```ts
* provider.sendNotFound(response);
* ```
*
* This example demonstrates how to send a 404 response using the `sendNotFound` method.
*/
private sendNotFound;
/**
* Sends an error response.
*
* @param res - The response object.
* @param error - The error object.
*
* @example
* ```ts
* provider.sendError(response, new Error('Some error'));
* ```
*
* This example shows how to send an error response using the `sendError` method.
*/
private sendError;
}
/**
* Import will remove at compile time
*/
/**
* Plugin provider for esbuild that registers hooks for lifecycle events such as onStart, onEnd, onResolve, and onLoad.
* This class allows dynamic behavior by registering multiple hooks for different stages of the build process.
*/
declare class PluginsProvider {
/**
* Holds the build state that hooks can modify.
*/
private buildState;
/**
* Holds the registered hooks for the `onEnd` lifecycle event.
* This array contains functions that are called after the build process completes.
*/
private onEndHooks;
/**
* Holds the registered hooks for the `onSuccess` lifecycle event.
* This array contains functions that are called after the build success finish.
*/
private onSuccess;
/**
* Holds the registered hooks for the `onLoad` lifecycle event.
* This array contains functions that are called when esbuild attempts to load a module.
*/
private onLoadHooks;
/**
* Holds the registered hooks for the `onStart` lifecycle event.
* This array contains functions that are called before the build process starts.
*/
private onStartHooks;
/**
* Holds the registered hooks for the `onResolve` lifecycle event.
* This array contains functions that are called when esbuild attempts to resolve a module path.
*/
private onResolveHooks;
/**
* Registers a hook function for the `onStart` lifecycle event.
* The hook will be called before the build process starts.
*
* @param fn - A function of type `OnStartType` that will be executed when the build process starts.
*
* @example
* ```ts
* pluginProvider.registerOnStart(async (build) => {
* console.log('Build started:', build);
* });
* ```
*/
registerOnStart(fn: OnStartType | undefined): void;
/**
* Registers a hook function for the `onEnd` lifecycle event.
* The hook will be called after the build process completes.
*
* @param fn - A function of type `OnEndType` that will be executed after the build completes.
*
* @example
* ```ts
* pluginProvider.registerOnEnd(async (result) => {
* console.log('Build finished:', result);
* });
* ```
*/
registerOnEnd(fn: OnEndType | undefined): void;
/**
* Registers a hook function for the `onSuccess` lifecycle event.
* The hook will be called after the build success completes.
*
* @param fn - A function of type `OnEndType` that will be executed after the build completes.
*
* @example
* ```ts
* pluginProvider.registerOnSuccess(async (result) => {
* console.log('Build Success finished:', result);
* });
* ```
*/
registerOnSuccess(fn: OnEndType | undefined): void;
/**
* Registers a hook function for the `onResolve` lifecycle event.
* The hook will be called when esbuild attempts to resolve a module path.
*
* @param fn - A function of type `OnResolveType` that will be executed during module resolution.
*
* @example
* ```ts
* pluginProvider.registerOnResolve(async (args) => {
* if (args.path === 'my-module') {
* return { path: './src/my-module.ts' };
* }
* return null;
* });
* ```
*/
registerOnResolve(fn: OnResolveType | undefined): void;
/**
* Registers a hook function for the `onLoad` lifecycle event.
* The hook will be called when esbuild attempts to load a module.
*
* @param fn - A function of type `OnLoadType` that will be executed during module loading.
*
* @example
* ```ts
* pluginProvider.registerOnLoad(async (contents, loader, args) => {
* if (args.path.endsWith('.json')) {
* return { contents: JSON.stringify({ key: 'value' }), loader: 'json' };
* }
* return null;
* });
* ```
*/
registerOnLoad(fn: OnLoadType | undefined): void;
/**
* Registers esbuild plugin hooks and sets up the middleware plugin.
*
* This function defines the setup for an esbuild plugin, enabling hooks for various lifecycle events:
* onStart, onEnd, onResolve, and onLoad. It ensures that hooks registered by the user are called at
* the appropriate stages of the build process.
*
* @returns An object with the plugin configuration that can be passed to esbuild's `plugins` array.
* The configuration includes the plugin name and setup function.
*
* @example
* ```ts
* // Example usage with esbuild:
* const esbuild = require('esbuild');
* const pluginProvider = new PluginsProvider();
*
* esbuild.build({
* entryPoints: ['./src/index.ts'],
* bundle: true,
* plugins: [pluginProvider.setup()],
* }).catch(() => process.exit(1));
* ```
*/
setup(): Plugin;
/**
* Executes all registered onStart hooks.
*
* This function is called when the build process starts and invokes each hook registered via
* `registerOnStart`. Hooks can perform actions such as initializing tasks, logging, or setting
* up build conditions.
*
* @param build - The esbuild `PluginBuild` object that represents the current build process.
*
* @returns A promise that resolves when all hooks have been executed.
*
* @example
* ```ts
* // Registering an onStart hook
* pluginProvider.registerOnStart(async (build) => {
* console.log('Build started:', build);
* });
* ```
*/
private handleOnStart;
/**
* Executes all registered onEnd hooks after the build finishes.
*
* This function is called after the build process completes and invokes each hook registered via
* `registerOnEnd`. Hooks can be used to process the build results, such as performing analysis or cleanup.
*
* @param buildResult - The build buildResult object provided by esbuild, containing details about the build process.
*
* @returns A promise that resolves when all hooks have been executed.
*
* @example
* ```ts
* // Registering an onEnd hook
* pluginProvider.registerOnEnd(async (buildResult) => {
* console.log('Build completed:', buildResult);
* });
* ```
*/
private handleOnEnd;
/**
* Resolves module imports using registered onResolve hooks.
*
* This function is called whenever esbuild attempts to resolve a module path. It iterates over all registered
* onResolve hooks and merges their results. If no hook resolves a path, `null` is returned.
*
* @param args - The esbuild `OnResolveArgs` object containing information about the module being resolved.
*
* @returns A promise that resolves to an `OnResolveResult` containing the resolved path, or `null` if no path is found.
*
* @example
* ```ts
* // Registering an onResolve hook
* pluginProvider.registerOnResolve(async (args) => {
* if (args.path === 'my-module') {
* return { path: './src/my-module.ts' };
* }
* return null;
* });
* ```
*/
private handleOnResolve;
/**
* Loads module contents using registered onLoad hooks.
*
* This function is called when esbuild attempts to load a module. It reads the module contents and then
* processes it through all registered onLoad hooks. The hooks can modify the contents and loader type.
*
* @param args - The esbuild `OnLoadArgs` object containing information about the module being loaded.
*
* @returns A promise that resolves to an `OnLoadResult` containing the module contents and loader, or `null` if no contents are loaded.
*
* @example
* ```ts
* // Registering an onLoad hook
* pluginProvider.registerOnLoad(async (contents, loader, args) => {
* if (args.path.endsWith('.json')) {
* return { contents: JSON.stringify({ key: 'value' }), loader: 'json' };
* }
* return null;
* });
* ```
*/
private handleOnLoad;
}
/**
* Parses and filters content based on conditional directives.
*
* This function processes the given code contents and removes sections that
* are conditionally compiled based on the provided `defines` object.
*
* @param contents - The code contents to be processed.
* @param defines - An object containing conditional
* definitions. Keys are condition names, and values are their definitions.
* @returns The processed code contents with conditional blocks removed
* according to the `defines` object.
*/
declare function parseIfDefConditionals(contents: string, defines: Record<string, unknown>): string;
/**
* Import will remove at compile time
*/
/**
* Manages TypeScript compilation, type checking, and declaration file generation using TypeScript's
* language service API.
*
* @remarks
* This module provides an interface to TypeScript's compiler API for performing type checking
* and generating declaration files. It uses the language service API rather than the direct
* compiler API for better performance with incremental compilation.
*
* @see ts.LanguageService
* @see ts.createLanguageService
*
* @since 1.5.9
*/
declare class TypescriptModule {
/**
* The root directory of the TypeScript project.
* @since 1.5.9
*/
readonly root: string;
/**
* Parsed TypeScript configuration from tsconfig.
* @since 1.5.9
*/
readonly config: ParsedCommandLine;
/**
* TypeScript language service instance for compiler operations.
* @since 1.5.9
*/
private readonly languageService;
/**
* Language service host that provides file system access to the language service.
* @since 1.5.9
*/
private readonly languageServiceHost;
/**
* Service for bundling TypeScript declaration files
*
* @remarks
* This service instance handles the bundling of TypeScript declaration files (.d.ts)
* by traversing the dependency graph starting from entry points, collecting exports,
* and generating single bundled declaration files.
*
* @see DeclarationBundlerService
*
* @since 1.5.9
*/
private readonly declarationBundlerService;
/**
* Creates a new TypeScript module with the specified configuration.
*
* @param tsconfigPath - Path to the tsconfig.json file
* @param outDir - Optional output directory to override the one in tsconfig
* @param fallbackOutDir - Optional fallback output directory to use if outDir is not specified in tsconfig or outDir
*
* @throws Error - If the TypeScript configuration cannot be parsed
*
* @since 1.5.9
*/
constructor(tsconfigPath: string, outDir?: string, fallbackOutDir?: string);
/**
* Updates the version of one or more files to indicate they have changed.
*
* @param touchFiles - Path or array of paths to files that have been modified
*
* @since 1.5.9
*/
updateFiles(touchFiles: string | Array<string>): void;
/**
* Performs type checking on all source files in the project.
*
* @returns Array of diagnostic
*
* @since 1.5.9
*/
check(): Array<Diagnostic>;
/**
* Generates TypeScript declaration (.d.ts) files for all source files.
*
* @throws Error - If outDir is not specified in the compiler options
*
* @since 1.5.9
*/
emitDeclarations(): void;
/**
* Generates and writes bundled declaration files for specified entry points
*
* @param entryPoints - Record mapping output filenames to source file paths
*
* @throws Error - If the language service program is not available
* @throws Error - If file system operations fail during writing
*
* @remarks
* This method generates bundled declaration files from the provided entry points
* and writes them to the configured output directory. The input is a record where:
* - Keys represent the output filenames (with or without .d.ts extension)
* - Values represent the source file paths to use as entry points
*
* The method handles directory creation, ensuring all necessary parent directories
* exist before writing the output files. If the output filename doesn't end with
* '.d.ts', the extension will be appended automatically.
*
* @example
* ```ts
* // Generate bundled declarations for multiple entry points
* typescriptModule.emitBundleDeclarations({
* 'index': 'src/index.ts',
* 'components/index': 'src/components/index.ts'
* });
* ```
*
* @see DeclarationBundlerService.emitBundledDeclarations
*
* @since 1.5.9
*/
emitBundleDeclarations(entryPoints: Record<string, string>): void;
/**
* Formats TypeScript diagnostic messages into human-readable, colored strings.
*
* @param diagnostics - Array of TypeScript diagnostic objects to format
* @returns Array of formatted diagnostic messages with location and error information
*
* @remarks
* This method transforms raw TypeScript diagnostic objects into user-friendly
* colored console output strings. For each diagnostic, it:
* - Extracts file path, line, and character position information
* - Formats error messages with proper indentation and coloring
* - Includes error codes and prefixes with consistent styling
*
* For diagnostics with file information, the output format is:
* `[TS] filename:line:column - error TS1234: Error message`
*
* For diagnostics without file information, only the flattened message text is returned.
*
* @example
* ```ts
* const ts = new TypescriptModule('tsconfig.json');
* const diagnostics = ts.check();
* const formattedMessages = ts.formatDiagnostics(diagnostics);
* console.log(formattedMessages.join('\n'));
* ```
*
* @since 1.5.9
*/
formatDiagnostics(diagnostics: readonly Diagnostic[]): Array<string>;
/**
* Generates TypeScript declaration file output for a specified file
*
* @param fileName - The path to the TypeScript file for which to generate declaration output
* @returns The result of the emit operation, including the declaration file content or an indication that emit was skipped
*
* @throws Error - When the language service fails to generate valid output
*
* @see ts.transform
* @see ts.LanguageService.getEmitOutput
*
* @since 1.5.9
*/
private getEmitOutput;
/**
* Resolves a module specifier to its file path relative to the root directory
*
* @param specifier - The module specifier string to resolve
* @returns The resolved file path relative to the root directory, or undefined if resolution fails
*
* @remarks
* This private method uses TypeScript's module resolution system to convert an import specifier
* into an actual file path. It specifically filters out node_modules dependencies and ensures
* paths are relative to the project's root directory.
*
* When rootDir is set to 'src' and baseUrl is set to the project root:
* - The method will only resolve files contained within the 'src' directory
* - All paths will be calculated relative to 'src', not the project root
* - For example, with project structure:
* ```text
* /project-root/
* ├── src/
* │ ├── components/
* │ │ └── button.ts
* │ └── utils/
* │ └── helpers.ts
* └── tsconfig.json
* ```
* - A resolved path might be 'components/button.ts' relative to 'src'
* - This maintains proper path structure for TypeScript's internal module resolution
*
* @example
* ```ts
* // For a specifier like '@components/button' with rootDir='src'
* const relativePath = this.resolveModuleFileName('@components/button');
* // Might return 'components/button.ts' (relative to src/)
* ```
*
* @see ts.resolveModuleName
*
* @since 1.5.9
*/
private resolveModuleFileName;
/**
* Calculates the relative path from a source file to a target file in the output directory
*
* @param fromFile - The source file path from which the relative path is calculated
* @param toFile - The target file path in the output directory
* @returns A properly formatted relative path string that can be used in import statements
*
* @remarks
* This private method computes a relative path from one file to another in the output directory,
* ensuring the path is properly formatted for JavaScript module imports.
*
* This is particularly useful when generating import statements in emitted files that
* need to reference other modules in the output directory structure.
*
* @example
* ```ts
* // If fromFile is '/project/dist/components/button.js'
* // toFile is 'utils/helpers.js'
* // outDir is '/project/dist'
* this.getRelativePathToOutDir(fromFile, toFile);
* // Returns '../utils/helpers'
* ```
*
* @since 1.5.9
*/
private getRelativePathToOutDir;
/**
* Creates a TypeScript transformer visitor that updates import and export paths
*
* @param fileName - The current file being transformed
* @param context - The TypeScript transformation context
* @returns A transformer function that processes a source file
*
* @remarks
* This private method creates a visitor function that transforms import and export declarations
* in TypeScript source files. The main purpose is to rewrite module specifiers to ensure they
* correctly point to the compiled output files.
*
* This is crucial for maintaining correct module references when TypeScript files are compiled
* and moved to an output directory with potentially different structure.
*
* When rootDir is set to 'src' and baseUrl is the project root:
* - Module paths are resolved within the 'src' directory
* - The new paths will be calculated relative to each file's position in the output structure
* - This ensures imports continue to work correctly after compilation
*
* @since 1.5.9
*/
private createVisitor;
/**
* Parses the TypeScript configuration file.
*
* @param tsconfigPath - Path to the tsconfig.json file
* @param outDir - Optional output directory to override the one in tsconfig
* @param fallbackOutDir - Optional fallback output directory to use if outDir is not specified in tsconfig or outDir
*
* @returns Parsed command line object containing compiler options
*
* @throws Error - If the TypeScript configuration cannot be parsed
*
* @since 1.5.9
*/
private parseConfig;
/**
* Creates a TypeScript language service.
*
* @returns Language service instance
*
* @see ts.createLanguageService
* @since 1.5.9
*/
private createLanguageService;
/**
* Initializes diagnostic plugins for macro supports
* @since 1.5.9
*/
private initializeDiagnostics;
/**
* Retrieves all diagnostics for a specified file.
*
* @param fileName - Path to the TypeScript file to analyze
* @returns Combined array of semantic, syntactic, and suggestion diagnostics
*
* @remarks
* This method aggregates all three types of TypeScript diagnostics:
* - Semantic diagnostics (type errors, etc.)
* - Syntactic diagnostics (parsing errors)
* - Suggestion diagnostics (code improvement hints)
*
* @see ts.LanguageService.getSemanticDiagnostics
* @see ts.LanguageService.getSyntacticDiagnostics
* @see ts.LanguageService.getSuggestionDiagnostics
*
* @since 1.5.9
*/
private getDiagnostics;
}
/**
* Import will remove at compile time
*/
/**
* Represents the result of a TypeScript compilation emit operation.
*
* @property outputFile - The emitted output file information,
* or undefined if no file was emitted. Contains details such as file name, content,
* and any related metadata.
*
* @property emitSkipped - Indicates whether the emit operation was skipped.
* When true, typically indicates compilation errors prevented emission or the operation
* was explicitly configured to skip emission.
*
* @remarks
* This interface is used to represent the result of TypeScript declaration emit operations.
*
* @since 1.5.9
*/
interface EmitOutputInterface {
outputFile: OutputFile | undefined;
emitSkipped: boolean;
}
/**
* Import will remove at compile time
*/
/**
* A host object that provides formatting functionality for typescript diagnostic messages
*
* @remarks
* This constant implements the FormatDiagnosticsHost interface from TypeScript,
* providing methods needed for proper diagnostic message formatting.
*
* @default Uses TypeScript's system utilities for line breaks and directory information
*
* @see FormatDiagnosticsHost - The TypeScript interface this implements
*
* @since 1.5.9
*/
declare const formatHost: FormatDiagnosticsHost;
/**
* Header text included at the top of generated declaration bundle files
*
* @remarks
* This constant provides a standardized header comment that prepended to all
* declaration bundle files generated by the DeclarationBundlerService. The header
* clearly indicates that the file was automatically generated and should not be
* edited manually.
*
* @example
* ```ts
* const bundledContent = `${HeaderDeclarationBundle}${actualContent}`;
* writeFileSync('dist/index.d.ts', bundledContent);
* ```
*
* @since 1.5.9
*/
declare const HeaderDeclarationBundle = "\n/**\n * This file was automatically generated by xBuild.\n * DO NOT EDIT MANUALLY.\n */\n ";
/**
* Import will remove at compile time
*/
/**
* Service that implements TypeScript's language service host interfaces required for compiler operations.
* This class provides the necessary methods for the TypeScript language service to interact with the
* file system and manage compilation resources.
*
* @remarks
* This service implements the TypeScript LanguageServiceHost interface, which is required
* for creating a TypeScript language service using ts.createLanguageService().
*
* @see ts.LanguageServiceHost
* @see ts.createLanguageService
*
* @since 1.5.9
*/
declare class LanguageHostService {
private readonly options;
/**
* Map to track file versions for detecting changes in source files.
* Keys are absolute file paths and values are incrementing version numbers.
*
* @since 1.5.9
*/
private readonly fileVersions;
/**
* Creates a new language host service with TypeScript compiler options.
*
* @param options - Compiler options to use for TypeScript operations
*
* @since 1.5.9
*/
constructor(options: CompilerOptions);
/**
* Increments the version number of a file to indicate it has changed.
* Used to signal to the language service that a file needs to be reprocessed.
*
* @param touchFiles - Path to the file that has been modified
*
* @since 1.5.9
*/
touchFiles(touchFiles: string): void;
/**
* Checks if a file exists at the specified path.
* Required by the LanguageServiceHost interface.
*
* @param path - Path to check for file existence
* @returns True if the file exists, false otherwise
*
* @see ts.LanguageServiceHost.fileExists
* @since 1.5.9
*/
fileExists(path: string): boolean;
/**
* Reads the content of a file at the specified path.
* Required by the LanguageServiceHost interface.
*
* @param path - Path to the file to read
* @param encoding - Optional encoding to use when reading the file
* @returns The content of the file as a string, or undefined if the file cannot be read
*
* @see ts.LanguageServiceHost.readFile
* @since 1.5.9
*/
readFile(path: string, encoding?: string): string | undefined;
/**
* Reads the contents of a directory with filtering options.
* Required by the LanguageServiceHost interface.
*
* @param path - Path to the directory to read
* @param extensions - Optional array of file extensions to filter by
* @param exclude - Optional array of glob patterns to exclude
* @param include - Optional array of glob patterns to include
* @param depth - Optional maximum depth to search
* @returns Array of file paths found in the directory
*
* @see ts.LanguageServiceHost.readDirectory
* @since 1.5.9
*/
readDirectory(path: string, extensions?: Array<string>, exclude?: Array<string>, include?: Array<string>, depth?: number): Array<string>;
/**
* Gets all subdirectories within a directory.
* Required by the LanguageServiceHost interface.
*
* @param path - Path to the directory to search
* @returns Array of directory paths found
*
* @see ts.LanguageServiceHost.getDirectories
* @since 1.5.9
*/
getDirectories(path: string): Array<string>;
/**
* Checks if a directory exists at the specified path.
*
* @param path - Path to check for directory existence
* @returns True if the directory exists, false otherwise
*
* @since 1.5.9
*/
directoryExists(path: string): boolean;
/**
* Gets the current working directory.
* Required by the LanguageServiceHost interface.
*
* @returns The current working directory path
*
* @see ts.LanguageServiceHost.getCurrentDirectory
* @since 1.5.9
*/
getCurrentDirectory(): string;
/**
* Gets all script file names tracked by this language host.
* Required by the LanguageServiceHost interface to identify the set of source files.
*
* @returns Array of script file paths that should be included in the program
*
* @see ts.LanguageServiceHost.getScriptFileNames
* @since 1.5.9
*/
getScriptFileNames(): Array<string>;
/**
* Gets the compiler options used by this language host.
* Required by the LanguageServiceHost interface to configure the TypeScript compiler.
*
* @returns The compiler options for program creation
*
* @see ts.LanguageServiceHost.getCompilationSettings
* @since 1.5.9
*/
getCompilationSettings(): CompilerOptions;
/**
* Gets the default library file name for TypeScript compilation.
* Required by the LanguageServiceHost interface to include standard TypeScript definitions.
*
* @param options - Compiler options to use for determining the default library
* @returns Path to the default library file
*
* @see ts.LanguageServiceHost.getDefaultLibFileName
* @since 1.5.9
*/
getDefaultLibFileName(options: CompilerOptions): string;
/**
* Gets the current version of a script file.
* Required by the LanguageServiceHost interface to determine if a file has changed.
*
* @param fileName - Path to the script file
* @returns The version of the file as a string
*
* @see ts.LanguageServiceHost.getScriptVersion
* @since 1.5.9
*/
getScriptVersion(fileName: string): string;
/**
* Gets a script snapshot for a file which represents its content.
* Required by the LanguageServiceHost interface to provide file content to the language service.
*
* @param fileName - Path to the script file
* @returns A script snapshot object or undefined if the file doesn't exist or can't be read
*
* @see ts.LanguageServiceHost.getScriptSnapshot
* @see ts.IScriptSnapshot
* @since 1.5.9
*/
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
}
/**
* Import will remove at compile time
*/
/**
* Service responsible for bundling TypeScript declaration files by collecting
* all exports from entry points and generating a single declaration bundle
*
* @throws Error - If the language service program is not available
* @throws Error - If a source file cannot be found
*
* @remarks
* This service handles the process of bundling TypeScript declaration files (.d.ts)
* by traversing the dependency graph starting from specified entry points.
* It collects all necessary files and symbols, processes their declarations,
* and generates a single bundled declaration file that can be used in place
* of multiple individual declaration files.
*
* The service maintains a cache of processed files to improve performance
* when processing multiple entry points or when called multiple times.
*
* @example
* ```ts
* const bundler = new DeclarationBundlerService(config, languageService);
* const bundledDeclarations = bundler.emitBundledDeclarations(['src/index.ts']);
* writeFileSync('dist/index.d.ts', bundledDeclarations[0]);
* ```
*
* @see ts.LanguageService
* @see ts.ParsedCommandLine
*
* @since 1.5.9
*/
declare class DeclarationBundlerService {
private readonly config;
private readonly languageService;
/**
* Creates a new DeclarationBundlerService instance
*
* @param config - TypeScript configuration with compiler options
* @param languageService - TypeScript language service for compilation
*
* @since 1.5.9
*/
constructor(config: ParsedCommandLine, languageService: LanguageService);
/**
* Generates bundled declaration files for the provided entry points
*
* @param entryPoints - Array of file paths to use as entry points
* @returns Array of bundled declaration content strings
*
* @remarks
* This method clears any existing cache and processes each entry point
* to generate bundled declarations. Entry points should be absolute paths
* to TypeScript source files.
*
* @since 1.5.9
*/
emitBundledDeclarations(entryPoints: Array<string>): Array<string>;
/**
* Generates a bundled declaration for a single entry point
*
* @param entryPath - Path to the entry point file
* @returns Bundled declaration content or undefined if generation fails
*
* @throws EntryPointError - When the specified entry point file cannot be found
* @throws CompilationError - When the TypeScript program cannot be accessed
*
* @remarks
* This method processes a single entry point to generate a bundled declaration file.
* It collects all necessary files and exported symbols, processes them, and
* combines them into a single declaration output.
*
* The method requires that the entry point file exists and is included in the
* TypeScript project configuration.
*
* @since 1.5.9
*/
private generateBundledDeclaration;
/**
* Resolves a module name to its file path
*
* @param moduleName - The module name to resolve
* @param containingFile - The file containing the import
* @param program - The TypeScript program
*
* @returns The resolved file path or undefined if resolution fails
*
* @since 1.5.9
*/
private resolveModule;
/**
* Recursively collects all files by following imports and exports
*
* @param sourceFile - The source file to process
* @param program - The TypeScript program
* @param collectedFiles - Set of collected file paths
*
* @remarks
* This method traverses the dependency graph starting from the provided source file
* and collects all files that contribute to the final bundle, excluding node_modules.
*
* @since 1.5.9
*/
private collectFilesRecursive;
/**
* Recursively collects exports from a module symbol
*
* @param symbol - The module symbol to process
* @param checker - The TypeScript type checker
* @param collectedSymbols - Set of collected symbol names
*
* @remarks
* This method collects all exported symbols from a module, including
* nested module exports for namespace declarations.
*
* @since 1.5.9
*/
private collectExportsRecursive;
/**
* Processes all collected files and extracts their declarations
*
* @param collectedFiles - Set of file paths to process
* @param collectedSymbols - Set of exported symbol names
* @returns Object containing bundled content and external imports
*
* @since 1.5.9
*/
private processDeclaredFiles;
/**
* Collects all exported symbols from a source file
*
* @param sourceFile - The source file to process
* @param checker - The TypeScript type checker
* @param collectedSymbols - Set to store collected symbol names
*
* @since 1.5.9
*/
private collectExportsFromSourceFile;
/**
* Processes a declaration file to extract its content
*
* @param fileName - Path to the declaration file
* @param collectedSymbols - Set of exported symbol names
* @param externalImports - Set to store external import statements
* @returns Processed declaration content or undefined if processing fails
*
* @remarks
* This method processes a single declaration file, filtering its content
* to include only relevant declarations and collecting external imports.
* It uses a cache to avoid reprocessing the same file multiple times.
*
* @since 1.5.9
*/
private processDeclarationFile;
/**
* Checks if a line is an import or export statement with a from clause
*
* @param line - The line to check
* @returns True if the line is an import or export with from clause
*
* @since 1.5.9
*/
private isImportOrExportWithFrom;
/**
* Extracts the module path from an import or export statement
*
* @param line - The import or export statement
* @returns The extracted module path or undefined if not found
*
* @since 1.5.9
*/
private extractModulePath;
/**
* Determines if a module is external (from node_modules)
*
* @param modulePath - The module path to check
* @param fileName - The file containing the import
* @returns True if the module is external
*
* @remarks
* This method determines if a module is external by checking if it's a relative
* or absolute path, and by resolving the module to see if it's in node_modules.
*
* @since 1.5.9
*/
private isExternalModule;
/**
* Processes an export line, removing 'export' if needed
*
* @param line - The export statement to process
* @param collectedSymbols - Set of exported symbol names
* @returns The processed line
*
* @remarks
* This method processes an export declaration line, removing the 'export'
* keyword if the symbol is not in the collected exports.
*
* @since 1.5.9
*/
private processExportLine;
/**
* Creates the final bundled declaration content
*
* @param externalImports - Set of external import statements
* @param bundledContent - Array of processed declaration content
* @returns The final bundled declaration content
*
* @since 1.5.9
*/
private createFinalBundleContent;
}
/**
* Imports
*/
/**
* Resolves path aliases in the provided content based on the specified paths and root directory.
*
* This function takes a string of content and replaces occurrences of defined path alias keys
* with their corresponding relative paths derived from the specified source file and root directory.
* It ensures that the resulting paths are relative to the directory of the source file and formatted
* correctly for use in a JavaScript/TypeScript environment.
*
* Example:
* Given the following inputs:
* ```ts
* const content = "import { foo } from '@core/foo';";
* const sourceFile = "/project/src/index.ts";
* const paths = {
* '@core/': 'src/core',
* '@utils/': 'src/utils'
* };
* const rootDir = "/project";
* ```
* The function will replace `@core/foo` with a relative path based on the source file's location,
* potentially resulting in:
* ```ts
* const content = "import { foo } from './core/foo';";
* ```
*
* @param content - The content in which path aliases need to be resolved.
* @param sourceFile - The path of the source file from which relative paths will be calculated.
* @param paths - An object mapping path alias keys to their corresponding paths.
* @param esm - A flag indicating whether ESM is enabled.
* @returns The updated content with resolved path aliases.
*/
declare function resolveAliasPlugin(content: string, sourceFile: string, paths: Record<string, string>, esm: boolean): string;
/**
* Import will remove at compile time
*/
/**
* Maps an array of file paths to an object where the keys are filenames (without extensions)
* and the values are the corresponding file paths.
*
* Each key in the resulting object is derived from the filename by removing the file extension.
* For example, given a file path `src/index.ts`, the key in the resulting object will be `src/index`.
*
* @param filePaths - An array of file paths to map. Each file path should be a string.
* @returns An object where the keys are filenames (without extensions) and the values are the corresponding file paths.
*
* @example
* ```ts
* const filePaths = ['src/index.ts', 'src/utils.ts'];
* const result = mapFilePathsToNames(filePaths);
* console.log(result);
* // Output: {
* // 'src/index': 'src/index.ts',
* // 'src/utils': 'src/utils.ts'
* // }
* ```
*/
declare function mapFilePathsToNames(filePaths: Array<string>): Record<string, string>;
/**
* Extracts and returns an object mapping output file paths to input file paths from the provided `EntryPointsType` object.
*
* This function handles multiple formats of entry points, including:
* - An array of strings representing file paths.
* - An array of objects containing `in` and `out` properties, where `in` is the input file path and `out` is the output file path.
* - A `Record<string, string>` where the keys represent input file paths and the values represent output file paths.
*
* Depending on the format, the function constructs an object with the output file paths as keys and the input file paths as values.
* If the output path is not available, the filename (without extension) is used as the key.
*
* If a regular object with string keys and values (not in the supported formats) is provided, it will be returned as is.
*
* @param entryPoints - The entry points to extract from, which can be in different formats: an array of strings,
* an array of objects with `in` and `out` properties, or a `Record<string, string>`.
*
* @returns An object mapping output file paths to input file paths, or filename (without extension) to file path.
*
* @throws Will throw an `Error` if the entry points format is unsupported.
*
* @example
* ```ts
* const entryPoints = extractEntryPoints(['src/index.ts', 'src/utils.ts']);
* console.log(entryPoints); // { 'index': 'src/index.ts', 'utils': 'src/utils.ts' }
* ```
*
* @example
* ```ts
* const entryPoints = extractEntryPoints([{ in: 'src/index.ts', out: 'dist/index.js' }]);
* console.log(entryPoints); // { 'dist/index.js': 'src/index.ts' }
* ```
*
* @example
* ```ts
* const entryPoints = extractEntryPoints({ index: 'src/index.ts', index2: 'dist/index2.js' });
* console.log(entryPoints); // { index: 'src/index.ts', index2: 'dist/index2.js' }
* ```
*/
declare function extractEntryPoints(entryPoints: EntryPointsType): Record<string, string>;
/**
* Import will remove at compile time
*/
/**
* Generates a `package.json` file with the appropriate `type` field
* based on the format specified in the configuration.
*
* - If the format is `esm`, the `type` will be set to `"module"`.
* - If the format is `cjs`, the `type` will be set to `"commonjs"`.
*
* The function will ensure that the specified output directory exists, and if it doesn't,
* it will create the necessary directories before writing the `package.json` file.
*
* @param config - The build configuration object containing
* esbuild-related settings, such as the format (`format`).
*
* - `config.esbuild.format`: The module format, either `'esm'` or `'cjs'`, that determines the `type` field.
*
* @throws Will throw an error if there is a problem creating the directory or writing the file.
*
* Example usage:
*
* ```ts
* const config = {
* esbuild: {
* format: 'esm'
* }
* };
* packageTypeComponent(config);
* // This will create 'dist/package.json' with the content: {"type": "module"}
* ```
*/
declare function packageTypeComponent(config: ConfigurationInterface): void;
/**
* Import will remove at compile time
*/
/**
* Parses a configuration file and returns a wrapped `ConfigurationInterface` object.
*
* This function reads the specified configuration file, transpiles it to a CommonJS format, and then executes it
* in a sandbox environment. The exported configuration object is wrapped so that any functions it contains will
* have sourcemap information attached to errors thrown during their execution.
*
* The wrapping of functions helps in debugging by associating errors with their source maps.
*
* @param file - The path to the configuration file that needs to be parsed and transpiled.
*
* @returns A promise that resolves to the parsed and transpiled `ConfigurationInterface` object.
* This object has its functions wrapped to attach sourcemap information to any errors thrown.
*
* @throws Will throw an error if the transpilation or execution of the configuration file fails.
* The thrown error will have sourcemap information attached if available.
* @example
* ```ts
* const config = await parseConfigurationFile('./config.jet.ts');
* console.log(config);
* ```
*/
declare function parseConfigurationFile(file: string): Promise<ConfigurationInterface>;
/**
* Import will remove at compile time
*/
/**
* Executes JavaScript code within a sandboxed environment using Node.js's `vm` module.
*
* @param code - The JavaScript code to be executed within the sandbox.
* @param sandbox - An optional context object to be used as the global scope for the executed code.
*
* @returns The result of executing the provided code within the sandboxed environment.
*
* @remarks
* The `sandboxExecute` function creates a new `Script` instance with the provided code and
* runs it within a sandboxed context using the `createContext` function from the `vm` module.
* This approach ensures that the executed code is isolated from the rest of the application,
* mitigating potential security risks.
*
* The `sandbox` parameter allows you to provide a custom context or global object for the
* sandboxed code. If not provided, an empty context is used. The function also supports
* breaking execution on interrupt signals (e.g., Ctrl+C) with the `breakOnSigint` option.
*
* @throws Error Throws an error if the code cannot be compiled or executed within the context.
*
* @example
* ```ts
* const result = sandboxExecute('return 2 + 2;', { myGlobal: 10 });
* console.log(result); // Output: 4
* ```
*
* In this example, the `sandboxExecute` function runs a simple JavaScript expression and returns
* the result. The `sandbox` parameter is provided with an empty object in this case.
*
* @public
* @category Services
*/
declare function sandboxExecute(code: string, sandbox?: Context): unknown;
/**
* Import will remove at compile time
*/
/**
* Merges user configurations with CLI configurations and default settings
* to produce a final configuration object for the build process.
* This function handles both single and multiple user configurations,
* allowing for flexible configuration merging.
*
* @param userConfig - An array or a single object of type `PartialDeepConfigurationsType`
* representing the user's configurations to merge. If a single object
* is provided, it is wrapped in an array for processing.
* @param cliConfig - An optional object of type `PartialDeepConfigurationsType` representing
* the CLI configurations to merge with the user configurations. Defaults to an empty object.
* @returns An array of `ConfigurationInterface` objects, each representing a merged configuration.
*
* @throws xBuildError Throws an error if the `entryPoints` property in the merged configuration is undefined.
* This ensures that the configuration is valid and complete for further processing.
*
* @example
* ```ts
* import { configuration } from './configuration';
*
* const userConfigs = [
* { esbuild: { entryPoints: ['src/index.ts'] } },
* { serve: { port: 3000 } }
* ];
* const cliConfigs = { esbuild: { minify: true } };
*
* const finalConfigs = await configuration(userConfigs, cliConfigs);
* console.log('Merged Configuration:', finalConfigs);
* ```
*/
declare function configuration(userConfig: Array<PartialDeepConfigurationsType> | PartialDeepConfigurationsType, cliConfig?: PartialDeepConfigurationsType): Promise<Array<ConfigurationInterface>>;
/**
* Merges CLI arguments with a configuration file to produce a final configuration object.
* This function reads the specified configuration file and merges its contents with
* the CLI arguments provided. The resulting configuration will be validated to ensure
* that required properties, such as `entryPoints`, are defined.
*
* @param configFile - The path to the configuration file to read and merge with CLI arguments.
* @param cli - An instance of `Argv<ArgvInterface>` containing CLI arguments and options.
* @returns A promise that resolves to an array of `ConfigurationInterface` objects, representing
* the final merged configuration.
* @throws Error Throws an error if the `entryPoints` property in the final configuration is undefined.
* This ensures that the configuration is valid for further processing.
*
* @example
* ```ts
* import { cliConfiguration } from './cli-configuration';
*
* const configFilePath = './config.json';
* const cliArgs = argv(); // Assuming `argv` is a function that retrieves CLI arguments
*
* cliConfiguration(configFilePath, cliArgs).then((finalConfig) => {
* console.log('Final configuration: ', finalConfig);
* }).catch((error) => {
* console.error('Error loading configuration:', error);
* });
* ```
*/
declare function cliConfiguration(configFile: string, cli: Argv<ArgvInterface>): Promise<Array<ConfigurationInterface>>;
/**
* Imports
*/
/**
* Compiles a given glob pattern into a regular expression.
*
* @param globPattern - The glob pattern to be converted into a regular expression.
* @return A regular expression derived from the provided glob pattern.
*
* @remarks This method processes a glob pattern by escaping special regex characters
* and translating glob syntax such as wildcards (*, ?, **) and braces into equivalent
* regex components.
*
* @since 1.6.0
*/
declare function compileGlobPattern(globPattern: string): RegExp;
/**
* Determines whether a given string is a glob pattern.
*
* A glob pattern typically contains special characters or patterns used for
* file matching, such as `*`, `?`, `[ ]`, `{ }`, `!`, `@`, `+`, `( )`, and `|`.
* It also checks for brace expressions like `{a,b}` and extglob patterns like `@(pattern)`.
*
* @param str - The string to be evaluated.
* @returns `true` if the input string is a glob pattern, otherwise `false`.
*
* @remarks This function checks for common globbing patterns and may not cover all edge cases.
*
* @since 1.6.0
*/
declare function isGlob(str: string): boolean;
/**
* Determines whether a given path matches any of the provided regular expression patterns.
*
* @param path - The string path to check against the patterns.
* @param patterns - An array of RegExp objects to test the path against.
* @returns A boolean indicating whether the path matches any of the patterns.
*
* @remarks This function is commonly used in file filtering operations like
* in the `collectFilesFromDir` function to determine which files to include
* or exclude based on pattern matching.
*
* @example
* ```ts
* const isMatch = matchesAny('src/file.ts', [/\.ts$/, /\.js$/]);
* console.log(isMatch); // true
* ```
*
* @since 1.6.0
*/
declare function matchesAny(path: string, patterns: RegExp[]): boolean;
/**
* Recursively collects files from a directory based on include and exclude patterns.
*
* @param baseDir - The base directory to start the file collection from.
* @param include - An array of glob patterns specifying which files to include.
* Patterns starting with '!' are treated as exclude patterns.
* @param exclude - An array of glob patterns specifying which files to exclude.
* @returns An array of file paths relative to the base directory that match the include
* patterns and don't match the exclude patterns.
*
* @remarks
* This function:
* - Returns an empty array if the base directory doesn't exist
* - Processes negative patterns (starting with '!') from both include and exclude arrays
* - Normalizes all paths to use forward slashes for consistent pattern matching
* - Uses depth-first traversal to walk through the directory structure
* - Performs pattern matching against paths relative to the base directory
*
* @example
* ```ts
* // Collect all TypeScript files except tests
* const files = collectFilesFromDir(
* 'src',
* ['**\/*.ts'],
* ['**\/*.spec.ts', '**\/*.test.ts']
* );
*
* // With negated patterns in include
* const files2 = collectFilesFromDir(
* 'src',
* ['**\/*.ts', '!**\/*.d.ts'],
* ['node_modules/**']
* );
* ```
*
* @since 1.6.0
*/
declare function collectFilesFromDir(baseDir: string, include: Array<string>, exclude: Array<string>): Array<string>;
/**
* Import will remove at compile time
*/
/**
* The default configuration options for the build.
*
* @example
* ```ts
* import { defaultConfiguration } from '@configuration/default-configuration';
*
* console.log(defaultConfiguration);
* ```
*
* In this example, the `defaultConfiguration` is imported and logged to the console to view the default settings.
*
* @public
* @category Configuration
*/
declare const defaultConfiguration: ConfigurationInterface;