@remotex-labs/xbuild 2.2.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bash.js +3 -3
- package/dist/bash.js.map +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/bash.js.map
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/bash.ts", "../src/errors/uncaught.error.ts", "../src/modules/symlinks/symlinks.module.ts", "../src/providers/stack.provider.ts", "../src/modules/typescript/models/files.model.ts", "../src/components/path.component.ts", "../src/services/framework.service.ts", "../src/modules/observable/pipe/operators.pipe.ts", "../src/modules/observable/services/observable.service.ts", "../src/modules/observable/services/subject.service.ts", "../src/modules/observable/services/behavior-subject.service.ts", "../src/components/object.component.ts", "../src/constants/configuration.constant.ts", "../src/services/configuration.service.ts", "../src/errors/base.error.ts", "../src/modules/argv/argv.module.ts", "../src/modules/argv/constants/argv.constant.ts", "../src/components/interactive.component.ts", "../src/components/glob.component.ts", "../src/errors/types.error.ts", "../src/errors/xbuild.error.ts", "../src/errors/esbuild.error.ts", "../src/providers/esbuild-messages.provider.ts", "../src/modules/server/server.module.ts", "../src/modules/server/html/server.html", "../src/components/banner.component.ts", "../src/services/watch.service.ts", "../src/services/variant.service.ts", "../src/modules/typescript/models/graph.model.ts", "../src/modules/typescript/components/transformer.component.ts", "../src/modules/typescript/services/typescript.service.ts", "../src/modules/typescript/services/bundler.service.ts", "../src/modules/typescript/constants/typescript.constant.ts", "../src/modules/typescript/services/emitter.service.ts", "../src/modules/typescript/services/hosts.service.ts", "../src/services/transpiler.service.ts", "../src/components/entry-points.component.ts", "../src/providers/lifecycle.provider.ts", "../src/directives/macros.directive.ts", "../src/directives/define.directive.ts", "../src/directives/inline.directive.ts", "../src/errors/inline.error.ts", "../src/services/vm.service.ts", "../src/directives/analyze.directive.ts", "../src/services/build.service.ts", "../src/index.ts", "../src/components/constants/interactive.constant.ts", "../src/providers/config-file.provider.ts", "../src/errors/vm-runtime.error.ts", "../src/components/printer.component.ts", "../src/components/color.component.ts"],
|
|
4
|
-
"sourceRoot": "https://github.com/remotex-labs/xBuild/tree/v2.2.
|
|
5
|
-
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Import will remove at compile time\n */\n\nimport type { ServerConfigurationInterface } from './index';\nimport type { ArgumentsInterface } from '@argv/interfaces/argv-module.interface';\nimport type { xBuildConfigInterface } from '@providers/interfaces/config-file-provider.interface';\n\n/**\n * Imports\n */\n\nimport { rmSync } from 'fs';\nimport { cwd } from 'process';\nimport '@errors/uncaught.error';\nimport { ArgvModule } from '@argv/argv.module';\nimport { join } from '@components/path.component';\nimport { inject } from '@symlinks/symlinks.module';\nimport { init } from '@components/interactive.component';\nimport { collectFilesFromGlob } from '@components/glob.component';\nimport { configFileProvider } from '@providers/config-file.provider';\nimport { bannerComponent, prefix } from '@components/banner.component';\nimport { BuildService, overwriteConfig, ServerModule, WatchService } from './index';\nimport { logError, logTypeDiagnostics, logBuildEnd } from '@components/printer.component';\nimport { errorColor, keywordColor, mutedColor, pathColor } from '@components/color.component';\nimport { logBuildStart, createActionPrefix, ERROR_SYMBOL } from '@components/printer.component';\n\n/**\n * Default glob patterns for excluding common non-source directories from entry point collection.\n *\n * @remarks\n * Applied when `--entryPoints` CLI flag is provided to filter out:\n * - `node_modules`: Third-party dependencies\n * - `dist`: Build output directory\n * - `bundle`: Alternative build output\n * - `**\\/*.d.ts`: TypeScript declaration files\n *\n * These patterns are prepended with `!` to indicate exclusion in glob syntax.\n *\n * @example\n * ```ts\n * const patterns = [...args.entryPoints, ...DEFAULT_IGNORE_PATTERNS];\n * // Result: ['src/**\\/*.ts', '!node_modules/**', '!dist/**', ...]\n * ```\n *\n * @see {@link configureEntryPoints} for usage context\n *\n * @since 2.0.0\n */\n\nconst DEFAULT_IGNORE_PATTERNS = [\n '!node_modules/**',\n '!dist/**',\n '!bundle/**',\n '!**/*.d.ts'\n] as const;\n\n/**\n * Glob patterns for directories excluded from watch mode file monitoring.\n *\n * @remarks\n * Prevents unnecessary rebuilds when files change in:\n * - `dist`: Build output (avoids rebuild loops)\n * - `.git`: Version control metadata\n * - `.idea`: IDE configuration files\n * - `node_modules`: Third-party dependencies (rarely change during development)\n *\n * Does not use `!` prefix as these are used directly with the watch service's\n * ignore configuration, not glob pattern matching.\n *\n * @example\n * ```ts\n * const watchService = new WatchService(WATCH_IGNORE_PATTERNS);\n * // Ignores changes in dist/, .git/, .idea/, node_modules/\n * ```\n *\n * @see {@link WatchService} for file monitoring implementation\n * @see {@link collectWatchIgnorePatterns} for dynamic pattern collection\n *\n * @since 2.0.0\n */\n\nconst WATCH_IGNORE_PATTERNS = [\n 'dist',\n 'dist/**',\n '.git/**',\n '.idea/**',\n 'node_modules/**'\n] as const;\n\n/**\n * Configures entry points from CLI glob patterns and injects them as a special \"argv\" build variant.\n *\n * @param config - The xBuild configuration object to modify\n * @param args - Parsed command-line arguments containing entry point patterns\n *\n * @remarks\n * When the `--entryPoints` CLI flag is provided, this function:\n * 1. Combines user patterns with default exclusion patterns\n * 2. Excludes custom output directories from config (both CLI and config file)\n * 3. Resolves glob patterns to actual file paths\n * 4. Creates an \"argv\" variant containing the collected entry points\n *\n * The \"argv\" variant is a special build variant that merges with other configured\n * variants or serves as the sole variant if none are defined in the config file.\n *\n * **Output directory exclusion**:\n * - Checks `args.outdir` (CLI flag)\n * - Checks `config.common.esbuild.outdir` (config file)\n * - Adds both as exclusion patterns to prevent output files from being processed as source\n *\n * @example With entry points CLI flag\n * ```ts\n * const args = { entryPoints: ['src/**\\/*.ts'], outdir: 'build' };\n * configureEntryPoints(config, args);\n *\n * // config.variants.argv now contains:\n * // {\n * // esbuild: {\n * // entryPoints: ['src/index.ts', 'src/utils.ts', ...]\n * // }\n * // }\n * ```\n *\n * @example Without entry points (no-op)\n * ```ts\n * const args = {};\n * configureEntryPoints(config, args);\n * // config unchanged\n * ```\n *\n * @see {@link ArgumentsInterface.entryPoints}\n * @see {@link DEFAULT_IGNORE_PATTERNS} for default exclusions\n * @see {@link collectFilesFromGlob} for glob pattern resolution\n *\n * @since 2.0.0\n */\n\nfunction configureEntryPoints(config: xBuildConfigInterface, args: ArgumentsInterface): void {\n if (!args.entryPoints) return;\n\n const ignorePatterns = [\n ...args.entryPoints,\n ...DEFAULT_IGNORE_PATTERNS\n ];\n\n if (args.outdir) {\n ignorePatterns.push(`!${ args.outdir }/**`, `!${ args.outdir }`);\n }\n\n if (config.common?.esbuild?.outdir) {\n ignorePatterns.push(`!${ config.common.esbuild.outdir }/**`, `!${ config.common.esbuild.outdir }`);\n }\n\n config.variants = {\n argv: {\n esbuild: {\n entryPoints: collectFilesFromGlob(cwd(), ignorePatterns)\n }\n }\n };\n}\n\n/**\n * Applies command-line argument overrides to all build variant configurations.\n *\n * @param config - The xBuild configuration object to modify\n * @param args - Parsed command-line arguments containing override values\n *\n * @remarks\n * Iterates through all configured variants and applies CLI flag overrides for:\n * - `--verbose`: Enable detailed logging\n * - `--types`: Enable/disable TypeScript type generation\n * - `--outdir`: Override output directory\n * - `--bundle`: Enable bundling and minification\n * - `--minify`: Enable code minification\n * - `--tsconfig`: Specify custom TypeScript configuration file\n * - `--platform`: Target platform (node, browser, neutral)\n * - `--declaration`: Enable/disable `.d.ts` generation\n * - `--failOnError`: Fail build on type errors\n *\n * **Precedence**: CLI flags take precedence over config file settings, allowing\n * temporary overrides without modifying the configuration file.\n *\n * **Top-level vs. variant settings**:\n * - `verbose` is set at the top level (affects all variants)\n * - Other settings are applied to each variant's configuration individually\n *\n * **Conditional application**: Only defined CLI arguments are applied, allowing\n * partial overrides while preserving other config file settings.\n *\n * @example Override output directory\n * ```ts\n * const args = { outdir: 'build' };\n * applyCommandLineOverrides(config, args);\n *\n * // All variants now have:\n * // variant.esbuild.outdir = 'build'\n * ```\n *\n * @example Multiple overrides\n * ```ts\n * const args = {\n * minify: true,\n * platform: 'node',\n * declaration: false\n * };\n * applyCommandLineOverrides(config, args);\n *\n * // All variants updated with these settings\n * ```\n *\n * @see {@link ArgumentsInterface} for available CLI flags\n * @see {@link xBuildConfigInterface} for configuration structure\n *\n * @since 2.0.0\n */\n\nfunction applyCommandLineOverrides(config: xBuildConfigInterface, args: ArgumentsInterface): void {\n if (args.verbose !== undefined) {\n config.verbose = args.verbose;\n }\n\n const variants = Object.values(config.variants ?? {});\n\n for (const variant of variants) {\n if (args.types !== undefined) variant.types = args.types;\n if (args.outdir !== undefined) variant.esbuild.outdir = args.outdir;\n if (args.bundle !== undefined) variant.esbuild.minify = args.bundle;\n if (args.minify !== undefined) variant.esbuild.minify = args.minify;\n if (args.tsconfig !== undefined) variant.esbuild.tsconfig = args.tsconfig;\n if (args.platform !== undefined) variant.esbuild.platform = args.platform;\n if (args.declaration !== undefined) variant.declaration = args.declaration;\n\n if (args.failOnError !== undefined) {\n variant.types = { failOnError: args.failOnError };\n }\n }\n}\n\n/**\n * Collects all directories that should be ignored by the file watcher.\n *\n * @param config - The xBuild configuration containing output directory settings\n *\n * @returns Array of directory patterns to exclude from watch monitoring\n *\n * @remarks\n * Combines default ignore patterns with dynamic output directories to create\n * a comprehensive exclusion list for the watch service. This prevents:\n * - Rebuild loops (watching build output directories)\n * - Unnecessary rebuild triggers from IDE/VCS file changes\n * - Performance issues from monitoring large node_modules directories\n *\n * **Dynamic pattern collection**:\n * 1. Starts with {@link WATCH_IGNORE_PATTERNS} (static patterns)\n * 2. Adds `config.common.esbuild.outdir` if present\n * 3. Adds each variant's `esbuild.outdir` if present\n * 4. For each directory, adds both the directory itself and a recursive pattern\n *\n * **Pattern format**:\n * - `dist`: Ignore the directory\n * - `dist/**`: Ignore all files within the directory recursively\n *\n * @example With common and variant output directories\n * ```ts\n * const config = {\n * common: { esbuild: { outdir: 'dist' } },\n * variants: {\n * prod: { esbuild: { outdir: 'build' } },\n * dev: { esbuild: { outdir: 'tmp' } }\n * }\n * };\n *\n * const patterns = collectWatchIgnorePatterns(config);\n * // Returns: [\n * // 'dist', '.git/**', 'node_modules/**', ...,\n * // 'dist', 'dist/**',\n * // 'build', 'build/**',\n * // 'tmp', 'tmp/**'\n * // ]\n * ```\n *\n * @example With no custom output directories\n * ```ts\n * const config = { variants: {} };\n * const patterns = collectWatchIgnorePatterns(config);\n * // Returns: ['dist', 'dist/**', '.git/**', '.idea/**', 'node_modules/**']\n * ```\n *\n * @see {@link WATCH_IGNORE_PATTERNS} for default exclusions\n * @see {@link WatchService} for watch service implementation\n *\n * @since 2.0.0\n */\n\nfunction collectWatchIgnorePatterns(config: xBuildConfigInterface): Array<string> {\n const ignorePatterns: Array<string> = [ ...WATCH_IGNORE_PATTERNS ];\n\n if (config.common?.esbuild?.outdir) {\n ignorePatterns.push(config.common.esbuild.outdir, `${ config.common.esbuild.outdir }/**`);\n }\n\n const variants = Object.values(config.variants ?? {});\n for (const variant of variants) {\n if (variant.esbuild.outdir) {\n ignorePatterns.push(variant.esbuild.outdir, `${ variant.esbuild.outdir }/**`);\n }\n }\n\n return ignorePatterns;\n}\n\n/**\n * Starts the development HTTP server if requested via CLI or configuration.\n *\n * @param config - The xBuild configuration containing server settings\n * @param args - Parsed command-line arguments containing serve flag\n *\n * @returns Promise resolving to the server URL string if started, otherwise undefined\n *\n * @remarks\n * The server is started when either:\n * - `--serve [dir]` CLI flag is provided (optionally with directory)\n * - `config.serve.start` is set to `true` in configuration file\n *\n * **Server directory resolution**:\n * 1. `config.serve.dir` (config file setting, highest priority)\n * 2. `args.serve` (CLI flag value, if string)\n * 3. `'dist'` (default fallback)\n *\n * **Configuration merging**:\n * - Merges config file server settings with CLI overrides\n * - Wraps the `onStart` callback to capture server URL and log startup message\n * - Preserves user-defined `onStart` callback if present\n *\n * **Startup logging**:\n * Displays formatted startup message:\n * ```\n * [serve] dist http://localhost:3000\n * ```\n *\n * @example Start server with CLI flag\n * ```ts\n * const args = { serve: 'public' };\n * const url = await startServer(config, args);\n * // Server started at http://localhost:3000\n * // Serving: public\n * ```\n *\n * @example Start server from config\n * ```ts\n * const config = {\n * serve: {\n * start: true,\n * dir: 'dist',\n * port: 8080\n * }\n * };\n * const url = await startServer(config, {});\n * // Server started at http://localhost:8080\n * ```\n *\n * @example No server (returns undefined)\n * ```ts\n * const config = { serve: { start: false } };\n * const url = await startServer(config, {});\n * // url === undefined\n * ```\n *\n * @see {@link ServerModule} for server implementation\n * @see {@link ServerConfigurationInterface} for configuration options\n *\n * @since 2.0.0\n */\n\nasync function startServer(config: xBuildConfigInterface, args: ArgumentsInterface): Promise<string | undefined> {\n const shouldStartServer = (args.serve ?? false) !== false || config.serve?.start;\n if (!shouldStartServer) return;\n\n let urlString = undefined;\n const serveDir = config.serve?.dir || args.serve || 'dist';\n const serverConfig: ServerConfigurationInterface = {\n ...config.serve,\n onStart({ host, port, url }): void {\n urlString = url;\n console.log(`${ createActionPrefix('serve') } ${ keywordColor(serveDir) } ${ pathColor(url) }\\n`);\n config.serve?.onStart?.({ host, port, url });\n }\n };\n\n const server = new ServerModule(serverConfig, serveDir);\n await server.start();\n\n return urlString;\n}\n\n/**\n * Executes a single build pass, handling clean, type checking, and build operations.\n *\n * @param buildService - The build service instance to execute\n * @param args - Parsed command-line arguments controlling build behavior\n *\n * @returns Promise that resolves when the build completes or fails\n *\n * @remarks\n * Orchestrates a complete build cycle with the following steps:\n * 1. **Clean**: Removes the `dist` directory (forced, recursive)\n * 2. **Type check or build**: Executes type checking if `--typeCheck` flag is set, otherwise performs full build\n * 3. **Error handling**: Catches and logs any build errors\n *\n * **Operational modes**:\n * - **Type check mode** (`--typeCheck`): Runs TypeScript compiler diagnostics without emitting files\n * - **Build mode**: Executes full build with optional build name parameter\n *\n * **Clean behavior**:\n * - Always removes `dist` directory before building\n * - Uses `{ recursive: true, force: true }` for safe deletion\n * - Errors during clean are silently ignored (directory may not exist)\n *\n * **Error handling**:\n * - All errors are caught and logged via {@link logError}\n * - Errors do not throw (suitable for watch mode)\n *\n * @example Standard build\n * ```ts\n * const args = { build: 'production' };\n * await executeBuild(buildService, args);\n * // 1. Removes dist/\n * // 2. Builds with 'production' configuration\n * ```\n *\n * @example Type check only\n * ```ts\n * const args = { typeCheck: true };\n * await executeBuild(buildService, args);\n * // 1. Removes dist/\n * // 2. Runs TypeScript diagnostics\n * // 3. Logs diagnostics (no files emitted)\n * ```\n *\n * @example Error during build\n * ```ts\n * await executeBuild(buildService, args);\n * // If build fails, error is logged but function doesn't throw\n * ```\n *\n * @see {@link logError} for error formatting\n * @see {@link BuildService.typeChack} for type checking\n * @see {@link BuildService.build} for build implementation\n * @see {@link logTypeDiagnostics} for diagnostic output formatting\n *\n * @since 2.0.0\n */\n\nasync function executeBuild(buildService: BuildService, args: ArgumentsInterface): Promise<void> {\n try {\n const distPath = join(process.cwd(), 'dist');\n rmSync(distPath, { recursive: true, force: true });\n\n if (args.typeCheck) {\n const diagnostics = await buildService.typeChack();\n logTypeDiagnostics(diagnostics);\n } else {\n const result = await buildService.build(args.build);\n Object.entries(result).forEach(([ name, variant ]) => {\n const errors = variant.errors.filter(\n (error: Error & { id?: string }) => error?.id === 'endHook'\n );\n\n if(!errors.length) return;\n const status = createActionPrefix('onEnd-hook', errorColor(ERROR_SYMBOL));\n console.log(status, name);\n\n errors.forEach((error: Error) => logError(error));\n console.log('');\n });\n }\n } catch (error) {\n logError(error);\n }\n}\n\n/**\n * Enters watch mode for continuous rebuilding on file changes.\n *\n * @param buildService - The build service instance to trigger rebuilds\n * @param config - The xBuild configuration containing watch patterns\n * @param args - Parsed command-line arguments controlling watch behavior\n * @param url - Optional server URL to display in interactive UI\n *\n * @returns Promise that resolves when watch mode is set up (never resolves in watch mode)\n *\n * @remarks\n * Watch mode is enabled when:\n * - `--watch` CLI flag is provided, OR\n * - `--serve` CLI flag is provided (implies watching), OR\n * - `config.serve.start` is `true` (implies watching)\n *\n * **Watch mode flow**:\n * 1. Collects ignore patterns from configuration\n * 2. Initializes watch service with ignore patterns\n * 3. Sets up interactive terminal UI (if applicable)\n * 4. Executes initial build\n * 5. Starts file system watcher\n * 6. On file changes:\n * - Touches changed files in TypeScript language service\n * - Reloads configuration if config file changed\n * - Logs rebuild trigger\n * - Executes rebuild\n *\n * **Configuration reloading**:\n * If the configuration file itself changes, the config is reloaded and\n * the build service is updated with the new configuration, allowing\n * configuration changes without restarting the process.\n *\n * **Interactive UI**:\n * Initializes an interactive terminal interface displaying:\n * - Server URL (if provided)\n * - Build status\n * - Keyboard shortcuts for manual actions\n *\n * **Early exit**:\n * If watch mode is not requested, the function returns immediately\n * without starting the watcher.\n *\n * @example Watch mode with server\n * ```ts\n * const args = { watch: true, serve: 'dist' };\n * await startWatchMode(buildService, config, args, 'http://localhost:3000');\n * // 1. Executes initial build\n * // 2. Starts watching files\n * // 3. Rebuilds on changes\n * // (Never returns)\n * ```\n *\n * @example Serve mode (implicit watch)\n * ```ts\n * const args = { serve: 'dist' };\n * await startWatchMode(buildService, config, args, url);\n * // Watch mode automatically enabled\n * ```\n *\n * @example No watch mode\n * ```ts\n * const args = {};\n * await startWatchMode(buildService, config, args);\n * // Returns immediately (no watching)\n * ```\n *\n * @see {@link WatchService} for file system monitoring\n * @see {@link BuildService.reload} for configuration reloading\n * @see {@link BuildService.touchFiles} for incremental compilation\n * @see {@link collectWatchIgnorePatterns} for ignore pattern collection\n *\n * @since 2.0.0\n */\n\nasync function startWatchMode(\n buildService: BuildService, config: xBuildConfigInterface, args: ArgumentsInterface, url?: string\n): Promise<void> {\n const shouldWatch = args.watch || args.serve !== undefined || config.serve?.start;\n if (!shouldWatch) return;\n\n const ignorePatterns = collectWatchIgnorePatterns(config);\n const watchService = new WatchService(ignorePatterns);\n\n init(async () => {\n await executeBuild(buildService, args);\n }, url);\n\n await executeBuild(buildService, args);\n await watchService.start(async (changedFiles: Array<string>): Promise<void> => {\n buildService.touchFiles(changedFiles);\n\n if(changedFiles.includes(args.config!)) {\n const config = await configFileProvider(args.config!);\n buildService.reload(config);\n }\n\n console.log(`\\n${ prefix() } ${ mutedColor('Rebuilding') }: files (${ changedFiles.length })\\n`);\n await executeBuild(buildService, args);\n });\n\n return;\n}\n\n/**\n * Main CLI entry point that orchestrates the complete xBuild execution lifecycle.\n *\n * @returns Promise that resolves when execution completes (or never in watch mode)\n *\n * @throws Errors are caught and logged internally, function does not throw\n *\n * @remarks\n * This is the primary entry point executed when the xBuild CLI is invoked.\n * It orchestrates the complete build lifecycle from configuration loading to\n * build execution, with support for watch mode, development server, and various\n * build configurations.\n *\n * **Execution flow**:\n * 1. **Banner**: Display xBuild version and branding\n * 2. **Configuration parsing**:\n * - Parse config file path from CLI args\n * - Load configuration file (if exists)\n * - Parse full CLI arguments with config context\n * - Extract user-defined arguments\n * 3. **Configuration setup**:\n * - Configure entry points from glob patterns\n * - Apply CLI overrides to variant configurations\n * - Finalize and validate configuration\n * 4. **Build service initialization**:\n * - Create build service instance with user args\n * - Register lifecycle callbacks (onStart, onEnd)\n * 5. **Server startup** (if requested):\n * - Start development HTTP server\n * - Capture server URL for UI display\n * 6. **Execution mode**:\n * - Enter watch mode if `--watch` or `--serve` flags present\n * - Otherwise, execute single build pass\n *\n * **Configuration precedence**:\n * 1. CLI flags (highest priority)\n * 2. Configuration file settings\n * 3. Built-in defaults (lowest priority)\n *\n * **User arguments**:\n * Custom CLI arguments defined in `config.userArgv` are parsed separately\n * and passed to the build service, allowing custom build scripts to extend\n * the CLI with additional flags.\n *\n * **Lifecycle callbacks**:\n * - `onStart`: Logs build start with timing information\n * - `onEnd`: Logs build completion with duration and status\n *\n * @example Standard build invocation\n * ```bash\n * xbuild\n * # 1. Displays banner\n * # 2. Loads xbuild.config.ts\n * # 3. Executes build\n * # 4. Exits\n * ```\n *\n * @example Watch mode with server\n * ```bash\n * xbuild --watch --serve dist --port 8080\n * # 1. Displays banner\n * # 2. Loads configuration\n * # 3. Starts server on port 8080\n * # 4. Executes initial build\n * # 5. Watches for changes\n * # (Runs indefinitely)\n * ```\n *\n * @example Custom configuration file\n * ```bash\n * xbuild --config custom.config.ts --minify\n * # Loads custom.config.ts instead of default\n * ```\n *\n * @see {@link startWatchMode} for watch mode\n * @see {@link executeBuild} for build execution\n * @see {@link startServer} for development server\n * @see {@link ArgvModule} for CLI argument parsing\n * @see {@link BuildService} for build orchestration\n * @see {@link configFileProvider} for configuration loading\n *\n * @since 2.0.0\n */\n\nasync function main(): Promise<void> {\n // Display banner\n console.log(bannerComponent());\n\n // Parse configuration\n const argvService = inject(ArgvModule);\n const preConfig = argvService.parseConfigFile(process.argv);\n\n globalThis.$argv = preConfig;\n const config = await configFileProvider(preConfig.config);\n const args = argvService.enhancedParse(process.argv, config.userArgv);\n const userArgs = argvService.parseUserArgv(process.argv, config.userArgv);\n\n // Configure build\n configureEntryPoints(config, args);\n applyCommandLineOverrides(config, args);\n overwriteConfig(config);\n\n // Initialize build service\n const buildService = new BuildService(userArgs);\n buildService.onEnd = logBuildEnd;\n buildService.onStart = logBuildStart;\n\n // Execute build pipeline\n const url = await startServer(config, args);\n await startWatchMode(buildService, config, args, url);\n await executeBuild(buildService, args);\n}\n\nmain();\n", "/**\n * Imports\n */\n\nimport process from 'node:process';\nimport { xBuildBaseError } from '@errors/base.error';\nimport { formatStack, getErrorMetadata } from '@providers/stack.provider';\n\n/**\n * Formats and logs error output in a standardized way.\n *\n * @remarks\n * This utility is designed for use in global error handlers such as\n * `uncaughtException` and `unhandledRejection`.\n * - If the error is an {@link AggregateError}, all individual errors are iterated and logged.\n * - Errors extending {@link xBuildBaseError} are logged directly without stack formatting.\n * - Standard {@link Error} instances are logged using {@link formatStack}, with both\n * framework and native frames included.\n * - Non-error values are logged as-is.\n *\n * @param reason - The error, aggregate error, or arbitrary value to log.\n *\n * @example\n * ```ts\n * formatErrors(new Error(\"Something went wrong\"));\n * ```\n *\n * @see formatStack\n * @see xJetBaseError\n * @see AggregateError\n *\n * @since 2.0.0\n */\n\nexport function formatErrors(reason: unknown): void {\n if (reason instanceof AggregateError) {\n console.error('AggregateError:', reason.message);\n for (const err of reason.errors) {\n if (err instanceof Error && !(err instanceof xBuildBaseError)) {\n const metadata = getErrorMetadata(err, { withFrameworkFrames: true, withNativeFrames: true });\n console.error(formatStack(metadata, err.name, err.message));\n } else {\n console.error(err);\n }\n }\n\n return;\n }\n\n if (reason instanceof Error && !(reason instanceof xBuildBaseError)) {\n const metadata = getErrorMetadata(reason, { withFrameworkFrames: true, withNativeFrames: true });\n console.error(formatStack(metadata, reason.name, reason.message));\n } else {\n console.error(reason);\n }\n}\n\n/**\n * Global handler for uncaught exceptions in Node.js.\n *\n * @param reason - The value or error object representing the uncaught exception\n *\n * @throws This handler does not throw, but catches uncaught exceptions\n *\n * @remarks\n * When an uncaught exception occurs, this handler logs the error using {@link formatStack}\n * with both framework and native frames included, and then terminates the process\n * with exit code `2`, signaling failure.\n *\n * @example\n * ```ts\n * // Automatically registered when this file is loaded,\n * throw new Error('This error will be logged and exit the process');\n * ```\n *\n * @see formatStack\n * @see process.exit\n * @see {@link https://nodejs.org/api/process.html#event-uncaughtexception | Node.js documentation on 'uncaughtException'}\n *\n * @since 2.0.0\n */\n\nprocess.on('uncaughtException', (reason: unknown) => {\n formatErrors(reason);\n process.exit(2);\n});\n\n/**\n * Global handler for unhandled promise rejections in Node.js.\n *\n * @param reason - The value or error object representing the reason for the unhandled promise rejection\n *\n * @throws This handler does not throw, but catches unhandled promise rejections\n *\n * @remarks\n * When an unhandled promise rejection occurs, this handler logs the error using {@link formatStack}\n * with both framework and native frames included, and then terminates the process\n * with exit code `2`. Using a distinct exit code allows differentiating between uncaught exceptions\n * and unhandled promise rejections.\n *\n * @example\n * ```ts\n * // Automatically registered when this file is loaded\n * Promise.reject(new Error('This rejection will be logged and exit the process'));\n * ```\n *\n * @see formatStack\n * @see process.exit\n * @see {@link https://nodejs.org/api/process.html#process_event_unhandledrejection | Node.js documentation on 'unhandledRejection'}\n *\n * @since 2.0.0\n */\n\nprocess.on('unhandledRejection', (reason: unknown) => {\n formatErrors(reason);\n process.exit(2);\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { InjectableOptionsInterface, ProvidersType } from './interfaces/symlinks.interface';\nimport type { ProviderUseFactoryInterface, ProviderUseValueInterface } from './interfaces/symlinks.interface';\nimport type { ProviderUseClassInterface, ConstructorType, ConstructorLikeType } from './interfaces/symlinks.interface';\n\n/**\n * A collection of singleton instances for injectable classes.\n *\n * @remarks\n * This map stores instances of classes marked as `singleton` in `@Injectable` metadata.\n * It ensures that only one instance exists for the lifetime of the application.\n *\n * @see ConstructorType\n * @since 2.0.0\n */\n\nexport const SINGLETONS = new Map<ConstructorType, unknown>();\n\n/**\n * Stores metadata for all classes marked with the `@Injectable` decorator.\n *\n * @remarks\n * The metadata includes scope, factory function, and provider dependencies.\n *\n * @see Injectable\n * @since 2.0.0\n */\n\nexport const INJECTABLES = new Map<ConstructorType, InjectableOptionsInterface>();\n\n/**\n * Type guard to check if a provider uses a class.\n *\n * @param provider - The provider to check.\n * @returns True if the provider is a {@link ProviderUseClassInterface}.\n *\n * @see ProviderUseClassInterface\n * @since 2.0.0\n */\n\nexport function isProviderUseClass(provider: unknown): provider is ProviderUseClassInterface {\n return typeof provider === 'object' && provider !== null && 'useClass' in provider;\n}\n\n/**\n * Type guard to check if a provider uses a factory function.\n *\n * @param provider - The provider to check.\n * @returns True if the provider is a {@link ProviderUseFactoryInterface}.\n *\n * @see ProviderUseFactoryInterface\n * @since 2.0.0\n */\n\nexport function isProviderUseFactory(provider: unknown): provider is ProviderUseFactoryInterface {\n return typeof provider === 'object' && provider !== null && 'useFactory' in provider;\n}\n\n/**\n * Type guard to check if a provider uses a value.\n *\n * @param provider - The provider to check.\n * @returns True if the provider is a {@link ProviderUseValueInterface}.\n *\n * @see ProviderUseValueInterface\n * @since 2.0.0\n */\n\nexport function isProviderUseValue(provider: unknown): provider is ProviderUseValueInterface {\n return typeof provider === 'object' && provider !== null && 'useValue' in provider;\n}\n\n/**\n * Marks a class as injectable, optionally providing metadata.\n *\n * @param options - Optional configuration for the injectable class.\n *\n * @remarks\n * The `@Injectable` decorator allows classes to be automatically instantiated\n * and injected with dependencies using the `inject` function.\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n *\n * const instance = inject(MyService);\n * ```\n *\n * ```ts\n * @Injectable()\n * class Database {\n * }\n *\n * @Injectable({\n * providers: [ Database ]\n * })\n * class UserService {\n * constructor(private db: Database) {\n * console.log(db); // db instance\n * }\n * }\n *\n * const userService = inject(UserService);\n * ```\n *\n * ```ts\n * @Injectable()\n * class Cache {}\n *\n * @Injectable({\n * providers: [{ useClass: Cache }]\n * })\n * class UserService {\n * constructor(cache: Cache) {\n * console.log(cache); // cache instance\n * }\n * }\n *\n * const userService = inject(UserService);\n * ```\n *\n * ```ts\n * @Injectable({\n * providers: [\n * {\n * useFactory(): Date {\n * return new Date();\n * }\n * }\n * ]\n * })\n * class ClockService {\n * constructor(now: Date) {\n * console.log(now.toLocaleTimeString()); // get time from the factory\n * }\n * }\n *\n * const clockService = inject(ClockService);\n * ```\n *\n * ```ts\n * @Injectable({\n * providers: [\n * {\n * useValue: 'https://api.example.com'\n * }\n * ]\n * })\n * class ApiService {\n * constructor(baseUrl: string) {\n * console.log(baseUrl);\n * }\n * }\n *\n *\n * const apiService = inject(ApiService); // log https://api.example.com\n * const apiService2 = inject(ApiService, 'https://api2.example.com'); // log https://api2.example.com\n * ```\n *\n * ```ts\n * @Injectable()\n * class Logger {\n * }\n *\n * @Injectable({\n * providers: [\n * Logger,\n * { useValue: 10 },\n * { useFactory: (): string => 'prod' }\n * ]\n * })\n * class AppService {\n * constructor(\n * logger: Logger,\n * retries: number,\n * env: string\n * ) {\n * console.log(logger, retries, env);\n * }\n * }\n *\n * const appService = inject(AppService); // log Logger {} 10 prod\n * const appService2 = inject(AppService, inject(Logger), 50, 'test'); // log Logger {} 50 test\n * ```\n *\n * @see InjectableOptionsInterface\n * @since 2.0.0\n */\n\nexport function Injectable<T extends ConstructorType = ConstructorType>(options?: InjectableOptionsInterface<T>) {\n return function (target: T): void {\n INJECTABLES.set(target, <InjectableOptionsInterface>options || {});\n };\n}\n\n/**\n * Converts an array of providers into constructor arguments for injection.\n *\n * @param providers - An optional array of providers to resolve.\n * @param args - Optional initial arguments to prepend before resolving providers.\n * @returns An array of resolved arguments including the results from providers.\n *\n * @remarks\n * This function iterates over the provided `ProvidersType` array and converts each provider\n * into its resolved value. It supports class providers, factory providers, value providers,\n * and direct constructor functions. The returned array can be used to construct instances\n * with dependencies injected in the correct order.\n *\n * @example\n * ```ts\n * const args = providersIntoArgs([{ useValue: 42 }, { useFactory: () => 'hello' }]);\n * // args = [42, 'hello']\n * ```\n *\n * @see isProviderUseClass\n * @see isProviderUseValue\n * @see isProviderUseFactory\n *\n * @since 2.0.0\n */\n\nexport function providersIntoArgs(providers?: ProvidersType, args: Array<unknown> = []): Array<unknown> {\n if (!providers) return args;\n\n const scopeAgs: Array<unknown> = args;\n for (const provider of providers.slice(scopeAgs.length)) {\n if (isProviderUseClass(provider)) {\n scopeAgs.push(inject(provider.useClass, ...providersIntoArgs(provider.providers)));\n } else if (isProviderUseFactory(provider)) {\n scopeAgs.push(provider.useFactory(...providersIntoArgs(provider.providers)));\n } else if (isProviderUseValue(provider)) {\n scopeAgs.push(provider.useValue);\n } else if (typeof provider === 'function') {\n scopeAgs.push(inject(provider));\n } else {\n throw new Error(`Unknown provider type: ${ typeof provider }`);\n }\n }\n\n return scopeAgs;\n}\n\n/**\n * Resolves and instantiates a class with its dependencies.\n *\n * @param token - The constructor function or class to instantiate.\n * @param args - Optional arguments to pass to the constructor, which can override\n * or supplement provider-resolved values.\n * @returns An instance of the class with all dependencies injected.\n *\n * @remarks\n * The `inject` function looks up metadata for the class marked with `@Injectable`.\n * It resolves all providers recursively using `providersIntoArgs`. If the class is\n * marked as a `singleton`, the same instance will be returned on further calls.\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n *\n * const instance = inject(MyService);\n * ```\n *\n * @see Injectable\n * @see providersIntoArgs\n *\n * @since 2.0.0\n */\n\nexport function inject<T, Args extends Array<unknown>>(token: ConstructorLikeType<T, Args>, ...args: Partial<Args>): T {\n if (SINGLETONS.has(token)) return <T>SINGLETONS.get(token);\n\n const metadata = INJECTABLES.get(token);\n if (!metadata) throw new Error(`Cannot inject ${ token.name } \u2013 not marked @Injectable`);\n\n const scopeAgs = providersIntoArgs(metadata.providers, args);\n const instance: T = metadata.factory\n ? <T>metadata.factory(...scopeAgs)\n : new token(...scopeAgs as Args);\n\n if (metadata?.scope === 'singleton') {\n SINGLETONS.set(token, instance);\n }\n\n return instance;\n}\n\n/**\n * Forces the instantiation of a class bypassing any existing singleton instance.\n *\n * @param token - The constructor function or class to instantiate.\n * @param args - Optional arguments to pass to the constructor, which can override\n * or supplement provider-resolved values.\n * @returns A new instance of the class, even if a singleton instance already exists.\n *\n * @remarks\n * Unlike the `inject` function, `forceInject` will delete any existing singleton\n * instance for the given class before creating a new one. This is useful when you\n * need a fresh instance regardless of the singleton scope.\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n *\n * const freshInstance = forceInject(MyService);\n * ```\n *\n * @see inject\n * @since 2.0.0\n */\n\nexport function forceInject<T, Args extends Array<unknown>>(token: ConstructorLikeType<T, Args>, ...args: Partial<Args>): T {\n if (SINGLETONS.has(token)) SINGLETONS.delete(token);\n\n return inject<T, Args>(token, ...args);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PartialMessage } from 'esbuild';\nimport type { SourceService } from '@remotex-labs/xmap';\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\nimport type { ParsedStackTraceInterface, StackFrameInterface } from '@remotex-labs/xmap/parser.component';\nimport type { StackInterface, StackContextInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { inject } from '@symlinks/symlinks.module';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { FrameworkService } from '@services/framework.service';\nimport { relative, dirname, join } from '@components/path.component';\nimport { parseErrorStack } from '@remotex-labs/xmap/parser.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { highlightCode } from '@remotex-labs/xmap/highlighter.component';\nimport { type PositionWithCodeInterface, Bias } from '@remotex-labs/xmap';\nimport { type SourceOptionsInterface, formatErrorCode } from '@remotex-labs/xmap/formatter.component';\n\n/**\n * Regular expression to match multiple consecutive spaces.\n *\n * @remarks\n * Used to normalize spacing in formatted strings by replacing sequences\n * of two or more spaces with a single space.\n *\n * @since 2.0.0\n */\n\nconst MULTIPLE_SPACES = /\\s{2,}/g;\n\n/**\n * Regular expression to detect HTTP or HTTPS URLs.\n *\n * @remarks\n * Used to identify URL-based source paths in stack traces or source maps.\n *\n * @since 2.0.0\n */\n\nconst URL_PATTERN = /^https?:\\/\\//;\n\n/**\n * Regular expression to detect file:// protocol URLs.\n *\n * @remarks\n * Used to identify and strip file protocol prefixes from file paths.\n *\n * @since 2.0.0\n */\n\nconst FILE_PROTOCOL = /^file:\\/\\//;\n\n/**\n * Extracts a parsed stack trace from either an Error object or an esbuild PartialMessage.\n *\n * @param raw - Either an {@link Error} object or an esbuild {@link PartialMessage}\n * @returns A {@link ParsedStackTraceInterface} containing structured stack frame data\n *\n * @remarks\n * - If `raw` is an Error instance, parses it directly using {@link parseErrorStack}.\n * - If `raw.detail` is an Error, parses that instead.\n * - For esbuild messages without location info, returns a minimal parsed stack.\n * - For esbuild messages with location, creates a single-frame stack from the location data.\n *\n * @example\n * ```ts\n * const error = new Error(\"Something went wrong\");\n * const parsed = getErrorStack(error);\n * console.log(parsed.stack); // Array of stack frames\n * ```\n *\n * @see parseErrorStack\n * @see ParsedStackTraceInterface\n *\n * @since 2.0.0\n */\n\nexport function getErrorStack(raw: Partial<PartialMessage> | Error): ParsedStackTraceInterface {\n if (raw instanceof Error) return parseErrorStack(raw);\n if (raw.detail instanceof Error) return parseErrorStack(raw.detail);\n\n if (!raw.location) {\n return { stack: [], name: 'esBuildMessage', message: raw.text ?? '', rawStack: '' };\n }\n\n return {\n name: 'esBuildMessage',\n message: raw.text ?? '',\n rawStack: '',\n stack: [\n {\n source: `@${ raw.location.file }`,\n line: raw.location.line,\n column: raw.location.column,\n fileName: raw.location.file,\n eval: false,\n async: false,\n native: false,\n constructor: false\n }\n ]\n };\n}\n\n/**\n * Retrieves a source service for a given stack frame, either from source maps or file snapshots.\n *\n * @param frame - The stack frame containing file information\n * @returns A {@link SourceService} if the source can be resolved, otherwise null\n *\n * @remarks\n * - First attempts to retrieve a mapped source using {@link FrameworkService.getSourceMap}.\n * - Falls back to file snapshots via {@link FilesModel.getSnapshot} if no source map exists.\n * - Creates a minimal {@link SourceService} implementation for snapshot-based sources.\n * - Returns null if neither a source map nor snapshot is available.\n * - The created service implements `getPositionWithCode` to extract code snippets with context lines.\n *\n * @example\n * ```ts\n * const source = getSource.call(context, frame);\n * if (source) {\n * const position = source.getPositionWithCode(10, 5, Bias.LOWER_BOUND);\n * }\n * ```\n *\n * @see SourceService\n * @see StackFrameInterface\n * @see StackContextInterface\n * @see FilesModel.getSnapshot\n * @see FrameworkService.getSourceMap\n *\n * @since 2.0.0\n */\n\nexport function getSource(this: StackContextInterface, frame: StackFrameInterface): SourceService | null {\n const fileName = frame.fileName ?? '';\n const mapped = this.framework.getSourceMap(fileName);\n if (mapped) return mapped;\n\n const snapshot = this.files.getOrTouchFile(fileName);\n const code = snapshot?.contentSnapshot?.text;\n\n if (!snapshot || !code) return null;\n const lines = code.split('\\n');\n\n return {\n getPositionWithCode: (line, column, _bias, options) => {\n const before = options?.linesBefore ?? 3;\n const after = options?.linesAfter ?? 3;\n\n const startLine = Math.max(line - before, 0);\n const endLine = Math.min(line + after, lines.length);\n\n return {\n line,\n column: column + 1,\n code: lines.slice(startLine, endLine).join('\\n'),\n source: fileName,\n name: null,\n startLine,\n endLine,\n sourceRoot: null,\n sourceIndex: -1,\n generatedLine: -1,\n generatedColumn: -1\n };\n }\n } as SourceService;\n}\n\n\n/**\n * Highlights code at a specific position with syntax coloring.\n *\n * @param position - The position object containing the code to highlight\n * @returns The code string with applied syntax highlighting and formatting\n *\n * @remarks\n * - Uses {@link highlightCode} to apply syntax highlighting to the `position.code`.\n * - Wraps the highlighted code with {@link formatErrorCode} for additional formatting.\n * - Default highlight color is {@link xterm.brightPink}.\n *\n * @example\n * ```ts\n * const highlighted = highlightPositionCode({ code: 'const x = 1;', line: 1, column: 0 });\n * console.log(highlighted); // Outputs syntax-highlighted code string\n * ```\n *\n * @see highlightCode\n * @see formatErrorCode\n * @see xterm.brightPink\n *\n * @since 2.0.0\n */\n\nexport function highlightPositionCode(position: PositionWithCodeInterface): string {\n return formatErrorCode(\n { ...position, code: highlightCode(position.code) },\n { color: xterm.brightPink }\n );\n}\n\n/**\n * Formats a stack frame into a human-readable string with colorized output.\n *\n * @param frame - The stack frame to format\n * @returns A formatted string representation of the stack frame\n *\n * @remarks\n * - Converts absolute file paths to relative paths based on {@link FrameworkService.rootPath}.\n * - Displays function name, file name, line number, and column number.\n * - Uses {@link xterm} color utilities for enhanced readability.\n * - Normalizes multiple consecutive spaces using {@link MULTIPLE_SPACES} regex.\n * - Falls back to `frame.source` if no file name is available.\n *\n * @example\n * ```ts\n * const formatted = formatStackFrame.call(context, frame);\n * console.log(formatted); // \"at myFunction src/utils.ts [10:5]\"\n * ```\n *\n * @see xterm\n * @see StackFrameInterface\n * @see StackContextInterface\n *\n * @since 2.0.0\n */\n\nexport function formatStackFrame(this: StackContextInterface, frame: StackFrameInterface): string {\n let fileName = frame.fileName;\n if (fileName?.includes(this.framework.rootPath)) {\n fileName = relative(this.framework.rootPath, fileName);\n }\n\n if (!fileName) return frame.source ?? '';\n\n const position =\n frame.line && frame.column\n ? xterm.gray(`[${ frame.line }:${ frame.column }]`)\n : '';\n\n return `at ${ frame.functionName ?? '' } ${ xterm.darkGray(fileName) } ${ position }`\n .replace(MULTIPLE_SPACES, ' ')\n .trim();\n}\n\n/**\n * Constructs a location string for a stack frame, suitable for links or display.\n *\n * @param frame - The stack frame being processed\n * @param position - The resolved source position with code\n * @returns A string representing the source location, including line number\n *\n * @remarks\n * - Handles HTTP/HTTPS URLs by appending `#L` line number format.\n * - Searches for embedded HTTP/HTTPS URLs within the source path.\n * - Prepends the source root if available and normalizes path separators.\n * - Appends the line number using `#L` format for all location strings.\n * - Falls back to the frame's fileName if no source is provided, stripping `file://` prefixes.\n *\n * @example\n * ```ts\n * const location = getSourceLocation.call(context, frame, position);\n * console.log(location); // \"src/utils/file.js#L12\"\n * ```\n *\n * @see URL_PATTERN\n * @see FILE_PROTOCOL\n * @see StackFrameInterface\n * @see PositionWithCodeInterface\n *\n * @since 2.0.0\n */\n\nexport function getSourceLocation(this: StackContextInterface, frame: StackFrameInterface, position: Required<PositionWithCodeInterface>): string {\n const { source, sourceRoot, line } = position;\n\n if (!source) {\n return frame.fileName ? frame.fileName.replace(FILE_PROTOCOL, '') : '';\n }\n\n const httpIndex = Math.max(source.lastIndexOf('http://'), source.lastIndexOf('https://'));\n if (httpIndex > 0) return `${ source.substring(httpIndex) }#L${ line }`;\n if (URL_PATTERN.test(source)) return `${ source }#L${ line }`;\n\n if (sourceRoot) {\n const path = relative(dirname(this.framework.distPath), join(this.framework.distPath, source));\n\n return `${ sourceRoot }${ path }#L${ line }`;\n }\n\n return `${ source }#L${ line }`;\n}\n\n/**\n * Formats a stack frame with enhanced position information from source maps.\n *\n * @param frame - The original stack frame\n * @param position - The resolved source position with code context\n * @returns A formatted string representing the enhanced stack frame\n *\n * @remarks\n * - Caches the first encountered code snippet in the context for later display.\n * - Stores highlighted code in {@link StackContextInterface.formatCode} on first call.\n * - Uses {@link highlightPositionCode} to generate syntax-highlighted code snippets.\n * - Delegates to {@link formatStackFrame} with updated position and location information.\n * - Updates frame properties with mapped source location via {@link getSourceLocation}.\n *\n * @example\n * ```ts\n * const formatted = formatFrameWithPosition.call(context, frame, position);\n * console.log(formatted); // Enhanced stack frame with source-mapped location\n * ```\n *\n * @see formatStackFrame\n * @see getSourceLocation\n * @see StackFrameInterface\n * @see StackContextInterface\n * @see highlightPositionCode\n * @see PositionWithCodeInterface\n *\n * @since 2.0.0\n */\n\nexport function formatFrameWithPosition(this: StackContextInterface, frame: StackFrameInterface, position: Required<PositionWithCodeInterface>): string {\n if (!this.code) {\n this.code = position.code;\n this.source = position.source;\n this.formatCode = highlightPositionCode(position);\n }\n\n return formatStackFrame.call(this, {\n ...frame,\n line: position.line,\n column: position.column,\n functionName: position.name ?? frame.functionName,\n fileName: getSourceLocation.call(this, frame, position)\n });\n}\n\n/**\n * Processes a single stack frame and formats it for display, optionally including source map information.\n *\n * @param frame - The stack frame to process\n * @param options - Optional {@link SourceOptionsInterface} for retrieving source positions\n * @returns A formatted string representing the stack frame, or an empty string if filtered out\n *\n * @remarks\n * - Skips native frames if {@link StackContextInterface.withNativeFrames} is false.\n * - Skips frames without any location information (line, column, fileName, or functionName).\n * - Attempts to resolve source positions using {@link getSource} and {@link SourceService.getPositionWithCode}.\n * - Filters out framework files if {@link StackContextInterface.withFrameworkFrames} is false.\n * - Applies line offset adjustments if {@link StackContextInterface.lineOffset} is set.\n * - Stores the resolved line and column in the context for reference.\n * - Delegates formatting to {@link formatFrameWithPosition} or {@link formatStackFrame} based on position availability.\n *\n * @example\n * ```ts\n * const formatted = stackEntry.call(context, frame, { linesBefore: 3, linesAfter: 3 });\n * console.log(formatted);\n * ```\n *\n * @see getSource\n * @see formatStackFrame\n * @see StackContextInterface\n * @see formatFrameWithPosition\n * @see SourceService.getPositionWithCode\n *\n * @since 2.0.0\n */\n\nexport function stackEntry(this: StackContextInterface, frame: StackFrameInterface, options?: SourceOptionsInterface): string {\n if (!this.withNativeFrames && frame.native) return '';\n if (!frame.line && !frame.column && !frame.fileName && !frame.functionName) return '';\n\n const source = getSource.call(this, frame);\n if (!source) return formatStackFrame.call(this, frame);\n\n const position = source.getPositionWithCode(\n frame.line ?? 0,\n frame.column ?? 0,\n Bias.LOWER_BOUND,\n options\n );\n\n if (!position) return formatStackFrame.call(this, frame);\n if (!this.withFrameworkFrames && this.framework.isFrameworkFile(position)) return '';\n if (this.lineOffset) {\n position.line += this.lineOffset;\n position.startLine += this.lineOffset;\n position.endLine += this.lineOffset;\n }\n\n this.line = position.line;\n this.column = position.column;\n\n return formatFrameWithPosition.call(this, frame, position);\n}\n\n\n/**\n * Parses error metadata into a structured stack representation with enhanced source information.\n *\n * @param raw - Either an esbuild {@link PartialMessage} or an {@link Error} object\n * @param options - Optional {@link StackTraceInterface} configuration for controlling stack parsing\n * @param lineOffset - Optional line number offset to apply to all positions (default: 0)\n * @returns A {@link StackInterface} object containing formatted stack frames and code context\n *\n * @remarks\n * - Creates a {@link StackContextInterface} using injected services for file and framework resolution.\n * - Respects the `verbose` configuration setting to control native and framework frame visibility.\n * - Uses {@link getErrorStack} to parse the raw error into stack frames.\n * - Processes each frame via {@link stackEntry}, filtering out empty results.\n * - Returns structured metadata including formatted code, line/column positions, and stack traces.\n * - Line offsets are applied to all resolved positions for alignment with external systems.\n *\n * @example\n * ```ts\n * try {\n * throw new Error(\"Something went wrong\");\n * } catch (error) {\n * const metadata = getErrorMetadata(error, { linesBefore: 5, linesAfter: 5 });\n * console.log(metadata.stacks); // Array of formatted stack lines\n * console.log(metadata.formatCode); // Highlighted code snippet\n * }\n * ```\n *\n * @see stackEntry\n * @see getErrorStack\n * @see StackInterface\n * @see StackTraceInterface\n * @see StackContextInterface\n * @see ConfigurationService\n *\n * @since 2.0.0\n */\n\nexport function getErrorMetadata(raw: PartialMessage | Error, options?: StackTraceInterface, lineOffset: number = 0): StackInterface {\n const verbose = inject(ConfigurationService).getValue(c => c.verbose) ?? false;\n const context: StackContextInterface = {\n code: '',\n line: 0,\n column: 0,\n source: '',\n formatCode: '',\n lineOffset,\n files: inject(FilesModel),\n framework: inject(FrameworkService),\n withNativeFrames: verbose,\n withFrameworkFrames: verbose,\n ...options\n };\n\n const parsed = getErrorStack(raw);\n const stacks = parsed.stack\n .map(frame => stackEntry.call(context, frame, options))\n .filter(Boolean);\n\n return {\n stacks,\n code: context.code,\n line: context.line ?? 0,\n column: context.column ?? 0,\n source: context.source,\n formatCode: context.formatCode\n };\n}\n\n/**\n * Formats error metadata into a human-readable string with enhanced styling.\n *\n * @param metadata - The {@link StackInterface} object containing parsed stack trace information\n * @param name - The error name (e.g., \"TypeError\", \"ReferenceError\")\n * @param message - The error message describing what went wrong\n * @param notes - Optional array of esbuild {@link PartialMessage} notes to display\n * @returns A string containing the formatted error output with colorized text, code snippet, and stack trace\n *\n * @remarks\n * - Constructs a formatted error output from pre-parsed stack metadata.\n * - Displays the error name and message at the top with {@link xterm.lightCoral} highlighting.\n * - Includes any additional notes in gray text below the error message.\n * - Appends syntax-highlighted code snippet if available in metadata.\n * - Appends formatted stack trace frames with proper indentation under \"Enhanced Stack Trace\".\n * - All formatting and syntax highlighting should be pre-applied in the metadata.\n *\n * @example\n * ```ts\n * const metadata: StackInterface = {\n * code: \"const x = undefined;\\nx.toString();\",\n * line: 2,\n * column: 1,\n * source: \"/path/to/file.ts\",\n * stacks: [\"at Object.<anonymous> (/path/to/file.ts:2:1)\"],\n * formatCode: \"1 | const x = undefined;\\n2 | x.toString();\\n ^\"\n * };\n *\n * const notes = [{ text: \"Did you forget to check for null?\" }];\n * console.log(formatStack(metadata, \"TypeError\", \"Cannot read property 'toString' of undefined\", notes));\n * ```\n *\n * @see xterm\n * @see PartialMessage\n * @see StackInterface\n * @see getErrorMetadata\n *\n * @since 2.0.0\n */\n\nexport function formatStack(metadata: StackInterface, name: string, message: string, notes: PartialMessage['notes'] = []): string {\n const parts = [ `\\n${ name }: ${ xterm.lightCoral(message) }` ];\n for (const note of notes ?? []) {\n if(note.text) parts.push('\\n ' + xterm.gray(note.text));\n }\n\n if (metadata.formatCode) parts.push(`\\n\\n${ metadata.formatCode }`);\n if (metadata.stacks.length) {\n parts.push(`\\n\\nEnhanced Stack Trace:\\n ${ metadata.stacks.join('\\n ') }\\n`);\n }\n\n return parts.join('');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FileSnapshotInterface, ScriptSnapshotType } from './interfaces/files-model.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { resolve } from '@components/path.component';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { closeSync, fstatSync, openSync, readFileSync } from 'fs';\n\n/**\n * In-memory cache that maintains lightweight snapshots of file contents (as TypeScript `IScriptSnapshot`)\n * together with modification time and version counters.\n *\n * Primarily used by language servers, transpiler, and incremental build systems to avoid unnecessary\n * file system reads and snapshot recreation when files have not changed.\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class FilesModel {\n /**\n * Cache that maps original (possibly relative) paths \u2192 normalized absolute paths with forward slashes\n * @since 2.0.0\n */\n\n private readonly resolvedPathCache = new Map<string, string>();\n\n /**\n * Main storage: resolved absolute path \u2192 current file snapshot state\n * @since 2.0.0\n */\n\n private readonly snapshotsByPath = new Map<string, FileSnapshotInterface>();\n\n /**\n * Removes all cached paths and snapshots.\n * @since 2.0.0\n */\n\n clear(): void {\n this.snapshotsByPath.clear();\n this.resolvedPathCache.clear();\n }\n\n /**\n * Returns the current known snapshot state for the given file path, or `undefined`\n * if the file has never been touched/observed by this cache.\n *\n * @param path - filesystem path (relative or absolute)\n * @returns current snapshot data or `undefined` if not tracked yet\n *\n * @since 2.0.0\n */\n\n getSnapshot(path: string): FileSnapshotInterface | undefined {\n return this.snapshotsByPath.get(this.resolve(path));\n }\n\n /**\n * Returns an existing snapshot entry for the given file path, or creates/updates it if not tracked yet.\n *\n * @param path - Filesystem path (relative or absolute).\n * @returns The current snapshot entry for the file (existing or newly created).\n *\n * @remarks\n * This is a convenience method combining:\n * - {@link getSnapshot} (fast path when already tracked), and\n * - {@link touchFile} (tracks the file, reads content if needed, updates version/mtime).\n *\n * Use this when you need a snapshot entry and don't want to handle the `undefined` case.\n *\n * @see {@link touchFile}\n * @see {@link getSnapshot}\n *\n * @since 2.0.0\n */\n\n getOrTouchFile(path: string): FileSnapshotInterface {\n return this.snapshotsByPath.get(this.resolve(path)) ?? this.touchFile(path);\n }\n\n /**\n * Returns array containing all currently tracked resolved absolute paths.\n *\n * @returns list of normalized absolute paths (using forward slashes)\n *\n * @since 2.0.0\n */\n\n getTrackedFilePaths(): Array<string> {\n return [ ...this.snapshotsByPath.keys() ];\n }\n\n /**\n * Ensures the file is tracked and returns an up-to-date snapshot state.\n *\n * @param path - Filesystem path (relative or absolute)\n * @returns Shallow copy of the current (possibly just updated) snapshot entry\n *\n * @remarks\n * This method implements incremental file tracking with three possible outcomes:\n *\n * **Fast path (no changes):**\n * - mtime hasn't changed \u2192 returns existing state without I/O\n *\n * **Update path (file changed):**\n * - mtime changed or file is new \u2192 reads content and creates fresh `ScriptSnapshot`\n * - Increments version number for TypeScript language service invalidation\n *\n * **Error path (file unavailable):**\n * - File cannot be read (deleted/permission denied) \u2192 clears snapshot and bumps version\n * - Version increment only occurs if there was previous content (prevents silent no-ops)\n *\n * Always returns a shallow copy to prevent accidental mutation of internal state.\n *\n * Typically used in watch mode to notify TypeScript of file changes without full rebuilds.\n *\n * @example\n * ```ts\n * const snapshot = filesModel.touchFile('./src/index.ts');\n *\n * if (snapshot.contentSnapshot) {\n * languageServiceHost.getScriptSnapshot = () => snapshot.contentSnapshot;\n * languageServiceHost.getScriptVersion = () => String(snapshot.version);\n * }\n * ```\n *\n * @see {@link getSnapshot}\n * @see {@link FileSnapshotInterface}\n *\n * @since 2.0.0\n */\n\n touchFile(path: string): FileSnapshotInterface {\n const resolvedPath = this.resolve(path);\n const entry = this.snapshotsByPath.get(resolvedPath) ?? this.createEntry(resolvedPath);\n\n try {\n this.syncEntry(resolvedPath, entry);\n } catch {\n /**\n * Currently, the catch block only increments the version if the snapshot exists, otherwise silently ignores errors.\n * Suggestion: always increase the version if the file cannot be read, so TS will treat it as changed.\n */\n\n if(entry.contentSnapshot !== undefined || entry.version > 0) {\n entry.version++;\n entry.mtimeMs = 0;\n entry.contentSnapshot = undefined;\n }\n }\n\n return { ...entry };\n }\n\n /**\n * Normalizes the given path to an absolute path using forward slashes.\n * Results are cached to avoid repeated `path.resolve` + replace calls.\n *\n * @param path - any filesystem path\n * @returns normalized absolute path (always `/` separators)\n *\n * @since 2.0.0\n */\n\n resolve(path: string): string {\n const cached = this.resolvedPathCache.get(path);\n if (cached) return cached;\n\n const resolved = resolve(path);\n this.resolvedPathCache.set(path, resolved);\n\n return resolved;\n }\n\n /**\n * Creates a new snapshot entry for a resolved file path and registers it in the cache.\n *\n * @param resolvedPath - Normalized absolute file path\n * @returns A new {@link FileSnapshotInterface} with initial state (version 0, no content)\n *\n * @remarks\n * This method initializes a new file tracking entry with default values:\n * - `version`: 0 (will increment on first read)\n * - `mtimeMs`: 0 (will update on first sync)\n * - `contentSnapshot`: undefined (will populate on first sync)\n *\n * The entry is immediately added to {@link snapshotsByPath} to prevent duplicate creation.\n *\n * Called internally by {@link touchFile} when encountering a previously unseen file path.\n *\n * @since 2.1.5\n */\n\n private createEntry(resolvedPath: string): FileSnapshotInterface {\n const entry: FileSnapshotInterface = { version: 0, mtimeMs: 0, contentSnapshot: undefined };\n this.snapshotsByPath.set(resolvedPath, entry);\n\n return entry;\n }\n\n /**\n * Synchronizes a snapshot entry with the current file system state.\n *\n * @param resolvedPath - Normalized absolute path to the file\n * @param entry - The snapshot entry to update\n *\n * @remarks\n * This method performs efficient incremental updates:\n *\n * **Optimization check:**\n * - Compares current mtime with cached mtime\n * - Returns immediately if file hasn't changed (fast path)\n *\n * **Update logic:**\n * - Reads file content only when mtime differs\n * - Increments version for TypeScript invalidation\n * - Updates mtime to current value\n * - Creates TypeScript `ScriptSnapshot` from content\n *\n * **File descriptor handling:**\n * - Opens file in read mode (`'r'`)\n * - Ensures file descriptor closure via `finally` block\n * - Throws on read errors (handled by caller)\n *\n * Empty file content results in `undefined` snapshot rather than empty snapshot,\n * signaling that the file has no compilable content.\n *\n * @throws Will propagate file system errors (ENOENT, EACCES, etc.) to caller\n *\n * @since 2.1.5\n */\n\n private syncEntry(resolvedPath: string, entry: FileSnapshotInterface): void {\n const fd = openSync(resolvedPath, 'r');\n\n try {\n const { mtimeMs } = fstatSync(fd);\n if (mtimeMs === entry.mtimeMs) return;\n const content = readFileSync(fd, 'utf-8');\n\n entry.version++;\n entry.mtimeMs = mtimeMs;\n entry.contentSnapshot = content\n ? <ScriptSnapshotType> ts.ScriptSnapshot.fromString(content)\n : undefined;\n } finally {\n closeSync(fd);\n }\n }\n}\n", "/**\n * Import\n */\n\nimport * as path from 'path';\nimport * as pathPosix from 'path/posix';\n\n/**\n * Regular expression to match backslashes in file paths.\n *\n * @remarks\n * Used by {@link toPosix} to convert Windows-style backslash path separators\n * to POSIX-style forward slashes for cross-platform path normalization.\n *\n * Matches: `\\`\n *\n * @since 2.0.0\n */\n\nconst BACKSLASH_RE = /\\\\/g;\n\n/**\n * Regular expression to match consecutive forward slashes in file paths.\n *\n * @remarks\n * Used by {@link toPosix} to normalize paths by collapsing multiple consecutive\n * forward slashes into a single slash. This ensures consistent path formatting\n * across different platforms and input sources.\n *\n * Matches: Two or more forward slashes (`//`, `///`, etc.)\n *\n * @since 2.0.0\n */\n\nconst DUPLICATE_SLASH_RE = /\\/+/g;\n\n/**\n * Converts a file path to POSIX format by normalizing backslashes and duplicate slashes.\n *\n * @param input - The file path to convert (can be null or undefined)\n *\n * @returns The path in POSIX format with forward slashes, or an empty string if input is falsy\n *\n * @remarks\n * This function performs the following transformations:\n * 1. Converts all backslashes (`\\`) to forward slashes (`/`)\n * 2. Collapses consecutive forward slashes into a single slash\n * 3. Returns an empty string for null, undefined, or empty input\n *\n * This is useful for normalizing Windows-style paths to POSIX-style paths for\n * cross-platform compatibility in build tools and file processing.\n *\n * @example Converting Windows path\n * ```ts\n * const windowsPath = 'C:\\\\Users\\\\Documents\\\\file.txt';\n * const posixPath = toPosix(windowsPath);\n * // 'C:/Users/Documents/file.txt'\n * ```\n *\n * @example Normalizing duplicate slashes\n * ```ts\n * const messyPath = 'src//components///Button.tsx';\n * const cleanPath = toPosix(messyPath);\n * // 'src/components/Button.tsx'\n * ```\n *\n * @example Handling falsy values\n * ```ts\n * toPosix(null); // ''\n * toPosix(undefined); // ''\n * toPosix(''); // ''\n * ```\n *\n * @since 2.0.0\n */\n\nexport function toPosix(input: string | null | undefined): string {\n if (!input) return '';\n\n let p = String(input);\n p = p.replace(BACKSLASH_RE, '/');\n p = p.replace(DUPLICATE_SLASH_RE, '/');\n\n return p;\n}\n\n/**\n * Normalizes a file path to POSIX format and resolves `.` and `..` segments.\n *\n * @param path - The file path to normalize\n *\n * @returns The normalized POSIX path with resolved relative segments\n *\n * @remarks\n * This function:\n * 1. Converts the path to POSIX format using {@link toPosix}\n * 2. Applies `path.posix.normalize()` to resolve `.` and `..` segments\n * 3. Removes trailing slashes (except for root `/`)\n *\n * @example Resolving relative segments\n * ```ts\n * const path = 'src/components/../utils/./helper.ts';\n * const normalized = normalize(path);\n * // 'src/utils/helper.ts'\n * ```\n *\n * @example Normalizing Windows path\n * ```ts\n * const windowsPath = 'C:\\\\Users\\\\..\\\\Documents\\\\file.txt';\n * const normalized = normalize(windowsPath);\n * // 'C:/Documents/file.txt'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function normalize(path: string): string {\n return pathPosix.normalize(toPosix(path));\n}\n\n/**\n * Joins multiple path segments into a single POSIX path.\n *\n * @param paths - Path segments to join\n *\n * @returns The joined path in POSIX format with normalized separators\n *\n * @remarks\n * This function:\n * 1. Converts each path segment to POSIX format using {@link toPosix}\n * 2. Joins them using `path.posix.join()`\n * 3. Normalizes the result (resolves `.` and `..`, removes duplicate slashes)\n *\n * @example Joining path segments\n * ```ts\n * const fullPath = join('src', 'components', 'Button.tsx');\n * // 'src/components/Button.tsx'\n * ```\n *\n * @example Joining mixed-format paths\n * ```ts\n * const fullPath = join('C:\\\\Users', 'Documents', '../Pictures/photo.jpg');\n * // 'C:/Users/Pictures/photo.jpg'\n * ```\n *\n * @example Joining with empty segments\n * ```ts\n * const fullPath = join('src', '', 'utils');\n * // 'src/utils'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function join(...paths: Array<string>): string {\n return pathPosix.join(...paths.map(toPosix));\n}\n\n/**\n * Resolves a sequence of paths into an absolute POSIX path.\n *\n * @param paths - Path segments to resolve (processed right-to-left until an absolute path is found)\n *\n * @returns The resolved absolute path in POSIX format\n *\n * @remarks\n * This function:\n * 1. Uses Node.js `path.resolve()` to compute the absolute path\n * 2. Converts the result to POSIX format using {@link toPosix}\n * 3. Processes paths right-to-left, stopping at the first absolute path\n *\n * The resolution process:\n * - If no absolute path is found, prepends the current working directory\n * - Relative segments (`.` and `..`) are resolved\n * - The result is always an absolute path\n *\n * @example Resolving relative paths\n * ```ts\n * // Current directory: /home/user/project\n * const absolutePath = resolve('src', 'components', 'Button.tsx');\n * // '/home/user/project/src/components/Button.tsx'\n * ```\n *\n * @example Resolving with an absolute path\n * ```ts\n * const absolutePath = resolve('/var/www', 'html', 'index.html');\n * // '/var/www/html/index.html'\n * ```\n *\n * @example Resolving on Windows\n * ```ts\n * // Current directory: C:\\Users\\project\n * const absolutePath = resolve('src\\\\utils', '../components/Button.tsx');\n * // 'C:/Users/project/src/components/Button.tsx'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function resolve(...paths: Array<string>): string {\n return toPosix(path.resolve(...paths));\n}\n\n/**\n * Returns the directory name of a path in POSIX format.\n *\n * @param p - The file path\n *\n * @returns The directory portion of the path, or `.` for paths without a directory component\n *\n * @remarks\n * This function:\n * 1. Converts the path to POSIX format using {@link toPosix}\n * 2. Extracts the directory portion using `path.posix.dirname()`\n * 3. Removes the last segment (file or final directory name)\n *\n * @example Getting directory name\n * ```ts\n * const dir = dirname('/home/user/file.txt');\n * // '/home/user'\n * ```\n *\n * @example Windows path\n * ```ts\n * const dir = dirname('C:\\\\Users\\\\Documents\\\\file.txt');\n * // 'C:/Users/Documents'\n * ```\n *\n * @example Path without directory\n * ```ts\n * const dir = dirname('file.txt');\n * // '.'\n * ```\n *\n * @example Root path\n * ```ts\n * const dir = dirname('/file.txt');\n * // '/'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function dirname(p: string): string {\n return toPosix(path.dirname(p));\n}\n\n/**\n * Calculates the relative path from one location to another in POSIX format.\n *\n * @param from - The source path (starting point)\n * @param to - The destination path (target)\n *\n * @returns The relative path from `from` to `to`, or `.` if paths are identical\n *\n * @remarks\n * This function:\n * 1. Converts both paths to POSIX format using {@link toPosix}\n * 2. Computes the relative path using `path.posix.relative()`\n * 3. Returns `.` when the result is empty (indicating the same location)\n *\n * The relative path uses `..` to navigate up directories and includes only\n * the necessary segments to reach the destination from the source.\n *\n * @example Basic relative path\n * ```ts\n * const rel = relative('/home/user/project', '/home/user/docs/file.txt');\n * // '../docs/file.txt'\n * ```\n *\n * @example Same directory\n * ```ts\n * const rel = relative('/home/user', '/home/user');\n * // '.'\n * ```\n *\n * @example Windows paths\n * ```ts\n * const rel = relative('C:\\\\Users\\\\project\\\\src', 'C:\\\\Users\\\\project\\\\dist\\\\bundle.js');\n * // '../dist/bundle.js'\n * ```\n *\n * @example Sibling directories\n * ```ts\n * const rel = relative('/app/src/components', '/app/src/utils');\n * // '../utils'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function relative(from: string, to: string): string {\n return pathPosix.relative(toPosix(from), toPosix(to)) || '.';\n}\n\n/**\n * Returns the last portion of a path (filename or directory name) in POSIX format.\n *\n * @param p - The file path\n * @param suffix - Optional file extension to remove from the result\n *\n * @returns The base name of the path, optionally with the suffix removed\n *\n * @remarks\n * This function:\n * 1. Converts the path to POSIX format using {@link toPosix}\n * 2. Extracts the final segment using `path.posix.basename()`\n * 3. Optionally removes the specified suffix if it matches the end of the basename\n *\n * The suffix parameter is useful for extracting filenames without extensions.\n *\n * @example Getting filename\n * ```ts\n * const name = basename('/home/user/documents/report.pdf');\n * // 'report.pdf'\n * ```\n *\n * @example Removing extension\n * ```ts\n * const name = basename('/home/user/documents/report.pdf', '.pdf');\n * // 'report'\n * ```\n *\n * @example Windows path\n * ```ts\n * const name = basename('C:\\\\Users\\\\Documents\\\\file.txt');\n * // 'file.txt'\n * ```\n *\n * @example Directory name\n * ```ts\n * const name = basename('/home/user/documents/');\n * // 'documents'\n * ```\n *\n * @example Suffix doesn't match\n * ```ts\n * const name = basename('file.txt', '.md');\n * // 'file.txt'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function basename(p: string, suffix?: string): string {\n return toPosix(path.basename(p, suffix));\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PositionInterface } from '@remotex-labs/xmap';\n\n/**\n * Imports\n */\n\nimport { readFileSync } from 'fs';\nimport { SourceService } from '@remotex-labs/xmap';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { resolve, toPosix } from '@components/path.component';\n\n/**\n * Provides access to the framework's file paths and associated source maps.\n *\n * @remarks\n * This service manages the framework's source map files, including the main framework\n * file and any additional source files. It caches initialized {@link SourceService}\n * instances for performance.\n *\n * @example\n * ```ts\n * const frameworkService = new FrameworkService();\n * console.log(frameworkService.rootPath);\n * const sourceMap = frameworkService.sourceMap(frameworkService.filePath);\n * ```\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class FrameworkService {\n /**\n * Absolute path to the current file.\n *\n * @readonly\n * @since 2.0.0\n */\n\n readonly filePath: string;\n\n /**\n * Absolute path to the distribution directory.\n *\n * @readonly\n * @since 2.0.0\n */\n\n readonly distPath: string;\n\n /**\n * Absolute path to the project root directory.\n *\n * @readonly\n * @since 2.0.0\n */\n\n readonly rootPath: string;\n\n /**\n * Cached {@link SourceService} instances for additional source files.\n * @since 2.0.0\n */\n\n private readonly sourceMaps = new Map<string, SourceService>();\n\n /**\n * Initializes a new {@link FrameworkService} instance.\n *\n * @remarks\n * Sets up the main framework source map, as well as root and distribution paths.\n *\n * @since 2.0.0\n */\n\n constructor() {\n this.filePath = import.meta.filename;\n this.setSourceFile(this.filePath);\n\n this.rootPath = this.getRootDir();\n this.distPath = this.getDistDir();\n }\n\n /**\n * Determines whether a given {@link PositionInterface} refers to a framework file.\n *\n * @param position - The position information to check\n * @returns `true` if the position is from the framework (contains \"xJet\"), otherwise `false`\n *\n * @see PositionInterface\n * @since 1.0.0\n */\n\n isFrameworkFile(position: PositionInterface): boolean {\n const { source, sourceRoot } = position;\n const lowerCaseSource = source?.toLowerCase();\n\n return Boolean(\n (source && lowerCaseSource.includes('xbuild') && !lowerCaseSource.includes('xbuild.config')) ||\n (sourceRoot && sourceRoot.includes('xBuild'))\n );\n }\n\n /**\n * Retrieves a cached {@link SourceService} for a given file path.\n *\n * @param path - Absolute path to the file\n * @returns A {@link SourceService} instance if found, otherwise `undefined`\n *\n * @remarks\n * Paths are normalized before lookup. Only previously initialized source maps\n * (via {@link setSource} or {@link setSourceFile}) are available in the cache.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n getSourceMap(path: string): SourceService | undefined {\n path = resolve(path);\n if (this.sourceMaps.has(path))\n return this.sourceMaps.get(path)!;\n\n return undefined;\n }\n\n /**\n * Registers and initializes a new {@link SourceService} for a provided source map string.\n *\n * @param source - The raw source map content\n * @param path - Absolute file path associated with the source map\n * @returns A new or cached {@link SourceService} instance\n *\n * @throws Error if initialization fails\n *\n * @remarks\n * If a source map for the given path is already cached, the cached instance is returned.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n setSource(source: string, path: string): void {\n const key = resolve(path);\n\n try {\n return this.initializeSourceMap(source, key);\n } catch (error) {\n throw new Error(\n `Failed to initialize SourceService: ${ key }\\n${ error instanceof Error ? error.message : String(error) }`\n );\n }\n }\n\n /**\n * Loads and initializes a {@link SourceService} for a file and its `.map` companion.\n *\n * @param path - Absolute path to the file\n * @returns A new or cached {@link SourceService} instance\n *\n * @throws Error if the `.map` file cannot be read or parsed\n *\n * @remarks\n * This method attempts to read the `.map` file located next to the provided file.\n * If already cached, returns the existing {@link SourceService}.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n setSourceFile(path: string): void {\n if(!path) return;\n\n const key = resolve(path);\n const map = `${ path }.map`;\n\n if (this.sourceMaps.has(key))\n return;\n\n try {\n const sourceMapData = readFileSync(map, 'utf-8');\n\n return this.initializeSourceMap(sourceMapData, key);\n } catch (error) {\n throw new Error(\n `Failed to initialize SourceService: ${ key }\\n${ error instanceof Error ? error.message : String(error) }`\n );\n }\n }\n\n /**\n * Retrieves the project root directory.\n * @returns Absolute path to the project root\n *\n * @since 2.0.0\n */\n\n private getRootDir(): string {\n return toPosix(process.cwd());\n }\n\n /**\n * Retrieves the distribution directory.\n * @returns Absolute path to the distribution folder\n *\n * @since 2.0.0\n */\n\n private getDistDir(): string {\n return toPosix(import.meta.dirname);\n }\n\n /**\n * Creates and caches a new {@link SourceService} instance for a given source map.\n *\n * @param source - Raw source map content\n * @param path - Normalized file path used as the cache key\n * @returns The newly created {@link SourceService} instance\n *\n * @remarks\n * This method is only used internally by {@link setSource} and {@link setSourceFile}.\n * The instance is cached in {@link sourceMaps} for reuse.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n private initializeSourceMap(source: string, path: string): void {\n if(source?.includes('\"mappings\": \"\"'))\n return;\n\n const sourceMap = new SourceService(source, path);\n this.sourceMaps.set(path, sourceMap);\n }\n}\n", "/**\n * Imports\n */\n\nimport { Observable } from '@observable/observable.module';\n\n/**\n * Transforms each emitted value using the provided transformation function.\n *\n * @template T - The input value type.\n * @template R - The output value type after transformation.\n *\n * @param project - Function that transforms each input value to an output value.\n * @returns An operator function that creates a new observable with transformed values.\n *\n * @throws Error - If the project function throws, the error is caught and emitted to the observer.\n *\n * @remarks\n * The `map` operator applies a transformation function to every value emitted by the source\n * observable and emits the transformed values. Errors thrown by the project function are\n * automatically caught and passed to the observer's error handler.\n *\n * Common use cases:\n * - Converting data formats (string to number, object property extraction)\n * - Mathematical transformations (doubling, negation)\n * - Type conversions and casting\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>((observer) => {\n * observer.next?.(5);\n * observer.next?.(10);\n * });\n *\n * const doubled = numbers.pipe(map((x) => x * 2));\n *\n * doubled.subscribe((value) => console.log(value)); // Outputs: 10, 20\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function map<T, R>(project: (value: T) => R) {\n return (source: Observable<T>): Observable<R> => {\n return new Observable<R>((observer) => {\n return source.subscribe({\n next: (value) => {\n try {\n const result = project(value);\n observer.next?.(result);\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n\n/**\n * Emits only values that are different from the previously emitted value.\n *\n * @template T - The type of values being compared.\n *\n * @param compareFn - Optional comparison function to determine equality. Defaults to strict equality (`===`).\n * @returns An operator function that creates a new observable with only distinct consecutive values.\n *\n * @remarks\n * The `distinctUntilChanged` operator filters out consecutive duplicate values using the provided\n * comparison function. Only values that differ from the last emitted value are passed through.\n * This is particularly useful for reducing redundant emissions when state changes are minimal.\n *\n * The comparison function receives the previous and current values and should return `true`\n * if they are considered equal (and thus should be filtered), or `false` if they are different\n * (and thus should be emitted).\n *\n * Errors thrown by the comparison function are caught and emitted to the observer's error handler.\n *\n * Common use cases:\n * - Avoiding redundant updates (e.g., state management)\n * - Filtering out echoed or repeated sensor data\n * - Preventing unnecessary re-renders in UI frameworks\n *\n * @example\n * ```ts\n * const values = new Observable<number>((observer) => {\n * observer.next?.(1);\n * observer.next?.(1);\n * observer.next?.(2);\n * observer.next?.(2);\n * observer.next?.(3);\n * });\n *\n * const distinct = values.pipe(distinctUntilChanged());\n *\n * distinct.subscribe((value) => console.log(value)); // Outputs: 1, 2, 3\n * ```\n *\n * @example\n * ```ts\n * // Custom comparison for objects\n * interface User { id: number; name: string; }\n *\n * const users = new Observable<User>((observer) => {\n * observer.next?.({ id: 1, name: 'Alice' });\n * observer.next?.({ id: 1, name: 'Alice' });\n * observer.next?.({ id: 2, name: 'Bob' });\n * });\n *\n * const distinctUsers = users.pipe(\n * distinctUntilChanged((prev, curr) => prev.id === curr.id)\n * );\n *\n * distinctUsers.subscribe((user) => console.log(user.name));\n * // Outputs: \"Alice\", \"Bob\"\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function distinctUntilChanged<T>(\n compareFn: (previous: T, current: T) => boolean = (a, b) => a === b\n) {\n return (source: Observable<T>): Observable<T> => {\n return new Observable<T>((observer) => {\n let hasPrevious = false;\n let previous: T;\n\n return source.subscribe({\n next: (value) => {\n try {\n if(!hasPrevious) {\n previous = value;\n hasPrevious = true;\n observer.next?.(value);\n\n return;\n }\n\n if (!compareFn(previous, value)) {\n previous = value;\n observer.next?.(value);\n }\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n\n/**\n * Filters emitted values based on a predicate function.\n *\n * @template T - The type of values being filtered.\n *\n * @param predicate - Function that returns `true` if the value should pass through, `false` otherwise.\n * @returns An operator function that creates a new observable with only filtered values.\n *\n * @remarks\n * The `filter` operator only emits values that satisfy the predicate condition. Values that\n * do not match the condition are silently skipped. All other events (error, complete) are\n * passed through unchanged.\n *\n * Errors thrown by the predicate function are caught and passed to the observer's error handler.\n *\n * Common use cases:\n * - Filtering by value range (e.g., only positive numbers)\n * - Filtering by type or property (e.g., only objects with specific properties)\n * - Conditional emission based on complex logic\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>((observer) => {\n * observer.next?.(1);\n * observer.next?.(2);\n * observer.next?.(3);\n * observer.next?.(4);\n * observer.next?.(5);\n * });\n *\n * const evens = numbers.pipe(filter((x) => x % 2 === 0));\n *\n * evens.subscribe((value) => console.log(value)); // Outputs: 2, 4\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function filter<T>(predicate: (value: T) => boolean) {\n return (source: Observable<T>): Observable<T> => {\n return new Observable<T>((observer) => {\n return source.subscribe({\n next: (value) => {\n try {\n if (predicate(value)) {\n observer.next?.(value);\n }\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n\n/**\n * Performs a side effect for each emitted value without modifying the value.\n *\n * @template T - The type of values being processed.\n *\n * @param sideEffect - Function to execute for each emitted value. The return value is ignored.\n * @returns An operator function that creates a new observable with the side effect applied.\n *\n * @remarks\n * The `tap` operator is used for debugging, logging, or triggering side effects without\n * altering the data flow. The provided function is called for each emitted value, and the\n * original value is passed through unchanged to the resulting observable.\n *\n * Errors thrown by the side effect function are caught and passed to the observer's error handler.\n * The original value is NOT emitted if the side effect throws an error.\n *\n * Common use cases:\n * - Logging values for debugging\n * - Triggering analytics or tracking events\n * - Updating external state or UI without changing the stream\n * - Performance monitoring\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>((observer) => {\n * observer.next?.(5);\n * observer.next?.(10);\n * });\n *\n * const logged = numbers.pipe(\n * tap((x) => console.log(`Processing: ${x}`))\n * );\n *\n * logged.subscribe((value) => console.log(`Received: ${value}`));\n * // Outputs:\n * // Processing: 5\n * // Received: 5\n * // Processing: 10\n * // Received: 10\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function tap<T>(sideEffect: (value: T) => void) {\n return (source: Observable<T>): Observable<T> => {\n return new Observable<T>((observer) => {\n return source.subscribe({\n next: (value) => {\n try {\n sideEffect(value);\n observer.next?.(value);\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ObserverInterface, UnsubscribeType } from '@observable/observable.module';\nimport type { NextType, ErrorType, CompleteType, OperatorFunctionType } from '@observable/observable.module';\n\n/**\n * Represents a push-based collection of values that can be observed over time\n *\n * This is the core type of lightweight observable implementation.\n * It allows subscription, safe error handling and operator chaining via pipe.\n *\n * @template T - Type of values emitted by this observable\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>(observer => {\n * [1, 2, 3].forEach(v => observer.next?.(v));\n * observer.complete?.();\n * return () => console.log('cleaned up');\n * });\n *\n * const sub = numbers.subscribe({\n * next: v => console.log(v),\n * complete: () => console.log('done')\n * });\n *\n * sub(); // triggers cleanup\n * ```\n *\n * @see {@link pipe}\n * @see {@link ObserverInterface}\n * @see {@link OperatorFunctionType}\n *\n * @since 2.0.0\n */\n\nexport class ObservableService<T = unknown> {\n /**\n * Creates a new observable service with a subscription handler.\n *\n * @param handler - Function called when someone subscribes.\n * It receives an observer and returns an optional cleanup function.\n *\n * @remarks\n * The handler function is called immediately when {@link subscribe} is invoked.\n * It receives the observer object and is responsible for:\n * - Calling `observer.next()` to emit values\n * - Calling `observer.error()` to emit errors\n * - Calling `observer.complete()` to signal completion\n * - Returning an optional cleanup function for resource management\n *\n * This design pattern allows for lazy initialization, external event binding and\n * fine-grained control over subscription lifecycle.\n *\n * @example\n * ```ts\n * const timerObservable = new ObservableService<number>((observer) => {\n * let count = 0;\n * const intervalId = setInterval(() => {\n * observer.next?.(count++);\n * }, 1000);\n *\n * // Return cleanup function\n * return () => clearInterval(intervalId);\n * });\n * ```\n *\n * @see ObserverInterface\n * @since 2.0.0\n */\n\n constructor(\n private readonly handler: (observer: ObserverInterface<T>) => UnsubscribeType | void\n ) {}\n\n /**\n * Subscribes to this observable and receives values, errors and completion\n *\n * @param observerOrNext - Either a full observer object or just the next handler\n * @param error - Optional error handler\n * @param complete - Optional completion handler\n * @returns Unsubscribe function \u2014 call it to stop receiving values and clean up\n *\n * @remarks\n * Supports three overload styles:\n * 1. Single observer object\n * 2. Separate next/error/complete callbacks\n * 3. Only the next callback (error and complete are optional)\n *\n * @example\n * ```ts\n * // Object style\n * subscription = source.subscribe({\n * next: v => console.log(v),\n * error: e => console.error(e),\n * complete: () => console.log('completed')\n * });\n *\n * // Callback style\n * subscription = source.subscribe(\n * v => console.log(v),\n * e => console.error(e),\n * () => console.log('completed')\n * );\n * ```\n *\n * @since 2.0.0\n */\n\n subscribe(\n observerOrNext?: ObserverInterface<T> | NextType<T>,\n error?: ErrorType,\n complete?: CompleteType\n ): UnsubscribeType {\n const observer = this.createSafeObserver(observerOrNext, error, complete);\n let cleanup: UnsubscribeType | void;\n\n try {\n cleanup = this.handler(observer);\n } catch (err) {\n observer.error?.(err);\n\n return () => {};\n }\n\n return () => {\n try {\n cleanup?.();\n } catch (err) {\n observer.error?.(err);\n }\n };\n }\n\n /**\n * Chains zero or more operators to transform this observable\n *\n * When called without arguments returns the same observable (identity).\n * Each operator receives the previous observable and returns a new one.\n *\n * @remarks\n * Type signatures are overloaded up to 5 explicit operators for best type inference.\n * After that, a rest version is used with weaker type information (the result is `Observable<T>`).\n *\n * @returns New observable (or same when no operators given)\n *\n * @since 2.0.0\n */\n\n pipe(): this;\n\n /**\n * Chains one observable operator to transform the observable.\n *\n * @template A - The output type of the first operator.\n *\n * @param op1 - First operator function to apply.\n * @returns An observable transformed by the operator.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A>(\n op1: OperatorFunctionType<T, A>\n ): ObservableService<A>;\n\n /**\n * Chains two observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @returns An observable transformed by both operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B>(\n op1: OperatorFunctionType<T, A>, op2: OperatorFunctionType<A, B>\n ): ObservableService<B>;\n\n /**\n * Chains three observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @returns An observable transformed by all three operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>\n ): ObservableService<C>;\n\n /**\n * Chains four observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n * @template D - The output type of the fourth operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @param op4 - Fourth operator function to apply.\n * @returns An observable transformed by all four operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C, D>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>,\n op4: OperatorFunctionType<C, D>\n ): ObservableService<D>;\n\n /**\n * Chains five observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n * @template D - The output type of the fourth operator.\n * @template E - The output type of the fifth operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @param op4 - Fourth operator function to apply.\n * @param op5 - Fifth operator function to apply.\n * @returns An observable transformed by all five operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C, D, E>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>,\n op4: OperatorFunctionType<C, D>,\n op5: OperatorFunctionType<D, E>\n ): ObservableService<E>;\n\n /**\n * Chains five or more observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n * @template D - The output type of the fourth operator.\n * @template E - The output type of the fifth operator.\n * @template Ops - Tuple type of additional operator functions beyond the first five.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @param op4 - Fourth operator function to apply.\n * @param op5 - Fifth operator function to apply.\n * @param operations - Additional operator functions to apply sequentially.\n * @returns An observable transformed by all operators in sequence with the output type inferred from the final operator.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C, D, E, Ops extends Array<OperatorFunctionType>>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>,\n op4: OperatorFunctionType<C, D>,\n op5: OperatorFunctionType<D, E>,\n ...operations: Ops\n ): ObservableService<\n Ops extends [...Array<unknown>, OperatorFunctionType<unknown, infer R>] ? R : T\n >;\n\n /**\n * Internal implementation of the pipe operator chain.\n *\n * @param operators - Array of operator functions to be reduced over the observable.\n * @returns The final transformed observable, or the original observable if no operators are provided.\n *\n * @remarks\n * This is the concrete implementation that executes the operator chain using a reducer pattern.\n * Each operator receives the current observable and returns a transformed observable, which becomes\n * the input for the next operator. The chain begins with the current observable instance.\n *\n * If the operator array is empty, the method returns the current observable unchanged, allowing\n * for safe calling of `pipe()` without arguments.\n *\n * Operators are applied sequentially from left to right, enabling composition of multiple\n * transformations such as mapping, filtering, debouncing and other value manipulations.\n *\n * @example\n * ```ts\n * const source = new ObservableService<number>((observer) => {\n * observer.next?.(10);\n * observer.next?.(20);\n * });\n *\n * // With operators\n * const doubled = source.pipe(\n * (obs) => new ObservableService((observer) =>\n * obs.subscribe((v) => observer.next?.(v * 2))\n * )\n * );\n *\n * // Without operators\n * const same = source.pipe();\n * ```\n *\n * @see OperatorFunctionType\n * @since 2.0.0\n */\n\n pipe<R = ObservableService<T>>(...operators: Array<OperatorFunctionType>): R {\n if (operators.length === 0) {\n return this as unknown as R;\n }\n\n return <R> operators.reduce<ObservableService>(\n (prev, op) => op(prev),\n this as ObservableService\n );\n }\n\n /**\n * Converts subscribe arguments into a consistent ObserverInterface shape\n *\n * @remarks Internal helper \u2013 not meant to be called directly\n *\n * @since 2.0.0\n */\n\n protected createSafeObserver(\n observerOrNext?: ObserverInterface<T> | NextType<T>,\n error?: ErrorType,\n complete?: CompleteType\n ): ObserverInterface<T> {\n return typeof observerOrNext === 'function'\n ? { next: observerOrNext, error, complete }\n : observerOrNext || {};\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ObserverInterface } from '@observable/observable.module';\n\n/**\n * Imports\n */\n\nimport { ObservableService } from '@observable/services/observable.service';\n\n/**\n * A subject that acts as both an observable and an observer.\n *\n * @template T - The type of values emitted by the subject.\n *\n * @remarks\n * The `SubjectService` extends {@link Observable} to provide a multicast observable\n * that maintains a collection of active observers. Unlike a regular observable that executes\n * its handler once per subscription, a subject allows multiple subscribers to share the same\n * emission sequence and receive values emitted directly via {@link next}, {@link error},\n * and {@link complete} methods.\n *\n * This is particularly useful for:\n * - Event buses where multiple listeners need the same events\n * - Sharing a single data source across multiple subscribers\n * - Implementing pub-sub patterns\n *\n * When a subscriber unsubscribes, they are automatically removed from the observer's collection.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * // Multiple subscribers\n * subject.subscribe((value) => console.log('Observer 1:', value));\n * subject.subscribe((value) => console.log('Observer 2:', value));\n *\n * // Emit values to all subscribers\n * subject.next(42); // Both observers receive 42\n * subject.next(100); // Both observers receive 100\n *\n * // Complete the subject\n * subject.complete();\n * ```\n *\n * @see ObservableService\n * @see ObserverInterface\n *\n * @since 2.0.0\n */\n\nexport class SubjectService<T> extends ObservableService<T> {\n /**\n * Tracks whether the subject has completed.\n *\n * @remarks\n * Once the subject is completed, no further values or errors can be emitted,\n * and new subscribers will immediately receive the complete notification.\n *\n * @since 2.0.0\n */\n\n protected isCompleted = false;\n\n /**\n * Collection of all active observers subscribed to this subject.\n *\n * @remarks\n * This set maintains references to all current observers. When {@link next}, {@link error},\n * or {@link complete} is called, all observers in this collection are notified.\n *\n * @see ObserverInterface\n * @since 2.0.0\n */\n\n private observers = new Set<ObserverInterface<T>>();\n\n /**\n * Creates a new subject service with a shared observer management handler.\n *\n * @template T - The type of values emitted by the subject.\n *\n * @remarks\n * The subject initializes with a handler function that manages the observer's collection.\n * When a new subscriber is added via {@link subscribe}, the observer is added to the\n * collection and a cleanup function is returned that removes the observer when unsubscribed.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<string>();\n * const unsub = subject.subscribe((value) => console.log(value));\n * subject.next('hello'); // Observer receives 'hello'\n * unsub(); // Remove observer from a subject\n * ```\n *\n * @since 2.0.0\n */\n\n constructor() {\n super((observer) => {\n if (this.isCompleted) {\n observer.complete?.();\n\n return;\n }\n\n this.observers.add(observer);\n\n return (): boolean => this.observers.delete(observer);\n });\n }\n\n /**\n * Emits a new value to all active observers.\n *\n * @template T - The type of values emitted by the subject.\n *\n * @param value - The value to emit to all observers.\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `next` handler throws an error.\n *\n * @remarks\n * This method calls the `next` handler on all current observers with the provided value.\n * If an observer's next handler throws an error, it is caught and passed to that observer's\n * error handler (if provided). All errors from handlers are collected and thrown together\n * as an {@link AggregateError} after all observers have been notified.\n *\n * The observers are iterated over a snapshot of the collection to allow observers to\n * unsubscribe during emission without affecting iteration.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * subject.subscribe((value) => console.log('A:', value));\n * subject.subscribe((value) => {\n * if (value === 0) throw new Error('Zero not allowed');\n * console.log('B:', value);\n * });\n *\n * try {\n * subject.next(0); // Observer B throws, wrapped in AggregateError\n * } catch (err) {\n * if (err instanceof AggregateError) {\n * console.log(`${err.errors.length} observer(s) failed`);\n * }\n * }\n * ```\n *\n * @see AggregateError\n * @since 2.0.0\n */\n\n next(value: T): void {\n if (this.isCompleted) return;\n const errors: Array<unknown> = [];\n\n for (const o of [ ...this.observers ]) {\n try {\n o.next?.(value);\n } catch (err) {\n errors.push(err);\n try {\n o.error?.(err);\n } catch {}\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, `${ errors.length } observer(s) failed in next()`);\n }\n }\n\n /**\n * Emits an error to all active observers.\n *\n * @param err - The error to emit to all observers.\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `error` handler throws an error.\n *\n * @remarks\n * This method calls the `error` handler on all current observers with the provided error.\n * If an observer's error handler throws an error, it is caught and collected. All errors\n * from handlers are thrown together as an {@link AggregateError} after all observers\n * have been notified.\n *\n * If an observer does not provide an error handler, it is skipped without any effect.\n *\n * The observers are iterated over a snapshot of the collection to allow observers to\n * unsubscribe during emission without affecting iteration.\n *\n * After an error is emitted, the subject behaves as completed (no further emissions allowed).\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * subject.subscribe({\n * error: (err) => console.log('Observer A error:', err)\n * });\n *\n * subject.subscribe({\n * error: () => { throw new Error('Handler failed'); }\n * });\n *\n * try {\n * subject.error(new Error('Something went wrong'));\n * } catch (err) {\n * if (err instanceof AggregateError) {\n * console.log(`${err.errors.length} observer(s) failed`);\n * }\n * }\n * ```\n *\n * @see AggregateError\n * @since 2.0.0\n */\n\n error(err: unknown): void {\n if (this.isCompleted) return;\n const errors: Array<unknown> = [];\n\n for (const o of [ ...this.observers ]) {\n try {\n o.error?.(err);\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, `${ errors.length } observer(s) failed in error()`);\n }\n }\n\n /**\n * Signals completion to all observers and clears all subscriptions.\n *\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `complete` handler throws an error.\n *\n * @remarks\n * This method calls the `complete` handler on all current observers, then clears the\n * observers collection to prevent further emissions. If an observer's complete handler\n * throws an error, it is caught and collected. All errors from handlers are thrown\n * together as an {@link AggregateError} after all observers have been notified.\n *\n * If an observer does not provide a complete handler, it is skipped without any effect.\n *\n * The observers are iterated over a snapshot of the collection to allow safe completion.\n * After completion, the subject will accept no further emissions and new subscribers\n * will immediately receive the complete notification.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * subject.subscribe({\n * complete: () => console.log('Observer A completed')\n * });\n *\n * subject.subscribe({\n * complete: () => { throw new Error('Handler failed'); }\n * });\n *\n * try {\n * subject.complete();\n * } catch (err) {\n * if (err instanceof AggregateError) {\n * console.log(`${err.errors.length} observer(s) failed`);\n * }\n * }\n * ```\n *\n * @see AggregateError\n * @since 2.0.0\n */\n\n complete(): void {\n if (this.isCompleted) return;\n const errors: Array<unknown> = [];\n\n\n for (const o of [ ...this.observers ]) {\n try {\n o.complete?.();\n } catch (err) {\n errors.push(err);\n }\n }\n\n this.observers.clear();\n this.isCompleted = true;\n if (errors.length > 0) {\n throw new AggregateError(errors, `${ errors.length } observer(s) failed in complete()`);\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CompleteType, NextType, ErrorType } from '@observable/observable.module';\nimport type { ObserverInterface, UnsubscribeType } from '@observable/observable.module';\n\n/**\n * Imports\n */\n\nimport { SubjectService } from '@observable/services/subject.service';\n\n/**\n * A subject that emits the most recent value to new subscribers immediately upon subscription.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @remarks\n * The `BehaviorSubject` extends {@link Subject} to maintain and replay the\n * latest emitted value to all new subscribers. Unlike a regular subject where new subscribers\n * only receive values emitted after subscription, behavior subjects guarantee that every new\n * subscriber immediately receives the current value.\n *\n * This is particularly useful for:\n * - State management where new subscribers need the current state\n * - Configuration or preference storage\n * - Real-time data feeds where latecomers need the latest snapshot\n *\n * The behavior subject always has a value available, even before any emission occurs, using\n * the initial value provided at construction.\n *\n * @example\n * ```ts\n * const count = new BehaviorSubject<number>(0);\n * count.subscribe((value) => console.log('Observer 1:', value)); // Immediately logs: 0\n * count.next(5);\n * count.subscribe((value) => console.log('Observer 2:', value)); // Immediately logs: 5\n * ```\n *\n * @see SubjectService\n * @see ObserverInterface\n *\n * @since 2.0.0\n */\n\nexport class BehaviorSubjectService<T> extends SubjectService<T> {\n /**\n * The most recently emitted value or the initial value.\n *\n * @remarks\n * This property stores the latest value that will be replayed to new subscribers.\n * It is initialized with the value provided to the constructor and updated whenever\n * {@link next} is called.\n *\n * @since 2.0.0\n */\n\n private lastValue: T;\n\n /**\n * Creates a new behavior subject with an initial or lazily-computed value.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @param initialValue - Either an initial value or a factory function that computes it.\n *\n * @remarks\n * The behavior subject requires an initial value at construction time. This value can be\n * provided in two ways:\n *\n * 1. **Direct value**: Pass the value directly (e.g., `new BehaviorSubject(0)`)\n * 2. **Factory function**: Pass a function that returns the value (e.g., `new BehaviorSubject(() => getInitialState())`)\n *\n * Using a factory function allows for lazy initialization and computation of the initial value,\n * which is useful when the initial state depends on side effects or is expensive to compute.\n *\n * @example\n * ```ts\n * // Direct value\n * const subject1 = new BehaviorSubject<number>(42);\n *\n * // Factory function for lazy initialization\n * const subject2 = new BehaviorSubject<string>(() => {\n * return localStorage.getItem('savedState') ?? 'default';\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(initialValue: T | (() => T)) {\n super();\n this.lastValue = typeof initialValue === 'function'\n ? (initialValue as () => T)()\n : initialValue;\n }\n\n /**\n * Retrieves the current value of the behavior subject.\n *\n * @template T - The type of the value.\n *\n * @returns The most recently emitted value or the initial value.\n *\n * @remarks\n * This getter provides read-only access to the current state of the behavior subject.\n * The value is always available and represents either the last emitted value or the\n * initial value if no emissions have occurred.\n *\n * @example\n * ```ts\n * const subject = new BehaviorSubject<number>(10);\n * console.log(subject.value); // Output: 10\n *\n * subject.next(20);\n * console.log(subject.value); // Output: 20\n * ```\n *\n * @since 2.0.0\n */\n\n get value(): T {\n return this.lastValue;\n }\n\n /**\n * Subscribes to the behavior subject with immediate replay of the current value.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @param observerOrNext - Either an observer object or a callback function for the `next` event.\n * @param error - Optional error handler callback.\n * @param complete - Optional completion handler callback.\n * @returns An unsubscribe function that removes the subscription.\n *\n * @remarks\n * This override adds behavior-specific subscription logic: immediately after the observer\n * is registered with the parent {@link SubjectService}, the current value is emitted to\n * the new observer. This ensures all subscribers, even those who join late, receive the\n * most recent value.\n *\n * The subscription follows the same modes as the parent:\n * 1. **Observer mode**: Pass a full {@link ObserverInterface}\n * 2. **Callback mode**: Pass a `next` callback with optional error and complete handlers\n * 3. **Empty mode**: Pass nothing to subscribe without any handlers\n *\n * @example\n * ```ts\n * const subject = new BehaviorSubject<number>(5);\n *\n * // Observer mode\n * const unsub1 = subject.subscribe({\n * next: (value) => console.log('A:', value)\n * }); // Immediately logs: \"A: 5\"\n *\n * subject.next(10);\n *\n * // Callback mode (late subscriber)\n * const unsub2 = subject.subscribe(\n * (value) => console.log('B:', value)\n * ); // Immediately logs: \"B: 10\"\n *\n * subject.next(15); // Both log their respective updates\n * ```\n *\n * @see ObserverInterface\n * @see SubjectService.subscribe\n *\n * @since 2.0.0\n */\n\n override subscribe(\n observerOrNext?: ObserverInterface<T> | NextType<T>,\n error?: ErrorType,\n complete?: CompleteType\n ): UnsubscribeType {\n if(this.isCompleted) return () => {};\n\n const observer = this.createSafeObserver(observerOrNext, error, complete);\n const unsub = super.subscribe(observer);\n observer.next?.(this.lastValue);\n\n return unsub;\n }\n\n /**\n * Emits a new value and updates the current state.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @param value - The new value to emit to all observers.\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `next` handler throws an error.\n *\n * @remarks\n * This override extends the parent {@link SubjectService.next} method by storing the\n * emitted value as the current state before broadcasting to all observers. This ensures\n * that any new subscribers added after this emission will receive this value.\n *\n * Error handling follows the parent behavior: if an observer's next handler throws,\n * the error is passed to that observer's error handler (if provided), and all errors\n * are collected and thrown together as an {@link AggregateError}.\n *\n * @example\n * ```ts\n * const subject = new BehaviorSubject<number>(0);\n *\n * subject.subscribe((value) => console.log('Observer 1:', value));\n *\n * subject.next(42); // Updates internal state and notifies observers\n *\n * subject.subscribe((value) => console.log('Observer 2:', value));\n * // Immediately logs: \"Observer 2: 42\" (receives the updated state)\n * ```\n *\n * @see AggregateError\n * @see SubjectService.next\n *\n * @since 2.0.0\n */\n\n override next(value: T): void {\n if (this.isCompleted) return;\n\n this.lastValue = value;\n super.next(value);\n }\n}\n", "/**\n * Checks whether a value is a plain object (not null, not an array, but an object).\n *\n * @param item - The value to check\n *\n * @returns `true` if the value is a plain object, `false` otherwise\n *\n * @remarks\n * This type guard function narrows the type to `Record<string, unknown>` when it returns `true`.\n * A value is considered a plain object if it meets all criteria:\n * - Is truthy (not `null`, `undefined`, `false`, `0`, `''`, etc.)\n * - Has type `'object'`\n * - Is not an array\n *\n * This function treats class instances, dates, and other object types as plain objects since\n * they satisfy the criteria. Use more specific checks if you need to exclude these.\n *\n * @example\n * ```ts\n * isObject({}); // true\n * isObject({ key: 'value' }); // true\n * isObject(null); // false\n * isObject([]); // false\n * isObject('string'); // false\n * isObject(new Date()); // true (it's an object, not an array)\n * ```\n *\n * @see {@link deepMerge}\n *\n * @since 2.0.0\n */\n\nexport function isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === 'object' && !Array.isArray(item);\n}\n\n/**\n * Recursively merges multiple source objects into a target object with deep property merging.\n *\n * @template T - The type of the target object must extend `object`\n *\n * @param target - The target object to merge into\n * @param sources - One or more source objects to merge from\n *\n * @returns The target object with all sources merged into it\n *\n * @remarks\n * This function performs a deep merge with the following behavior:\n * - Primitive values in sources overwrite values in target\n * - Arrays are concatenated (target items first, then source items)\n * - Objects are recursively merged\n * - Sources are processed left-to-right, with later sources overwriting earlier ones\n * - The target object is mutated and returned\n *\n * Merge strategy by type:\n * - **Both arrays**: Concatenates `[...targetValue, ...sourceValue]`\n * - **Both objects**: Recursively merges properties\n * - **Source is object, target is not**: Creates a new object with source properties\n * - **Other cases**: Source value overwrites target value\n *\n * @example\n * ```ts\n * const target = { a: 1, b: { x: 10 } };\n * const source = { b: { y: 20 }, c: 3 };\n *\n * const result = deepMerge(target, source);\n * // { a: 1, b: { x: 10, y: 20 }, c: 3 }\n * ```\n *\n * @example\n * ```ts\n * // Array concatenation\n * const target = { items: [1, 2] };\n * const source = { items: [3, 4] };\n *\n * deepMerge(target, source);\n * // { items: [1, 2, 3, 4] }\n * ```\n *\n * @example\n * ```ts\n * // Multiple sources\n * const result = deepMerge(\n * { a: 1 },\n * { b: 2 },\n * { c: 3 }\n * );\n * // { a: 1, b: 2, c: 3 }\n * ```\n *\n * @see {@link isObject}\n *\n * @since 2.0.0\n */\nexport function deepMerge<T extends object>(target: T, ...sources: Array<object>): T {\n if (!sources.length) return target;\n const source = sources.shift();\n\n if (isObject(target) && isObject(source)) {\n for (const key in source) {\n const sourceValue = source[key];\n const targetValue = target[key];\n\n if (Array.isArray(sourceValue) && Array.isArray(targetValue)) {\n Object.assign(target, { [key]: [ ...targetValue, ...sourceValue ] });\n } else if (isObject(sourceValue)) {\n Object.assign(target, {\n [key]: deepMerge(\n isObject(targetValue) ? targetValue : {},\n sourceValue\n )\n });\n } else {\n Object.assign(target, { [key]: sourceValue });\n }\n }\n\n return deepMerge(target, ...sources);\n }\n\n return target;\n}\n\n/**\n * Performs deep equality comparison between two values with support for primitives, objects, arrays, and special types.\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param strictCheck - When `true`, requires arrays and objects to have the same length/key count; defaults to `true`\n *\n * @returns `true` if values are deeply equal, `false` otherwise\n *\n * @remarks\n * This function performs comprehensive equality checking with special handling for:\n * - **Primitives**: Uses strict equality (`===`) and `Object.is()` for `NaN` and `-0` handling\n * - **Dates**: Compares timestamps using `getTime()`\n * - **RegExp**: Compares source patterns and flags\n * - **URLs**: Compares full `href` strings\n * - **Arrays**: Recursively compares elements\n * - **Objects**: Recursively compares properties\n *\n * The `strictCheck` parameter controls comparison behavior:\n * - `true` (default): Arrays must have the same length, objects must have the same key count.\n * - `false`: Allows partial matches (subset comparison)\n *\n * **Null handling**:\n * Returns `false` if either value is `null` (unless both are `null`, caught by `===` check).\n *\n * @example\n * ```ts\n * equals(1, 1); // true\n * equals('test', 'test'); // true\n * equals(NaN, NaN); // true (via Object.is)\n * equals(null, null); // true\n * ```\n *\n * @example\n * ```ts\n * // Date comparison\n * const date1 = new Date('2024-01-01');\n * const date2 = new Date('2024-01-01');\n * equals(date1, date2); // true\n * ```\n *\n * @example\n * ```ts\n * // Deep object comparison\n * equals(\n * { a: 1, b: { c: 2 } },\n * { a: 1, b: { c: 2 } }\n * ); // true\n * ```\n *\n * @example\n * ```ts\n * // Strict vs non-strict array comparison\n * equals([1, 2], [1, 2, 3], true); // false (different lengths)\n * equals([1, 2], [1, 2, 3], false); // true (subset match)\n * ```\n *\n * @see {@link deepEquals}\n * @see {@link hasKey}\n *\n * @since 2.0.0\n */\n\nexport function equals(a: unknown, b: unknown, strictCheck = true): boolean {\n if (a === b) return true;\n if (Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n\n if (URL && a instanceof URL && b instanceof URL)\n return a.href === b.href;\n\n if (typeof a === 'object' && typeof b === 'object') {\n return deepEquals(a, b, strictCheck);\n }\n\n return false;\n}\n\n/**\n * Checks whether an object or function has a specific property key.\n *\n * @param obj - The object or function to check\n * @param key - The property key to search for (string or symbol)\n *\n * @returns `true` if the key exists on the object, `false` otherwise\n *\n * @remarks\n * This function performs two checks to determine the key existence:\n * 1. Uses the `in` operator to check the prototype chain\n * 2. Uses `Object.prototype.hasOwnProperty.call()` for own properties\n *\n * Returns `false` if the value is:\n * - `null` or `undefined`\n * - Not an object or function (primitives like strings, numbers, booleans)\n *\n * This function is safer than direct property access when dealing with unknown objects,\n * as it handles `null` and `undefined` gracefully without throwing errors.\n *\n * @example\n * ```ts\n * const obj = { name: 'test' };\n * hasKey(obj, 'name'); // true\n * hasKey(obj, 'age'); // false\n * hasKey(null, 'key'); // false\n * hasKey('string', 'length'); // true\n * ```\n *\n * @example\n * ```ts\n * // Symbol keys\n * const sym = Symbol('key');\n * const obj = { [sym]: 'value' };\n * hasKey(obj, sym); // true\n * ```\n *\n * @see {@link deepEquals}\n *\n * @since 2.0.0\n */\n\nexport function hasKey(obj: unknown, key: string | symbol): boolean {\n if (obj == null || (typeof obj !== 'object' && typeof obj !== 'function'))\n return false;\n\n return key in obj || Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Performs deep equality comparison on objects and arrays with configurable strictness.\n *\n * @param a - The first object to compare\n * @param b - The second object to compare\n * @param strictCheck - When `true`, requires same length/key count; defaults to `true`\n *\n * @returns `true` if objects are deeply equal, `false` otherwise\n *\n * @remarks\n * This internal helper function is called by {@link equals} to handle object and array comparisons.\n * It recursively compares nested structures using the following logic:\n *\n * **Array comparison**:\n * - In strict mode: Arrays must have identical length\n * - Compares elements by index using {@link equals}\n * - Order matters (different order means not equal)\n *\n * **Object comparison**:\n * - In strict mode: Objects must have same number of keys\n * - Iterates through keys of the first object\n * - Checks if each key exists in the second object\n * - Recursively compares property values using {@link equals}\n *\n * **Non-strict mode** allows partial matches where the first value can be a subset of the second.\n *\n * @example\n * ```ts\n * // Arrays\n * deepEquals([1, 2, 3], [1, 2, 3], true); // true\n * deepEquals([1, 2], [1, 2, 3], false); // true (subset)\n * deepEquals([1, 2], [1, 2, 3], true); // false (different lengths)\n * ```\n *\n * @example\n * ```ts\n * // Nested objects\n * deepEquals(\n * { user: { name: 'Alice', age: 30 } },\n * { user: { name: 'Alice', age: 30 } },\n * true\n * ); // true\n * ```\n *\n * @see {@link equals}\n * @see {@link hasKey}\n *\n * @since 2.0.0\n */\n\nfunction deepEquals(a: object, b: object, strictCheck: boolean = true): boolean {\n if (Array.isArray(a) && Array.isArray(b)) {\n if(strictCheck && a.length !== b.length) return false;\n\n return a.every((val, i) => equals(val, b[i], strictCheck));\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (strictCheck && aKeys.length !== bKeys.length) return false;\n\n for (const key of aKeys) {\n if (!hasKey(b, key)) return false;\n if (!equals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], strictCheck)) {\n return false;\n }\n }\n\n return true;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PartialBuildConfigType } from '@interfaces/configuration.interface';\n\n/**\n * Default build configuration shared across all variants.\n * Provides sensible defaults for common build settings including TypeScript compilation and esbuild options.\n *\n * @remarks\n * This frozen configuration object serves as the foundation for all builds when no custom\n * common configuration is provided. It establishes defaults for:\n * - Type checking enabled\n * - Declaration file generation enabled\n * - Bundle mode with minification\n * - CommonJS output format\n * - Browser platform target\n * - Output to `dist` directory\n *\n * All nested objects are deeply frozen using `Object.freeze()` to prevent accidental mutation\n * and ensure configuration immutability. This makes the defaults safe to reference without\n * defensive copying.\n *\n * These defaults are merged with user-provided configuration, with user values taking precedence.\n * Individual variants can override any of these settings for their specific build targets.\n *\n * @example\n * ```ts\n * // User config merges with defaults\n * const userConfig: BuildConfigInterface = {\n * ...DEFAULTS_COMMON_CONFIG,\n * common: {\n * ...DEFAULTS_COMMON_CONFIG.common,\n * esbuild: {\n * ...DEFAULTS_COMMON_CONFIG.common?.esbuild,\n * format: 'esm', // Override default 'cjs'\n * minify: false // Override default true\n * }\n * },\n * variants: { ... }\n * };\n * ```\n *\n * @example\n * ```ts\n * // Accessing default values\n * const defaultFormat = DEFAULTS_COMMON_CONFIG.common?.esbuild?.format;\n * // 'cjs'\n *\n * const defaultOutDir = DEFAULTS_COMMON_CONFIG.common?.esbuild?.outdir;\n * // 'dist'\n * ```\n *\n * @see {@link PartialBuildConfigType}\n *\n * @since 2.0.0\n */\n\nexport const DEFAULTS_COMMON_CONFIG: PartialBuildConfigType = Object.freeze({\n verbose: false,\n common: Object.freeze({\n types: true,\n declaration: true,\n esbuild: Object.freeze({\n write: true,\n bundle: true,\n minify: true,\n format: 'cjs',\n outdir: 'dist',\n platform: 'browser',\n absWorkingDir: process.cwd()\n })\n })\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { UnsubscribeType, Observable } from '@observable/observable.module';\nimport type { BuildConfigInterface, DeepPartialType } from '@interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { BehaviorSubject } from '@observable/observable.module';\nimport { deepMerge, equals } from '@components/object.component';\nimport { map, distinctUntilChanged } from '@observable/observable.module';\nimport { DEFAULTS_COMMON_CONFIG } from '@constants/configuration.constant';\n\n/**\n * Provides a centralized service for managing and observing configuration state.\n *\n * @template T - The configuration object type must extend {@link BuildConfigInterface}\n *\n * @remarks\n * Configuration changes are deeply merged with existing values, preserving unmodified properties.\n * Type-safe selectors enable reactive access to nest or derived configuration properties.\n *\n * @example\n * ```ts\n * // Initialize with default or custom configuration\n * const configService = new ConfigurationService({ name: 'myApp' });\n *\n * // Get current configuration value\n * const config = configService.getValue();\n *\n * // Get a specific configuration property\n * const name = configService.getValue(cfg => cfg.name);\n *\n * // Subscribe to configuration changes\n * const unsubscribe = configService.subscribe((config) => {\n * console.log('Config updated:', config);\n * });\n *\n * // Select and observe specific properties reactively\n * configService.select(cfg => cfg.name)\n * .subscribe(name => console.log('Name changed:', name));\n *\n * // Update configuration (deep merge)\n * configService.patch({ name: 'newApp' });\n *\n * // Cleanup subscription\n * unsubscribe();\n * ```\n *\n * @see {@link BuildConfigInterface} for the configuration contract\n * @see {@link BehaviorSubject} for the underlying reactive implementation\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class ConfigurationService<T extends BuildConfigInterface> {\n /**\n * Internal configuration state managed by a {@link BehaviorSubject}.\n *\n * @remarks\n * This private property holds the current configuration and emits changes\n * to all active subscribers. All public methods delegate state access through this subject.\n *\n * @see {@link BehaviorSubject}\n *\n * @since 2.0.0\n */\n\n private readonly config$: BehaviorSubject<T>;\n\n /**\n * Initializes a new {@link ConfigurationService} instance.\n *\n * @param initialConfig - The initial configuration object (defaults to {@link DEFAULTS_COMMON_CONFIG})\n *\n * @remarks\n * - Creates a deep copy of the provided configuration to prevent external mutations\n * - If no configuration is provided, uses the default configuration\n * - The configuration is wrapped in a {@link BehaviorSubject} for reactive updates\n *\n * @example\n * ```ts\n * // With default configuration\n * const service = new ConfigurationService();\n *\n * // With custom configuration\n * const service = new ConfigurationService({ name: 'customApp' });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(private initialConfig: T = DEFAULTS_COMMON_CONFIG as T) {\n this.config$ = new BehaviorSubject<T>(deepMerge({}, initialConfig) as T);\n }\n\n /**\n * Retrieves the current configuration value synchronously.\n *\n * @overload\n * @returns The complete current configuration object\n *\n * @example\n * ```ts\n * const config = configService.getValue();\n * console.log(config.name);\n * ```\n *\n * @since 2.0.0\n */\n\n getValue(): T;\n\n /**\n * Retrieves a computed value derived from the current configuration.\n *\n * @overload\n * @typeParam R - The return type of the selector function\n * @param selector - A function that extracts or transforms a value from the configuration\n * @returns The computed value returned by the selector function\n *\n * @remarks\n * This overload allows synchronous extraction of specific configuration properties\n * or computed values without creating an Observable subscription.\n *\n * @example\n * ```ts\n * const name = configService.getValue(cfg => cfg.name);\n * const nameLength = configService.getValue(cfg => cfg.name?.length ?? 0);\n * ```\n *\n * @since 2.0.0\n */\n\n getValue<R>(selector: (config: T) => R): R;\n\n /**\n * Implementation of getValue that handles both overloads.\n *\n * @param selector - Optional selector function for computed values\n * @returns The current configuration or a computed value derived from it\n *\n * @remarks\n * When no selector is provided, it returns the complete configuration.\n * When a selector is provided, applies it to the current configuration value\n * and returns the result.\n *\n * @since 2.0.0\n */\n\n getValue<R>(selector?: (config: T) => R): T | R {\n if (!selector)\n return this.config$.value;\n\n return selector(this.config$.value);\n }\n\n /**\n * Subscribes to configuration changes and executes a callback for each update.\n *\n * @param observer - A callback function invoked with the new configuration value on each change\n * @returns An unsubscribe function that removes this subscription when called\n *\n * @remarks\n * - The observer is immediately called with the current configuration value\n * - Subsequent calls occur whenever the configuration is updated via {@link patch}\n * - Returns an unsubscribe function for cleanup; it should be called to prevent memory leaks\n * - For more sophisticated reactive operations, consider using {@link select} instead\n *\n * @example\n * ```ts\n * const unsubscribe = configService.subscribe((config) => {\n * console.log('Configuration changed:', config);\n * });\n *\n * // Later, stop listening to changes\n * unsubscribe();\n * ```\n *\n * @see {@link select} for reactive selector-based subscriptions\n *\n * @since 1.0.0\n */\n\n subscribe(observer: (value: T) => void): UnsubscribeType {\n return this.config$.subscribe(observer);\n }\n\n /**\n * Creates an Observable that emits selected configuration values whenever they change.\n *\n * @typeParam R - The return type of the selector function\n * @param selector - A function that extracts or transforms a value from the configuration\n * @returns An Observable that emits distinct selector results on configuration changes\n *\n * @remarks\n * - Uses the provided selector to extract a computed value from the configuration\n * - Only emits values that are distinct from the previous emission (via {@link distinctUntilChanged})\n * - Distinction is determined using the {@link equals} utility for deep equality comparison\n * - Allows reactive composition using RxJS operators and subscriptions\n * - Ideal for observing nested properties or computed values without pollution from unchanged properties\n *\n * @example\n * ```ts\n * // Observe a specific property\n * configService.select(cfg => cfg.name)\n * .subscribe(name => console.log('Name is now:', name));\n *\n * // Observe a derived value\n * configService.select(cfg => cfg.name?.toUpperCase() ?? '')\n * .subscribe(uppercaseName => console.log('Upper name:', uppercaseName));\n *\n * // Compose with other RxJS operators\n * configService.select(cfg => cfg.name)\n * .pipe(\n * filter(name => name?.length > 0),\n * map(name => name.toUpperCase())\n * )\n * .subscribe(uppercaseName => console.log('Valid uppercase name:', uppercaseName));\n * ```\n *\n * @see {@link equals} for equality comparison logic\n * @see {@link distinctUntilChanged} for deduplication behavior\n * @see {@link subscribe} for simple subscription-based value access\n *\n * @since 2.0.0\n */\n\n select<R>(selector: (config: T) => R): Observable<R> {\n return this.config$.pipe(\n map(selector),\n distinctUntilChanged((prev, curr) => equals(prev, curr))\n ) as Observable<R>;\n }\n\n /**\n * Updates the configuration with partial changes, performing a deep merge.\n *\n * @param partial - A partial configuration object containing the properties to update\n *\n * @remarks\n * - Performs a deep merge of the provided partial configuration with the current configuration\n * - Unmodified properties are preserved from the current configuration\n * - The merge operation uses {@link deepMerge} to ensure nested objects are properly merged\n * - After merging, emits the updated configuration to all active subscribers via the BehaviorSubject\n * - For complete replacement rather than merging, create a new ConfigurationService instance\n *\n * @example\n * ```ts\n * // Update a single property\n * configService.patch({ name: 'updatedApp' });\n *\n * // Update multiple properties (existing properties are preserved)\n * configService.patch({\n * name: 'newApp',\n * // other properties remain unchanged\n * });\n *\n * // Patch with nested updates\n * configService.patch({\n * name: 'app',\n * // nested properties would be merged deeply if they existed\n * });\n * ```\n *\n * @see {@link subscribe} to observe changes\n * @see {@link deepMerge} for the merging implementation\n * @see {@link select} to observe specific properties reactively\n *\n * @since 1.0.0\n */\n\n patch(partial: DeepPartialType<T>): void {\n const mergedConfig = deepMerge<T>(\n {} as T,\n this.config$.value,\n partial\n );\n\n this.config$.next(mergedConfig);\n }\n\n /**\n * Replaces the entire configuration with a new configuration object.\n *\n * @param config - The complete configuration object to set\n *\n * @remarks\n * - Performs a complete replacement of the configuration (unlike {@link patch} which merges)\n * - The provided configuration object is used directly without deep cloning\n * - Emits the new configuration to all active subscribers via the BehaviorSubject\n * - Useful when you need to reset or swap the entire configuration state\n * - No properties are preserved from the previous configuration\n *\n * @example\n * ```ts\n * // Replace entire configuration\n * configService.reload({\n * verbose: true,\n * variants: { production: { esbuild: { minify: true } } },\n * common: { esbuild: { write: true } }\n * });\n *\n * // Reset to default configuration\n * configService.reload(DEFAULTS_COMMON_CONFIG);\n *\n * // Swap between different configuration profiles\n * const prodConfig = loadProductionConfig();\n * configService.reload(prodConfig);\n * ```\n *\n * @see {@link patch} for partial configuration updates with deep merging\n * @see {@link subscribe} to observe configuration changes\n * @see {@link select} to observe specific configuration properties reactively\n *\n * @since 2.0.0\n */\n\n reload(config: Partial<T>): void {\n this.config$.next(deepMerge({}, this.initialConfig, config) as T);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StackTraceInterface, StackInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { formatStack, getErrorMetadata } from '@providers/stack.provider';\n\n/**\n * A base class for custom errors with enhanced stack trace formatting and source code information.\n *\n * @remarks\n * The `xBuildBaseError` class extends the native `Error` class, adding functionality to:\n * - Parse and store structured stack trace metadata via {@link StackInterface}\n * - Format stack traces with syntax highlighting and source mapping\n * - Provide enhanced console output through custom Node.js inspection\n *\n * This is particularly useful for debugging errors in compiled or transpiled code by providing\n * clearer information about the original source of the error, including\n * - Original source file paths (from source maps)\n * - Highlighted code snippets showing the error location\n * - Enhanced stack frame formatting with proper indentation\n *\n * @example\n * ```ts\n * class ValidationError extends xBuildBaseError {\n * constructor(message: string, field: string) {\n * super(message, 'ValidationError');\n * this.reformatStack(this, { withFrameworkFrames: false });\n * }\n * }\n *\n * throw new ValidationError('Invalid email format', 'email');\n * ```\n *\n * @see {@link formatStack} for stack formatting\n * @see {@link getErrorMetadata} for stack parsing\n * @see {@link StackInterface} for the metadata structure\n * @see {@link StackTraceInterface} for formatting options\n *\n * @since 2.0.0\n */\n\nexport abstract class xBuildBaseError extends Error {\n /**\n * Structured metadata from the parsed stack trace.\n *\n * @remarks\n * Contains the parsed stack information including\n * - Original source code snippet\n * - Line and column numbers\n * - Source file path (from source maps)\n * - Formatted stack frames\n * - Syntax-highlighted code\n *\n * This property is populated by calling {@link reformatStack}.\n *\n * @since 2.0.0\n */\n\n protected errorMetadata: StackInterface | undefined;\n\n /**\n * Pre-formatted stack trace string ready for display.\n *\n * @remarks\n * Contains the complete formatted output including\n * - Error name and message\n * - Syntax-highlighted code snippet (if available)\n * - Enhanced stack trace with proper indentation\n *\n * This is generated by {@link formatStack} and used by the custom\n * Node.js inspector for console output.\n *\n * @since 2.0.0\n */\n\n protected formattedStack: string | undefined;\n\n /**\n * Creates a new instance of the base error class.\n *\n * @param message - The error message describing the problem\n * @param name - The error type name; defaults to `'xBuildBaseError'`\n *\n * @remarks\n * This constructor:\n * - Properly sets up the prototype chain to ensure `instanceof` checks work for derived classes\n * - Captures the stack trace if supported by the runtime environment\n * - Sets the error name for identification\n *\n * **Important:** This is a protected constructor and should only be called by derived classes.\n * Subclasses should call {@link reformatStack} after construction to enable enhanced formatting.\n *\n * @example\n * ```ts\n * class DatabaseError extends xBuildBaseError {\n * constructor(message: string, public readonly query: string) {\n * super(message, 'DatabaseError');\n * this.reformatStack(this);\n * }\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n protected constructor(message: string, name: string = 'xBuildBaseError') {\n super(message);\n\n // Ensure a correct prototype chain (important for `instanceof`)\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Gets the structured stack trace metadata.\n *\n * @returns The parsed stack metadata, or `undefined` if {@link reformatStack} has not been called\n *\n * @remarks\n * Provides read-only access to the error's structured stack information,\n * which can be used for:\n * - Custom error logging\n * - Error reporting services\n * - Debugging tools\n * - Stack analysis\n *\n * @example\n * ```ts\n * try {\n * throw new ValidationError('Invalid input');\n * } catch (error) {\n * if (error instanceof xBuildBaseError) {\n * const meta = error.metadata;\n * console.log(`Error at ${meta?.source}:${meta?.line}:${meta?.column}`);\n * }\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n get metadata(): StackInterface | undefined {\n return this.errorMetadata;\n }\n\n /**\n * Custom inspect behavior for Node.js console output.\n *\n * @returns The enhanced formatted stack trace if available, otherwise falls back to the raw stack trace\n *\n * @remarks\n * This method is automatically called by Node.js when the error is logged to the console\n * using `console.log()`, `console.error()`, or `util.inspect()`.\n *\n * The formatted output includes:\n * - Colored and styled error name and message\n * - Syntax-highlighted code snippet showing the error location\n * - Enhanced stack frames with source-mapped paths\n *\n * @example\n * ```ts\n * const error = new ValidationError('Invalid data');\n * console.log(error); // Automatically uses this method for formatting\n * ```\n *\n * @see {@link https://nodejs.org/api/util.html#custom-inspection-functions-on-objects | Node.js Custom Inspection}\n *\n * @since 2.0.0\n */\n\n [Symbol.for('nodejs.util.inspect.custom')](): string | undefined {\n return this.formattedStack || this.stack;\n }\n\n /**\n * Parses the error stack trace and generates enhanced formatting with metadata.\n *\n * @param error - The error object to parse and format\n * @param options - Optional configuration for stack trace parsing and formatting\n *\n * @remarks\n * This method performs two operations:\n * 1. Parses the error's stack trace using {@link getErrorMetadata} to extract structured metadata\n * 2. Formats the metadata using {@link formatStack} to create a styled, human-readable output\n *\n * The parsed metadata is stored in {@link errorMetadata} and the formatted string in {@link formattedStack}.\n *\n * **Typical usage:** Call this method in the constructor of derived error classes to enable\n * enhanced stack trace formatting.\n *\n * @example\n * ```ts\n * class NetworkError extends xBuildBaseError {\n * constructor(message: string, public readonly statusCode: number) {\n * super(message, 'NetworkError');\n * // Enable enhanced formatting without framework frames\n * this.reformatStack(this, {\n * withFrameworkFrames: false,\n * withNativeFrames: true\n * });\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * class CustomError extends xBuildBaseError {\n * constructor(message: string) {\n * super(message, 'CustomError');\n * // Use default options\n * this.reformatStack(this);\n * }\n * }\n * ```\n *\n * @see {@link formatStack} for formatting logic\n * @see {@link getErrorMetadata} for parsing logic\n * @see {@link StackTraceInterface} for available options\n *\n * @since 2.0.0\n */\n\n protected reformatStack(error: Error, options?: StackTraceInterface): void {\n this.errorMetadata = getErrorMetadata(error, options);\n this.formattedStack = formatStack(this.errorMetadata, error.name, error.message);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Argv, Options } from 'yargs';\nimport type { BaseArgumentsInterface } from '@argv/interfaces/argv-module.interface';\nimport type { UserExtensionInterface, ArgumentsInterface } from '@argv/interfaces/argv-module.interface';\n\n/**\n * Imports\n */\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { CLI_DEFAULT_OPTIONS, CLI_USAGE_EXAMPLES } from '@argv/constants/argv.constant';\n\n/**\n * Command-line argument parser and processor for xBuild.\n *\n * @remarks\n * This module provides three levels of argument parsing to support different stages\n * of the build tool's initialization and execution:\n *\n * - **Configuration file parsing**: Early-stage parsing to locate custom config files\n * - **User extension parsing**: Parses custom options defined in configuration files\n * - **Enhanced parsing**: Full-featured CLI with help, version, examples, and validation\n *\n * The module is designed as a singleton service, ensuring consistent argument parsing\n * across the entire application lifecycle. It integrates with yargs to provide a\n * comprehensive command-line interface with:\n * - Automatic help generation with custom branding\n * - Usage examples and documentation links\n * - Type-safe argument validation\n * - Support for custom user-defined options\n * - Strict mode to catch typos and invalid options\n *\n * **Parsing Strategy:**\n *\n * The three-stage parsing approach allows xBuild to:\n * 1. First, parse just the `--config` flag to locate a configuration file\n * 2. Load configuration and discover user-defined CLI options\n * 3. Reparse all arguments with a complete option set for full validation\n *\n * This strategy enables configuration files to extend the CLI dynamically while\n * maintaining type safety and proper error handling.\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n *\n * // Parse config path only\n * const { config } = parseConfigFile(process.argv);\n *\n * // Load config and get user extensions\n * const userOptions = await configFileProvider(config);\n *\n * // Full parse with all options\n * const args = argvModule.enhancedParse(process.argv, userOptions.userArgv);\n *\n * // User argv\n * const userArgs = argvService.parseUserArgv(process.argv, userOptions.userArgv);\n * ```\n *\n * @see {@link bannerComponent}\n * @see {@link CLI_USAGE_EXAMPLES}\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class ArgvModule {\n /**\n * Parses command-line arguments to extract the configuration file path.\n *\n * @param argv - Raw command-line arguments array\n * @returns Parsed arguments containing the config file path\n *\n * @remarks\n * This method performs minimal parsing focused solely on extracting the `--config`\n * option. It's used during the initial bootstrap phase before the configuration\n * file is loaded, enabling xBuild to locate and load custom configuration files.\n *\n * **Parsing behavior:**\n * - Only processes the `config` option\n * - Disables help and version flags to prevent premature exit\n * - Returns a default config path if not specified\n * - Ignores all other arguments for performance\n *\n * The returned config path is used to load the build configuration file,\n * which may define additional CLI options that require reparsing with\n * the complete option set.\n *\n * This is the first step in a multi-stage parsing strategy that allows\n * configuration files to extend the CLI dynamically.\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n * const result = argvModule.parseConfigFile(process.argv);\n *\n * console.log(result.config);\n * // Output: 'config.xbuild.ts' (default)\n * // Or: 'custom.xbuild.ts' (if --config custom.xbuild.ts was passed)\n * ```\n *\n * @example\n * ```ts\n * // Command: xBuild --config build/prod.xbuild.ts src/index.ts\n * const { config } = argvModule.parseConfigFile(process.argv);\n * // Result: { config: 'build/prod.xbuild.ts', _: [...], $0: '...' }\n * ```\n *\n * @see {@link enhancedParse}\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\n parseConfigFile(argv: Array<string>): BaseArgumentsInterface & { config: string } {\n return yargs(argv)\n .help(false)\n .version(false)\n .options({\n config: CLI_DEFAULT_OPTIONS.config\n }).parseSync() as BaseArgumentsInterface & { config: string };\n }\n\n /**\n * Parses user-defined command-line options from configuration files.\n *\n * @param argv - Raw command-line arguments array\n * @param argvOptions - Optional user-defined CLI options from configuration\n * @returns Parsed arguments containing user-defined option values\n *\n * @remarks\n * This method parses custom CLI options defined in the build configuration file,\n * allowing users to extend xBuild's command-line interface with project-specific\n * arguments. It's used after loading the configuration file but before the final\n * enhanced parse.\n *\n * **Parsing behavior:**\n * - Only processes user-defined options (not xBuild defaults)\n * - Returns an empty object if no user options are provided\n * - Disables help and version to prevent premature exit\n * - Maintains type safety with generic return type\n *\n * User-defined options can include custom flags for:\n * - Build environment selection (staging, production)\n * - Feature flags and conditional compilation\n * - Custom output paths or naming schemes\n * - Integration with other build tools\n *\n * The parsed values are available in lifecycle hooks and configuration functions,\n * enabling dynamic build behavior based on CLI arguments.\n *\n * @example\n * ```ts\n * // In config.xbuild.ts\n * export default {\n * cliOptions: {\n * env: {\n * describe: 'Build environment',\n * type: 'string',\n * choices: ['dev', 'staging', 'prod']\n * }\n * }\n * };\n * ```\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n * const userArgs = argvModule.parseUserArgv<{ env: string }>(\n * process.argv,\n * config.cliOptions\n * );\n *\n * console.log(userArgs.env);\n * // Output: 'prod' (if --env prod was passed)\n * ```\n *\n * @example\n * ```ts\n * // No user options defined\n * const userArgs = argvModule.parseUserArgv(process.argv);\n * // Returns: {}\n * ```\n *\n * @see {@link enhancedParse}\n * @see {@link parseConfigFile}\n *\n * @since 2.0.0\n */\n\n parseUserArgv<T extends BaseArgumentsInterface>(argv: Array<string>, argvOptions?: Record<string, Options>): T {\n if (!argvOptions) return <T>{};\n\n return yargs(argv)\n .help(false)\n .version(false)\n .options(argvOptions).parseSync() as T;\n }\n\n /**\n * Performs comprehensive argument parsing with full CLI features and validation.\n *\n * @param argv - Raw command-line arguments array\n * @param userExtensions - Optional user-defined CLI options from configuration\n * @returns Fully parsed and validated arguments with all xBuild and user options\n *\n * @remarks\n * This method provides the complete command-line interface experience with all\n * features enabled. It combines xBuild's default options with user-defined extensions\n * to create a unified, fully validated CLI.\n *\n * **Enhanced features:**\n * - **Custom help formatting**: Displays xBuild banner and grouped options\n * - **Usage examples**: Shows common command patterns with descriptions\n * - **Strict validation**: Catches unknown options and invalid values\n * - **Help and version**: Standard `--help` and `--version` flags\n * - **Documentation links**: Provides epilogue with documentation URL\n * - **Positional arguments**: Supports file paths as positional parameters\n *\n * **Help output structure:**\n * 1. xBuild ASCII banner\n * 2. Usage syntax\n * 3. Commands section\n * 4. xBuild Options (grouped)\n * 5. User Options (grouped, if any)\n * 6. Examples\n * 7. Documentation link\n *\n * **Option grouping:**\n * - Separates xBuild core options from user-defined options\n * - Improves help readability for complex configurations\n * - Makes custom options clearly identifiable\n *\n * The method overrides yargs' `showHelp` to inject custom branding and option\n * grouping, providing a polished CLI experience consistent with xBuild's design.\n *\n * This is the final parsing stage and should be called after configuration loading\n * is complete and all user extensions have been discovered.\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n * const args = argvModule.enhancedParse(process.argv, {\n * env: {\n * describe: 'Build environment',\n * type: 'string',\n * choices: ['dev', 'prod']\n * }\n * });\n *\n * console.log(args.entryPoints); // ['src/index.ts']\n * console.log(args.minify); // true\n * console.log(args.env); // 'prod'\n * ```\n *\n * @example\n * ```ts\n * // Command: xBuild src/app.ts --bundle --minify --env prod\n * const args = argvModule.enhancedParse(process.argv, userOptions);\n * // Result: {\n * // entryPoints: ['src/app.ts'],\n * // bundle: true,\n * // minify: true,\n * // ...\n * // }\n * ```\n *\n * @example\n * ```ts\n * // Displaying help\n * // Command: xBuild --help\n * // Shows:\n * // - ASCII banner\n * // - Usage: xBuild [files..] [options]\n * // - xBuild Options: (--bundle, --minify, etc.)\n * // - User Options: (--env, custom options)\n * // - Examples: Common usage patterns\n * // - Documentation link\n * ```\n *\n * @see {@link parseUserArgv}\n * @see {@link parseConfigFile}\n * @see {@link bannerComponent}\n * @see {@link CLI_USAGE_EXAMPLES}\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\n enhancedParse(argv: Array<string>, userExtensions: UserExtensionInterface = {}): ArgumentsInterface {\n const parser = yargs(hideBin(argv)).locale('en');\n const originalShowHelp = parser.showHelp;\n parser.showHelp = function (consoleFunction?: string | ((s: string) => void)): Argv<unknown> {\n this.group(Object.keys(CLI_DEFAULT_OPTIONS), 'xBuild Options:');\n this.group(Object.keys(userExtensions), 'user Options:');\n\n return originalShowHelp.call(this, consoleFunction as (s: string) => void);\n };\n\n parser\n .usage('Usage: xBuild [files..] [options]')\n .command('* [entryPoints..]', 'Specific files to build (supports glob patterns)', (yargs) => {\n return yargs.positional('entryPoints', {\n describe: 'Specific files to build (supports glob patterns)',\n type: 'string',\n array: true\n });\n })\n .options(userExtensions)\n .options(CLI_DEFAULT_OPTIONS)\n .epilogue('For more information, check the documentation https://remotex-labs.github.io/xBuild/')\n .help()\n .alias('help', 'h')\n .strict()\n .version();\n\n CLI_USAGE_EXAMPLES.forEach(([ command, description ]) => {\n parser.example(command, description);\n });\n\n return parser.parseSync();\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Options } from 'yargs';\n\n/**\n * Default path to the xBuild configuration file.\n *\n * @remarks\n * This constant defines the standard location for xBuild's build configuration.\n * Used as the default value for the `--config` CLI option when no custom path is provided.\n *\n * The configuration file contains:\n * - Build variant definitions (production, development, etc.)\n * - Common build settings shared across variants\n * - esbuild compiler options\n * - TypeScript integration settings\n * - Custom lifecycle hooks\n * - Define replacements and injections\n *\n * The file is a TypeScript module that exports build configuration, enabling\n * type-safe configuration with IDE autocomplete support.\n *\n * @example\n * ```ts\n * // Default usage\n * xBuild src/index.ts\n * // Automatically looks for: config.xbuild.ts\n * ```\n *\n * @example\n * ```ts\n * // Custom config path\n * xBuild src/index.ts --config build/custom.xbuild.ts\n * ```\n *\n * @since 2.0.0\n */\n\nexport const CLI_CONFIG_PATH = 'config.xbuild.ts' as const;\n\n/**\n * Default command-line interface options and their configurations.\n *\n * @remarks\n * This constant defines all available CLI flags and arguments for the xBuild tool,\n * providing comprehensive build customization from the command line. Each option\n * includes type validation, aliases, descriptions, and default values.\n *\n * **Option Categories:**\n *\n * **Input/Output:**\n * - `entryPoints`: Source files to compile (supports glob patterns)\n * - `outdir`: Output directory for compiled files\n *\n * **Build Modes:**\n * - `watch`: Enable watch mode for automatic rebuilds\n * - `serve`: Start development server\n * - `typeCheck`: Type check only without output\n *\n * **Build Configuration:**\n * - `bundle`: Bundle dependencies into output\n * - `minify`: Minify output code\n * - `format`: Module format (cjs, esm, iife)\n * - `platform`: Target platform (browser, node, neutral)\n *\n * **TypeScript:**\n * - `declaration`: Generate .d.ts files\n * - `types`: Enable type checking during build\n * - `failOnError`: Fail build on type errors\n * - `tsconfig`: Custom tsconfig.json path\n *\n * **Configuration:**\n * - `config`: Custom build configuration file path\n * - `verbose`: Enable detailed error messages\n *\n * All options can be used individually or combined to create complex build workflows.\n * Options specified on the command line override configuration file settings.\n *\n * @example\n * ```ts\n * // Single file build with defaults\n * xBuild src/index.ts\n * ```\n *\n * @example\n * ```ts\n * // Production build with bundling and minification\n * xBuild src/app.ts --bundle --minify --format esm\n * ```\n *\n * @example\n * ```ts\n * // Development mode with watch and server\n * xBuild src/app.ts --watch --serve dist\n * ```\n *\n * @example\n * ```ts\n * // Library build with type definitions\n * xBuild src/lib.ts --declaration --format esm --outdir dist\n * ```\n *\n * @example\n * ```ts\n * // Type checking only (no output)\n * xBuild --typeCheck\n * ```\n *\n * @see {@link TSCONFIG_PATH}\n * @see {@link CLI_CONFIG_PATH}\n * @see {@link CLI_USAGE_EXAMPLES}\n *\n * @since 2.0.0\n */\n\nexport const CLI_DEFAULT_OPTIONS: Record<string, Options> = {\n entryPoints: {\n describe: 'Source files to build (supports glob patterns)',\n type: 'string',\n array: true\n },\n typeCheck: {\n describe: 'Perform type checking without building output',\n alias: 'tc',\n type: 'boolean'\n },\n platform: {\n describe: 'Target platform for the build output',\n alias: 'p',\n type: 'string',\n choices: [ 'browser', 'node', 'neutral' ] as const\n },\n serve: {\n describe: 'Start server to the <folder>',\n alias: 's',\n type: 'string'\n },\n outdir: {\n describe: 'Directory for build output files',\n alias: 'o',\n type: 'string'\n },\n declaration: {\n describe: 'Generate TypeScript declaration files (.d.ts)',\n alias: 'de',\n type: 'boolean'\n },\n watch: {\n describe: 'Watch mode - rebuild on file changes',\n alias: 'w',\n type: 'boolean'\n },\n config: {\n describe: 'Path to build configuration file',\n alias: 'c',\n type: 'string',\n default: CLI_CONFIG_PATH\n },\n tsconfig: {\n describe: 'Path to TypeScript configuration file',\n alias: 'tsc',\n type: 'string'\n },\n minify: {\n describe: 'Minify the build output',\n alias: 'm',\n type: 'boolean'\n },\n bundle: {\n describe: 'Bundle dependencies into output files',\n alias: 'b',\n type: 'boolean'\n },\n types: {\n describe: 'Enable type checking during build process',\n alias: 'btc',\n type: 'boolean'\n },\n failOnError: {\n describe: 'Fail build when TypeScript errors are detected',\n alias: 'foe',\n type: 'boolean'\n },\n format: {\n describe: 'Output module format',\n alias: 'f',\n type: 'string',\n choices: [ 'cjs', 'esm', 'iife' ]\n },\n verbose: {\n describe: 'Verbose error stack traces',\n alias: 'v',\n type: 'boolean'\n },\n build: {\n describe: 'Select an build configuration variant by names (as defined in your config file)',\n alias: 'xb',\n type: 'string',\n array: true\n }\n} as const;\n\n/**\n * Example command-line usage patterns demonstrating common build scenarios.\n *\n * @remarks\n * This constant provides a curated collection of practical CLI usage examples\n * that demonstrate how to combine xBuild options for common development workflows.\n * Each example includes the complete command and a description of its purpose.\n *\n * **Example Categories:**\n *\n * **Basic Builds:**\n * - Single file compilation with defaults\n * - Multi-file bundling with optimization\n *\n * **Development Workflows:**\n * - Watch mode with development server\n * - Custom server directory configuration\n *\n * **Library Publishing:**\n * - ESM library with type definitions\n * - Platform-specific builds\n *\n * **Validation:**\n * - Type checking without output\n * - Custom configuration files\n *\n * These examples are displayed in CLI help output and serve as quick-start\n * templates for developers learning the tool.\n *\n * @example\n * ```ts\n * // Displayed when running: xBuild --help\n * // Shows all usage examples with descriptions\n * ```\n *\n * @example\n * ```ts\n * // Example: Production library build\n * xBuild src/lib.ts --format esm --declaration\n * // Generates: dist/lib.js and dist/lib.d.ts as ESM\n * ```\n *\n * @example\n * ```ts\n * // Example: Development with hot reload\n * xBuild src/app.ts -s dist\n * // Starts: Watch mode + dev server serving from dist/\n * ```\n *\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\nexport const CLI_USAGE_EXAMPLES = [\n [ 'xBuild src/index.ts', 'Build a single file with default settings' ],\n [ 'xBuild src/**/*.ts --bundle --minify', 'Bundle and minify all TypeScript files' ],\n [ 'xBuild src/app.ts -s', 'Development mode with watch and dev server' ],\n [ 'xBuild src/app.ts -s dist', 'Development mode with watch and dev server from dist folder' ],\n [ 'xBuild src/lib.ts --format esm --declaration', 'Build ESM library with type definitions' ],\n [ 'xBuild src/server.ts --platform node --outdir dist', 'Build Node.js application to dist folder' ],\n [ 'xBuild --typeCheck', 'Type check only without generating output' ],\n [ 'xBuild --config custom.xbuild.ts', 'Use custom configuration file' ]\n] as const;\n", "/**\n * Imports\n */\n\nimport readline from 'readline';\nimport { exec } from 'child_process';\nimport { patchConfig } from '../index';\nimport { inject } from '@symlinks/symlinks.module';\nimport { prefix } from '@components/banner.component';\nimport { platform, exit, stdin, stdout } from 'process';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { EXIT_SIGNALS, KEY_MAPPINGS, COMMAND_MAP } from '@components/constants/interactive.constant';\n\n/**\n * Generates a formatted help message displaying available keyboard shortcuts.\n *\n * @param activeUrl - Whether to include URL-related shortcuts (show/open in browser)\n * @returns A formatted multi-line string containing all available shortcuts\n *\n * @remarks\n * Dynamically builds a help menu based on the current context. When a server is active\n * (indicated by `activeUrl`), additional shortcuts for URL display and browser opening are included.\n *\n * The output uses ANSI styling via {@link xterm} for visual hierarchy:\n * - Dimmed prefix text \"press\"\n * - Bold key name\n * - Dimmed action description\n *\n * **Shortcuts included**:\n * - `u` - Show server URL (when `activeUrl` is true)\n * - `o` - Open in browser (when `activeUrl` is true)\n * - `v` - Toggle verbose mode\n * - `r` - Reload/restart build\n * - `c` - Clear console\n * - `q` - Quit application\n *\n * @example\n * ```ts\n * const helpText = generateHelp(true);\n * console.log(helpText);\n * // Output:\n * // \uD83D\uDE80 Shortcuts\n * // press u to show server url\n * // press o to open in browser\n * // press v to enable / disable verbose mode\n * // ...\n * ```\n *\n * @see {@link xterm} for ANSI styling\n * @see {@link KEY_MAPPINGS} for key definitions\n *\n * @since 2.0.0\n */\n\nexport function generateHelp(activeUrl: boolean = false): string {\n const shortcuts: Array<string> = [ '\uD83D\uDE80 Shortcuts' ];\n const prefix = xterm.dim(' press ');\n\n const addShortcut = (key: string, description: string): void => {\n shortcuts.push(`${ prefix }${ xterm.bold(key) }${ xterm.dim(description) }`);\n };\n\n if (activeUrl) {\n addShortcut(KEY_MAPPINGS.SHOW_URL, ' to show server url');\n addShortcut(KEY_MAPPINGS.OPEN_BROWSER, ' to open in browser');\n }\n\n addShortcut(KEY_MAPPINGS.VERBOSE, ' to enable / disable verbose mode');\n addShortcut(KEY_MAPPINGS.RELOAD, ' to reload');\n addShortcut(KEY_MAPPINGS.CLEAR, ' to clear console');\n addShortcut(KEY_MAPPINGS.QUIT, ' to quit\\n');\n\n return shortcuts.join('\\n');\n}\n\n/**\n * Clears the terminal screen without scrollback, moving the cursor to the top.\n *\n * @remarks\n * Performs a visual clear by:\n * 1. Calculating available terminal rows (minus 2 for buffer)\n * 2. Printing newlines to push content out of view\n * 3. Moving cursor to position (0, 0)\n * 4. Clearing all content from the cursor downward\n *\n * This approach ensures a clean visual reset without modifying scrollback history.\n * The function is safe to call regardless of terminal size; it handles small terminals\n * gracefully by ensuring `repeatCount` is never negative.\n *\n * @example\n * ```ts\n * // User presses 'c' to clear console\n * clearScreen();\n * // Terminal is cleared, cursor at top-left\n * ```\n *\n * @see {@link handleKeypress} for usage in keypress handling\n *\n * @since 2.0.0\n */\n\nexport function clearScreen(): void {\n const repeatCount = Math.max(0, stdout.rows - 2);\n if (repeatCount > 0) {\n console.log('\\n'.repeat(repeatCount));\n }\n\n readline.cursorTo(stdout, 0, 0);\n readline.clearScreenDown(stdout);\n}\n\n/**\n * Opens the specified URL in the system's default browser.\n *\n * @param url - The URL to open in the browser\n *\n * @remarks\n * Provides cross-platform browser opening by executing the appropriate shell command\n * for the current operating system:\n * - **Windows**: `start <url>`\n * - **macOS**: `open <url>`\n * - **Linux**: `xdg-open <url>` (also used as fallback)\n *\n * The function uses Node.js {@link exec} to spawn the command asynchronously.\n * No error handling is performed; if the command fails, it silently continues.\n *\n * @example\n * ```ts\n * // User presses 'o' to open server URL\n * openInBrowser('http://localhost:3000');\n * // Browser opens with the specified URL\n * ```\n *\n * @see {@link COMMAND_MAP} for platform-to-command mapping\n * @see {@link handleKeypress} for usage in keypress handling\n *\n * @since 2.0.0\n */\n\nexport function openInBrowser(url: string): void {\n const command = COMMAND_MAP[<keyof typeof COMMAND_MAP> platform] ?? 'xdg-open';\n exec(`${ command } ${ url }`);\n}\n\n/**\n * Handles keyboard input events and executes corresponding actions.\n *\n * @param code - The raw character code from the keypress event\n * @param key - The parsed key information including name, sequence, and modifiers\n * @param reload - Callback function to trigger a build reload/restart\n * @param help - Pre-generated help text to display when help key is pressed\n * @param url - Optional server URL for URL display and browser opening features\n *\n * @remarks\n * Acts as the central dispatcher for interactive terminal commands. Processes both\n * exit signals (Ctrl+C, Ctrl+D) and single-key shortcuts, executing appropriate actions\n * for each recognized input.\n *\n * **Processing flow**:\n * 1. Validates key information exists\n * 2. Checks for exit signals \u2192 exits with code 1\n * 3. Matches key name against {@link KEY_MAPPINGS}\n * 4. Executes corresponding action (clear, reload, toggle verbose, etc.)\n *\n * **Available actions**:\n * - **Clear** (`c`): Clears the terminal screen\n * - **Verbose** (`v`): Toggles verbose/debug mode via {@link ConfigurationService}\n * - **Reload** (`r`): Clears screen and invokes the reload callback\n * - **Help** (`h`): Displays the help menu\n * - **Show URL** (`u`): Prints the server URL (if provided)\n * - **Open Browser** (`o`): Opens the server URL in browser (if provided)\n * - **Quit** (`q`): Exits the process with a goodbye message\n *\n * The function safely handles cases where `url` is undefined by checking existence\n * before executing URL-dependent actions.\n *\n * @example Basic usage\n * ```ts\n * handleKeypress('r', { name: 'r' }, async () => rebuild(), helpText);\n * // Clears screen and triggers rebuild\n * ```\n *\n * @example Exit signal\n * ```ts\n * handleKeypress('\\x03', { name: 'c', sequence: '\\x03' }, reload, help);\n * // Prints \"\uD83D\uDC4B Exiting...\" and exits with code 1\n * ```\n *\n * @example Toggle verbose\n * ```ts\n * // Current verbose: false\n * handleKeypress('v', { name: 'v' }, reload, help);\n * // Prints: \"\uD83D\uDC1E Debug mode: ENABLED\"\n * // Updates config: { verbose: true }\n * ```\n *\n * @see {@link init} for event listener setup\n * @see {@link EXIT_SIGNALS} for exit signal codes\n * @see {@link KEY_MAPPINGS} for recognized key names\n *\n * @since 2.0.0\n */\n\nexport function handleKeypress(code: string, key: readline.Key, reload: () => void, help: string, url?: string): void {\n if (!key?.name) return;\n if (key.sequence === KEY_MAPPINGS.QUIT || code === EXIT_SIGNALS.SIGINT || code === EXIT_SIGNALS.SIGQUIT) {\n console.log('\\n\uD83D\uDC4B Exiting...');\n exit(1);\n }\n\n switch (key.name) {\n case KEY_MAPPINGS.CLEAR:\n clearScreen();\n break;\n case KEY_MAPPINGS.VERBOSE:\n const verbose = inject(ConfigurationService).getValue(cfg => cfg.verbose);\n console.log(`\uD83D\uDC1E Debug mode: ${ !verbose ? 'ENABLED' : 'DISABLED' }`);\n patchConfig({ verbose: !verbose });\n break;\n case KEY_MAPPINGS.RELOAD:\n clearScreen();\n reload();\n break;\n case KEY_MAPPINGS.HELP:\n clearScreen();\n console.log(help);\n break;\n case KEY_MAPPINGS.SHOW_URL:\n if (url) {\n console.log(`${ prefix() } ${ xterm.canaryYellow(url) }`);\n }\n break;\n case KEY_MAPPINGS.OPEN_BROWSER:\n if (url) {\n openInBrowser(url);\n }\n break;\n }\n}\n\n/**\n * Initializes the interactive terminal interface for watch mode.\n *\n * @param reload - Callback function to trigger a build reload/restart when requested\n * @param url - Optional server URL to enable URL-related shortcuts and functionality\n *\n * @remarks\n * Sets up the interactive development environment by configuring the terminal for raw\n * input mode and registering keypress event handlers. This function should be called\n * once during watch mode initialization.\n *\n * **Initialization flow**:\n * 1. **TTY check**: Exits early if stdin is not a TTY (e.g., piped input, CI environment)\n * 2. **Help generation**: Creates context-aware help text based on URL availability\n * 3. **Help display**: Prints the shortcuts menu immediately\n * 4. **Raw mode**: Enables character-by-character input without requiring Enter\n * 5. **Event setup**: Configures keypress event emission and registers handler\n *\n * **TTY requirement**:\n * Interactive mode is disabled when stdin is not a TTY. This prevents issues in:\n * - CI/CD pipelines\n * - Piped/redirected input scenarios\n * - Non-interactive shells\n *\n * **Raw mode implications**:\n * - Characters are processed immediately without buffering\n * - Standard terminal line editing (backspace, etc.) is disabled\n * - Allows single-key shortcuts without an Enter key\n *\n * The function keeps the process alive by registering an event listener, which should\n * persist for the duration of the watch session.\n *\n * @example Basic initialization\n * ```ts\n * // In watch mode without server\n * init(async () => {\n * await rebuild();\n * });\n * // Displays shortcuts without URL options\n * ```\n *\n * @example With server URL\n * ```ts\n * // In watch mode with dev server\n * init(async () => {\n * await rebuild();\n * }, 'http://localhost:3000');\n * // Displays all shortcuts including 'u' and 'o'\n * ```\n *\n * @example Non-TTY environment (CI)\n * ```ts\n * // stdin.isTTY === false\n * init(reload, url);\n * // Function returns immediately without setup\n * ```\n *\n * @see {@link generateHelp} for help text generation\n * @see {@link handleKeypress} for keypress handling logic\n *\n * @since 2.0.0\n */\n\nexport function init(reload: () => void, url?: string): void {\n if (!stdin.isTTY) return;\n const helpString = generateHelp(!!url);\n console.log(helpString);\n\n stdin.setRawMode(true);\n readline.emitKeypressEvents(stdin);\n stdin.on('keypress', (code, key) => {\n handleKeypress(code, key, reload, helpString, url);\n });\n}\n\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ParseGlobInterface } from '@components/interfaces/glob-component.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { readdirSync } from 'fs';\nimport { matchesGlob } from 'path';\nimport { join } from '@components/path.component';\n\n/**\n * Separates glob patterns into include and exclude arrays.\n *\n * @param globs - Array of glob patterns (patterns starting with '!' are treated as excludes)\n * @returns Object containing separate include and exclude pattern arrays\n *\n * @example\n * ```ts\n * const { include, exclude } = parseGlobs([\n * '**\\/*.ts',\n * '!**\\/*.test.ts',\n * '**\\/*.js',\n * '!node_modules/**'\n * ]);\n * // include: ['**\\/*.ts', '**\\/*.js']\n * // exclude: ['**\\/*.test.ts', 'node_modules/**']\n * ```\n *\n * @since 2.0.0\n */\n\nexport function parseGlobs(globs: Array<string>): ParseGlobInterface {\n const include: Array<string> = [];\n const exclude: Array<string> = [];\n\n for (const g of globs) {\n if (g.startsWith('!')) {\n exclude.push(g.slice(1));\n } else {\n include.push(g);\n }\n }\n\n return { include, exclude };\n}\n\n/**\n * Checks if a path matches any pattern in the provided array.\n *\n * @param p - Path to test against patterns\n * @param patterns - Array of glob patterns to match against\n * @returns True if a path matches at least one pattern, false otherwise\n *\n * @remarks\n * Uses early exit optimization - stops checking as soon as a match is found.\n * A pattern is treated as a match when either:\n * - The pattern string ends with the provided path\n * - `matchesGlob(p, pattern)` returns true\n *\n * @example\n * ```ts\n * matchesAny('src/app.ts', ['**\\/*.ts', '**\\/*.js']); // true\n * matchesAny('src/app.ts', ['prefix/src/app.ts']); // true (suffix check)\n * matchesAny('README.md', ['**\\/*.ts', '**\\/*.js']); // false\n * ```\n *\n * @see matchesGlob\n * @since 2.0.0\n */\n\nexport function matchesAny(p: string, patterns: Array<string>): boolean {\n for (const pattern of patterns) {\n if (pattern.endsWith(p) || matchesGlob(p, pattern)) return true;\n }\n\n return false;\n}\n\n/**\n * Determines if a directory should be excluded from traversal.\n *\n * @param relativePath - Relative path of the directory to check\n * @param exclude - Array of glob patterns for exclusion\n * @returns True if directory matches any exclude pattern, false otherwise\n *\n * @remarks\n * Checks both the directory path itself and the directory with `/**` appended\n * to properly handle patterns like `node_modules/**`.\n *\n * @example\n * ```ts\n * isDirectoryExcluded('node_modules', ['node_modules/**']); // true\n * isDirectoryExcluded('src', ['node_modules/**']); // false\n * ```\n *\n * @see matchesGlob\n * @since 2.0.0\n */\n\nexport function isDirectoryExcluded(relativePath: string, exclude: Array<string>): boolean {\n const dirWithGlob = relativePath + '/**';\n\n for (const pattern of exclude) {\n if (matchesGlob(relativePath, pattern) || matchesGlob(dirWithGlob, pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n\n/**\n * Determines if a file should be included based on include and exclude patterns.\n *\n * @param relativePath - Relative path of the file to check\n * @param include - Array of glob patterns for inclusion\n * @param exclude - Array of glob patterns for exclusion\n * @returns True if file matches include patterns and not exclude patterns, false otherwise\n *\n * @remarks\n * A file must match at least one include pattern AND not match any exclude pattern\n * to be considered for inclusion.\n *\n * @example\n * ```ts\n * shouldIncludeFile('src/app.ts', ['**\\/*.ts'], ['**\\/*.test.ts']); // true\n * shouldIncludeFile('src/app.test.ts', ['**\\/*.ts'], ['**\\/*.test.ts']); // false\n * ```\n *\n * @see matchesAny\n * @since 2.0.0\n */\n\nexport function shouldIncludeFile(relativePath: string, include: Array<string>, exclude: Array<string>): boolean {\n // Must match at least one an include pattern\n if (!matchesAny(relativePath, include)) return false;\n\n // Must NOT match any exclude pattern\n return !matchesAny(relativePath, exclude);\n}\n\n/**\n * Collects files matching glob patterns from a directory tree.\n *\n * @param baseDir - Base directory to start searching from\n * @param globs - Array of glob patterns (use '!' prefix to exclude)\n * @returns Record mapping file paths without extension to full file paths\n *\n * @remarks\n * This function performs a depth-first traversal with several optimizations:\n * - Separates include/exclude patterns once upfront\n * - Early exits on excluded directories to avoid unnecessary traversal\n * - Returns Record instead of Array for O(1) lookups\n * - Keys are relative to baseDir (without extension)\n * - Values are relative to process.cwd() (with extension)\n * - Optimized with cached length calculations and index-based loops\n * - Avoids unnecessary string allocations\n *\n * @example\n * ```ts\n * // If baseDir is 'src' and file is at <cwd>/src/errors/uncaught-error.spec.ts\n * const files = collectFilesFromGlob('src', ['**\\/*.ts']);\n * // Returns: { 'errors/uncaught-error.spec': 'src/errors/uncaught-error.spec.ts' }\n * ```\n *\n * @since 2.0.0\n */\n\nexport function collectFilesFromGlob(baseDir: string, globs: Array<string>): Record<string, string> {\n const { include, exclude } = parseGlobs(globs);\n const collected: Record<string, string> = Object.create(null);\n const cwdPath = cwd();\n const rootDirLength = cwdPath.length + 1; // +1 for trailing slash\n const baseDirLength = baseDir.length + 1; // +1 for trailing slash\n const hasExcludes = exclude.length > 0;\n\n function walk(dir: string): void {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n const len = entries.length;\n for (let i = 0; i < len; i++) {\n const entry = entries[i];\n const fullPath = join(dir, entry.name);\n const relativeFromBase = fullPath.slice(baseDirLength);\n\n if (entry.isDirectory()) {\n if (!hasExcludes || !isDirectoryExcluded(relativeFromBase, exclude)) walk(fullPath);\n continue;\n }\n\n if (hasExcludes && matchesAny(relativeFromBase, exclude)) continue;\n if (matchesAny(relativeFromBase, include)) {\n const relativeFromRoot = fullPath.slice(rootDirLength);\n const lastDotIndex = relativeFromBase.lastIndexOf('.');\n const keyPath = lastDotIndex > 0 ? relativeFromBase.slice(0, lastDotIndex) : relativeFromBase;\n\n collected[keyPath] = relativeFromRoot;\n }\n }\n }\n\n walk(baseDir);\n\n return collected;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DiagnosticInterface } from '@typescript/typescript.module';\n\n/**\n * Represents a TypeScript type checking error with associated diagnostic information.\n *\n * @remarks\n * The `TypesError` class extends the native `Error` class to provide enhanced error reporting\n * for TypeScript type checking failures. It captures and preserves diagnostic information\n * from TypeScript's type checker, allowing structured access to individual diagnostics.\n *\n * **Error context**:\n * Each `TypesError` can contain zero or more {@link DiagnosticInterface} objects that provide:\n * - Source file location (file path, line, column)\n * - Diagnostic code for error identification\n * - Detailed error messages\n *\n * @example\n * ```ts\n * import { TypesError } from '@errors/types.error';\n * import type { DiagnosticInterface } from '@typescript/interfaces/typescript.interface';\n *\n * // Create error with diagnostics from type checker\n * const diagnostics: DiagnosticInterface[] = [\n * {\n * file: 'src/index.ts',\n * line: 10,\n * column: 5,\n * code: 2322,\n * message: 'Type \"string\" is not assignable to type \"number\"'\n * }\n * ];\n *\n * throw new TypesError('Type checking failed', diagnostics);\n * ```\n *\n * @see {@link Typescript.check} for type checking context\n * @see {@link DiagnosticInterface} for diagnostic structure\n *\n * @since 2.0.0\n */\n\nexport class TypesError extends Error {\n\n /**\n * Array of diagnostic information from TypeScript type checking.\n *\n * @remarks\n * Contains all diagnostics collected during type checking that led to this error.\n * May be empty if the error is not directly related to specific diagnostics.\n *\n * Each diagnostic includes:\n * - **file**: Source file path relative to project root\n * - **line**: 1-based line number where the issue occurred\n * - **column**: 1-based column number where the issue occurred\n * - **code**: TypeScript error code for identifying error type\n * - **message**: Human-readable error description\n *\n * Read-only to prevent modification after error creation.\n *\n * @example\n * ```ts\n * const error = new TypesError('Type check failed', diagnostics);\n * for (const diag of error.diagnostics) {\n * console.log(`${diag.file}:${diag.line}:${diag.column} - ${diag.message}`);\n * }\n * ```\n *\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\n readonly diagnostics: Array<DiagnosticInterface>;\n\n /**\n * Creates a new instance of `TypesError`.\n *\n * @param message - Optional error message describing the type checking failure\n * @param diagnostics - Optional array of diagnostic information (defaults to an empty array)\n *\n * @remarks\n * Initializes the error with:\n * 1. Message passed to parent `Error` class\n * 2. Error name set to `'TypesError'` for identification\n * 3. Stored diagnostics array for later inspection\n * 4. Prototype chain properly configured for instanceof checks\n *\n * **Prototype chain setup**:\n * Sets the prototype explicitly to ensure `instanceof` checks work correctly\n * across different execution contexts and transpilation scenarios.\n *\n * @example\n * ```ts\n * // Create error with message and diagnostics\n * const error = new TypesError('Type checking failed', [{\n * file: 'src/app.ts',\n * line: 42,\n * column: 15,\n * code: 2339,\n * message: 'Property \"config\" does not exist'\n * }]);\n *\n * // Create error with a message only\n * const simple = new TypesError('Type checking failed');\n *\n * // Create error with diagnostics only\n * const diag = new TypesError(undefined, diagnostics);\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(message?: string, diagnostics: Array<DiagnosticInterface> = []) {\n super(message);\n this.name = 'TypesError';\n this.diagnostics = diagnostics;\n\n Object.setPrototypeOf(this, TypesError.prototype);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\n\n/**\n * Represents a generic xBuild framework error.\n *\n * Extends {@link xBuildBaseError} and automatically formats the stack trace\n * according to the provided options.\n *\n * @remarks\n * This class is intended for general-purpose errors within the xBuild framework.\n * The stack trace is formatted automatically during construction, with\n * framework-specific frames included by default.\n *\n * @example\n * ```ts\n * throw new xBuildError('An unexpected error occurred');\n * ```\n *\n * @since 1.0.0\n */\n\nexport class xBuildError extends xBuildBaseError {\n\n /**\n * Creates a new instance of `xBuildError`.\n *\n * @param message - The error message to display\n * @param options - Optional stack trace formatting options (default includes framework frames)\n *\n * @remarks\n * The constructor passes the message to the base `xBuildBaseError` class,\n * then reformats the stack trace using {@link xBuildBaseError.reformatStack}.\n *\n * @since 1.0.0\n */\n\n constructor(message: string, options: StackTraceInterface = { withFrameworkFrames: true }) {\n super(message);\n this.reformatStack(this, options);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PartialMessage } from 'esbuild';\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\nimport { getErrorMetadata, formatStack } from '@providers/stack.provider';\n\n/**\n * Normalized runtime error wrapper for esbuild diagnostics.\n *\n * @remarks\n * `esBuildError` converts an esbuild {@link PartialMessage} into an {@link xBuildBaseError}\n * with framework-aware metadata and a formatted stack string.\n *\n * Construction behavior:\n * - Uses `message.text` as the runtime error message (defaults to empty string)\n * - Copies `message.id` to {@link id} (defaults to empty string)\n * - Builds structured metadata via {@link getErrorMetadata}\n * - Replaces `stack` using {@link formatStack}, including any diagnostic notes\n *\n * @example\n * ```ts\n * const message = {\n * id: 'transform',\n * text: 'Unexpected token',\n * location: { file: 'src/index.ts', line: 1, column: 5 },\n * notes: [{ text: 'Check syntax near this token' }]\n * };\n *\n * const error = new esBuildError(message);\n * console.error(error.id); // \"transform\"\n * console.error(error.stack);\n * ```\n *\n * @see {@link xBuildBaseError}\n * @see {@link getErrorMetadata}\n * @see {@link formatStack}\n *\n * @since 2.0.0\n */\n\nexport class esBuildError extends xBuildBaseError {\n /**\n * Optional esbuild diagnostic identifier copied from `PartialMessage.id`.\n *\n * @remarks\n * This value is useful for categorizing diagnostics by producer (for example,\n * plugin- or phase-specific IDs). When absent in the source message, it defaults\n * to an empty string.\n *\n * @since 2.0.0\n */\n\n readonly id: string;\n\n /**\n * Creates a new esbuild error with formatted output and metadata.\n *\n * @param message - The esbuild {@link PartialMessage} containing diagnostic details\n * @param options - Optional stack parsing/formatting options used when deriving metadata\n *\n * @remarks\n * The constructor:\n * 1. Initializes the base error with `message.text ?? ''`\n * 2. Persists `message.id ?? ''` on {@link id}\n * 3. If `message.detail` is an `Error`, uses its `message` and `stack` as runtime values\n * 4. Builds structured metadata from either the original message or `detail` error\n * 5. Produces formatted output (stack replacement for message-based diagnostics, or\n * formatted inspector output for `detail`-based diagnostics)\n *\n * The error name is always set to `'esBuildError'`. Formatted output includes:\n * - Error name and message with color coding\n * - Any diagnostic notes from esbuild\n * - Highlighted code snippet showing the error location\n * - Enhanced stack trace with file path and position\n *\n * @see {@link getErrorMetadata} for formatting logic\n * @see {@link PartialMessage} for esbuild message structure\n *\n * @since 2.0.0\n */\n\n constructor(message: PartialMessage, options?: StackTraceInterface) {\n super(message.text ?? '', 'esBuildError');\n\n this.id = message.id ?? '';\n if(message.detail instanceof Error) {\n this.stack = message.detail.stack;\n this.message = message.detail.message;\n this.reformatStack(message.detail, options);\n } else {\n this.errorMetadata = getErrorMetadata(message, { withFrameworkFrames: true });\n this.stack = formatStack(this.errorMetadata, this.name, this.message, message.notes);\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildResult, Message } from 'esbuild';\nimport type { BuildResultInterface } from './interfaces/esbuild-messages-provider.interface';\n\n/**\n * Imports\n */\n\nimport { TypesError } from '@errors/types.error';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { xBuildBaseError } from '@errors/base.error';\nimport { esBuildError } from '@errors/esbuild.error';\n\n/**\n * Converts an esbuild message to a normalized Error instance.\n *\n * @param msg - The esbuild message object containing error or warning details\n * @returns A normalized Error instance appropriate for the message type\n *\n * @remarks\n * This function handles different types of esbuild messages and converts them to the appropriate\n * error classes used throughout the xBuild system. It prioritizes preserving existing error\n * instances while wrapping raw messages in appropriate error types.\n *\n * **Conversion priority**:\n * 1. If `msg.detail` is already an `xBuildBaseError` or `TypesError`, return it unchanged\n * 2. If `msg.detail` is any other Error, wrap it in `VMRuntimeError` with framework frames\n * 3. If `msg.location` exists, create an `esBuildError` with a formatted code snippet\n * 4. Otherwise, wrap the message text in a `VMRuntimeError`\n *\n * This normalization ensures consistent error handling and reporting throughout the build\n * pipeline, with appropriate context and formatting for each error type.\n *\n * @example\n * ```ts\n * // Message with location information\n * const msg: Message = {\n * text: 'Unexpected token',\n * location: { file: 'src/index.ts', line: 10, column: 5 }\n * };\n * const error = normalizeMessageToError(msg);\n * // Returns esBuildError with formatted code snippet\n *\n * // Message with existing error detail\n * const msgWithError: Message = {\n * text: 'Build failed',\n * detail: new TypesError('Type checking failed', [])\n * };\n * const error2 = normalizeMessageToError(msgWithError);\n * // Returns the TypesError unchanged\n * ```\n *\n * @see {@link TypesError}\n * @see {@link esBuildError}\n * @see {@link VMRuntimeError}\n * @see {@link xBuildBaseError}\n *\n * @since 2.0.0\n */\n\nexport function normalizeMessageToError(msg: Message | esBuildError): Error | undefined {\n if (msg instanceof xBuildBaseError)\n return msg;\n\n if (msg.detail instanceof xBuildBaseError || msg.detail instanceof TypesError)\n return msg.detail;\n\n if (msg.detail instanceof Error)\n return new esBuildError(msg, { withFrameworkFrames: true });\n\n if (msg.location)\n return new esBuildError(msg);\n\n if(msg.text)\n return new xBuildError(msg.text);\n}\n\n/**\n * Processes an array of esbuild messages and converts them to normalized errors.\n *\n * @param messages - Array of esbuild message objects to process\n * @param target - Array to populate with normalized error instances\n *\n * @remarks\n * This function iterates through esbuild messages and converts each one to a normalized\n * Error instance using {@link normalizeMessageToError}, appending the results to the\n * target array.\n *\n * The target array is modified in place, allowing errors and warnings from different\n * sources to be aggregated into the same collection.\n *\n * **Processing behavior**:\n * - Each message is converted independently\n * - Conversion failures do not stop processing of remaining messages\n * - a Target array is modified in place (no return value)\n * - Empty message arrays are handled gracefully\n *\n * Common use cases:\n * - Converting esbuild error arrays to normalized errors\n * - Converting esbuild warning arrays to normalized errors\n * - Aggregating messages from multiple build results\n *\n * @example\n * ```ts\n * const buildResult: BuildResult = await build({ ... });\n * const errors: Array<Error> = [];\n * const warnings: Array<Error> = [];\n *\n * // Process errors and warnings\n * processEsbuildMessages(buildResult.errors, errors);\n * processEsbuildMessages(buildResult.warnings, warnings);\n *\n * console.log(`Build completed with ${errors.length} errors and ${warnings.length} warnings`);\n * ```\n *\n * @see {@link enhancedBuildResult}\n * @see {@link normalizeMessageToError}\n *\n * @since 2.0.0\n */\n\nexport function processEsbuildMessages(messages: Array<Message> = [], target: Array<Error>): void {\n for (const msg of messages) {\n const error = normalizeMessageToError(msg);\n if(error) target.push(error);\n }\n}\n\n/**\n * Converts esbuild's BuildResult into xBuild's BuildResultInterface with normalized errors.\n *\n * @param source - Partial esbuild BuildResult containing build artifacts and messages\n * @returns A BuildResultInterface with normalized errors and warnings\n *\n * @remarks\n * This function transforms esbuild's build result into the xBuild-specific result interface,\n * converting all error and warning messages to normalized Error instances while preserving\n * build artifacts like metafiles, output files, and mangle cache.\n *\n * **Transformation process**:\n * 1. Creates a new BuildResultInterface with empty error/warning arrays\n * 2. Copies build artifacts (metafile, outputFiles, mangleCache) directly\n * 3. Processes errors array through {@link processEsbuildMessages}\n * 4. Processes warnings array through {@link processEsbuildMessages}\n * 5. Returns the fully populated result object\n *\n * **Preserved artifacts**:\n * - `metafile`: Build metadata including inputs, outputs, and dependencies\n * - `outputFiles`: Generated file contents when `write: false`\n * - `mangleCache`: Identifier mangling cache for consistent minification\n *\n * All esbuild Message objects are converted to Error instances, providing consistent\n * error handling throughout the xBuild system with proper stack traces, formatting,\n * and error classification.\n *\n * @example\n * ```ts\n * const esbuildResult = await build({\n * entryPoints: ['src/index.ts'],\n * write: false,\n * metafile: true\n * });\n *\n * const result = enhancedBuildResult(esbuildResult);\n * // result.errors: Array<Error> (normalized)\n * // result.warnings: Array<Error> (normalized)\n * // result.metafile: Metafile (preserved)\n * // result.outputFiles: OutputFile[] (preserved)\n *\n * console.log(`Build produced ${result.errors.length} errors`);\n * ```\n *\n * @see {@link BuildResultInterface}\n * @see {@link processEsbuildMessages}\n * @see {@link normalizeMessageToError}\n *\n * @since 2.0.0\n */\n\nexport function enhancedBuildResult(source: Partial<BuildResult>): BuildResultInterface {\n const target: BuildResultInterface = {\n errors: [],\n warnings: [],\n metafile: source.metafile,\n outputFiles: source.outputFiles,\n mangleCache: source.mangleCache\n };\n\n processEsbuildMessages(source.errors, target.errors);\n processEsbuildMessages(source.warnings, target.warnings);\n\n return target;\n}\n\n/**\n * Type guard that checks if an unknown value is an esbuild BuildResult error object.\n *\n * @param error - The value to check, typically from a catch block\n * @returns `true` if the value is a BuildResult with errors property, `false` otherwise\n *\n * @remarks\n * This type guard validates that an error object follows the esbuild BuildResult structure,\n * which includes an `errors` property. It's useful for distinguishing between esbuild-specific\n * errors and other error types during error handling.\n *\n * The function performs two checks:\n * 1. Verifies the value is an object (not null)\n * 2. Checks for the presence of an `errors` property\n *\n * When the function returns `true`, TypeScript will narrow the type of the parameter to\n * `BuildResult`, allowing type-safe access to BuildResult properties like `errors`,\n * `warnings`, `metafile`, etc.\n *\n * Common use cases:\n * - Catch block error type discrimination\n * - Conditional error handling based on an error source\n * - Type narrowing for BuildResult-specific error processing\n *\n * @example\n * ```ts\n * try {\n * await build({ entryPoints: ['src/index.ts'] });\n * } catch (error) {\n * if (isBuildResultError(error)) {\n * // TypeScript knows error is BuildResult here\n * console.error(`Build failed with ${error.errors.length} errors`);\n * processEsbuildMessages(error.errors, errorList);\n * } else if (error instanceof Error) {\n * // Handle generic errors\n * console.error(error.message);\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // In error aggregation\n * const errors: Array<Error> = [];\n *\n * if (isBuildResultError(caughtError)) {\n * const result = enhancedBuildResult(caughtError);\n * errors.push(...result.errors);\n * } else {\n * errors.push(new Error(String(caughtError)));\n * }\n * ```\n *\n * @see {@link BuildResult}\n * @see {@link enhancedBuildResult}\n * @see {@link processEsbuildMessages}\n *\n * @since 2.0.0\n */\n\nexport function isBuildResultError(error: unknown): error is BuildResult {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { ServerConfigurationInterface } from '@server/interfaces/server.interface';\n\n/**\n * Imports\n */\n\nimport * as http from 'http';\nimport * as https from 'https';\nimport { extname } from 'path';\nimport { readFileSync } from 'fs';\nimport html from './html/server.html';\nimport { inject } from '@symlinks/symlinks.module';\nimport { prefix } from '@components/banner.component';\nimport { readdir, stat, readFile } from 'fs/promises';\nimport { resolve, join } from '@components/path.component';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { FrameworkService } from '@services/framework.service';\n\n/**\n * Provides a basic HTTP/HTTPS server module with static file serving\n * and directory listing capabilities.\n *\n * @remarks\n * The `ServerModule` supports serving static files, directories, and\n * optional HTTPS configuration. It handles request logging and error\n * responses and can invoke user-defined hooks via the configuration.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * server.start();\n * ```\n *\n * @see ServerConfigurationInterface\n * @since 2.0.0\n */\n\nexport class ServerModule {\n\n /**\n * The underlying HTTP or HTTPS server instance.\n *\n * @remarks\n * This property holds the active server instance created by either {@link startHttpServer}\n * or {@link startHttpsServer}. It remains undefined until {@link start} is called.\n * The server instance is used to manage the lifecycle of the HTTP/HTTPS server,\n * including stopping and restarting operations.\n *\n * @see start\n * @see stop\n * @see restart\n * @see startHttpServer\n * @see startHttpsServer\n *\n * @since 2.0.0\n */\n\n private server?: http.Server;\n\n /**\n * Normalized absolute root directory for serving files.\n *\n * @readonly\n * @since 2.0.0\n */\n\n private readonly rootDir: string;\n\n /**\n * Injected {@link FrameworkService} instance used for path resolution and framework assets.\n *\n * @readonly\n * @see FrameworkService\n *\n * @since 2.0.0\n */\n\n private readonly framework = inject(FrameworkService);\n\n /**\n * Initializes a new {@link ServerModule} instance.\n *\n * @param config - Server configuration including host, port, HTTPS options, and hooks.\n * @param dir - Root directory from which files will be served.\n *\n * @example\n * ```ts\n * import { ServerProvider } from './server-provider';\n *\n * const serverConfig = {\n * port: 8080,\n * keyfile: './path/to/keyfile',\n * certfile: './path/to/certfile',\n * onRequest: (req, res, next) => { /* custom request handling *\\/ }\n * };\n * const provider = new ServerProvider(serverConfig, './public');\n * provider.start();\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(readonly config: ServerConfigurationInterface, dir: string) {\n this.rootDir = resolve(dir);\n this.config.port ||= 0;\n this.config.host ||= 'localhost';\n }\n\n /**\n * Starts the HTTP or HTTPS server based on configuration.\n *\n * @returns A promise that resolves when the server is fully started and listening.\n *\n * @remarks\n * This method performs the following steps:\n * 1. Invokes the optional {@link ServerConfigurationInterface.onStart} hook if provided.\n * 2. Determines whether to start an HTTPS or HTTP server based on the {@link ServerConfigurationInterface.https} flag.\n * 3. Calls {@link startHttpsServer} if HTTPS is enabled, otherwise calls {@link startHttpServer}.\n *\n * @example\n * ```ts\n * const server = new ServerModule({\n * port: 3000,\n * host: 'localhost',\n * https: true,\n * onStart: () => console.log('Server starting...')\n * }, '/var/www');\n * await server.start();\n * ```\n *\n * @see stop\n * @see restart\n * @see startHttpServer\n * @see startHttpsServer\n * @see ServerConfigurationInterface\n *\n * @since 2.0.0\n */\n\n async start(): Promise<void> {\n if (this.config.https)\n return await this.startHttpsServer();\n\n await this.startHttpServer();\n }\n\n /**\n * Stops the running HTTP or HTTPS server.\n *\n * @returns A promise that resolves when the server is fully stopped.\n *\n * @remarks\n * This method gracefully shuts down the server by closing all active connections.\n * If no server is currently running, it logs a message and returns early.\n * Once stopped, the {@link server} instance is set to `undefined`.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * server.start();\n * // Later...\n * await server.stop();\n * ```\n *\n * @see start\n * @see server\n * @see restart\n *\n * @since 2.0.0\n */\n\n async stop(): Promise<void> {\n if (!this.server) {\n console.log(prefix(), xterm.gray('No server is currently running.'));\n\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n this.server!.close(err => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n console.log(prefix(), xterm.dim('Server stopped.'));\n this.server = undefined;\n }\n\n /**\n * Restarts the HTTP or HTTPS server.\n *\n * @returns A promise that resolves when the server has been stopped and restarted.\n *\n * @remarks\n * This method performs a graceful restart by first calling {@link stop} to shut down\n * the current server instance, then calling {@link start} to create a new server\n * with the same configuration. This is useful when configuration changes need to be\n * applied or when recovering from errors.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * server.start();\n * // Later, restart the server...\n * await server.restart();\n * ```\n *\n * @see stop\n * @see start\n *\n * @since 2.0.0\n */\n\n async restart(): Promise<void> {\n console.log(prefix(), xterm.burntOrange('Restarting server...'));\n await this.stop();\n await this.start();\n }\n\n /**\n * Updates the configuration with the actual port assigned by the system.\n *\n * @remarks\n * This method is called after the server starts listening to retrieve and store the\n * actual port number when port `0` was specified in the configuration. When port `0`\n * is used, the operating system automatically assigns an available port, and this\n * method captures that assigned port for use throughout the application.\n *\n * **When this method is needed**:\n * - {@link ServerConfigurationInterface.port} is set to `0` (dynamic port allocation)\n * - The server has started and bound to a port\n * - The actual port needs to be known for logging, testing, or external configuration\n *\n * **Behavior**:\n * 1. Checks if the configured port is `0` (indicating dynamic allocation request)\n * 2. Retrieves the address information from the active server using {@link Server.address}\n * 3. Validates that the address is an object containing a port property\n * 4. Updates {@link config.port} with the system-assigned port number\n *\n * This is particularly useful in:\n * - Testing environments where multiple servers run simultaneously\n * - CI/CD pipelines where port conflicts must be avoided\n * - Containerized deployments with dynamic port mapping\n * - Development tools that spawn multiple server instances\n *\n * The method safely handles cases where the server address might not be available\n * or might not be in the expected format, preventing runtime errors.\n *\n * @example\n * ```ts\n * // Configuration with dynamic port\n * const config = { port: 0, host: 'localhost' };\n * const server = new ServerModule(config, '/var/www');\n *\n * await server.start();\n * // After start, setActualPort() is called internally\n *\n * console.log(config.port); // Now shows actual assigned port, e.g., 54321\n *\n * // Use case: Testing with dynamic ports\n * async function createTestServer() {\n * const config = { port: 0, host: 'localhost' };\n * const server = new ServerModule(config, './public');\n * await server.start();\n * // setActualPort() has updated config.port\n * return { server, port: config.port }; // Return actual port for tests\n * }\n *\n * const { server, port } = await createTestServer();\n * console.log(`Test server running on port ${port}`);\n * ```\n *\n * @see Server.address\n * @see startHttpServer\n * @see startHttpsServer\n * @see ServerConfigurationInterface.port\n *\n * @since 2.0.0\n */\n\n private setActualPort(): void {\n if (this.config.port === 0) {\n const address = this.server!.address();\n if(address && typeof address === 'object' && address.port)\n this.config.port = address.port;\n }\n }\n\n /**\n * Starts an HTTP server.\n *\n * @returns A promise that resolves when the server is listening and ready to accept connections.\n *\n * @remarks\n * Creates an HTTP server instance using Node.js's built-in {@link http} module.\n * All incoming requests are passed to {@link handleRequest}, which routes them to\n * {@link defaultResponse} for serving static files or directories.\n *\n * The server listens on the configured {@link ServerConfigurationInterface.host} and\n * {@link ServerConfigurationInterface.port} from the {@link config}.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * await server.start(); // Internally calls startHttpServer if HTTPS is not configured\n * ```\n *\n * @see start\n * @see handleRequest\n * @see defaultResponse\n * @see ServerConfigurationInterface\n *\n * @since 2.0.0\n */\n\n private startHttpServer(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.server = http.createServer((req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n this.server.listen(this.config.port, this.config.host, () => {\n this.setActualPort();\n this.config.onStart?.({\n host: this.config.host!,\n port: this.config.port!,\n url: `http://${ this.config.host }:${ this.config.port }`\n });\n resolve();\n });\n });\n }\n\n /**\n * Starts an HTTPS server using configured certificate and key files.\n *\n * @returns A promise that resolves when the server is listening and ready to accept connections.\n *\n * @remarks\n * Creates an HTTPS server instance using Node.js's built-in {@link https} module.\n * If {@link ServerConfigurationInterface.key} or {@link ServerConfigurationInterface.cert}\n * are not provided in the configuration, defaults are loaded from the framework's\n * distribution path at `certs/server.key` and `certs/server.crt`.\n *\n * All incoming requests are passed to {@link handleRequest}, which routes them to\n * {@link defaultResponse} for serving static files or directories.\n *\n * The server listens on the configured {@link ServerConfigurationInterface.host} and\n * {@link ServerConfigurationInterface.port} from the {@link config}.\n *\n * @example\n * ```ts\n * const server = new ServerModule({\n * port: 3000,\n * host: 'localhost',\n * https: true,\n * key: './path/to/key.pem',\n * cert: './path/to/cert.pem'\n * }, '/var/www');\n * await server.start(); // Internally calls startHttpsServer\n * ```\n *\n * @see start\n * @see handleRequest\n * @see defaultResponse\n * @see FrameworkService\n * @see ServerConfigurationInterface\n *\n * @since 2.0.0\n */\n\n private startHttpsServer(): Promise<void> {\n return new Promise((resolve) => {\n const options = {\n key: readFileSync(this.config.key ?? join(this.framework.distPath, '..', 'certs', 'server.key')),\n cert: readFileSync(this.config.cert ?? join(this.framework.distPath, '..', 'certs', 'server.crt'))\n };\n\n this.server = https.createServer(options, (req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n this.server.listen(this.config.port, this.config.host, () => {\n this.setActualPort();\n this.config.onStart?.({\n host: this.config.host!,\n port: this.config.port!,\n url: `https://${ this.config.host }:${ this.config.port }`\n });\n resolve();\n });\n });\n }\n\n /**\n * Handles incoming HTTP/HTTPS requests, optionally invoking user-defined hooks.\n *\n * @param req - Incoming HTTP request.\n * @param res - Server response object.\n * @param defaultHandler - Callback for default request handling.\n *\n * @remarks\n * If `config.verbose` is true, logs requests to the console.\n * Errors during handling are forwarded to {@link sendError}.\n *\n * @see sendError\n * @since 2.0.0\n */\n\n private handleRequest(req: IncomingMessage, res: ServerResponse, defaultHandler: () => void): void {\n try {\n if(this.config.verbose) {\n console.log(\n `${ prefix() } Request ${ xterm.lightCoral(req.url?.toString() ?? '') }`\n );\n }\n\n if (this.config.onRequest) {\n this.config.onRequest(req, res, defaultHandler);\n } else {\n defaultHandler();\n }\n } catch (error) {\n this.sendError(res, <Error> error);\n }\n }\n\n /**\n * Returns the MIME content type for a given file extension.\n *\n * @param ext - File extension without the leading dot.\n * @returns MIME type string for the provided extension.\n *\n * @since 2.0.0\n */\n\n private getContentType(ext: string): string {\n const contentTypes: Record<string, string> = {\n html: 'text/html',\n css: 'text/css',\n js: 'application/javascript',\n cjs: 'application/javascript',\n mjs: 'application/javascript',\n ts: 'text/plain',\n map: 'application/json',\n json: 'application/json',\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n txt: 'text/plain'\n };\n\n return contentTypes[ext] || 'application/octet-stream';\n }\n\n /**\n * Handles default responses for requests by serving files or directories.\n *\n * @param req - Incoming HTTP request.\n * @param res - Server response.\n *\n * @remarks\n * Ensures the requested path is within the server root.\n * Calls {@link handleDirectory} or {@link handleFile} depending on resource type.\n *\n * @see handleFile\n * @see sendNotFound\n * @see handleDirectory\n *\n * @since 2.0.0\n */\n\n private async defaultResponse(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const requestPath = req.url === '/' ? '' : req.url?.replace(/^\\/+/, '') || '';\n const fullPath = join(this.rootDir, requestPath);\n\n if (!fullPath.startsWith(this.rootDir)) {\n res.statusCode = 403;\n res.end();\n\n return;\n }\n\n try {\n const stats = await stat(fullPath);\n\n if (stats.isDirectory()) {\n await this.handleDirectory(fullPath, requestPath, res);\n } else if (stats.isFile()) {\n await this.handleFile(fullPath, res);\n }\n } catch (error) {\n const msg = (<Error> error).message;\n if (!msg.includes('favicon')) {\n console.log(prefix(), msg);\n }\n\n this.sendNotFound(res);\n }\n }\n\n /**\n * Handles directory listing for a request path.\n *\n * @param fullPath - Absolute directory path.\n * @param requestPath - Relative path from the server root.\n * @param res - Server response.\n *\n * @remarks\n * Generates an HTML listing with icons\n * Invalid filenames are skipped.\n *\n * @see fileIcons\n * @since 2.0.0\n */\n\n private async handleDirectory(fullPath: string, requestPath: string, res: ServerResponse): Promise<void> {\n const files = await readdir(fullPath);\n let fileList = files.map(file => {\n const fullPath = join(requestPath, file);\n const ext = extname(file).slice(1) || 'folder';\n\n if(ext === 'folder') {\n return `\n <a href=\"/${ fullPath }\" class=\"folder-row\">\n <div class=\"icon\"><i class=\"fa-solid fa-folder\"></i></div>\n <div class=\"meta\"><div class=\"name\">${ file }</div><div class=\"sub\">Folder</div></div>\n </a>\n `;\n }\n\n return `\n <a href=\"/${ fullPath }\" class=\"file-row\">\n <div class=\"icon\"><i class=\"fa-solid fa-file-code\"></i></div>\n <div class=\"meta\"><div class=\"name\">${ file }</div><div class=\"sub\">${ ext }</div></div>\n </a>\n `;\n }).join('');\n\n if(!fileList) {\n fileList = '<div class=\"empty\">No files or folders here.</div>';\n } else {\n fileList = `<div class=\"list\">${ fileList }</div>`;\n }\n\n let activePath = '/';\n const segments = requestPath.split('/').map(path => {\n activePath += `${ path }/`;\n\n return `<li><a href=\"${ activePath }\">${ path }</a></li>`;\n }).join('');\n\n const htmlResult = html.replace('${ fileList }', fileList)\n .replace('${ paths }', '<li><a href=\"/\">root</a></li>' + segments)\n .replace('${ up }', '/' + requestPath.split('/').slice(0, -1).join('/'));\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(htmlResult);\n }\n\n /**\n * Serves a static file.\n *\n * @param fullPath - Absolute path to the file.\n * @param res - Server response.\n *\n * @remarks\n * Determines MIME type using {@link getContentType}.\n *\n * @see getContentType\n * @since 2.0.0\n */\n\n private async handleFile(fullPath: string, res: ServerResponse): Promise<void> {\n const ext = extname(fullPath).slice(1) || 'txt';\n const contentType = this.getContentType(ext);\n\n const data = await readFile(fullPath);\n res.writeHead(200, { 'Content-Type': contentType });\n res.end(data);\n }\n\n /**\n * Sends a 404 Not Found response.\n *\n * @param res - Server response.\n *\n * @since 2.0.0\n */\n\n private sendNotFound(res: ServerResponse): void {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n\n /**\n * Sends a 500 Internal Server Error response and logs the error.\n *\n * @param res - Server response.\n * @param error - Error object to log.\n *\n * @since 2.0.0\n */\n\n private sendError(res: ServerResponse, error: Error): void {\n console.error(prefix(), error.toString());\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end('Internal Server Error');\n }\n}\n", "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/><title>Dark File Browser \u2014 FTP-like</title><link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css\" integrity=\"sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class=\"app\"><aside class=\"sidebar\"><div class=\"brand\"><div class=\"logo\">F</div><div><h1>xBuildFTP</h1><div class=\"muted\">Browse & serve files</div></div></div><div class=\"search\"><input placeholder=\"Search files & folders...\"/></div><div class=\"quick-list\"><a href=\"/\">\uD83C\uDFE0 Home</a><a href=\"${ up }\">\u2B06\uFE0F Up</a></div></aside><main class=\"main\"><div class=\"topbar\"><div class=\"topbar\"><ul class=\"breadcrumbs\"> ${ paths } </ul></div></div> ${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>", "/**\n * Imports\n */\n\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\n\n/**\n * ASCII Logo and Version Information\n *\n * @remarks\n * The `asciiLogo` constant stores an ASCII representation of the project logo\n * that will be displayed in the banner. This banner is rendered in a formatted\n * string in the `bannerComponent` function.\n *\n * The `cleanScreen` constant contains an ANSI escape code to clear the terminal screen.\n */\n\nexport const asciiLogo = `\n ______ _ _ _\n | ___ \\\\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\\\ \\\\/ / ___ \\\\ | | | | |/ _\\` |\n > <| |_/ / |_| | | | (_| |\n/_/\\\\_\\\\____/ \\\\__,_|_|_|\\\\__,_|\n`;\n\n/**\n * Renders the banner with the ASCII logo and version information.\n *\n * @returns A formatted string containing the ASCII logo and version number with color formatting\n *\n * @remarks\n * This function constructs and returns a formatted banner string that includes:\n * - An ASCII logo rendered in burnt orange\n * - The current version number displayed in bright pink\n *\n * The function uses ANSI color codes through the xterm utility to create visually\n * distinct elements in the banner. The version number is retrieved from the global\n * `__VERSION` variable.\n *\n * The banner is designed with appropriate spacing and carriage returns to ensure\n * a consistent display across different terminal environments.\n *\n * @example\n * ```ts\n * // Display the banner in the console.\n * console.log(bannerComponent());\n * ```\n *\n * @since 1.0.0\n */\n\nexport function bannerComponent(): string {\n return `\n \\r${ xterm.burntOrange(asciiLogo) }\n \\rVersion: ${ xterm.brightPink(__VERSION) }\n \\r`;\n}\n\n/**\n * Returns a formatted prefix string for xBuild log messages.\n *\n * @returns A string containing the xBuild prefix formatted in light coral color\n *\n * @remarks\n * This function creates a consistent, visually distinct prefix for all xBuild\n * logging output. The prefix is formatted with light coral coloring using the\n * xterm color utility to make xBuild logs easily identifiable in console output.\n *\n * The function is used throughout the build system to maintain consistent\n * log formatting and improve readability when multiple tools or processes\n * are outputting to the same console.\n *\n * @example\n * ```ts\n * // Basic usage in log messages\n * console.log(`${prefix()} Starting build process...`);\n * // Output: \"[xBuild] Starting build process...\" (with \"[xBuild]\" in light coral)\n *\n * // In a logger utility\n * function log(message: string): void {\n * console.log(`${prefix()} ${message}`);\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function prefix(): string {\n return xterm.lightCoral('[xBuild]');\n}\n", "/**\n * Imports\n */\n\nimport { matchesGlob } from 'path';\nimport { stat, watch } from 'fs/promises';\nimport { inject } from '@symlinks/symlinks.module';\nimport { normalize, join } from '@components/path.component';\nimport { FrameworkService } from '@services/framework.service';\n\n/**\n * Provides a file-watching service that tracks changes in the framework's root directory.\n *\n * @remarks\n * This service sets up a recursive file system watcher, filters excluded files,\n * and debounces changes to optimize performance. It is mainly used for monitoring\n * source files or test files and triggering callbacks on changes.\n *\n * @example\n * ```ts\n * const watcher = new WatchService(['**\\/node_modules\\/**']);\n * await watcher.start((changedFiles) => {\n * console.log('Changed files:', changedFiles);\n * });\n * ```\n *\n * @see FrameworkService\n * @since 2.0.0\n */\n\nexport class WatchService {\n /**\n * Glob patterns that **exclude** paths from being emitted.\n *\n * @remarks\n * Patterns use **Node.js native glob semantics** via `matchesGlob`.\n * Negation syntax (`!pattern`) is **not supported** and must be expressed\n * through explicit include/exclude separation.\n *\n * Typical examples:\n *\n * - `**\\/node_modules\\/**`\n * - `**\\/dist\\/**`\n * - `**\\/*.spec.ts`\n *\n * @since 2.0.0\n */\n\n readonly excludes: Array<string>;\n\n /**\n * Glob patterns that **allow** paths to be emitted.\n *\n * @remarks\n * A file must match **at least one** an include pattern to be considered.\n * Defaults to `['**\\/*']`, meaning all files are eligible unless excluded.\n *\n * @since 2.0.0\n */\n\n readonly include: Array<string>;\n\n\n /**\n * Timer used for debouncing file change events.\n *\n * @remarks\n * When multiple file changes occur in quick succession, this timer ensures that\n * the `handleChangedFiles` method is called only once after a short delay,\n * preventing redundant executions and improving performance.\n *\n * @since 2.0.0\n */\n\n private debounceTimer: NodeJS.Timeout | null = null;\n\n /**\n * Reference to the core {@link FrameworkService}.\n *\n * @remarks\n * Injected via the {@link inject} helper, this service provides access to\n * framework-level configuration such as the project root path, runtime\n * environment, and shared utilities.\n * It is used here for resolving relative paths and coordinating with the\n * broader testing infrastructure.\n *\n * @see inject\n * @see FrameworkService\n *\n * @since 2.0.0\n */\n\n private readonly framework: FrameworkService = inject(FrameworkService);\n\n /**\n * Creates a new {@link WatchService}.\n *\n * @param excludes - Glob patterns to ignore.\n * @param include - Glob patterns to allow. Defaults to `['**\\/*']`.\n *\n * @remarks\n * Include and exclude rules are evaluated as:\n *\n * ```\n * included AND NOT excluded\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(excludes: Array<string> = [], include: Array<string> = [ '**/*' ]) {\n this.include = include;\n this.excludes = excludes;\n }\n\n /**\n * Start the file watcher.\n *\n * @param callback - Function to call with the changed file paths.\n * Expects a callback that accepts an array of files.\n * @returns A promise that resolves when the watcher is ready.\n *\n * @remarks\n * This method performs the following steps:\n * 1. Sets up a recursive file system watcher on the framework's root directory.\n * 2. On file changes, normalizes paths, filters excluded files, and schedules\n * handling of changed files with a debouncing to avoid excessive executions.\n *\n * @example\n * ```ts\n * const watcher = new WatchService();\n * await watcher.start((changedFiles) => {\n * console.log('Files changed:', changedFiles);\n * });\n * ```\n *\n * @see handleChangedFiles\n *\n * @since 2.0.0\n */\n\n async start(callback: (files: Array<string>) => void): Promise<void> {\n const changedFilesSet = new Set<string>();\n const watcher = watch(this.framework.rootPath, { recursive: true });\n for await (const { filename } of watcher) {\n if (!filename) continue;\n\n const fullPath = normalize(filename);\n if (fullPath.endsWith('~')) continue;\n\n if (!this.include.some((pattern) => matchesGlob(fullPath, pattern))) continue;\n if (this.excludes.some((pattern) => matchesGlob(fullPath, pattern))) continue;\n\n // Check if the path is a file (not a directory)\n const absolutePath = join(this.framework.rootPath, fullPath);\n try {\n const stats = await stat(absolutePath);\n if (!stats.isFile()) continue;\n } catch {\n // File might have been deleted or doesn't exist yet\n }\n\n changedFilesSet.add(fullPath);\n this.debounce(() => this.handleChangedFiles(callback, changedFilesSet));\n }\n }\n\n /**\n * Handles the changed files after debouncing.\n *\n * @param callback - Function to call with the changed file paths. Expects a callback that accepts an array of files.\n * @param changedFilesSet - Set of changed file paths containing normalized paths of modified files.\n *\n * @remarks\n * Executes the callback with a copy of the changed files and then clears the set\n * for the next batch of changes.\n *\n * @see start\n * @see debounce\n *\n * @since 2.0.0\n */\n\n private async handleChangedFiles(callback: (files: Array<string>) => void, changedFilesSet: Set<string>): Promise<void> {\n callback?.([ ...changedFilesSet ]);\n changedFilesSet.clear();\n }\n\n /**\n * Debounce the execution of a function to limit how frequently it runs.\n *\n * @param fn - The function to execute after the debounced delay.\n * @param delay - Optional debounce delay in milliseconds (default is 150 ms).\n *\n * @remarks\n * If multiple calls are made within the delay period, only the last one will execute.\n * This is used in the file watcher to prevent excessive calls to handle file changes\n * when multiple filesystem events occur in quick succession.\n *\n * @see debounceTimer\n * @see handleChangedFiles\n *\n * @since 2.0.0\n */\n\n private debounce(fn: () => void, delay = 150): void {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(fn, delay);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LifecycleProvider } from '@providers/lifecycle.provider';\nimport type { BuildOptions, OnStartResult, BuildResult } from 'esbuild';\nimport type { DiagnosticInterface } from '@typescript/typescript.module';\nimport type { VariantBuildInterface } from '@interfaces/configuration.interface';\nimport type { UnsubscribeType } from '@observable/interfaces/observable.interface';\nimport type { ResultContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { ConfigSubscriptionInterface } from '@services/interfaces/variant-service.interface';\nimport type { CommonBuildInterface, LifecycleHooksInterface } from '@interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { build } from 'esbuild';\nimport { writeFile, mkdir } from 'fs/promises';\nimport { TypesError } from '@errors/types.error';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { deepMerge } from '@components/object.component';\nimport { Typescript } from '@typescript/typescript.module';\nimport { analyzeDependencies } from '@services/transpiler.service';\nimport { relative, resolve, join } from '@components/path.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { extractEntryPoints } from '@components/entry-points.component';\nimport { isBuildResultError } from '@providers/esbuild-messages.provider';\n\n/**\n * Manages a single build \u201Cvariant\u201D (e.g. `dev`, `prod`) end-to-end.\n *\n * @remarks\n * A variant combines:\n * - Variant-specific configuration (esbuild options, hooks, define/banner/footer)\n * - Common configuration shared across variants\n *\n * Responsibilities:\n * - Merge and normalize configuration (`initializeConfig`)\n * - Register lifecycle hooks (core + user-defined)\n * - Keep a TypeScript service instance in sync (type-checking + declaration emission)\n * - Build using esbuild\n * - Hot-reload on configuration changes (temporarily deactivating builds during updates)\n *\n * @example\n * ```ts\n * const variant = new VariantService('production', lifecycle, variantConfig, { watch: true });\n *\n * // Build once\n * await variant.build();\n *\n * // Access computed dependency entry points (only meaningful when bundle=false)\n * console.log(Object.keys(variant.dependencies));\n *\n * // Cleanup\n * variant.dispose();\n * ```\n *\n * @since 2.0.0\n */\n\nexport class VariantService {\n /**\n * Dependency-to-entry-point map produced by {@link buildDependencyMap}.\n *\n * @remarks\n * This map is always refreshed before each build. When `esbuild.bundle === false`,\n * it is assigned to `esbuild.entryPoints` so that every discovered input becomes an entry point.\n *\n * Keys are output-like paths (relative to `rootDir`) **without** file extensions.\n * Values are source file paths.\n *\n * @example\n * ```ts\n * // Example shape:\n * // {\n * // \"index\": \"/abs/path/src/index.ts\",\n * // \"utils/math\": \"/abs/path/src/utils/math.ts\"\n * // }\n * console.log(variant.dependencies);\n * ```\n *\n * @since 2.0.0\n */\n\n private dependenciesFile: undefined | Record<string, string>;\n\n /**\n * Indicates whether this variant is currently active and should execute builds.\n *\n * @remarks\n * Set to `false` temporarily during configuration updates to prevent builds from running\n * with stale configuration. Re-enabled after configuration is successfully reloaded.\n *\n * @since 2.0.0\n */\n\n private active: boolean = true;\n\n /**\n * Path of the TypeScript configuration file currently in use.\n *\n * @remarks\n * Tracks the tsconfig file for this variant. When configuration changes and a different\n * tsconfig is specified, the old TypeScript instance is disposed and a new one is created.\n *\n * @since 2.0.0\n */\n\n private tsConfigPath: string;\n\n /**\n * TypeScript language service instance for type checking and declaration generation.\n *\n * @remarks\n * Manages the TypeScript compiler for this variant, providing type checking diagnostics\n * and declaration file emission. Recreated when tsconfig changes.\n *\n * @since 2.0.0\n */\n\n private typescriptModule: Typescript;\n\n /**\n * Unsubscribe function for configuration change subscription.\n *\n * @remarks\n * Called during disposal to stop listening to configuration updates and prevent memory leaks.\n *\n * @since 2.0.0\n */\n\n private readonly configUnsubscribe: UnsubscribeType;\n\n /**\n * Configuration service instance providing reactive configuration access.\n *\n * @remarks\n * Injected dependency for accessing and subscribing to build configuration changes.\n *\n * @since 2.0.0\n */\n\n private readonly configService = inject(ConfigurationService);\n\n /**\n * Creates a new variant service instance.\n *\n * @param name - Variant name (used for configuration lookup and hook identification)\n * @param lifecycle - Lifecycle provider used to register build hooks/plugins\n * @param buildConfig - Initial variant build configuration\n * @param argv - Optional CLI/extra arguments passed to dynamic config functions\n *\n * @remarks\n * During construction this service:\n * - Initializes the TypeScript module using `esbuild.tsconfig` (default: `\"tsconfig.json\"`)\n * - Merges variant configuration with common configuration\n * - Normalizes/expands entry points\n * - Registers core lifecycle hooks (`start`/`end`)\n * - Subscribes to configuration changes for hot-reload\n *\n * @example\n * ```ts\n * const variant = new VariantService(\n * 'dev',\n * lifecycle,\n * config,\n * { watch: true }\n * );\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(\n readonly name: string,\n private lifecycle: LifecycleProvider,\n private buildConfig: VariantBuildInterface,\n private argv: Record<string, unknown> = {}\n ) {\n if (!this.buildConfig?.esbuild) {\n throw new xBuildError(`Variant '${ this.name }' not found configuration`);\n }\n\n this.tsConfigPath = this.buildConfig.esbuild.tsconfig ?? 'tsconfig.json';\n this.typescriptModule = new Typescript(this.tsConfigPath);\n this.buildConfig = this.initializeConfig(\n this.getConfig(this.buildConfig, this.configService.getValue().common)!\n );\n\n this.typescriptModule.languageHostService.touchFiles(\n Object.values(<Record<string, string>> this.buildConfig.esbuild.entryPoints)\n );\n\n this.lifecycle.onEnd(this.end.bind(this), `${ this.name }-core`);\n this.lifecycle.onStart(this.start.bind(this), `${ this.name }-core`);\n\n this.configUnsubscribe = this.configService.select(config => ({\n variantConfig: config.variants?.[this.name],\n commonConfig: config.common\n })).subscribe(\n this.handleConfigChange.bind(this),\n error => {\n throw error;\n }\n );\n }\n\n /**\n * Provides access to the TypeScript language service instance for this variant.\n *\n * @returns The TypeScript module instance used for type checking and declaration generation\n *\n * @remarks\n * This getter exposes the variant's TypeScript language service, which provides:\n * - Type checking and diagnostics\n * - Declaration file generation\n * - File change tracking\n * - TypeScript compiler integration\n *\n * The TypeScript module is initialized during construction with the variant's `tsconfig.json`\n * configuration and is recreated when the TypeScript configuration file path changes during\n * hot-reload. The instance is disposed when the variant service is disposed.\n *\n * Use this getter to access TypeScript functionality externally, such as\n * - Manually triggering type checks\n * - Accessing diagnostics without building\n * - Integrating with IDE tooling\n * - Custom declaration file processing\n *\n * @example\n * ```ts\n * const service = new VariantService('production', lifecycle);\n * const typescript = service.typescript;\n *\n * // Check for type errors\n * const diagnostics = typescript.check();\n * console.log(`Found ${diagnostics.length} type errors`);\n *\n * // Emit declarations manually\n * await typescript.emit('types');\n * ```\n *\n * @see {@link dispose}\n * @see {@link Typescript}\n * @see {@link touchFiles}\n *\n * @since 2.0.0\n */\n\n get typescript(): Typescript {\n return this.typescriptModule;\n }\n\n /**\n * Provides access to the merged build configuration for this variant.\n *\n * @returns The complete variant build configuration including esbuild options, TypeScript settings, and lifecycle hooks\n *\n * @remarks\n * This getter exposes the variant's fully merged configuration, which combines:\n * - Common configuration shared across all variants\n * - Variant-specific configuration overrides\n * - Applied to define replacements\n * - Configured lifecycle hooks\n * - TypeScript and declaration settings\n *\n * The configuration is automatically updated when hot-reload detects changes to the\n * configuration file. The returned object reflects the current active configuration\n * used for builds.\n *\n * Configuration structure includes:\n * - `esbuild`: esbuild compiler options (entry points, output, format, minification)\n * - `types`: TypeScript type checking settings\n * - `declaration`: Declaration file generation settings\n * - `define`: Compile-time constant replacements\n * - `banner`: Text to prepend to output files\n * - `footer`: Text to append to output files\n * - `lifecycle`: Custom build lifecycle hooks\n *\n * Use this getter to:\n * - Inspect current build settings\n * - Debug configuration merging\n * - Access configuration in custom lifecycle hooks\n * - Validate variant settings\n *\n * @example\n * ```ts\n * const service = new VariantService('production', lifecycle);\n * const config = service.config;\n *\n * console.log(`Minification: ${config.esbuild.minify}`);\n * console.log(`Output format: ${config.esbuild.format}`);\n * console.log(`Type checking: ${config.types !== false}`);\n * ```\n *\n * @example\n * ```ts\n * // Access in lifecycle hook\n * lifecycle.onStart(async (context) => {\n * const config = variantService.config;\n * if (config.esbuild.minify) {\n * console.log('Building minified output');\n * }\n * });\n * ```\n *\n * @see {@link getConfig}\n * @see {@link handleConfigChange}\n * @see {@link VariantBuildInterface}\n *\n * @since 2.0.0\n */\n\n get config(): VariantBuildInterface {\n return this.buildConfig;\n }\n\n /**\n * Returns the latest dependency entry-point map computed for this variant.\n *\n * @remarks\n * Mainly useful when `esbuild.bundle === false`, because in that mode the build\n * rewrites `esbuild.entryPoints` to this map.\n *\n * @example\n * ```ts\n * await variant.build();\n * for (const [outPath, sourcePath] of Object.entries(variant.dependencies)) {\n * console.log(outPath, '->', sourcePath);\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n get dependencies(): Record<string, string> {\n return this.dependenciesFile ?? {};\n }\n\n /**\n * Disposes this variant service instance and releases resources.\n *\n * @remarks\n * Disposal performs two cleanup steps:\n * 1. Unsubscribes from configuration updates (stops hot-reload notifications)\n * 2. Releases the underlying TypeScript service resources for the current `tsconfig` path\n *\n * Call this when the variant is no longer needed to avoid keeping subscriptions alive and\n * to prevent TypeScript language service instances from lingering in memory.\n *\n * @example\n * ```ts\n * const variant = new VariantService('dev', lifecycle, config);\n *\n * // ... run builds, watch, etc. ...\n *\n * variant.dispose();\n * ```\n *\n * @since 2.0.0\n */\n\n dispose(): void {\n this.configUnsubscribe();\n this.typescriptModule.dispose(this.tsConfigPath);\n }\n\n /**\n * Notifies the TypeScript language service that files have been modified.\n *\n * @param files - Array of file paths that have been modified\n *\n * @remarks\n * This method updates the TypeScript language service's internal state to reflect\n * file changes, ensuring type checking and diagnostics remain accurate. Typically\n * called by file watchers when source files are modified.\n *\n * The TypeScript module will invalidate cached diagnostics for the touched files\n * and recalculate them on the next type check.\n *\n * @example\n * ```ts\n * // In a file watcher\n * watcher.on('change', (filePath) => {\n * service.touchFiles([filePath]);\n * });\n * ```\n *\n * @see {@link Typescript.touchFiles}\n *\n * @since 2.0.0\n */\n\n touchFiles(files: Array<string>): void {\n this.typescriptModule.touchFiles(files);\n }\n\n /**\n * Performs TypeScript type checking for all files in the variant's dependency graph.\n *\n * @returns Array of diagnostic information containing errors, warnings, and suggestions\n *\n * @remarks\n * This method executes type checking on all source files discovered through dependency\n * analysis. It ensures the dependency map is built before checking, building it lazily\n * on the first invocation if not already available.\n *\n * The type checking process:\n * 1. Builds the dependency map if not already cached (first invocation only)\n * 2. Extracts all source file paths from the dependency map\n * 3. Passes the file list to the TypeScript module for semantic analysis\n * 4. Returns diagnostics for all type errors, warnings, and suggestions\n *\n * This method can be called independently of the build process to perform\n * type checking without compilation. It's also used internally by the `start`\n * lifecycle hook during builds when type checking is enabled.\n *\n * The dependency file map is cached after the first build, so subsequent\n * type checks reuse the same file list unless the variant is rebuilt or\n * dependencies change.\n *\n * @example\n * ```ts\n * const service = new VariantService('production', lifecycle, config);\n *\n * // Check types without building\n * const diagnostics = await service.check();\n *\n * if (diagnostics.length > 0) {\n * console.error(`Found ${diagnostics.length} type issues`);\n * diagnostics.forEach(d => {\n * console.error(`${d.file}:${d.line}:${d.column} - ${d.message}`);\n * });\n * }\n * ```\n *\n * @example\n * ```ts\n * // Used in CI pipeline\n * const errors = (await service.check()).filter(\n * d => d.category === DiagnosticCategory.Error\n * );\n *\n * if (errors.length > 0) {\n * process.exit(1);\n * }\n * ```\n *\n * @see {@link start}\n * @see {@link Typescript.check}\n * @see {@link buildDependencyMap}\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\n async check(): Promise<DiagnosticInterface[]> {\n if(!this.dependenciesFile)\n this.dependenciesFile = await this.buildDependencyMap();\n\n return this.typescriptModule.check(Object.values(this.dependenciesFile!));\n }\n\n /**\n * Executes a build for this variant.\n *\n * @returns The esbuild {@link BuildResult}, or `undefined` if the variant is inactive.\n *\n * @remarks\n * High-level steps:\n * 1. Skip if inactive (used during configuration hot-reload)\n * 2. Apply banner/footer injections\n * 3. Compute dependency map\n * 4. If `bundle === false`, replace `entryPoints` with the computed dependency map\n * 5. Run esbuild\n * 6. Write `package.json` with the correct `\"type\"` for the output format\n *\n * @example\n * ```ts\n * const result = await variant.build();\n * if (result) {\n * console.log('warnings:', result.warnings.length);\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n async build(): Promise<BuildResult | undefined> {\n if (!this.active) return;\n this.applyInjections();\n\n const config = Object.assign({}, this.buildConfig.esbuild);\n this.dependenciesFile = await this.buildDependencyMap();\n if (this.buildConfig.esbuild.bundle === false) {\n Object.assign(config, { entryPoints: this.dependenciesFile });\n }\n\n try {\n const result = await build(config);\n await this.packageTypeComponent();\n\n return result;\n } catch (error: unknown) {\n if (isBuildResultError(error)) {\n const errors = error.errors.filter(error => error.location);\n if (errors.length > 0) throw error;\n\n return {\n errors: error?.errors ?? [],\n warnings: error?.warnings ?? []\n } as BuildResult;\n }\n }\n }\n\n /**\n * Merges variant-specific configuration with common configuration.\n *\n * @param config - Variant-specific build configuration\n * @param common - Common build configuration shared across variants\n * @returns Merged configuration, or null if variant config is undefined\n *\n * @remarks\n * This method performs a deep merge where variant-specific settings override\n * common settings. The merge is performed using the `deepMerge` utility, which\n * recursively combines nested objects and arrays.\n *\n * Merge priority (highest to lowest):\n * 1. Variant-specific configuration\n * 2. Common configuration\n * 3. Empty object (default base)\n *\n * If the variant configuration is undefined, it returns null to signal that the\n * variant doesn't exist.\n *\n * @example\n * ```ts\n * const common = { esbuild: { minify: false } };\n * const variant = { esbuild: { minify: true, sourcemap: true } };\n * const merged = getConfig(variant, common);\n * // Result: { esbuild: { minify: true, sourcemap: true } }\n * ```\n *\n * @see {@link deepMerge}\n *\n * @since 2.0.0\n */\n\n private getConfig(config?: VariantBuildInterface, common: CommonBuildInterface = {}): VariantBuildInterface | null {\n if (!config) return null;\n\n return deepMerge<VariantBuildInterface>(\n {} as VariantBuildInterface,\n common,\n config\n );\n }\n\n /**\n * Core start hook handler that runs type checking and declaration generation.\n *\n * @returns Start result containing any type errors and warnings\n *\n * @remarks\n * This private method is registered as an onStart hook during construction and executes\n * at the beginning of each build. It runs two tasks concurrently:\n * 1. **Type checking**: Validates TypeScript types and reports diagnostics\n * 2. **Declaration generation**: Emits .d.ts declaration files\n *\n * Both tasks run in parallel using `Promise.all` for optimal performance.\n *\n * Type checking behavior depends on the `types` configuration:\n * - If `types.failOnError` is false, type errors become warnings\n * - If `types.failOnError` is true (default), type errors fail the build\n *\n * Declaration generation behavior depends on the `declaration` configuration:\n * - If `declaration.bundle` is true (default), declarations are bundled\n * - If `declaration.bundle` is false, individual declarations are emitted\n * - Custom output directory can be specified with `declaration.outDir`\n *\n * @since 2.0.0\n */\n\n private async start(): Promise<OnStartResult | undefined> {\n const result: OnStartResult = { errors: [], warnings: [] };\n if (!this.buildConfig.types) return result;\n\n const diagnostics = this.typescriptModule.check(\n Object.values(this.dependenciesFile ?? {})\n );\n\n if (diagnostics.length === 0) return result;\n const buildOnError = typeof this.buildConfig.types === 'object' &&\n !this.buildConfig.types.failOnError;\n\n if (buildOnError) {\n const error = new TypesError('Type checking failed', diagnostics);\n result.warnings?.push({ detail: error, location: undefined });\n } else {\n const errors: Array<DiagnosticInterface> = [];\n const warnings: Array<DiagnosticInterface> = [];\n const error = new TypesError('Type checking failed', errors);\n const warning = new TypesError('Type checking failed', warnings);\n\n for (const d of diagnostics) {\n (d.category === ts.DiagnosticCategory.Error ? errors : warnings).push(d);\n }\n\n if(errors.length)\n result.errors?.push({ detail: error, location: undefined });\n\n if(warnings.length)\n result.warnings?.push({ detail: warning, location: undefined });\n }\n\n return result;\n }\n\n /**\n * Core end hook handler that generates declaration files after a successful build.\n *\n * @param context - The result context containing build results and metadata\n *\n * @returns Start result containing any declaration generation warnings, or undefined if build has errors\n *\n * @remarks\n * This private method is registered as an onEnd hook during construction and executes\n * at the end of each build. It performs declaration file generation only if the build is\n * completed successfully without errors.\n *\n * The method follows this execution flow:\n * 1. Checks if the build produced any errors\n * 2. Returns early (undefined) if errors exist, skipping declaration generation\n * 3. Creates a new result object for collecting warnings\n * 4. Executes declaration file emission\n * 5. Returns the result with any warnings from the emission process\n *\n * Declaration generation only runs for successful builds to avoid creating declaration\n * files for code that failed to compile. This ensures type definitions remain consistent\n * with the compiled JavaScript output.\n *\n * Any errors during declaration generation are captured as warnings and included in the\n * returned result, allowing the build to complete while reporting the issue.\n *\n * @example\n * ```ts\n * // Registered during construction\n * this.lifecycle.onEnd(this.end.bind(this), `${this.name}-core`);\n *\n * // Called automatically by lifecycle provider after build\n * // If build succeeded: generates declarations\n * // If build failed: skips declaration generation\n * ```\n *\n * @see {@link ResultContextInterface}\n * @see {@link start} for the corresponding start hook\n *\n * @since 2.0.0\n */\n\n private async end(context: ResultContextInterface): Promise<OnStartResult | undefined> {\n if (context.buildResult.errors?.length > 0) return;\n\n const result: OnStartResult = { errors: [], warnings: [] };\n if (!this.buildConfig.declaration) return;\n\n const decl = this.buildConfig.declaration;\n const shouldBundle = typeof decl === 'object' ? decl.bundle !== false : true;\n const outDir = typeof decl === 'object' ? decl.outDir : undefined;\n\n try {\n if (shouldBundle) {\n await this.typescriptModule.emitBundle(\n <Record<string, string>> this.buildConfig.esbuild.entryPoints, outDir\n );\n } else {\n await this.typescriptModule.emit(outDir);\n }\n } catch (err) {\n result.warnings?.push({ detail: err, location: undefined });\n }\n\n return result;\n }\n\n /**\n * Registers lifecycle hooks from configuration with the lifecycle provider.\n *\n * @param hooks - Lifecycle hooks interface containing hook handlers\n *\n * @remarks\n * This method extracts individual hook handlers from the configuration and\n * registers them with the variant's lifecycle provider. Hooks are registered\n * using the default variant name identifier.\n *\n * Only defined hooks are registered; undefined hooks are skipped. This allows\n * partial hook configuration where only specific lifecycle stages need custom logic.\n *\n * Hook registration order:\n * 1. onStart\n * 2. onResolve\n * 3. onLoad\n * 4. onEnd\n * 5. onSuccess\n *\n * If no hooks are provided in the configuration, the method returns early\n * without registering anything.\n *\n * @example\n * ```ts\n * // In build configuration\n * {\n * lifecycle: {\n * onStart: async (context) => {\n * console.log('Custom start hook');\n * },\n * onSuccess: async (context) => {\n * console.log('Build succeeded!');\n * }\n * }\n * }\n * ```\n *\n * @see {@link LifecycleProvider.onStart}\n * @see {@link LifecycleProvider.onResolve}\n * @see {@link LifecycleProvider.onLoad}\n * @see {@link LifecycleProvider.onEnd}\n * @see {@link LifecycleProvider.onSuccess}\n *\n * @since 2.0.0\n */\n\n private registerConfigHooks(hooks?: LifecycleHooksInterface): void {\n if (!hooks) return;\n const { onStart, onResolve, onLoad, onEnd, onSuccess } = hooks;\n\n if (onStart) this.lifecycle.onStart(onStart);\n if (onResolve) this.lifecycle.onResolve(onResolve);\n if (onLoad) this.lifecycle.onLoad(onLoad);\n if (onEnd) this.lifecycle.onEnd(onEnd);\n if (onSuccess) this.lifecycle.onSuccess(onSuccess);\n }\n\n /**\n * Generates a `package.json` file with the appropriate `type` field\n * based on the format specified in the configuration.\n *\n * - If the format is `esm`, the `type` will be set to `\"module\"`.\n * - If the format is `cjs`, the `type` will be set to `\"commonjs\"`.\n *\n * The function will ensure that the specified output directory exists, and if it doesn't,\n * it will create the necessary directories before writing the `package.json` file.\n *\n * @throws Error - throw an error if there is a problem creating the directory or writing the file.\n *\n * @example\n * ```ts\n * const config = {\n * esbuild: {\n * format: 'esm'\n * }\n * };\n * packageTypeComponent(config);\n * // This will create 'dist/package.json' with the content: {\"type\": \"module\"}\n * ```\n *\n * @since 2.0.0\n */\n\n private async packageTypeComponent(): Promise<void> {\n const outDir = this.buildConfig.esbuild.outdir ?? 'dist';\n const type = this.buildConfig.esbuild.format === 'esm' ? 'module' : 'commonjs';\n\n await mkdir(outDir, { recursive: true });\n await writeFile(join(outDir, 'package.json'), `{\"type\": \"${ type }\"}`);\n }\n\n /**\n * Validates and normalizes the merged variant configuration.\n *\n * @param config - Merged variant configuration (common + variant)\n * @returns The normalized configuration used internally for builds.\n *\n * @remarks\n * This method:\n * - Ensures required config fields exist (e.g. `esbuild.entryPoints`)\n * - Registers configured lifecycle hooks\n * - Normalizes `esbuild.tsconfig` (default: `\"tsconfig.json\"`)\n * - Expands entry points relative to `rootDir`\n * - Applies computed esbuild options (`define`, `logLevel`, and lifecycle plugin)\n *\n * @example\n * ```ts\n * // Called internally during construction and config hot-reload.\n * // You typically don't call this directly.\n * ```\n *\n * @since 2.0.0\n */\n\n private initializeConfig(config: VariantBuildInterface): VariantBuildInterface {\n if (!config) {\n throw new xBuildError(`Variant '${ this.name }' not found configuration`);\n }\n\n if (!config.esbuild.entryPoints) {\n throw new xBuildError('Entry points are required in esbuild configuration');\n }\n\n const defineFromConfig = config.define;\n const define: Record<string, string> | undefined = defineFromConfig\n ? Object.fromEntries(\n Object.entries(defineFromConfig).map(\n ([ key, value ]) => [ key, JSON.stringify(value) ]\n )\n )\n : undefined;\n\n this.registerConfigHooks(config.lifecycle);\n config.esbuild.entryPoints = extractEntryPoints(\n this.typescriptModule.config.options.rootDir ?? process.cwd(), config.esbuild.entryPoints\n );\n\n config.esbuild = Object.assign({}, config.esbuild, {\n define,\n logLevel: 'silent',\n plugins: [ this.lifecycle.create() ]\n }) as BuildOptions;\n\n return config;\n }\n\n /**\n * Handles configuration change events and updates variant settings.\n *\n * @param variantConfig - Updated variant-specific configuration\n * @param commonConfig - Updated common configuration\n *\n * @remarks\n * This method is called whenever the configuration service detects changes to the\n * variant's configuration. It performs a hot-reload of all variant settings without\n * requiring a restart.\n *\n * The reload process:\n * 1. Temporarily deactivates the variant (prevents builds during reload)\n * 2. Merges new variant and common configuration\n * 3. Validates that the variant still exists (returns if removed)\n * 4. Reactivates the variant\n * 5. Updates the build configuration\n * 6. Recreates TypeScript module if tsconfig changed\n * 7. Re-registers lifecycle hooks from a new configuration\n * 8. Reapplies define replacements and esbuild options\n * 9. Rebuilds entry points mapping\n *\n * TypeScript module recreation logic:\n * - Disposes old TypeScript instance if tsconfig path changed\n * - Creates new instance with updated tsconfig\n * - Preserves TypeScript instance if tsconfig unchanged\n *\n * This enables configuration changes to take effect immediately without stopping\n * watch mode or restarting the build process.\n *\n * @example\n * ```ts\n * // Configuration changes from:\n * { minify: false, tsconfig: 'tsconfig.json' }\n * // To:\n * { minify: true, tsconfig: 'tsconfig.prod.json' }\n * // TypeScript module is recreated with new tsconfig\n * // All other settings are updated\n * ```\n *\n * @see {@link getConfig}\n * @see {@link registerConfigHooks}\n *\n * @since 2.0.0\n */\n\n private async handleConfigChange({ variantConfig, commonConfig }: ConfigSubscriptionInterface): Promise<void> {\n this.active = false;\n const config = this.getConfig(variantConfig, commonConfig);\n if (!config) return;\n\n this.active = true;\n this.buildConfig = this.initializeConfig(config);\n\n if(config.esbuild.outdir && config.esbuild.outfile)\n this.buildConfig.esbuild.outdir = undefined;\n\n if (config.esbuild.tsconfig && config.esbuild.tsconfig !== this.tsConfigPath) {\n this.typescriptModule.dispose(this.tsConfigPath);\n this.tsConfigPath = config.esbuild.tsconfig;\n this.typescriptModule = new Typescript(this.tsConfigPath);\n }\n }\n\n /**\n * Removes file extension from a path.\n *\n * @param filePath - Path with extension\n * @returns Path without extension\n *\n * @since 2.0.0\n */\n\n private stripExtension(filePath: string): string {\n const lastDotIndex = filePath.lastIndexOf('.');\n\n return lastDotIndex > 0 ? filePath.substring(0, lastDotIndex) : filePath;\n }\n\n /**\n * Analyzes build dependencies and maps all source files to their output paths.\n *\n * @returns Record mapping output paths (without extensions) to source file paths\n *\n * @remarks\n * This method performs the following steps:\n * - Analyzes the dependency graph using esbuild's metafile\n * - Extracts configured entry points\n * - Discovers all transitive dependencies from the build\n * - Maps each file to its relative output path based on rootDir\n *\n * Entry points are preserved as-is, while dependencies are mapped relative to the\n * TypeScript root directory with extensions removed for output path calculation.\n *\n * @example\n * ```ts\n * const fileMap = await this.buildDependencyMap();\n * // {\n * // 'index': 'src/index.ts',\n * // 'utils/helper': 'src/utils/helper.ts',\n * // 'components/button': 'src/components/button.ts'\n * // }\n * ```\n *\n * @since 2.0.0\n */\n\n private async buildDependencyMap(): Promise<Record<string, string>> {\n const { esbuild } = this.buildConfig;\n const { metafile } = await analyzeDependencies(esbuild.entryPoints, {\n loader: esbuild.loader,\n platform: esbuild.platform\n });\n\n const result: Record<string, string> = {};\n for (const file of Object.keys(metafile.inputs)) {\n const relativePath = relative(this.typescriptModule.config.options.rootDir!, resolve(file));\n const path = this.stripExtension(relativePath);\n result[path] = file;\n }\n\n return result;\n }\n\n /**\n * Injects banner or footer text into esbuild output configuration.\n *\n * @param type - Type of text block to inject ('banner' or 'footer')\n *\n * @remarks\n * This method processes banner or footer configuration and injects the resulting\n * text into esbuild options. The configuration can specify text for different\n * output types (js, CSS).\n *\n * Text can be specified in two ways:\n * - **Static string**: Used directly as the banner/footer text\n * - **Function**: Called with variant name and argv, returns the text\n *\n * The function form allows dynamic text generation based on build context.\n *\n * If no banner/footer is configured for this variant, the method returns early\n * without modifying esbuild options.\n *\n * @example\n * ```ts\n * // Static banner\n * {\n * banner: {\n * js: '// Copyright 2024'\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // Dynamic banner with function\n * {\n * banner: {\n * js: (variantName, argv) => `// Build: ${variantName} at ${new Date()}`\n * }\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n private injectTextBlock(type: 'banner' | 'footer'): void {\n const content = this.buildConfig[type];\n if (!content) return;\n\n const esbuild: BuildOptions = this.buildConfig.esbuild;\n esbuild[type] ??= {};\n\n for (const [ target, value ] of Object.entries(content)) {\n esbuild[type][target] = typeof value === 'function'\n ? value(this.name, this.argv)\n : value;\n }\n }\n\n /**\n * Applies banner and footer text injections before build execution.\n *\n * @remarks\n * This method injects custom text into the build output by calling `injectTextBlock`\n * for both 'banner' and 'footer' configuration options. Banners are prepended to\n * output files, while footers are appended.\n *\n * This is called at the start of each build to ensure injections reflect the\n * current configuration state.\n *\n * @see {@link injectTextBlock}\n *\n * @since 2.0.0\n */\n\n private applyInjections(): void {\n this.injectTextBlock('banner');\n this.injectTextBlock('footer');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LanguageService, SourceFile } from 'typescript';\nimport type { LanguageHostService } from '@typescript/services/hosts.service';\nimport type { FileNodeInterface, ModuleInfoInterface } from '@typescript/models/interfaces/graph-model.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { inject, Injectable } from '@symlinks/symlinks.module';\nimport { cleanContent, removeExportModifiers } from '@typescript/components/transformer.component';\n\n/**\n * Builds a simplified, declaration-only dependency graph for TypeScript files.\n *\n * Analyzes source files to extract internal dependencies, named/default/namespace imports & exports,\n * and produces cleaned `.d.ts`-like content with imports and export keywords removed.\n *\n * Primarily used for module federation analysis, tree-shaking verification, public API extraction,\n * or generating documentation / type-only bundles.\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class GraphModel {\n /**\n * Active TypeScript language service instance used to emit declaration files.\n *\n * Set temporarily during the ` scan () ` call via `Object.assign` trick\n * because we want to avoid passing it through every private method signature.\n *\n * @remarks\n * The `!` assertion is safe because `scan()` always assigns both services\n * before any method that uses them is called.\n *\n * @since 2.0.0\n */\n\n private languageService!: LanguageService;\n\n /**\n * Language host providing module resolution, file system access, and version tracking.\n *\n * Like `languageService`, it is temporarily attached during `scan()` execution.\n *\n * @remarks\n * The definite assignment assertion (`!`) is valid only because `scan()`\n * guarantees both fields are set before private methods are invoked.\n *\n * @since 2.0.0\n */\n\n private languageHostService!: LanguageHostService;\n\n /**\n * Printer used to serialize cleaned AST nodes back to text\n * @since 2.0.0\n */\n\n private readonly printer: ts.Printer;\n\n /**\n * Cache of already analyzed files \u2192 their dependency and export graph nodes\n * @since 2.0.0\n */\n\n private readonly nodesCache: Map<string, FileNodeInterface> = new Map();\n\n /**\n * Injected singleton instance of the file snapshot cache.\n *\n * Provides fast access to file versions, resolved paths, and content snapshots\n * without repeated disk I/O.\n *\n * @see {@link FilesModel}\n * @since 2.0.0\n */\n\n private readonly filesCache = inject(FilesModel);\n\n /**\n * Initializes a new {@link GraphModel} instance.\n *\n * @remarks\n * Creates a TypeScript printer configured for consistent line ending formatting.\n * The printer is reused across all analysis operations for efficiency.\n *\n * @since 2.0.0\n */\n\n constructor() {\n this.printer = ts.createPrinter({\n newLine: ts.NewLineKind.LineFeed\n });\n }\n\n /**\n * Clears all cached file analysis results.\n * @since 2.0.0\n */\n\n clear(): void {\n this.nodesCache.clear();\n }\n\n /**\n * Retrieves a previously analyzed graph node for a file if it exists.\n *\n * @param path - file path (relative or absolute)\n * @returns cached node or `undefined` if not yet scanned or invalidated\n *\n * @since 2.0.0\n */\n\n get(path: string): FileNodeInterface | undefined {\n const resolvedPath = this.filesCache.resolve(path);\n\n return this.nodesCache.get(resolvedPath);\n }\n\n /**\n * Scans a source file, emits its declaration file, analyzes imports/exports,\n * and returns a dependency & export graph node.\n *\n * @param source - already parsed TypeScript source file\n * @param languageService - active TS language service (used for emitting)\n * @param languageHostService - host providing resolution and file system access\n * @returns graph node containing version, cleaned content, internal deps, and import/export maps\n *\n * @remarks\n * Re-uses a cached result if a file version hasn't changed.\n *\n * Temporarily attaches `languageService` and `languageHostService` to `this` for private method calls.\n *\n * @example\n * ```ts\n * const sourceFile = program.getSourceFile(fileName, ts.ScriptTarget.Latest)!;\n * const node = graphModel.scan(sourceFile, languageService, hostService);\n *\n * console.log(node.internalDeps.size, 'internal dependencies');\n * console.log(Object.keys(node.externalImports.named), 'external named imports');\n * ```\n *\n * @see {@link FilesModel}\n * @see {@link FileNodeInterface}\n *\n * @since 2.0.0\n */\n\n scan(source: SourceFile, languageService: LanguageService, languageHostService: LanguageHostService): FileNodeInterface {\n const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this, {\n languageService,\n languageHostService\n });\n\n const version = this.filesCache.getSnapshot(source.fileName)!.version.toString();\n const cached = this.nodesCache.get(source.fileName);\n if (cached?.version === version) return cached;\n\n const node = this.initDeclaration(source.fileName, version);\n const declarationSource = this.emitDeclaration.call(self, source);\n\n node.content = this.stripImportsExports.call(self, declarationSource, node);\n this.nodesCache.set(source.fileName, node);\n\n return node;\n }\n\n /**\n * Creates empty graph node skeleton with given file name and version.\n *\n * @param fileName - resolved absolute file path\n * @param version - snapshot version string\n * @returns initialized node structure\n *\n * @since 2.0.0\n */\n\n private initDeclaration(fileName: string, version: string): FileNodeInterface {\n return {\n version,\n fileName,\n content: '',\n internalDeps: new Set(),\n externalImports: {\n named: Object.create(null),\n default: Object.create(null),\n namespace: Object.create(null)\n },\n internalExports: {\n star: [],\n exports: [],\n namespace: Object.create(null)\n },\n externalExports: {\n star: [],\n exports: Object.create(null),\n namespace: Object.create(null)\n }\n };\n }\n\n /**\n * Resolves a module specifier to either an internal file path or external module name.\n *\n * @param moduleSpecifier - string literal from import/export declaration\n * @param currentFile - path of the file containing the import/export\n * @returns module info or `null` if resolution fails\n *\n * @since 2.0.0\n */\n\n private resolveModule(moduleSpecifier: ts.Expression, currentFile: string): ModuleInfoInterface | null {\n if (!ts.isStringLiteral(moduleSpecifier)) return null;\n\n const modulePath = moduleSpecifier.text;\n const resolvedFileName = this.languageHostService.resolveModuleName(modulePath, currentFile)\n .resolvedModule?.resolvedFileName;\n\n if (!resolvedFileName || resolvedFileName.includes('node_modules')) {\n return { fileName: modulePath, isExternal: true };\n }\n\n return { fileName: resolvedFileName, isExternal: false };\n }\n\n /**\n * Appends named import/export specifiers (with optional `as` aliases) to the target array.\n *\n * @param target - array to push names into\n * @param elements - import/export specifiers\n *\n * @since 2.0.0\n */\n\n private addNamedElements(target: Array<string>, elements: ts.NodeArray<ts.ImportSpecifier | ts.ExportSpecifier>): void {\n for (const element of elements) {\n const name = element.propertyName\n ? `${ element.propertyName.text } as ${ element.name.text }`\n : element.name.text;\n target.push(name);\n }\n }\n\n /**\n * Checks whether a statement has an `export` modifier.\n *\n * @param stmt - any statement node\n * @returns `true` if statement is exported\n *\n * @since 2.0.0\n */\n\n private hasExportModifier(stmt: ts.Statement): boolean {\n if (!ts.canHaveModifiers(stmt)) return false;\n const modifiers = ts.getModifiers(stmt);\n\n return modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;\n }\n\n /**\n * Emits a declaration file (.d.ts content) for a given source file using language service.\n *\n * @param source - source file to emit declarations from\n * @returns parsed declaration source file\n *\n * @throws Error when emit output is empty or missing\n *\n * @since 2.0.0\n */\n\n private emitDeclaration(source: SourceFile): SourceFile {\n const output = this.languageService.getEmitOutput(\n source.fileName,\n true,\n true\n );\n\n const declarationText = output.outputFiles[0]?.text;\n if (!declarationText) {\n throw new Error(`Failed to emit declaration: ${ source.fileName }`);\n }\n\n return ts.createSourceFile(\n source.fileName.replace(/\\.tsx?$/, '.d.ts'),\n declarationText,\n ts.ScriptTarget.Latest,\n true\n );\n }\n\n /**\n * Removes imports, exports, and export modifiers from a declaration file,\n * collects dependency/export information, and cleans alias references.\n *\n * @param sourceFile - emitted declaration source file\n * @param node - graph node being populated\n * @returns final cleaned declaration text (no imports/exports)\n *\n * @since 2.0.0\n */\n\n private stripImportsExports(sourceFile: SourceFile, node: FileNodeInterface): string {\n const aliasStatements: Array<string> = [];\n const keptStatements: Array<ts.Statement> = [];\n\n for (const stmt of sourceFile.statements) {\n if (ts.isImportDeclaration(stmt)) {\n this.handleImport(stmt, node, aliasStatements);\n continue;\n }\n\n if (ts.isExportDeclaration(stmt)) {\n this.handleExport(stmt, node);\n continue;\n }\n\n if (this.hasExportModifier(stmt)) {\n this.extractExportName(stmt, node);\n }\n\n keptStatements.push(stmt);\n }\n\n const nodeArray = ts.factory.createNodeArray(keptStatements);\n const printed = this.printer.printList(\n ts.ListFormat.MultiLine,\n nodeArray,\n sourceFile\n );\n\n let content = removeExportModifiers(cleanContent(printed));\n for (const alias of aliasStatements) {\n if(alias.includes(' as ')) {\n const [ aliasName, aliasType ] = alias.split(' as ');\n content = content.replace(new RegExp(`\\\\b${ aliasType }\\\\b`, 'g'), aliasName);\n } else {\n content = content.replace(new RegExp(`\\\\b${ alias }\\\\.`, 'g'), '');\n }\n }\n\n return content;\n }\n\n /**\n * Processes import declaration \u2192 tracks dependencies and collects imported names.\n *\n * @param stmt - import declaration AST node\n * @param node - graph node to update\n * @param aliasStatements - mutable list of local alias names to clean later\n *\n * @since 2.0.0\n */\n\n private handleImport(stmt: ts.ImportDeclaration, node: FileNodeInterface, aliasStatements: Array<string>): void {\n const { importClause, moduleSpecifier } = stmt;\n if (!importClause || !moduleSpecifier) return;\n\n const moduleInfo = this.resolveModule(moduleSpecifier, node.fileName);\n if (!moduleInfo) return;\n\n const { fileName, isExternal } = moduleInfo;\n\n if (!isExternal) {\n node.internalDeps.add(fileName);\n\n const { namedBindings } = importClause;\n if(!namedBindings) return;\n\n if (ts.isNamespaceImport(namedBindings)) {\n aliasStatements.push(namedBindings.name.text);\n } else if (ts.isNamedImports(namedBindings)) {\n this.addNamedElements(aliasStatements, namedBindings.elements);\n }\n\n return;\n }\n\n if (!importClause) {\n // Side-effect import: import 'module'\n node.externalImports.namespace[fileName] = '';\n\n return;\n }\n\n // Default import: import Foo from 'module'\n if (importClause.name) {\n node.externalImports.default[fileName] = importClause.name.text;\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) return;\n\n if (ts.isNamespaceImport(namedBindings)) {\n // import * as Foo from 'module'\n node.externalImports.namespace[namedBindings.name.text] = fileName;\n } else if (ts.isNamedImports(namedBindings)) {\n // import { a, b as c } from 'module'\n this.addNamedElements(\n node.externalImports.named[fileName] ??= [],\n namedBindings.elements\n );\n }\n }\n\n /**\n * Processes re-export declaration (`export \u2026 from \u2026`).\n *\n * @param stmt - export declaration AST node\n * @param node - graph node to update\n *\n * @since 2.0.0\n */\n\n private handleExport(stmt: ts.ExportDeclaration, node: FileNodeInterface): void {\n const { moduleSpecifier, exportClause } = stmt;\n if (!moduleSpecifier) return;\n\n const moduleInfo = this.resolveModule(moduleSpecifier, node.fileName);\n if (!moduleInfo) return;\n\n const { fileName, isExternal } = moduleInfo;\n\n // Track internal dependencies\n if (!isExternal) {\n node.internalDeps.add(fileName);\n }\n\n // export * from 'module'\n if (!exportClause) {\n if (isExternal) {\n node.externalExports.star.push(fileName);\n } else {\n node.internalExports.star.push(fileName);\n }\n\n return;\n }\n\n // export * as Foo from 'module'\n if (ts.isNamespaceExport(exportClause)) {\n if (isExternal) {\n node.externalExports.namespace[exportClause.name.text] = fileName;\n } else {\n node.internalExports.namespace[exportClause.name.text] = fileName;\n }\n\n return;\n }\n\n if (ts.isNamedExports(exportClause)) {\n // export { a, b as c } from 'module'\n if (isExternal) {\n this.addNamedElements(\n node.externalExports.exports[fileName] ??= [],\n exportClause.elements\n );\n } else {\n this.addNamedElements(\n node.internalExports.exports,\n exportClause.elements\n );\n }\n }\n }\n\n /**\n * Extracts locally declared export names from statements with the ` export ` modifier.\n *\n * @param stmt - statement with export modifier\n * @param node - graph node to update\n *\n * @since 2.0.0\n */\n\n private extractExportName(stmt: ts.Statement, node: FileNodeInterface): void {\n if (ts.isVariableStatement(stmt)) {\n for (const decl of stmt.declarationList.declarations) {\n if (ts.isIdentifier(decl.name)) {\n node.internalExports.exports.push(decl.name.text);\n }\n }\n\n return;\n }\n\n // Handle other named declarations\n if (ts.isEnumDeclaration(stmt) ||\n ts.isClassDeclaration(stmt) ||\n ts.isFunctionDeclaration(stmt) ||\n ts.isInterfaceDeclaration(stmt) ||\n ts.isTypeAliasDeclaration(stmt)) {\n if (stmt.name && ts.isIdentifier(stmt.name)) {\n node.internalExports.exports.push(stmt.name.text);\n }\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CompilerOptions } from 'typescript';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { dirname, relative, toPosix } from '@components/path.component';\n\n/**\n * Matches Unix shebang lines at the beginning of files for removal during compilation.\n *\n * @remarks\n * Matches shebang lines (e.g., `#!/usr/bin/env node`) at the start of files,\n * including optional carriage return and line feed characters for cross-platform compatibility.\n *\n * Pattern breakdown:\n * - `^#!` - Start of line with `#!`\n * - `.*` - Any characters until the end of line\n * - `(\\r?\\n)?` - Optional CR+LF or LF line ending\n *\n * @example\n * ```ts\n * const content = '#!/usr/bin/env node\\nconsole.log(\"hello\");';\n * SHEBANG_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeShebang}\n *\n * @since 2.0.0\n */\n\nexport const SHEBANG_REGEX = /^#!.*(\\r?\\n)?/;\n\n/**\n * Matches empty export statements that should be removed from declaration files.\n *\n * @remarks\n * Matches TypeScript empty export statements (`export {};`) which are often\n * generated during compilation but are invalid in final declaration files.\n *\n * Pattern breakdown:\n * - `export {};` - Literal empty export statement\n * - `\\n?` - Optional trailing newline\n *\n * The global flag ensures all occurrences are matched throughout the content.\n *\n * @example\n * ```ts\n * const content = 'export {};\\nexport const x = 1;';\n * EMPTY_EXPORT_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeEmptyExports}\n *\n * @since 2.0.0\n */\n\nexport const EMPTY_EXPORT_REGEX = /export {};\\n?/g;\n\n/**\n * Matches orphaned JSDoc comment blocks that are not associated with any declaration.\n *\n * @remarks\n * Matches consecutive JSDoc comment blocks that appear without associated declarations.\n * These orphaned comments commonly appear in bundled files where comments are preserved\n * during bundling but lose their associated declarations.\n *\n * Pattern breakdown:\n * - `(?:\\/\\*\\*[\\s\\S]*?\\*\\/\\s*)+` - One or more JSDoc blocks with the following whitespace (non-capturing)\n * - `(\\/\\*\\*[\\s\\S]*?\\*\\/)` - Final JSDoc block (captured for potential reuse)\n *\n * The captured group allows preserving the last comment if needed during replacement.\n *\n * @example\n * ```ts\n * const content = '/** Comment 1 *\\/\\n/** Comment 2 *\\/\\nexport const x = 1;';\n * ORPHAN_COMMENT_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeOrphanComments}\n *\n * @since 2.0.0\n */\n\nexport const ORPHAN_COMMENT_REGEX = /(?:\\/\\*\\*[\\s\\S]*?\\*\\/\\s*)+(\\/\\*\\*[\\s\\S]*?\\*\\/)/g;\n\n/**\n * Matches export modifiers on declarations for removal while preserving the declarations themselves.\n *\n * @remarks\n * Matches the `export` keyword (and optional `default`) at the start of lines\n * in declaration files. Used to strip export modifiers while preserving the\n * declaration itself when consolidating exports.\n *\n * Pattern breakdown:\n * - `^export` - Export keyword at line start (multiline mode)\n * - `\\s+` - Required whitespace after export\n * - `(?:default\\s+)?` - Optional default keyword with whitespace\n *\n * The multiline flag (`m`) ensures `^` matches line starts throughout the content.\n *\n * @example\n * ```ts\n * const content = 'export interface Config { x: number; }';\n * content.replace(EXPORT_MODIFIER_REGEX, ''); // 'interface Config { x: number; }'\n * ```\n *\n * @see {@link removeExportModifiers}\n *\n * @since 2.0.0\n */\n\nexport const EXPORT_MODIFIER_REGEX = /^export\\s+(?:default\\s+)?/gm;\n\n/**\n * Matches single-line trailing JSDoc comment blocks at the end of lines for removal.\n *\n * @remarks\n * Matches JSDoc comment blocks that appear at the end of lines, including\n * surrounding whitespace. Used to clean up documentation comments that are\n * misplaced or unnecessary in bundled output.\n *\n * Pattern breakdown:\n * - `\\s*` - Leading whitespace\n * - `\\/\\*\\*[^\\\\r\\\\n]*?\\*\\/` - Single-line JSDoc comment block (no line breaks)\n * - `\\s*$` - Trailing whitespace and end of line\n *\n * @example\n * ```ts\n * const content = 'const x = 1; /** Documentation *\\/';\n * TRAILING_COMMENT_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeOrphanComments}\n *\n * @since 2.0.0\n */\n\nexport const TRAILING_COMMENT_REGEX = /(?<=[:;,{}\\[\\]()\\w\"'`])[ \\t]*\\/\\*\\*[^\\r\\n]*?\\*\\/[ \\t]*$/gm;\n\n/**\n * Removes shebang line from the beginning of file content.\n *\n * @param content - The file content to process\n *\n * @returns Content with shebang line removed, or unchanged if no shebang present\n *\n * @remarks\n * Removes Unix shebang lines (e.g., `#!/usr/bin/env node`) from the start of files.\n * Uses character code checks for performance (35 = '#', 33 = '!'), avoiding regex\n * execution for files that don't have shebangs.\n *\n * Shebang lines are typically only present in executable scripts and are not valid\n * in declaration files or bundled TypeScript code.\n *\n * @example\n * ```ts\n * const withShebang = '#!/usr/bin/env node\\nconsole.log(\"hello\");';\n * const cleaned = removeShebang(withShebang);\n * // 'console.log(\"hello\");'\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link SHEBANG_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeShebang(content: string): string {\n // 35 = '#', 33 = '!'\n return (content.charCodeAt(0) === 35 && content.charCodeAt(1) === 33)\n ? content.replace(SHEBANG_REGEX, '')\n : content;\n}\n\n/**\n * Removes empty export statements from file content.\n *\n * @param content - The file content to process\n *\n * @returns Content with all empty export statements removed\n *\n * @remarks\n * Removes `export {};` statements which TypeScript often generates to mark\n * a file as an ES module without exporting anything. These statements are invalid\n * in declaration files and should be removed during compilation.\n *\n * Performs a quick string check before applying the regex for performance optimization.\n *\n * @example\n * ```ts\n * const content = 'export {};\\nexport const x = 1;';\n * const cleaned = removeEmptyExports(content);\n * // 'export const x = 1;'\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link EMPTY_EXPORT_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeEmptyExports(content: string): string {\n return content.includes('export {}')\n ? content.replace(EMPTY_EXPORT_REGEX, '')\n : content;\n}\n\n/**\n * Removes orphaned and trailing JSDoc comment blocks from file content.\n *\n * @param content - The file content to process\n *\n * @returns Content with orphaned and trailing comments removed\n *\n * @remarks\n * Performs two sequential cleaning operations:\n * 1. Removes trailing JSDoc comments at the end of lines\n * 2. Removes orphaned JSDoc blocks (comments not associated with declarations)\n *\n * Orphaned comments commonly appear in bundled files where comments are preserved\n * during bundling but lose their associated declarations due to tree shaking or\n * module consolidation.\n *\n * The replacement pattern `'$1'` preserves the last comment in a sequence of orphaned\n * comments if it might still be associated with a declaration.\n *\n * @example\n * ```ts\n * const content = '/** Orphan *\\/\\n/** Doc *\\/\\nexport const x = 1;';\n * const cleaned = removeOrphanComments(content);\n * // Removes orphaned comments while preserving declaration-associated ones\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link ORPHAN_COMMENT_REGEX}\n * @see {@link TRAILING_COMMENT_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeOrphanComments(content: string): string {\n content = content.replace(TRAILING_COMMENT_REGEX, '');\n\n return content.replace(ORPHAN_COMMENT_REGEX, '$1');\n}\n\n/**\n * Removes export modifiers from all declarations while preserving the declarations themselves.\n *\n * @param content - The file content to process\n *\n * @returns Content with export modifiers removed from all declarations\n *\n * @remarks\n * Strips `export` and `export default` keywords from declarations, transforming:\n * - `export const x = 1;` \u2192 `const x = 1;`\n * - `export default interface Config {}` \u2192 `interface Config {}`\n * - `export function foo() {}` \u2192 `function foo() {}`\n *\n * This transformation is used when bundling declarations to remove export modifiers\n * from internal declarations that will be consolidated into a single export list or\n * re-exported through a barrel file.\n *\n * @example\n * ```ts\n * const content = 'export const x = 1;\\nexport function foo() {}';\n * const cleaned = removeExportModifiers(content);\n * // 'const x = 1;\\nfunction foo() {}'\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link EXPORT_MODIFIER_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeExportModifiers(content: string): string {\n return content.replace(EXPORT_MODIFIER_REGEX, '');\n}\n\n/**\n * Checks whether file content contains elements that require cleaning.\n *\n * @param content - The file content to check\n *\n * @returns `true` if content requires cleaning operations, `false` otherwise\n *\n * @remarks\n * Performs quick checks to determine if cleaning operations are necessary:\n * - Checks for shebang (character code 35 = '#')\n * - Checks for empty export statements\n * - Checks for JSDoc comments\n *\n * Used to short-circuit expensive cleaning operations when content doesn't need\n * processing, improving performance on already-clean files.\n *\n * @example\n * ```ts\n * needsCleaning('export const x = 1;'); // false\n * needsCleaning('#!/bin/bash\\nexport const x = 1;'); // true\n * needsCleaning('export {};\\nexport const x = 1;'); // true\n * needsCleaning('/** Doc *\\/\\nexport const x = 1;'); // true\n * ```\n *\n * @see {@link cleanContent}\n *\n * @since 2.0.0\n */\n\nexport function needsCleaning(content: string): boolean {\n return content.charCodeAt(0) === 35 || // '#' for shebang\n content.includes('export {}') ||\n content.includes('/**');\n}\n\n/**\n * Applies all cleaning transformations to file content in sequence.\n *\n * @param content - The file content to clean\n *\n * @returns Cleaned content with all transformations applied\n *\n * @remarks\n * Applies cleaning operations in the following order:\n * 1. Short-circuit check using {@link needsCleaning} for performance\n * 2. Removes shebang lines\n * 3. Removes empty export statements\n * 4. Removes orphaned JSDoc comments\n *\n * Typically applied to declaration files during emission or bundling to remove\n * artifacts that are not valid in `.d.ts` files or that clutter bundled output.\n * The sequential application ensures all unwanted elements are removed while\n * preserving valid TypeScript declarations.\n *\n * @example\n * ```ts\n * const raw = `#!/usr/bin/env node\n * /**\n * * Orphaned comment\n * *\\/\n * export {};\n * export const x = 1;`;\n *\n * const cleaned = cleanContent(raw);\n * // 'export const x = 1;'\n * ```\n *\n * @see {@link needsCleaning}\n * @see {@link removeShebang}\n * @see {@link removeEmptyExports}\n * @see {@link removeOrphanComments}\n *\n * @since 2.0.0\n */\n\nexport function cleanContent(content: string): string {\n if (!needsCleaning(content)) return content;\n\n content = removeShebang(content);\n content = removeEmptyExports(content);\n content = removeOrphanComments(content);\n\n return content;\n}\n\n\n/**\n * Calculates the output file path for a compiled TypeScript declaration file.\n *\n * @param sourcePath - The source TypeScript file path\n * @param options - TypeScript compiler options containing output directory settings\n *\n * @returns The normalized output path for the declaration file with forward slashes\n *\n * @remarks\n * Determines an output path using the following logic:\n * 1. Selects output base: `declarationDir` `>` `outDir` `>` source directory\n * 2. Selects root directory: `rootDir` `>` source directory\n * 3. Computes a relative path from root to a source file\n * 4. Changes file extension from `.ts`/`.tsx` to `.d.ts`\n * 5. Combines an output base path with the output file name\n * 6. Resolves a full path and normalizes to forward slashes\n *\n * Path resolution example:\n * - Source: `/project/src/components/Button.tsx`\n * - Root: `/project/src`\n * - Relative: `components/Button.tsx`\n * - Output file: `components/Button.d.ts`\n * - Final: `/project/dist/components/Button.d.ts`\n *\n * @example\n * ```ts\n * const sourcePath = '/project/src/index.ts';\n * const options: CompilerOptions = {\n * outDir: 'dist',\n * rootDir: 'src'\n * };\n *\n * const outputPath = calculateOutputPath(sourcePath, options);\n * // '/project/dist/index.d.ts'\n * ```\n *\n * @example\n * ```ts\n * // With declarationDir override\n * const options: CompilerOptions = {\n * outDir: 'dist',\n * declarationDir: 'types',\n * rootDir: 'src'\n * };\n *\n * const outputPath = calculateOutputPath(sourcePath, options);\n * // '/project/types/index.d.ts'\n * ```\n *\n * @see {@link EmitterService}\n * @see {@link BundlerService}\n *\n * @since 2.0.0\n */\n\nexport function calculateOutputPath(sourcePath: string, options: CompilerOptions): string {\n const { outDir, rootDir, declarationDir } = options;\n\n const outputBase = declarationDir || outDir || dirname(sourcePath);\n const root = rootDir || dirname(sourcePath);\n\n const relativePath = relative(root, sourcePath);\n const outputFileName = relativePath.replace(/\\.tsx?$/, '.d.ts');\n const fullPath = ts.sys.resolvePath(`${ outputBase }/${ outputFileName }`);\n\n return toPosix(fullPath);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ParsedCommandLine, LanguageService, Diagnostic } from 'typescript';\nimport type { CachedServiceInterface, DiagnosticInterface } from './interfaces/typescript-service.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { BundlerService } from '@typescript/services/bundler.service';\nimport { EmitterService } from '@typescript/services/emitter.service';\nimport { LanguageHostService } from '@typescript/services/hosts.service';\n\n/**\n * Manages TypeScript language services with caching and reference counting for shared compiler instances.\n * Provides type checking, code emission, and bundling capabilities through a unified interface that coordinates\n * multiple internal services while maintaining efficient resource usage across multiple consumers.\n *\n * @remarks\n * This service implements a caching strategy to share language service instances across multiple consumers\n * that reference the same `tsconfig.json` file. The lifecycle is managed through reference counting:\n * - Each instantiation increments the reference count for the config path\n * - Calling {@link dispose} decrements the count\n * - When the count reaches zero, the language service is cleaned up automatically\n *\n * The service coordinates three key subsystems:\n * - Language service and host for type checking and analysis\n * - Emitter service for standard TypeScript compilation output\n * - Bundler service for creating bundled outputs from entry points\n *\n * @example\n * ```ts\n * const service = new TypescriptService('tsconfig.json');\n *\n * // Type check all files\n * const diagnostics = service.check();\n * if (diagnostics.length > 0) {\n * console.error('Type errors found:', diagnostics);\n * }\n *\n * // Emit compiled output\n * await service.emit('./dist');\n *\n * // Clean up when done\n * service.dispose('tsconfig.json');\n * ```\n *\n * @see {@link EmitterService}\n * @see {@link BundlerService}\n * @see {@link LanguageHostService}\n *\n * @since 2.0.0\n */\n\n@Injectable({\n providers: [{ useValue: 'tsconfig.json' }]\n})\nexport class TypescriptService {\n /**\n * Parsed TypeScript compiler configuration including options, file names, and project references.\n * @since 2.0.0\n */\n\n readonly config: ParsedCommandLine;\n\n /**\n * TypeScript language service instance providing type checking, intellisense, and compilation capabilities.\n * @since 2.0.0\n */\n\n readonly languageService: LanguageService;\n\n /**\n * Custom language service host managing file system interactions and compiler options.\n * @since 2.0.0\n */\n\n readonly languageHostService: LanguageHostService;\n\n /**\n * Shared cache mapping config paths to language service instances with reference counting.\n *\n * @remarks\n * This static cache enables multiple service instances to share the same underlying language service\n * when they reference the same `tsconfig.json` file, reducing memory usage and compilation overhead.\n * Entries are automatically cleaned up when reference counts reach zero.\n *\n * @since 2.0.0\n */\n\n private static readonly serviceCache = new Map<string, CachedServiceInterface>();\n\n /**\n * Service responsible for emitting compiled TypeScript output files.\n * @since 2.0.0\n */\n\n private readonly emitterService: EmitterService;\n\n /**\n * Service responsible for creating bundled outputs from entry points.\n * @since 2.0.0\n */\n\n private readonly bundlerService: BundlerService;\n\n /**\n * Creates a new TypeScript service instance or retrieves a cached one for the specified configuration.\n *\n * @param configPath - Path to the `tsconfig.json` file, defaults to `'tsconfig.json'` in the current directory\n *\n * @remarks\n * The constructor performs the following initialization steps:\n * - Acquires or creates a cached language service for the config path\n * - Increments the reference count for the shared service instance\n * - Touches all files listed in the parsed configuration to ensure they're loaded\n * - Initializes emitter and bundler services with the language service\n *\n * If a language service already exists for the given config path, it will be reused rather than\n * creating a new instance, improving performance and reducing memory usage.\n *\n * @example\n * ```ts\n * // Use default tsconfig.json\n * const service = new TypescriptService();\n *\n * // Use custom config path\n * const customService = new TypescriptService('./custom-tsconfig.json');\n * ```\n *\n * @see {@link acquireLanguageService}\n * @see {@link LanguageHostService.touchFiles}\n *\n * @since 2.0.0\n */\n\n constructor(private configPath: string = 'tsconfig.json') {\n const { config, host, service } = this.acquireLanguageService();\n\n this.config = config;\n this.languageService = service;\n this.languageHostService = host;\n this.languageHostService.touchFiles(this.config.fileNames);\n\n this.emitterService = new EmitterService(service, host);\n this.bundlerService = new BundlerService(service, host);\n }\n\n /**\n * Performs type checking on all source files in the project and returns collected diagnostics.\n *\n * @returns Array of formatted diagnostic information including errors, warnings, and suggestions\n *\n * @remarks\n * This method filters out files that should not be checked (such as `node_modules` and declaration files)\n * and collects three types of diagnostics for each remaining file:\n * - Semantic diagnostics (type errors, type mismatches)\n * - Syntactic diagnostics (parse errors, invalid syntax)\n * - Suggestion diagnostics (optional improvements can be slow)\n *\n * If the language service has no program available, an empty array is returned.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n * const diagnostics = service.check();\n *\n * for (const diagnostic of diagnostics) {\n * console.log(`${diagnostic.file}:${diagnostic.line}:${diagnostic.column}`);\n * console.log(`${diagnostic.message}`);\n * }\n * ```\n *\n * @see {@link shouldCheckFile}\n * @see {@link collectDiagnostics}\n *\n * @since 2.0.0\n */\n\n check(filesList?: Array<string>): Array<DiagnosticInterface> {\n const program = this.languageService.getProgram();\n if (!program) return [];\n\n const files = (filesList && filesList.length > 0) ?\n filesList.map(file => program.getSourceFile(file)!) :\n this.languageService.getProgram()?.getSourceFiles();\n\n if (!files) return [];\n\n return files\n .filter(file => this.shouldCheckFile(file))\n .flatMap(file => this.collectDiagnostics(file));\n }\n\n /**\n * Marks files as modified to trigger recompilation and updates configuration if the config file changed.\n *\n * @param files - Array of file paths that have been modified or created\n *\n * @remarks\n * This method performs two key operations:\n * - For files that exist in the script snapshot cache, marks them as touched to invalidate cached data\n * - If the modified files include the `tsconfig.json` file, reloads the configuration and updates the host options\n *\n * This is essential for watch mode scenarios where files change during development and the service\n * needs to stay synchronized with the file system state.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n *\n * // Notify service of file changes\n * service.touchFiles(['src/index.ts', 'src/utils.ts']);\n *\n * // Config change triggers reload\n * service.touchFiles(['tsconfig.json']);\n * ```\n *\n * @see {@link LanguageHostService.touchFile}\n * @see {@link LanguageHostService.hasScriptSnapshot}\n *\n * @since 2.0.0\n */\n\n touchFiles(files: Array<string>): void {\n for (const file of files) {\n if (this.languageHostService.hasScriptSnapshot(file)) {\n this.languageHostService.touchFile(file);\n }\n\n if (file.includes(this.configPath)) {\n const cached = TypescriptService.serviceCache.get(this.configPath)!;\n cached.config = this.parseConfig();\n cached.host.options = cached.config.options;\n }\n }\n }\n\n /**\n * Emits a bundled output by processing specified entry points through the bundler service.\n *\n * @param entryPoints - Record mapping bundle names to their entry point file paths\n * @param outdir - Optional output directory path, uses compiler options default if not specified\n *\n * @returns Promise that resolves when bundling and emission completes\n *\n * @remarks\n * This method delegates to the bundler service which handles dependency resolution, tree shaking,\n * and output generation. Unlike standard emission, bundling combines multiple modules into\n * optimized output files.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n *\n * await service.emitBundle(\n * { 'main': './src/index.ts', 'worker': './src/worker.ts' },\n * './dist/bundles'\n * );\n * ```\n *\n * @see {@link BundlerService.emit}\n *\n * @since 2.0.0\n */\n\n async emitBundle(entryPoints: Record<string, string>, outdir?: string): Promise<void> {\n await this.bundlerService.emit(entryPoints, outdir);\n }\n\n /**\n * Emits compiled TypeScript output files to the specified directory.\n *\n * @param outdir - Optional output directory path, uses compiler options default if not specified\n *\n * @returns Promise that resolves when emission completes\n *\n * @remarks\n * This method performs standard TypeScript compilation, emitting JavaScript files, declaration files,\n * and source maps according to the compiler options. The emission includes all files in the program\n * that are not excluded by configuration.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n *\n * // Emit to default outDir from tsconfig\n * await service.emit();\n *\n * // Emit to custom directory\n * await service.emit('./build');\n * ```\n *\n * @see {@link EmitterService.emit}\n *\n * @since 2.0.0\n */\n\n async emit(outdir?: string): Promise<void> {\n await this.emitterService.emit(outdir);\n }\n\n /**\n * Decrements the reference count for a cached service and cleans up if no longer in use.\n *\n * @param tsconfigPath - Path to the TypeScript configuration file identifying which cached service to dispose\n *\n * @remarks\n * This method implements the cleanup phase of the reference counting lifecycle. When the reference count\n * reaches zero, the language service is disposed of and removed from the cache. This should be called\n * when a consumer no longer needs the TypeScript service to prevent resource leaks.\n *\n * If no cached service exists for the given path, this method does nothing.\n *\n * @example\n * ```ts\n * const service = new TypescriptService('tsconfig.json');\n *\n * // Use the service...\n * const diagnostics = service.check();\n *\n * // Clean up when done\n * service.dispose('tsconfig.json');\n * ```\n *\n * @see {@link cleanupUnusedServices}\n *\n * @since 2.0.0\n */\n\n dispose(tsconfigPath: string): void {\n const cached = TypescriptService.serviceCache.get(tsconfigPath);\n if (!cached) return;\n\n cached.refCount--;\n TypescriptService.cleanupUnusedServices();\n }\n\n /**\n * Removes cached language services with zero references and disposes of their resources.\n *\n * @remarks\n * This static method iterates through the service cache and removes entries where the reference\n * count has dropped below one. For each removed entry, the language service's `dispose()` method\n * is called to clean up internal resources before deletion from the cache.\n *\n * This method is called automatically by {@link dispose} and should not typically be invoked directly.\n *\n * @see {@link dispose}\n *\n * @since 2.0.0\n */\n\n private static cleanupUnusedServices(): void {\n for (const [ path, cached ] of this.serviceCache) {\n if (cached.refCount < 1) {\n cached.service.dispose();\n this.serviceCache.delete(path);\n }\n }\n }\n\n /**\n * Determines whether a source file should be included in type checking.\n *\n * @param file - TypeScript source file to evaluate\n *\n * @returns `true` if the file should be checked, `false` if it should be excluded\n *\n * @remarks\n * Files are excluded from checking if they meet either condition:\n * - Located in the ` node_modules ` directory (third-party dependencies)\n * - Are TypeScript declaration files (`.d.ts` files)\n *\n * @since 2.0.0\n */\n\n private shouldCheckFile(file: ts.SourceFile): boolean {\n return file && !file.fileName.includes('node_modules') && !file.isDeclarationFile;\n }\n\n /**\n * Collects all diagnostic information for a source file, including errors, warnings, and suggestions.\n *\n * @param file - TypeScript source file to collect diagnostics from\n *\n * @returns Array of formatted diagnostic objects with file location and message details\n *\n * @remarks\n * This method gathers three types of diagnostics:\n * - Semantic diagnostics: type errors, undefined variables, type mismatches\n * - Syntactic diagnostics: parse errors, invalid syntax, malformed code\n * - Suggestion diagnostics: optional code improvements (can impact performance)\n *\n * Each diagnostic is formatted using {@link formatDiagnostic} to provide consistent output.\n *\n * @see {@link formatDiagnostic}\n *\n * @since 2.0.0\n */\n\n private collectDiagnostics(file: ts.SourceFile): DiagnosticInterface[] {\n return [\n ...this.languageService.getSemanticDiagnostics(file.fileName),\n ...this.languageService.getSyntacticDiagnostics(file.fileName),\n ...this.languageService.getSuggestionDiagnostics(file.fileName) // optional: slow\n ].map(d => this.formatDiagnostic(d));\n }\n\n /**\n * Retrieves an existing cached language service or creates a new one if none exists.\n *\n * @returns Cached service interface containing config, host, service, and reference count\n *\n * @remarks\n * This method checks the static service cache for an existing language service matching the\n * current `configPath`. If found, it increments the reference count and returns the cached instance.\n * If not found, it delegates to {@link createLanguageService} to create and cache a new instance.\n *\n * @see {@link createLanguageService}\n *\n * @since 2.0.0\n */\n\n private acquireLanguageService(): CachedServiceInterface {\n const cached = TypescriptService.serviceCache.get(this.configPath);\n if (cached) {\n cached.refCount++;\n\n return cached;\n }\n\n return this.createLanguageService();\n }\n\n /**\n * Creates a new language service instance with host and caches it for future reuse.\n *\n * @returns Newly created cached service interface with reference count initialized to 1\n *\n * @remarks\n * This method performs the following steps:\n * - Parses the TypeScript configuration using {@link parseConfig}\n * - Creates a new language service host with the parsed options\n * - Initializes a TypeScript language service with the host and document registry\n * - Wraps everything in a cache entry with `refCount` set to 1\n * - Stores the entry in the static service cache\n *\n * @see {@link parseConfig}\n * @see {@link LanguageHostService}\n *\n * @since 2.0.0\n */\n\n private createLanguageService(): CachedServiceInterface {\n const config = this.parseConfig();\n const host = new LanguageHostService(config.options);\n const service = ts.createLanguageService(host, ts.createDocumentRegistry());\n\n const cached: CachedServiceInterface = { config, host, service, refCount: 1 };\n TypescriptService.serviceCache.set(this.configPath, cached);\n\n return cached;\n }\n\n /**\n * Creates a new language service instance with host and caches it for future reuse.\n *\n * @returns Newly created cached service interface with reference count initialized to 1\n *\n * @remarks\n * This method performs the following steps:\n * - Parses the TypeScript configuration using {@link parseConfig}\n * - Creates a new language service host with the parsed options\n * - Initializes a TypeScript language service with the host and document registry\n * - Wraps everything in a cache entry with `refCount` set to 1\n * - Stores the entry in the static service cache\n *\n * @see {@link parseConfig}\n * @see {@link LanguageHostService}\n *\n * @since 2.0.0\n */\n\n private parseConfig(): ParsedCommandLine {\n let config = ts.getParsedCommandLineOfConfigFile(\n this.configPath,\n {\n skipLibCheck: true,\n stripInternal: true,\n emitDeclarationOnly: true\n },\n {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {}\n }\n );\n\n if (!config) {\n config = {\n options: {\n strict: true,\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.NodeNext,\n declaration: true,\n skipLibCheck: true,\n moduleResolution: ts.ModuleResolutionKind.NodeNext\n },\n errors: [],\n fileNames: [],\n projectReferences: undefined\n };\n }\n\n config.options = {\n ...config.options,\n rootDir: config.options?.rootDir ?? process.cwd()\n };\n\n return config;\n }\n\n /**\n * Converts a TypeScript diagnostic into a standardized diagnostic interface with a formatted message and location.\n *\n * @param diagnostic - Raw TypeScript diagnostic from the compiler\n *\n * @returns Formatted diagnostic object with message, file path, line, column, and error code\n *\n * @remarks\n * This method flattens multi-line diagnostic messages into a single string using newline separators.\n * If the diagnostic includes file and position information, it calculates the human-readable line and\n * column numbers (1-indexed) and includes the diagnostic code.\n *\n * If no file or position information is available, only the message is included in the result.\n *\n * @since 2.0.0\n */\n\n private formatDiagnostic(diagnostic: Diagnostic): DiagnosticInterface {\n const result: DiagnosticInterface = {\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n category: diagnostic.category\n };\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n result.file = diagnostic.file.fileName;\n result.line = line + 1;\n result.column = character + 1;\n result.code = diagnostic.code;\n }\n\n return result;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LanguageService, Program, SourceFile } from 'typescript';\nimport type { LanguageHostService } from '@typescript/services/hosts.service';\nimport type { FileNodeInterface } from '@typescript/models/interfaces/graph-model.interface';\nimport type { BundleExportsInterface } from '@typescript/services/interfaces/bundler-serrvice.interface';\nimport type { ModuleImportsInterface } from '@typescript/services/interfaces/bundler-serrvice.interface';\nimport type { NamespaceExportsInterface } from '@typescript/services/interfaces/bundler-serrvice.interface';\n\n/**\n * Imports\n */\n\nimport { mkdir, writeFile } from 'fs/promises';\nimport { inject } from '@symlinks/symlinks.module';\nimport { join, dirname } from '@components/path.component';\nimport { GraphModel } from '@typescript/models/graph.model';\nimport { HeaderDeclarationBundle } from '@typescript/constants/typescript.constant';\n\n/**\n * Bundles multiple internal TypeScript files into consolidated, cleaned declaration files (.d.ts bundles).\n *\n * Starting from one or more entry points, traverses the internal dependency graph, collects all\n * relevant declarations, flattens namespaces, deduplicates exports, gathers external imports,\n * and writes a single portable declaration file per entry point.\n *\n * Primarily used for module federation, library publishing, public API bundling, or\n * creating type-only entry points that hide implementation details.\n *\n * @since 2.0.0\n */\n\nexport class BundlerService {\n /**\n * Injected singleton instance of the dependency graph builder.\n *\n * Provides scanned file nodes with cleaned content, internal dependencies,\n * and detailed import/export information.\n *\n * @remarks\n * Resolved via the framework's `inject()` helper \u2014 always returns the shared singleton.\n *\n * @see {@link GraphModel}\n * @since 2.0.0\n */\n\n private readonly graphModel = inject(GraphModel);\n\n /**\n * Creates bundler bound to a specific language service and host.\n *\n * @param languageService - active TS language service\n * @param languageHostService - host with compiler options and resolution\n *\n * @since 2.0.0\n */\n\n constructor(private languageService: LanguageService, private languageHostService: LanguageHostService) {\n }\n\n /**\n * Bundles declarations for each entry point and writes consolidated .d.ts files.\n *\n * @param entryPoints - map of output filename (without extension) \u2192 entry file path\n * @param outdir - optional override for output directory\n * @returns promise that resolves when all bundles are written\n *\n * @throws Error when language service program is unavailable\n *\n * @example\n * ```ts\n * await bundler.emit({\n * index: './src/index.ts',\n * components: './src/components/index.ts',\n * utils: './src/utils/index.ts'\n * }, './dist/types');\n *\n * // Results in:\n * // dist/types/index.d.ts\n * // dist/types/components.d.ts\n * // dist/types/utils.d.ts\n * ```\n *\n * @see {@link bundleCollectDeclarations}\n * @since 2.0.0\n */\n\n async emit(entryPoints: Record<string, string>, outdir?: string): Promise<void> {\n const program = this.languageService?.getProgram();\n if (!program) throw new Error('Language service program not available');\n\n let config = this.languageHostService.getCompilationSettings();\n if (outdir) config = { ...config, outDir: outdir };\n\n await Promise.all(\n Object.entries(entryPoints).map(async ([ outputPath, entryFile ]) => {\n const sourceFile = program.getSourceFile(entryFile);\n if (!sourceFile) return;\n\n const outputFile = join(config.outDir!, `${ outputPath }.d.ts`);\n await this.bundleCollectDeclarations(sourceFile, program, outputFile);\n })\n );\n }\n\n /**\n * Scans entry point, collects transitive declarations, and writes a bundled file.\n *\n * @param source - entry source file\n * @param program - current program (for source file lookup)\n * @param output - target output file path\n * @returns promise that resolves when write completes\n *\n * @since 2.0.0\n */\n\n private async bundleCollectDeclarations(source: SourceFile, program: Program, output: string): Promise<void> {\n const entryDeclaration = this.graphModel.scan(\n source, this.languageService, this.languageHostService\n );\n\n const content = await this.getBundleContent(entryDeclaration, program);\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, content, 'utf-8');\n }\n\n /**\n * Performs DFS traversal of internal dependencies, collects all relevant content,\n * and prepares it for final bundling.\n *\n * @param entryPoint - scanned entry file node\n * @param program - program for source file lookup\n * @returns concatenated and processed bundle content\n *\n * @remarks\n * Handles transitive star exports by propagating them during traversal.\n *\n * @since 2.0.0\n */\n\n private async getBundleContent(entryPoint: FileNodeInterface, program: Program): Promise<string> {\n const visited = new Set<string>();\n const exportList = new Set([ entryPoint ]);\n const dependencyList = new Set([ entryPoint ]);\n const dependencyQueue = [ ...entryPoint.internalDeps ];\n const starExportModules = new Set(entryPoint.internalExports.star);\n\n let content = '';\n while (dependencyQueue.length > 0) {\n const currentFile = dependencyQueue.pop()!;\n if (visited.has(currentFile)) continue;\n visited.add(currentFile);\n\n const sourceFile = program.getSourceFile(currentFile);\n if (!sourceFile) continue;\n\n const declaration = this.graphModel.scan(sourceFile, this.languageService, this.languageHostService);\n dependencyList.add(declaration);\n\n if (starExportModules.has(currentFile)) {\n exportList.add(declaration);\n for (const starModule of declaration.internalExports.star) starExportModules.add(starModule);\n }\n\n for (const dep of declaration.internalDeps) {\n if (!visited.has(dep)) dependencyQueue.push(dep);\n }\n\n content += declaration.content;\n }\n\n content += entryPoint.content;\n\n return this.parseContent(content, dependencyList, exportList);\n }\n\n /**\n * Aggregates all external imports across the bundle into a deduplicated map.\n *\n * @param declarations - set of scanned file nodes in the bundle\n * @returns map of module \u2192 consolidated imports (default, named, namespace)\n *\n * @since 2.0.0\n */\n\n private collectExternalImports(declarations: Set<FileNodeInterface>): Map<string, ModuleImportsInterface> {\n const imports = new Map<string, ModuleImportsInterface>();\n for (const declaration of declarations) {\n // Default imports: import Foo from 'module'\n for (const [ module, name ] of Object.entries(declaration.externalImports.default)) {\n if (!imports.has(module)) {\n imports.set(module, { named: new Set(), namespace: new Map() });\n }\n const moduleImports = imports.get(module)!;\n if (!moduleImports.default) {\n moduleImports.default = name;\n }\n }\n\n // Named imports: import { a, b } from 'module'\n for (const [ module, names ] of Object.entries(declaration.externalImports.named)) {\n if (!imports.has(module)) {\n imports.set(module, { named: new Set(), namespace: new Map() });\n }\n for (const name of names) {\n imports.get(module)!.named.add(name);\n }\n }\n\n // Namespace imports: import * as Foo from 'module'\n for (const [ name, module ] of Object.entries(declaration.externalImports.namespace)) {\n if (!imports.has(module)) {\n imports.set(module, { named: new Set(), namespace: new Map() });\n }\n imports.get(module)!.namespace.set(name, module);\n }\n }\n\n return imports;\n }\n\n /**\n * Converts collected external imports into sorted import statements.\n *\n * @param imports - deduplicated imports map\n * @returns array of `import \u2026 from \u2026` statements\n *\n * @remarks\n * Namespace imports are emitted separately to preserve `* as` semantics.\n *\n * @since 2.0.0\n */\n\n private generateImportStatements(imports: Map<string, ModuleImportsInterface>): Array<string> {\n const statements: Array<string> = [];\n for (const [ module, { default: defaultImport, named, namespace }] of imports) {\n const parts: Array<string> = [];\n\n if (defaultImport) {\n parts.push(defaultImport);\n }\n\n if (named.size > 0) {\n parts.push(`{ ${ Array.from(named).sort().join(', ') } }`);\n }\n\n if (namespace.size > 0) {\n for (const [ name ] of namespace) {\n statements.push(`import * as ${ name } from '${ module }';`);\n }\n }\n\n if (parts.length > 0) {\n statements.push(`import ${ parts.join(', ') } from '${ module }';`);\n }\n }\n\n return statements;\n }\n\n /**\n * Recursively collects exports from a namespace-exported module.\n *\n * @param fileName - file to start recursion from\n * @param visited - prevents cycles\n * @returns collected exports and supporting declarations\n *\n * @since 2.0.0\n */\n\n private collectNamespaceExports(fileName: string, visited = new Set<string>()): NamespaceExportsInterface {\n if (visited.has(fileName)) {\n return { exports: [], declarations: [] };\n }\n visited.add(fileName);\n\n const declaration = this.graphModel.get(fileName);\n if (!declaration) {\n return { exports: [], declarations: [] };\n }\n\n const exports: Array<string> = [ ...declaration.internalExports.exports ];\n const declarations: Array<string> = [];\n\n // Handle namespace exports: export * as Foo from './module'\n for (const [ namespaceName, targetModule ] of Object.entries(declaration.internalExports.namespace)) {\n const nested = this.collectNamespaceExports(targetModule, visited);\n\n if (nested.exports.length > 0) {\n declarations.push(...nested.declarations);\n declarations.push(`const ${ namespaceName } = { ${ nested.exports.join(', ') } };`);\n exports.push(namespaceName);\n }\n }\n\n // Handle star exports: export * from './module'\n for (const starModule of declaration.externalExports.star) {\n const nested = this.collectNamespaceExports(starModule, visited);\n exports.push(...nested.exports);\n declarations.push(...nested.declarations);\n }\n\n return { exports, declarations };\n }\n\n /**\n * Gathers all exports and supporting declarations for the bundle entry points.\n *\n * @param exportList - set of files that should be re-exported\n * @returns structured bundle exports\n *\n * @since 2.0.0\n */\n\n private collectBundleExports(exportList: Set<FileNodeInterface>): BundleExportsInterface {\n const exports: Array<string> = [];\n const declarations: Array<string> = [];\n const externalExports: Array<string> = [];\n\n for (const declaration of exportList) {\n exports.push(...declaration.internalExports.exports);\n\n // Namespace exports: export * as Foo from './module'\n for (const [ namespaceName, targetModule ] of Object.entries(declaration.internalExports.namespace)) {\n const nested = this.collectNamespaceExports(targetModule);\n\n if (nested.exports.length > 0) {\n declarations.push(...nested.declarations);\n declarations.push(`const ${ namespaceName } = { ${ nested.exports.join(', ') } };`);\n exports.push(namespaceName);\n }\n }\n\n // External star exports: export * from 'external-module'\n for (const module of declaration.externalExports.star) {\n declarations.push(`export * from '${ module }';`);\n }\n\n // External namespace exports: export * as Foo from 'external-module'\n for (const [ namespaceName, module ] of Object.entries(declaration.externalExports.namespace)) {\n externalExports.push(`export * as ${ namespaceName } from '${ module }';`);\n }\n\n // External named exports: export { a, b } from 'external-module'\n for (const [ module, names ] of Object.entries(declaration.externalExports.exports)) {\n externalExports.push(`export { ${ names.join(',\\n') } } from '${ module }';`);\n }\n }\n\n return { exports, declarations, externalExports };\n }\n\n /**\n * Combines all parts into final bundle content with header, imports, declarations, content, and exports.\n *\n * @param content - concatenated cleaned declaration text\n * @param dependencyList - all files in dependency closure\n * @param exportList - files whose exports should be re-exported\n * @returns final bundled declaration text\n *\n * @since 2.0.0\n */\n\n private parseContent(content: string, dependencyList: Set<FileNodeInterface>, exportList: Set<FileNodeInterface>): string {\n const parts: Array<string> = [ HeaderDeclarationBundle ];\n const imports = this.collectExternalImports(dependencyList);\n const importStatements = this.generateImportStatements(imports);\n parts.push(...importStatements);\n\n if (importStatements.length > 0) parts.push(''); // Empty line after imports\n const { exports, declarations, externalExports } = this.collectBundleExports(exportList);\n if (declarations.length > 0) {\n parts.push(...declarations);\n parts.push('');\n }\n\n parts.push(content);\n if (exports.length > 0) {\n const uniqueExports = Array.from(new Set(exports)).sort();\n parts.push(`export {\\n\\t${ uniqueExports.join(',\\n\\t') }\\n};`);\n }\n\n if (externalExports.length > 0) {\n parts.push(...externalExports);\n }\n\n return parts.join('\\n');\n }\n}\n", "/**\n * Header text included at the top of generated declaration bundle files.\n *\n * @remarks\n * This constant provides a standardized header comment prepended to all\n * declaration bundle files generated by the TypeScript module. The header clearly\n * indicates that the file was automatically generated and should not be edited manually.\n *\n * The header serves as:\n * - A warning to developers not to manually modify generated files\n * - Documentation indicating the source of the file\n * - A consistent marker for identifying generated declaration files\n *\n * @example\n * ```ts\n * import { HeaderDeclarationBundle } from './typescript.constant';\n * import { writeFileSync } from 'fs';\n *\n * const bundledContent = `${HeaderDeclarationBundle}\\n${actualDeclarations}`;\n * writeFileSync('dist/index.d.ts', bundledContent);\n * ```\n *\n * @since 1.5.9\n */\n\nexport const HeaderDeclarationBundle = `/**\n * This file was automatically generated by xBuild.\n * DO NOT EDIT MANUALLY.\n */\n`;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LanguageHostService } from '@typescript/services/hosts.service';\nimport type { CompilerOptions, Program, SourceFile, LanguageService } from 'typescript';\n\n/**\n * Imports\n */\n\nimport { mkdir, writeFile } from 'fs/promises';\nimport { dirname } from '@components/path.component';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { calculateOutputPath, cleanContent } from '@typescript/components/transformer.component';\n\n/**\n * Incremental declaration emitter that writes cleaned `.d.ts` files to disk.\n *\n * Uses the TypeScript language service to emit declaration files only for changed\n * project files (skipping external libraries and unchanged versions), applies alias\n * path resolution, cleans unnecessary content, and writes files to the configured `outDir`.\n *\n * Designed for build tools, watch-mode compilers, module federation setups, or\n * public API packaging workflows that need fresh, minimal type declarations.\n *\n * @since 2.0.0\n */\n\nexport class EmitterService {\n /**\n * Maps output declaration path \u2192 last emitted version string.\n *\n * Used to skip redundant emits when file content/version has not changed.\n *\n * @remarks\n * Static, so the cache survives across service instances (useful in long-running processes).\n *\n * @since 2.0.0\n */\n\n private static emittedVersions: Map<string, string> = new Map();\n\n /**\n * Creates emitter bound to a specific language service and host.\n *\n * @param languageService - active TS language service instance\n * @param languageHostService - host with compiler options and resolution capabilities\n *\n * @since 2.0.0\n */\n\n constructor(private languageService: LanguageService, private languageHostService: LanguageHostService) {\n }\n\n /**\n * Clears the static version cache used for incremental emit decisions.\n * @since 2.0.0\n */\n\n static clearCache(): void {\n this.emittedVersions.clear();\n }\n\n /**\n * Emits cleaned declaration files for all changed project source files.\n *\n * @param outdir - optional override for output directory (overrides `outDir` in config)\n * @returns promise that resolves when all writes are complete\n *\n * @throws Error when language service program is unavailable\n *\n * @example\n * ```ts\n * // One-time full emit to custom directory\n * await emitter.emit('./dist/types');\n *\n * // Incremental emit on watch change\n * emitter.emit(); // uses original compilerOptions.outDir\n * ```\n *\n * @see {@link shouldEmitFile}\n * @see {@link emitSingleDeclaration}\n *\n * @since 2.0.0\n */\n\n async emit(outdir?: string): Promise<void> {\n const program = this.languageService.getProgram();\n if (!program) {\n throw new Error(`${ xterm.deepOrange('[TS]') } Language service program is not available`);\n }\n\n let config = this.languageHostService.getCompilationSettings();\n if (outdir) config = { ...config, outDir: outdir };\n\n const filesToEmit: Array<SourceFile> = [];\n const sourceFiles = program.getSourceFiles();\n for (let i = 0; i < sourceFiles.length; i++) {\n const file = sourceFiles[i];\n if (this.shouldEmitFile(file, program, config)) {\n filesToEmit.push(file);\n }\n }\n\n if (filesToEmit.length === 0) return;\n await Promise.all(filesToEmit.map(\n source => this.emitSingleDeclaration(source, config)\n ));\n }\n\n /**\n * Determines whether a source file should be (re-)emitted based on version and type.\n *\n * @param file - candidate source file\n * @param program - current program (for external library check)\n * @param config - effective compiler options (with possible outDir override)\n * @returns `true` if a file needs emission\n *\n * @remarks\n * Skips:\n * - `.d.ts` files\n * - files from external libraries (node_modules)\n * - files whose version matches the last emitted version\n *\n * Updates cache when emission is needed.\n *\n * @since 2.0.0\n */\n\n private shouldEmitFile(file: SourceFile, program: Program, config: CompilerOptions): boolean {\n if (file.isDeclarationFile || program.isSourceFileFromExternalLibrary(file))\n return false;\n\n const outputPath = calculateOutputPath(file.fileName, config);\n const version = EmitterService.emittedVersions.get(outputPath);\n const currentVersion = this.languageHostService.getScriptVersion(file.fileName);\n\n if (!version) {\n EmitterService.emittedVersions.set(\n outputPath, currentVersion\n );\n\n return true;\n }\n\n if (version !== currentVersion) {\n EmitterService.emittedVersions.set(outputPath, currentVersion);\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Emits and writes a single cleaned declaration file to disk.\n *\n * @param sourceFile - file to emit\n * @param options - compiler options (including outDir)\n * @returns promise that resolves when write completes\n *\n * @remarks\n * - Uses `emitOnlyDtsFiles: true`\n * - Applies `cleanContent` and alias resolution (if aliases are configured)\n * - Creates directories recursively if needed\n *\n * @example\n * ```ts\n * // Internal usage pattern\n * const output = languageService.getEmitOutput(file.fileName, true);\n * let text = output.outputFiles[0].text;\n * text = cleanContent(text);\n * if (aliasRegex) text = this.resolveAliases(aliasRegex, text, sourceFile);\n * await writeFile(calculatedPath, text, 'utf8');\n * ```\n *\n * @since 2.0.0\n */\n\n private async emitSingleDeclaration(sourceFile: SourceFile, options: CompilerOptions): Promise<void> {\n const output = this.languageService.getEmitOutput(sourceFile.fileName, true);\n if (output.emitSkipped) return;\n\n let content = output.outputFiles[0].text;\n const fileName = calculateOutputPath(sourceFile.fileName, options);\n\n content = cleanContent(content);\n content = this.languageHostService.resolveAliases(content, sourceFile.fileName, '.d.ts');\n\n await mkdir(dirname(fileName), { recursive: true });\n await writeFile(fileName, content, 'utf8');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ResolvedModuleWithFailedLookupLocations } from 'typescript';\nimport type { CompilerOptions, IScriptSnapshot, ModuleResolutionCache } from 'typescript';\nimport type { FileSnapshotInterface } from '@typescript/models/interfaces/files-model.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { inject } from '@symlinks/symlinks.module';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { relative, dirname } from '@components/path.component';\n\n/**\n * Implements a TypeScript Language Service host with file snapshot caching and module resolution.\n *\n * @remarks\n * The `LanguageHostService` implements the {@link ts.LanguageServiceHost} interface to provide\n * TypeScript's language service with file system access, file snapshots, and compiler configuration.\n *\n * @example\n * ```ts\n * // Initialize with compiler options\n * const host = new LanguageHostService({\n * target: ts.ScriptTarget.ES2020,\n * module: ts.ModuleKind.ESNext,\n * paths: {\n * '@utils/*': ['src/utils/*'],\n * '@components/*': ['src/components/*']\n * }\n * });\n *\n * // Track files for analysis\n * host.touchFile('src/index.ts');\n * host.touchFiles(['src/utils.ts', 'src/types.ts']);\n *\n * // Get file snapshots for language service\n * const snapshot = host.getScriptSnapshot('src/index.ts');\n *\n * // Resolve module imports\n * const resolved = host.resolveModuleName('@utils/helpers', 'src/index.ts');\n *\n * // Check for path aliases\n * const hasAliases = host.aliasRegex !== undefined;\n *\n * // Update configuration\n * host.options = { target: ts.ScriptTarget.ES2022 };\n * ```\n *\n * @see {@link ts.LanguageServiceHost} for the implemented interface specification\n * @see {@link FilesModel} for file snapshot caching implementation\n *\n * @since 2.0.0\n */\n\nexport class LanguageHostService implements ts.LanguageServiceHost {\n /**\n * Reference to TypeScript's system interface for file operations.\n *\n * @remarks\n * Static reference to `ts.sys` that provides abstracted file system operations\n * (read, write, directory traversal) compatible with different environments (Node.js, browsers, etc.).\n * Used for all file I/O operations in this service to maintain platform independence.\n *\n * @see {@link ts.sys}\n *\n * @since 2.0.0\n */\n\n private static readonly sys = ts.sys;\n\n /**\n * Cached regular expression for matching import/export statements with path aliases.\n *\n * @remarks\n * Compiled from `compilerOptions.paths` to efficiently detect imports using path aliases.\n * Regenerated when compiler options change. Undefined if no path aliases are configured.\n *\n * Used by tools that need to identify which import statements use aliases for proper\n * handling during transformation or bundling.\n *\n * @see {@link generateAliasRegex} for pattern generation\n *\n * @since 2.0.0\n */\n\n private alias: RegExp | undefined;\n\n private aliasCache = new Map<string, string | undefined>();\n\n /**\n * Cache for TypeScript module resolution results.\n *\n * @remarks\n * TypeScript's internal module resolution cache that stores resolution results to avoid\n * redundant lookups. Improves performance significantly when resolving many imports,\n * especially in large projects with complex path mappings.\n *\n * Recreated when compiler options change (since different options may affect resolution).\n *\n * @see {@link ts.createModuleResolutionCache}\n *\n * @since 2.0.0\n */\n\n private moduleResolutionCache: ModuleResolutionCache;\n\n /**\n * A set containing the file paths of all actively tracked script files.\n *\n * @remarks\n * This set ensures that files are tracked for later operations, such as retrieving script versions\n * or snapshots. Files are added to this set when they are first processed or read by the service.\n *\n * @example\n * ```ts\n * trackFiles.add('/src/main.ts');\n * console.log(trackFiles.has('/src/main.ts')); // true\n * ```\n *\n * @see {@link getScriptFileNames} - Retrieves all tracked files.\n *\n * @since 2.0.0\n */\n\n private readonly trackFiles = new Set<string>();\n\n /**\n * Model for managing file snapshots and version tracking.\n *\n * @remarks\n * Delegates file snapshot management to {@link FilesModel} for centralized\n * caching and change detection. Snapshots are tracked by modification time\n * to detect file changes efficiently.\n *\n * @see {@link FilesModel}\n *\n * @since 2.0.0\n */\n\n private readonly filesCache = inject(FilesModel);\n\n /**\n * Initializes a new {@link LanguageHostService} instance.\n *\n * @param compilerOptions - Optional TypeScript compiler options (defaults to an empty object)\n *\n * @remarks\n * Performs initialization including:\n * 1. Stores compiler options for later use\n * 2. Generates path alias regex from options if configured\n * 3. Creates module resolution cache with appropriate settings\n *\n * The module resolution cache is necessary for efficient resolution of imports in large projects.\n * Path alias regex is generated up-front and cached for performance.\n *\n * @example\n * ```ts\n * // Create host with default options\n * const host = new LanguageHostService();\n *\n * // Create host with specific compiler options\n * const host = new LanguageHostService({\n * target: ts.ScriptTarget.ES2020,\n * module: ts.ModuleKind.ESNext,\n * paths: {\n * '@utils/*': ['src/utils/*']\n * }\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(private compilerOptions: CompilerOptions = {}) {\n this.alias = LanguageHostService.generateAliasRegex(compilerOptions);\n this.moduleResolutionCache = ts.createModuleResolutionCache(\n process.cwd(),\n s => s,\n this.compilerOptions\n );\n }\n\n /**\n * Regular expression that matches import/export statements using path aliases (if `paths` is configured).\n *\n * @remarks\n * Used mainly for advanced refactoring or rewrite tools that need to identify aliased imports.\n *\n * @since 2.0.0\n */\n\n get aliasRegex(): RegExp | undefined {\n return this.alias;\n }\n\n /**\n * Replaces current compiler options and regenerates derived state (alias regex, module cache).\n *\n * @param options - new compiler configuration\n *\n * @since 2.0.0\n */\n\n set options(options: CompilerOptions) {\n this.compilerOptions = options;\n this.alias = LanguageHostService.generateAliasRegex(options);\n this.moduleResolutionCache = ts.createModuleResolutionCache(\n process.cwd(),\n s => s,\n this.compilerOptions\n );\n }\n\n /**\n * Updates file snapshot in the cache and returns the current state.\n *\n * @param path - file path (relative or absolute)\n * @returns current snapshot data (version, mtime, content snapshot)\n *\n * @see {@link FilesModel#touchFile}\n * @since 2.0.0\n */\n\n touchFile(path: string): FileSnapshotInterface {\n this.trackFiles.add(this.filesCache.resolve(path));\n\n return this.filesCache.touchFile(path);\n }\n\n /**\n * Ensures multiple files are tracked and their snapshots are up to date.\n *\n * @param filesPath - list of file paths to touch\n *\n * @since 2.0.0\n */\n\n touchFiles(filesPath: Array<string>): void {\n for (const file of filesPath) {\n this.touchFile(file);\n }\n }\n\n /**\n * Returns current compiler options used by this host.\n *\n * @returns active TypeScript compiler configuration\n *\n * @since 2.0.0\n */\n\n getCompilationSettings(): CompilerOptions {\n return this.compilerOptions;\n }\n\n /**\n * Checks whether a file exists on disk.\n *\n * @param path - absolute path\n * @returns `true` if file exists\n *\n * @since 2.0.0\n */\n\n fileExists(path: string): boolean {\n return LanguageHostService.sys.fileExists(path);\n }\n\n /**\n * Reads file content from disk.\n *\n * @param path - absolute path\n * @param encoding - optional encoding (defaults to UTF-8)\n * @returns file content or `undefined` if read fails\n *\n * @since 2.0.0\n */\n\n readFile(path: string, encoding?: string): string | undefined {\n return LanguageHostService.sys.readFile(path, encoding);\n }\n\n /**\n * Lists files and/or directories matching criteria.\n *\n * @param path - starting directory\n * @param extensions - allowed file extensions\n * @param exclude - glob exclude patterns\n * @param include - glob include patterns\n * @param depth - max recursion depth\n * @returns matching file paths\n *\n * @since 2.0.0\n */\n\n readDirectory(path: string, extensions?: Array<string>, exclude?: Array<string>, include?: Array<string>, depth?: number): Array<string> {\n return LanguageHostService.sys.readDirectory(path, extensions, exclude, include, depth);\n }\n\n /**\n * Returns immediate subdirectories of a given path.\n *\n * @param path - directory to list\n * @returns subdirectory names\n *\n * @since 2.0.0\n */\n\n getDirectories(path: string): Array<string> {\n return LanguageHostService.sys.getDirectories(path);\n }\n\n /**\n * Checks whether a directory exists.\n *\n * @param path - absolute path\n * @returns `true` if directory exists\n *\n * @since 2.0.0\n */\n\n directoryExists(path: string): boolean {\n return LanguageHostService.sys.directoryExists(path);\n }\n\n /**\n * Returns the current working directory used as resolution base.\n *\n * @returns absolute path of cwd\n *\n * @since 2.0.0\n */\n\n getCurrentDirectory(): string {\n return LanguageHostService.sys.getCurrentDirectory();\n }\n\n /**\n * Returns names of all known script files tracked by this host.\n *\n * @returns array of resolved absolute paths\n *\n * @remarks\n * Only includes files previously requested via `getScriptSnapshot` or explicitly `touchFile`/`touchFiles`.\n *\n * @since 2.0.0\n */\n\n getScriptFileNames(): Array<string> {\n return [ ...this.trackFiles ];\n }\n\n /**\n * Returns a path to a default lib `.d.ts` file matching the given target.\n *\n * @param options - compiler options (mainly `target`)\n * @returns absolute path to lib.d.ts / lib.esxxxx.d.ts\n *\n * @since 2.0.0\n */\n\n getDefaultLibFileName(options: CompilerOptions): string {\n return ts.getDefaultLibFilePath(options);\n }\n\n /**\n * Returns string version identifier for the given file.\n *\n * @param path - file path\n * @returns version as string (usually `\"0\"`, `\"1\"`, `\"2\"`, \u2026)\n *\n * @remarks\n * Tracks file in `trackFiles` set as a side effect so it appears in `getScriptFileNames()`.\n *\n * @since 2.0.0\n */\n\n getScriptVersion(path: string): string {\n const state = this.filesCache.getSnapshot(path);\n this.trackFiles.add(this.filesCache.resolve(path));\n\n return state ? state.version.toString() : '0';\n }\n\n /**\n * Checks whether a file is actively tracked (has been requested before).\n *\n * @param path - file path\n * @returns `true` if the file is known to this host\n *\n * @since 2.0.0\n */\n\n hasScriptSnapshot(path: string): boolean {\n return this.trackFiles.has(this.filesCache.resolve(path));\n }\n\n /**\n * Returns an up-to-date script snapshot for the file.\n *\n * @param path - file path\n * @returns `IScriptSnapshot` or `undefined` if a file is missing/empty\n *\n * @remarks\n * Automatically touches the file (reads disk if needed) when no snapshot exists yet.\n *\n * @since 2.0.0\n */\n\n getScriptSnapshot(path: string): IScriptSnapshot | undefined {\n const state = this.filesCache.getSnapshot(path);\n this.trackFiles.add(this.filesCache.resolve(path));\n if (state) return state.contentSnapshot;\n\n return this.touchFile(path).contentSnapshot;\n }\n\n /**\n * Resolves module import using current compiler options and cache.\n *\n * @param moduleName - module specifier\n * @param containingFile - path of a file containing the import\n * @returns resolution result (success and failed lookups)\n *\n * @since 2.0.0\n */\n\n resolveModuleName(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations {\n return ts.resolveModuleName(\n moduleName, containingFile, this.compilerOptions, ts.sys, this.moduleResolutionCache\n );\n }\n\n /**\n * Resolves a module specifier to its absolute file path using the host.\n *\n * @param moduleName - import/export specifier (e.g. \"lodash\", \"./utils\")\n * @param containingFile - path of a file containing the import\n * @returns resolved absolute path or `undefined` if resolution fails\n *\n * @since 2.0.0\n */\n\n resolveModuleFileName(moduleName: string, containingFile: string): string | undefined {\n if (this.aliasCache.has(moduleName)) {\n return this.aliasCache.get(moduleName);\n }\n\n const resolved = this.resolveModuleName(moduleName, containingFile);\n const result = resolved.resolvedModule?.resolvedFileName;\n this.aliasCache.set(moduleName, result);\n\n return result;\n }\n\n /**\n * Rewrites path aliases in declaration content to relative paths.\n *\n * @param content - raw declaration text\n * @param fileName - source file name\n * @param type - file extension to append to resolved paths (e.g., `'.d.ts'`, `'.js'`), defaults to empty string\n * @returns content with aliases replaced by relative paths\n *\n * @remarks\n * Ensures emitted files use portable relative imports instead of aliases.\n * The `type` parameter allows flexible transformation of resolved TypeScript source file extensions\n * (`.ts`, `.tsx`) to any target extension.\n *\n * **Common use cases**:\n * - Pass `'.d.ts'` for declaration file generation\n * - Pass `'.js'` for JavaScript output paths\n * - Pass `''` (default) to preserve the resolved file extension\n *\n * @example\n * ```ts\n * // For regular source files (preserve extension)\n * const code = host.resolveAliases(content, 'src/index.ts');\n *\n * // For declaration files\n * const dts = host.resolveAliases(content, 'src/index.ts', '.d.ts');\n * // '@utils/helpers' -> './utils/helpers.d.ts'\n *\n * // For JavaScript output\n * const js = host.resolveAliases(content, 'src/index.ts', '.js');\n * // '@utils/helpers' -> './utils/helpers.js'\n * ```\n *\n * @since 2.0.0\n */\n\n resolveAliases(content: string, fileName: string, type: string = ''): string {\n if(!this.alias) return content;\n\n return content.replace(this.alias, (match, importPath) => {\n const resolve = this.resolveModuleFileName(importPath, fileName);\n if (!resolve) return match;\n\n const targetFile = resolve.replace(/\\.tsx?$/, type);\n const relativePath = relative(dirname(fileName), targetFile);\n\n return match.replace(importPath, relativePath.startsWith('.') ? relativePath : './' + relativePath);\n });\n }\n\n /**\n * Builds regex that matches import/export declarations using any configured path alias.\n *\n * @param config - compiler options containing `paths`\n * @returns regex or `undefined` if no `paths` configured\n *\n * @since 2.0.0\n */\n\n private static generateAliasRegex(config: CompilerOptions): RegExp | undefined {\n const paths = config.paths;\n if (!paths || Object.keys(paths).length < 1) return;\n\n const aliases = Object.keys(paths)\n .map(alias => alias.replace('/*', '').replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('|');\n\n return new RegExp(\n '(?:^|\\\\s)(?:import|export)\\\\s+' + // import or export keyword\n '(?:type\\\\s+)?' + // optional 'type' keyword\n '(?:[^\\'\"]*from\\\\s+)?' + // optional '... from' (non-greedy)\n `['\"]((${ aliases })[^'\"]*)['\"]` + // capture the quoted path with alias\n ';?', // optional semicolon\n 'gm'\n );\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions, BuildResult, Metafile } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { build } from 'esbuild';\nimport { isBuildResultError, processEsbuildMessages } from '@providers/esbuild-messages.provider';\n\n/**\n * Default ESBuild options used when building or transpiling files.\n *\n * @remarks\n * These defaults bundle, minify, preserve symlinks, and generate external sourcemaps\n * targeting modern browser environments.\n *\n * see BuildOptions\n * @since 2.0.0\n */\n\nexport const defaultBuildOptions: BuildOptions = {\n write: false,\n bundle: true,\n minify: true,\n outdir: `${ cwd() }`,\n format: 'esm',\n target: 'esnext',\n platform: 'browser',\n sourcemap: 'external',\n mangleQuoted: true,\n sourcesContent: true,\n preserveSymlinks: true\n};\n\n/**\n * Builds multiple files using ESBuild with specified options.\n *\n * @param entryPoints - Array of entry points to build\n * @param buildOptions - Optional override build options\n *\n * @returns A promise resolving to an ESBuild BuildResult including metafile information\n *\n * @throws AggregateError - Thrown if esBuild encounters errors during build\n *\n * @remarks\n * This function merges user-provided options with default options and ensures\n * that a metafile is generated. If any errors occur during the build, they are\n * wrapped in a {@link AggregateError} for consistent error reporting.\n *\n * @example\n * ```ts\n * const result = await buildFiles(['src/index.ts'], { minify: false });\n * console.log(result.outputFiles);\n * ```\n *\n * @see esBuildError\n * @see AggregateError\n *\n * @since 2.0.0\n */\n\nexport async function buildFiles(entryPoints: BuildOptions['entryPoints'], buildOptions: BuildOptions = {}): Promise<BuildResult<BuildOptions & Metafile>> {\n try {\n return await build({\n absWorkingDir: cwd(),\n ...defaultBuildOptions,\n ...buildOptions,\n metafile: true,\n entryPoints: entryPoints\n }) as BuildResult<BuildOptions & Metafile>;\n } catch (err) {\n if(isBuildResultError(err)) {\n const aggregateError = new AggregateError([], 'Failed to build entryPoints');\n processEsbuildMessages(err.errors, aggregateError.errors);\n\n throw aggregateError;\n }\n\n throw err;\n }\n}\n\n/**\n * Transpiles TypeScript source code from a string into bundled JavaScript output without writing to disk.\n *\n * @param source - TypeScript source code as a string to transpile\n * @param path - Source file path used for source map generation and error reporting\n * @param buildOptions - Optional esbuild configuration options to override defaults\n *\n * @returns Promise resolving to a {@link BuildResult} containing transpiled code, source maps, and metadata\n *\n * @remarks\n * This function performs in-memory transpilation of TypeScript code using esbuild's stdin feature.\n * It's particularly useful for:\n * - Runtime code evaluation and transformation\n * - Macro expansion and inline directives\n * - Dynamic code generation during builds\n * - Testing and validation without file system writes\n *\n * The function applies the following configuration:\n * - Uses {@link defaultBuildOptions} as the base configuration\n * - Overrides with provided `buildOptions` parameter\n * - Forces `write: false` to keep output in memory\n * - Enables `metafile: true` for dependency analysis\n * - Sets `logLevel: 'silent'` to suppress build output\n * - Generates external source maps for debugging\n *\n * The source code is treated as TypeScript (`loader: 'ts'`) and resolved relative to the current\n * working directory. The `path` parameter is used for source map generation and error messages\n * but does not need to reference an actual file on disk.\n *\n * @example\n * ```ts\n * // Basic transpilation\n * const result = await buildFromString(\n * 'const x: number = 42; export default x;',\n * 'virtual.ts'\n * );\n * console.log(result.outputFiles[0].text); // Transpiled JS\n * ```\n *\n * @example\n * ```ts\n * // With custom build options\n * const result = await buildFromString(\n * 'export const add = (a: number, b: number) => a + b;',\n * 'math.ts',\n * {\n * format: 'cjs',\n * target: 'node16',\n * minify: true\n * }\n * );\n * ```\n *\n * @example\n * ```ts\n * // Used in macro evaluation\n * const code = extractExecutableCode(node, state);\n * const transpiled = await buildFromString(\n * code.data,\n * state.sourceFile.fileName,\n * {\n * bundle: false,\n * format: 'cjs',\n * packages: 'external',\n * platform: 'node'\n * }\n * );\n * // Execute transpiled code in VM\n * ```\n *\n * @see {@link BuildResult} for output structure\n * @see {@link defaultBuildOptions} for base configuration\n * @see {@link BuildOptions} for available configuration options\n * @see {@link analyzeDependencies} for dependency analysis without transpilation\n *\n * @since 2.0.0\n */\n\nexport async function buildFromString(source: string, path: string, buildOptions: BuildOptions = {}): Promise<BuildResult> {\n return await build({\n absWorkingDir: cwd(),\n ...defaultBuildOptions,\n ...buildOptions,\n stdin: {\n loader: 'ts',\n contents: source,\n resolveDir: cwd(),\n sourcefile: path\n },\n write: false,\n metafile: true,\n logLevel: 'silent',\n sourcemap: 'external'\n });\n}\n\n/**\n * Analyzes dependencies of entry point files without writing output.\n *\n * @param entryPoint - Entry point file path(s) for dependency analysis.\n * @param buildOptions - Optional esbuild configuration options to customize the analysis.\n * @returns A promise that resolves to a {@link BuildResult} with metafile metadata containing dependency information.\n *\n * @remarks\n * This function performs a lightweight dependency analysis by:\n *\n * 1. Running esbuild in bundling mode to resolve all imports and dependencies\n * 2. Generating a metafile containing detailed dependency graph information\n * 3. Marking external packages to avoid bundling node_modules\n * 4. Disabling file output to keep the analysis fast and non-destructive\n * 5. Suppressing log output for cleaner execution\n *\n * The resulting metafile contains:\n * - All resolved imports and their relationships\n * - Module dependencies and their sizes\n * - Entry point analysis\n * - Import/export structure information\n *\n * This is useful for:\n * - Understanding project dependency graphs\n * - Identifying circular dependencies\n * - Analyzing import chains\n * - Profiling bundle composition\n * - Validating module resolution\n *\n * @example\n * ```ts\n * // Basic dependency analysis\n * const result = await analyzeDependencies('src/index.ts');\n * console.log('Dependencies:', Object.keys(result.metafile.inputs));\n *\n * // With custom build options\n * const result = await analyzeDependencies('src/main.ts', {\n * external: ['lodash', 'react'],\n * alias: { '@utils': './src/utils' }\n * });\n *\n * // Analyze multiple entry points\n * const result = await analyzeDependencies(\n * ['src/index.ts', 'src/cli.ts']\n * );\n *\n * for (const [input, data] of Object.entries(result.metafile.inputs)) {\n * console.log(`File: ${input}`);\n * console.log(`Imports: ${data.imports.map(i => i.path).join(', ')}`);\n * }\n * ```\n *\n * @see Metafile\n * @see BuildResult\n * @see BuildOptions\n *\n * @since 1.0.0\n */\n\nexport async function analyzeDependencies(entryPoint: BuildOptions['entryPoints'], buildOptions: BuildOptions = {}): Promise<\n BuildResult & { metafile: Metafile }\n> {\n try {\n return await build({\n ...buildOptions,\n outdir: 'tmp',\n write: false, // Prevent writing output files\n bundle: true, // Bundle to analyze imports\n metafile: true, // Generate a metafile to analyze dependencies\n packages: 'external',\n logLevel: 'silent',\n entryPoints: entryPoint\n });\n } catch(err) {\n if(isBuildResultError(err)) {\n const aggregateError = new AggregateError([], 'Failed to analyze entryPoint');\n processEsbuildMessages(err.errors, aggregateError.errors);\n\n throw aggregateError;\n }\n\n throw err;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { xBuildError } from '@errors/xbuild.error';\nimport { collectFilesFromGlob } from '@components/glob.component';\n\n/**\n * Extracts and normalizes entry points from various esbuild entry point formats.\n *\n * @param baseDir - Base directory to resolve glob patterns from\n * @param entryPoints - Entry points in any esbuild-supported format\n * @returns Normalized object mapping output names to input file paths\n *\n * @remarks\n * Supports three esbuild entry point formats:\n *\n * **Array of strings (glob patterns):**\n * - Treats entries as glob patterns to match files\n * - Keys are filenames without extensions\n *\n * **Array of objects with `in` and `out` properties:**\n * - `in`: Input file path\n * - `out`: Output file path\n * - Keys are the `out` values\n *\n * **Record object:**\n * - Keys are output names\n * - Values are input file paths\n * - Returned as-is without modification\n *\n * @throws {@link xBuildError}\n * Thrown when entry points format is unsupported or invalid\n *\n * @example\n * Array of glob patterns:\n * ```ts\n * const entries = extractEntryPoints('./src', ['**\\/*.ts', '!**\\/*.test.ts']);\n * // Returns: { 'index': 'index.ts', 'utils/helper': 'utils/helper.ts' }\n * ```\n *\n * @example\n * Array of in/out objects:\n * ```ts\n * const entries = extractEntryPoints('./src', [\n * { in: 'src/index.ts', out: 'bundle' },\n * { in: 'src/worker.ts', out: 'worker' }\n * ]);\n * // Returns: { 'bundle': 'src/index.ts', 'worker': 'src/worker.ts' }\n * ```\n *\n * @example\n * Record object:\n * ```ts\n * const entries = extractEntryPoints('./src', {\n * main: 'src/index.ts',\n * worker: 'src/worker.ts'\n * });\n * // Returns: { 'main': 'src/index.ts', 'worker': 'src/worker.ts' }\n * ```\n *\n * @see {@link https://esbuild.github.io/api/#entry-points|esbuild Entry Points}\n *\n * @since 2.0.0\n */\n\nexport function extractEntryPoints(baseDir: string, entryPoints: BuildOptions['entryPoints']): Record<string, string> {\n if (Array.isArray(entryPoints)) {\n let result: Record<string, string> = {};\n\n if (entryPoints.length > 0 && typeof entryPoints[0] === 'object') {\n (entryPoints as { in: string, out: string }[]).forEach(entry => {\n result[entry.out] = entry.in;\n });\n } else if (typeof entryPoints[0] === 'string') {\n result = collectFilesFromGlob(baseDir, <Array<string>> entryPoints);\n }\n\n return result;\n } else if (entryPoints && typeof entryPoints === 'object') {\n return entryPoints;\n }\n\n throw new xBuildError('Unsupported entry points format');\n}\n", "/**\n * Type imports (removed at compile time)\n */\n\nimport type { PluginBuild, Plugin, OnStartResult, PartialMessage, Message } from 'esbuild';\nimport type { OnEndType, OnLoadType, OnStartType } from './interfaces/lifecycle-provider.interface';\nimport type { BuildResult, OnResolveResult, OnResolveArgs, OnLoadResult, OnLoadArgs } from 'esbuild';\nimport type { OnResolveType, LifecycleContextInterface } from './interfaces/lifecycle-provider.interface';\n\n/**\n * Imports\n */\n\nimport { readFile } from 'fs/promises';\nimport { inject } from '@symlinks/symlinks.module';\nimport { resolve } from '@components/path.component';\nimport { FilesModel } from '@typescript/models/files.model';\n\n/**\n * Manages lifecycle hooks for esbuild plugins with support for build stages and hook execution coordination.\n * Provides a centralized system for registering and executing hooks during different phases of the build process,\n * including resolution, loading, start, end, and success stages.\n *\n * @remarks\n * This provider implements a hook-based architecture that allows multiple handlers to be registered\n * for each build lifecycle stage. Hooks are stored in maps keyed by name, allowing for organized\n * registration and execution of build-time logic.\n *\n * The lifecycle stages are executed in the following order:\n * 1. **onStart**: Executed when the build begins, before any file processing\n * 2. **onResolve**: Executed during module resolution for each import\n * 3. **onLoad**: Executed when loading file contents for each module\n * 4. **onEnd**: Executed when the build completes (success or failure)\n * 5. **onSuccess**: Executed only when the build completes without errors\n *\n * Hook execution strategy:\n * - Start and end hooks aggregate errors and warnings from all handlers\n * - Resolve hooks merge results from multiple handlers\n * - Load hooks apply transformations sequentially (pipeline pattern)\n * - All hooks receive a specialized context object appropriate for their lifecycle stage\n *\n * @example\n * ```ts\n * const provider = new LifecycleProvider('my-plugin', { debug: true });\n *\n * provider.onStart(async (context) => {\n * console.log('Build starting...');\n * return { warnings: [] };\n * });\n *\n * provider.onLoad(async (context) => {\n * // Transform TypeScript files\n * if (context.args.path.endsWith('.ts')) {\n * return { contents: transformCode(context.contents), loader: 'ts' };\n * }\n * });\n *\n * const plugin = provider.create();\n * ```\n *\n * @see {@link FilesModel}\n * @see {@link LoadContextInterface}\n * @see {@link BuildContextInterface}\n * @see {@link ResultContextInterface}\n * @see {@link ResolveContextInterface}\n * @see {@link LifecycleContextInterface}\n *\n * @since 2.0.0\n */\n\nexport class LifecycleProvider {\n /**\n * File model for accessing TypeScript language service snapshots and file content.\n * @since 2.0.0\n */\n\n private filesModel: FilesModel = inject(FilesModel);\n\n /**\n * Registered handlers to execute when the build completes, regardless of success or failure.\n * @since 2.0.0\n */\n\n private readonly endHooks = new Map<string, OnEndType>();\n\n /**\n * Registered handlers to execute when loading file contents during module processing.\n * @since 2.0.0\n */\n\n private readonly loadHooks = new Map<string, OnLoadType>();\n\n /**\n * Registered handlers to execute when the build process begins.\n * @since 2.0.0\n */\n\n private readonly startHooks = new Map<string, OnStartType>();\n\n /**\n * Registered handlers to execute when the build completes successfully without errors.\n * @since 2.0.0\n */\n\n private readonly successHooks = new Map<string, OnEndType>();\n\n /**\n * Registered handlers to execute during module path resolution.\n * @since 2.0.0\n */\n\n private readonly resolveHooks = new Map<string, OnResolveType>();\n\n /**\n * Creates a new lifecycle provider instance with the specified variant name and configuration.\n *\n * @param variantName - The variant name used for identification and included in hook contexts\n * @param argv - Command-line arguments and configuration options passed to hook handlers\n *\n * @remarks\n * The constructor initializes empty hook maps for each lifecycle stage. The `variantName` parameter\n * is used as the default identifier when registering hooks without explicit names and is\n * included in the context passed to all handlers as `variantName`.\n *\n * The `argv` configuration is stored and made available to all hooks through their context objects,\n * allowing build-time behavior to be customized based on command-line flags or configuration.\n *\n * @example\n * ```ts\n * const provider = new LifecycleProvider('production', {\n * watch: false,\n * sourcemap: true,\n * minify: true\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(protected variantName: string, protected argv: Record<string, unknown>) {\n }\n\n /**\n * Registers a handler to execute when the build process begins.\n *\n * @param handler - Optional callback function to execute at build start\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Start hooks are executed before any file processing occurs and receive a build context\n * containing the esbuild `PluginBuild` object, variant name, arguments, and stage state.\n * They can return errors and warnings that will be aggregated with results from other start hooks.\n *\n * If no handler is provided, this method does nothing (allowing conditional registration).\n * Multiple start hooks can be registered with different names and will all execute in\n * registration order.\n *\n * Common use cases:\n * - Initialization and setup tasks\n * - Validation of build configuration\n * - Cleaning output directories\n * - Logging build start time\n *\n * @example\n * ```ts\n * provider.onStart(async (context) => {\n * console.log(`${context.variantName} build started at ${context.stage.startTime}`);\n * return { warnings: [], errors: [] };\n * });\n * ```\n *\n * @see {@link executeStartHooks}\n * @see {@link BuildContextInterface}\n *\n * @since 2.0.0\n */\n\n onStart(handler?: OnStartType, name: string = this.variantName): void {\n if (handler) this.startHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute when the build completes, regardless of success or failure.\n *\n * @param handler - Optional callback function to execute at build end\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * End hooks are executed after all build operations are complete and receive a result context\n * containing the final build result, calculated duration, variant name, arguments, and stage state.\n * They can return additional errors and warnings to append to the build output.\n *\n * If no handler is provided, this method does nothing. Multiple end hooks execute in registration\n * order, and all results are aggregated.\n *\n * Common use cases:\n * - Cleanup and resource disposal\n * - Logging build completion and duration\n * - Generating build reports or statistics\n * - Post-processing output files\n *\n * @example\n * ```ts\n * provider.onEnd(async (context) => {\n * console.log(`${context.variantName} build completed in ${context.duration}ms`);\n * return { warnings: [], errors: [] };\n * });\n * ```\n *\n * @see {@link onSuccess}\n * @see {@link executeEndHooks}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\n onEnd(handler?: OnEndType, name: string = this.variantName): void {\n if (handler) this.endHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute when the build completes successfully without errors.\n *\n * @param handler - Optional callback function to execute on successful build\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Success hooks are a specialized subset of end hooks that only execute when the build\n * completes with zero errors. They receive a result context containing the build result,\n * duration, and stage state, and are guaranteed to run only after successful builds.\n *\n * If no handler is provided, this method does nothing. Success hooks execute after all\n * regular end hooks have completed. Any errors thrown by success hooks are captured and\n * appended to the aggregated end-hook error list.\n *\n * Common use cases:\n * - Deploying build artifacts\n * - Running post-build validation\n * - Updating deployment status\n * - Sending success notifications\n *\n * @example\n * ```ts\n * provider.onSuccess(async (context) => {\n * console.log('Build succeeded! Deploying...');\n * await deploy(context.buildResult.metafile);\n * });\n * ```\n *\n * @see {@link onEnd}\n * @see {@link executeEndHooks}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\n onSuccess(handler?: OnEndType, name: string = this.variantName): void {\n if (handler) this.successHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute during module path resolution.\n *\n * @param handler - Optional callback function to execute during resolution\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Resolve hooks are executed when esbuild needs to resolve import paths to file system locations.\n * They receive a resolve context containing the resolution arguments, variant name, and stage state.\n * Hooks can return modified resolution results or redirect imports.\n *\n * If no handler is provided, this method does nothing. Multiple resolve hooks can execute, and\n * their results are merged, with later hooks potentially overriding earlier ones.\n *\n * Common use cases:\n * - Implementing custom module resolution algorithms\n * - Redirecting imports to alternative locations\n * - Handling path aliases and mappings\n * - Resolving virtual modules\n *\n * @example\n * ```ts\n * provider.onResolve(async (context) => {\n * if (context.args.path.startsWith('@/')) {\n * return { path: resolve('src', context.args.path.slice(2)) };\n * }\n * });\n * ```\n *\n * @see {@link executeResolveHooks}\n * @see {@link ResolveContextInterface}\n *\n * @since 2.0.0\n */\n\n onResolve(handler?: OnResolveType, name: string = this.variantName): void {\n if (handler) this.resolveHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute when loading file contents during module processing.\n *\n * @param handler - Optional callback function to execute during file loading\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Load hooks are executed when esbuild loads file contents and receive a load context containing\n * the current contents (potentially transformed by previous hooks), loader type, load arguments,\n * variant name, and stage state. Hooks can transform the contents and change the loader,\n * with transformations applied sequentially in a pipeline pattern.\n *\n * If no handler is provided, this method does nothing. Multiple load hooks execute in\n * registration order, with each hook receiving the transformed output of previous hooks\n * through the context.\n *\n * Common use cases:\n * - Transforming file contents (transpilation, minification)\n * - Injecting code or imports\n * - Applying preprocessors\n * - Changing file loader types\n *\n * @example\n * ```ts\n * provider.onLoad(async (context) => {\n * if (context.args.path.endsWith('.custom')) {\n * return {\n * contents: transformCustomSyntax(context.contents),\n * loader: 'ts'\n * };\n * }\n * });\n * ```\n *\n * @see {@link executeLoadHooks}\n * @see {@link LoadContextInterface}\n *\n * @since 2.0.0\n */\n\n onLoad(handler?: OnLoadType, name: string = this.variantName): void {\n if (handler) this.loadHooks.set(name, handler);\n }\n\n /**\n * Clears all registered hooks from all lifecycle stages.\n *\n * @remarks\n * This method removes all registered handlers for start, end, success, resolve, and load hooks.\n * It's typically used when resetting the provider state or preparing for a new build configuration.\n *\n * After calling this method, the provider has no registered hooks and will not execute any\n * handlers until new ones are registered.\n *\n * @example\n * ```ts\n * provider.onStart(startHandler);\n * provider.onEnd(endHandler);\n *\n * // Remove all hooks\n * provider.clearAll();\n *\n * // Provider now has no registered hooks\n * ```\n *\n * @since 2.0.0\n */\n\n clearAll(): void {\n this.endHooks.clear();\n this.loadHooks.clear();\n this.startHooks.clear();\n this.successHooks.clear();\n this.resolveHooks.clear();\n }\n\n /**\n * Creates an esbuild plugin instance with all registered hooks configured.\n *\n * @returns Configured esbuild plugin object ready for use in build configuration\n *\n * @remarks\n * This method generates an esbuild plugin that wires up all registered hooks to the\n * appropriate esbuild lifecycle events. The plugin setup function:\n * - Initializes a base lifecycle context with variant name, arguments, and start time\n * - Enables metafile generation for build metadata\n * - Registers onStart handler if any start hooks exist\n * - Registers onEnd handler if any end or success hooks exist\n * - Registers onResolve handler with catch-all filter if any resolve hooks exist\n * - Registers onLoad handler with catch-all filter if any load hooks exist\n *\n * Each hook receives a specialized context appropriate for its lifecycle stage:\n * - Start hooks receive `BuildContextInterface` with the build object\n * - End/Success hooks receive `ResultContextInterface` with build result and duration\n * - Resolve hooks receive `ResolveContextInterface` with resolution arguments\n * - Load hooks receive `LoadContextInterface` with contents, loader, and load arguments\n *\n * Handlers are bound at setup time using `Function.prototype.bind` with the shared\n * lifecycle context, avoiding repeated closure allocations on each invocation.\n *\n * @example\n * ```ts\n * const provider = new LifecycleProvider('production', {});\n * provider.onStart(startHandler);\n * provider.onLoad(loadHandler);\n *\n * const plugin = provider.create();\n *\n * await esbuild.build({\n * entryPoints: ['src/index.ts'],\n * plugins: [plugin]\n * });\n * ```\n *\n * @see {@link executeEndHooks}\n * @see {@link executeLoadHooks}\n * @see {@link executeStartHooks}\n * @see {@link executeResolveHooks}\n *\n * @since 2.0.0\n */\n\n create(): Plugin {\n return {\n name: this.variantName,\n setup: (build: PluginBuild): void => {\n const context: LifecycleContextInterface = {\n argv: this.argv,\n options: build.initialOptions,\n variantName: this.variantName,\n stage: { startTime: new Date() }\n };\n\n build.initialOptions.metafile = true;\n\n if (this.startHooks.size > 0)\n build.onStart(this.executeStartHooks.bind(this, context, build));\n\n if (this.endHooks.size > 0 || this.successHooks.size > 0)\n build.onEnd(this.executeEndHooks.bind(this, context));\n\n if (this.resolveHooks.size > 0)\n build.onResolve({ filter: /.*/ }, this.executeResolveHooks.bind(this, context));\n\n if (this.loadHooks.size > 0)\n build.onLoad({ filter: /.*/ }, this.executeLoadHooks.bind(this, context));\n }\n };\n }\n\n /**\n * Appends a caught error to the provided error list as a normalized `PartialMessage`.\n *\n * @param errors - The error array to append to\n * @param id - Logical source identifier for the failing hook phase (e.g. `startHook`, `endHook`)\n * @param err - The thrown value to wrap\n * @param names - The hook name to set as `pluginName`, defaults to the variant name\n *\n * @remarks\n * Captured errors are normalized with:\n * - `id` to identify which lifecycle phase produced the message\n * - `pluginName` to attribute the failure to the registered hook name\n * - `location: null` because these errors are runtime hook failures, not source-mapped diagnostics\n *\n * @since 2.0.0\n */\n\n private pushError(errors: Array<PartialMessage>, id: string, err: unknown, names: string = this.variantName): void {\n errors.push({\n id,\n detail: err,\n location: null,\n pluginName: names\n });\n }\n\n /**\n * Executes all registered start hooks and aggregates their results.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param build - The esbuild plugin build object\n * @returns Aggregated result containing all errors and warnings from start hooks\n *\n * @remarks\n * This method resets the start time in the stage object, then executes all registered\n * start hooks in order. Each hook receives a build context that includes the esbuild\n * build object along with the base lifecycle context.\n *\n * Results from all hooks are aggregated:\n * - Errors from all hooks are combined into a single array\n * - Warnings from all hooks are combined into a single array\n *\n * Errors thrown by a hook are caught and appended to the error array rather than\n * propagating, so all hooks always execute regardless of individual failures.\n * Each captured error is attributed to its hook's registered name via `pluginName`\n * on the `PartialMessage`, making the source of the failure identifiable in esbuild output.\n *\n * The context object is passed through to later lifecycle stages for consistent\n * state management across the build.\n *\n * @see {@link onStart}\n * @see {@link BuildContextInterface}\n *\n * @since 2.0.0\n */\n\n private async executeStartHooks(context: LifecycleContextInterface, build: PluginBuild): Promise<OnStartResult> {\n context.stage.startTime = new Date();\n const errors: Array<PartialMessage> = [];\n const warnings: Array<PartialMessage> = [];\n const hookContext = { build, ...context };\n\n for (const [ name, hook ] of this.startHooks.entries()) {\n try {\n const result = await hook(hookContext);\n if (result?.errors) errors.push(...result.errors);\n if (result?.warnings) warnings.push(...result.warnings);\n } catch (err) {\n this.pushError(errors, 'startHook', err, name);\n }\n }\n\n return { errors, warnings };\n }\n\n /**\n * Executes all registered end hooks and success hooks, mutating the provided `buildResult`.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param buildResult - The final build result from esbuild (mutated in place)\n *\n * @remarks\n * This method computes build duration and executes hooks in two phases:\n * 1. **End hooks**: Always run. Returned `errors`/`warnings` are appended to `buildResult`.\n * Thrown errors are captured and normalized through {@link pushError} using `id: \"endHook\"`.\n * 2. **Success hooks**: Run only when `buildResult.errors.length === 0` after end hooks.\n * Return values are ignored; thrown errors are captured as `endHook`-scoped messages.\n *\n * Hook handlers share a single result context object that includes `duration`, `buildResult`,\n * and the base lifecycle metadata.\n *\n * @see {@link onEnd}\n * @see {@link onSuccess}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\n private async executeEndHooks(context: LifecycleContextInterface, buildResult: BuildResult): Promise<void> {\n const { errors, warnings } = buildResult;\n const duration = Date.now() - context.stage.startTime.getTime();\n const hookContext = { buildResult, duration, ...context };\n\n for (const [ name, hook ] of this.endHooks.entries()) {\n try {\n const result = await hook(hookContext);\n if (result?.errors) errors.push(...result.errors as Array<Message>);\n if (result?.warnings) warnings.push(...result.warnings as Array<Message>);\n } catch (err) {\n this.pushError(errors, 'endHook', err, name);\n }\n }\n\n if (buildResult.errors.length === 0) {\n for (const [ name, hook ] of this.successHooks.entries()) {\n try {\n await hook(hookContext);\n } catch (err) {\n this.pushError(errors, 'endHook', err, name);\n }\n }\n }\n }\n\n /**\n * Executes all registered resolve hooks and merges their results.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param args - The resolution arguments from esbuild\n * @returns Merged resolution result from all hooks, always including an `errors` array\n *\n * @remarks\n * This method executes all resolve hooks in registration order, passing each hook a resolve\n * context that includes the resolution arguments along with the base lifecycle context.\n * Results are merged using object spreading, meaning later hooks can override properties\n * set by earlier hooks.\n *\n * The result is initialized as `{ errors: [] }` and used as the merge base. If all hooks\n * return `undefined`/`null`, the method still returns this base result.\n *\n * Unlike start/end/load hooks, resolve hook errors are not caught \u2014 esbuild will surface\n * them directly as build errors.\n *\n * @see {@link onResolve}\n * @see {@link ResolveContextInterface}\n *\n * @since 2.0.0\n */\n\n private async executeResolveHooks(context: LifecycleContextInterface, args: OnResolveArgs): Promise<OnResolveResult> {\n let result: OnResolveResult = { errors: [] };\n const hookContext = { args, ...context };\n\n for (const [ name, hook ] of this.resolveHooks.entries()) {\n try {\n const hookResult = await hook(hookContext);\n if (!hookResult) continue;\n result = { ...result, ...hookResult };\n } catch (err) {\n this.pushError(result.errors!, 'endResolve', err, name);\n }\n }\n\n return result;\n }\n\n /**\n * Executes all registered load hooks in sequence, applying content transformations as a pipeline.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param args - The load arguments from esbuild containing file path and namespace\n * @returns Load result with final transformed contents and loader type\n *\n * @remarks\n * This method implements a transformation pipeline where:\n * 1. Initial contents are loaded from a TypeScript snapshot or file system\n * 2. Each load hook receives a load context with current contents, loader, and arguments\n * 3. Hooks can transform contents and change the loader\n * 4. Each hook's output becomes the input for the next hook's context\n *\n * Content loading priority:\n * - First attempts to load from TypeScript language service snapshot (if available),\n * accessed via optional chaining on `contentSnapshot`\n * - Falls back to reading the file from disk using `fs/promises`\n *\n * The loader starts as `'default'` and can be changed by any hook in the pipeline.\n * Errors thrown by individual hooks are caught and appended to the error list, attributed to\n * the hook's registered name via `pluginName` on the `PartialMessage`, so the pipeline continues\n * running for subsequent hooks and the failing hook is clearly identifiable in esbuild output.\n * The final contents, loader, errors, and warnings are returned to esbuild for processing.\n *\n * @see {@link onLoad}\n * @see {@link LoadContextInterface}\n * @see {@link FilesModel.getSnapshot}\n *\n * @since 2.0.0\n */\n\n private async executeLoadHooks(context: LifecycleContextInterface, args: OnLoadArgs): Promise<OnLoadResult | null> {\n const errors: Array<PartialMessage> = [];\n const warnings: Array<PartialMessage> = [];\n let loader: OnLoadResult['loader'] = 'default';\n\n const filePath = resolve(args.path);\n const snapshot = this.filesModel.getSnapshot(filePath);\n let contents: string | Uint8Array = snapshot?.contentSnapshot\n ? snapshot.contentSnapshot.text\n : await readFile(filePath, 'utf8');\n\n for (const [ name, hook ] of this.loadHooks.entries()) {\n try {\n const result = await hook({ contents, loader, args, ...context });\n if (!result) continue;\n if (result.contents !== undefined) contents = result.contents;\n if (result.loader) loader = result.loader;\n if (result.errors) errors.push(...result.errors);\n if (result.warnings) warnings.push(...result.warnings);\n } catch (err) {\n this.pushError(errors, 'loadHook', err, name);\n }\n }\n\n return { contents, loader, errors, warnings };\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OnLoadResult } from 'esbuild';\nimport type { VariantService } from '@services/variant.service';\nimport type { CallExpression, VariableStatement, ExpressionStatement } from 'typescript';\nimport type { MacrosStateInterface } from '@directives/interfaces/analyze-directive.interface';\nimport type { LoadContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { SubstInterface, StateInterface } from '@directives/interfaces/macros-directive.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { esBuildError } from '@errors/esbuild.error';\nimport { highlightCode } from '@remotex-labs/xmap/highlighter.component';\nimport { astDefineVariable, astDefineCallExpression } from '@directives/define.directive';\nimport { astInlineCallExpression, astInlineVariable } from '@directives/inline.directive';\n\n/**\n * Regular expression matching TypeScript and JavaScript file extensions.\n *\n * @remarks\n * Used to filter files that should undergo macro transformation. Only files\n * with `.ts` or `.js` extensions are processed by the transformer directive.\n *\n * @since 2.0.0\n */\n\nconst TS_JS_REGEX = /\\.(ts|js)$/;\n\n/**\n * Array of recognized macro function names for conditional compilation and inline evaluation.\n *\n * @remarks\n * Defines the complete set of macro directives supported by xBuild:\n * - `$$ifdef`: Conditional inclusion when definition is truthy\n * - `$$ifndef`: Conditional inclusion when definition is falsy or undefined\n * - `$$inline`: Runtime code evaluation during build time\n *\n * Used for:\n * - Validating macro calls during AST traversal\n * - Determining argument count requirements\n * - Filtering disabled macro references\n *\n * @since 2.0.0\n */\n\nconst MACRO_FUNCTIONS = [ '$$ifdef', '$$ifndef', '$$inline' ];\n\n/**\n * Checks whether a given AST node\u2019s source text contains any supported macro function name.\n *\n * @param node - AST node to inspect\n * @param sourceFile - Optional source file used by TypeScript to compute node text\n *\n * @returns `true` if the node text contains at least one macro identifier; otherwise `false`.\n *\n * @remarks\n * This is a fast, text-based pre-check used to avoid deeper macro parsing work when a node\n * clearly cannot contain macro calls.\n *\n * @since 2.0.0\n */\n\nexport function nodeContainsMacro(node: ts.Node, sourceFile?: ts.SourceFile): boolean {\n return (MACRO_FUNCTIONS as ReadonlyArray<string>).some(m => node.getText(sourceFile).includes(m));\n}\n\n/**\n * Returns the expected argument count for a supported macro function.\n *\n * @param fnName - Macro function name (e.g. `$$ifdef`, `$$ifndef`, `$$inline`)\n *\n * @returns The required number of arguments for the macro.\n *\n * @remarks\n * - `$$inline` expects 1 argument (a thunk/callback)\n * - `$$ifdef` / `$$ifndef` expect 2 arguments (name + callback/value)\n *\n * @since 2.0.0\n */\n\nfunction expectedArgCount(fnName: string): number {\n return fnName === MACRO_FUNCTIONS[2] ? 1 : 2;\n}\n\n/**\n * Processes variable statements containing macro calls and adds replacements to the replacement set.\n *\n * @param node - The variable statement node to process\n * @param replacements - Set of code replacements to populate\n * @param state - The macro transformation state containing definitions and source file\n *\n * @returns A promise that resolves when all variable declarations have been processed\n *\n * @remarks\n * This function handles macro variable declarations of the form:\n * ```ts\n * const $$myFunc = $$ifdef('DEFINITION', callback);\n * export const $$inline = $$inline(() => computeValue());\n * let $$feature = $$ifndef('PRODUCTION', devFeature);\n * ```\n *\n * The processing flow:\n * 1. Iterates through all variable declarations in the statement\n * 2. Validates that the initializer is a macro call expression\n * 3. Checks that the macro function name is recognized\n * 4. Validates argument count (2 for ifdef/ifndef, 1 for inline)\n * 5. Detects export modifiers to preserve in the output\n * 6. Delegates to the appropriate transformer based on macro type\n * 7. Adds successful transformations to the replacement set\n *\n * **Macro type routing**:\n * - `$$inline`: Delegates to {@link astInlineVariable} (async evaluation)\n * - `$$ifdef`/`$$ifndef`: Delegates to {@link astDefineVariable} (conditional inclusion)\n *\n * Replacements track the start and end positions of the original statement\n * for accurate text substitution during the final transformation pass.\n *\n * @example Processing conditional macro\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * // With: { DEBUG: true }\n * await isVariableStatement(node, replacements, state);\n * // replacements contains: {\n * // start: 0,\n * // end: 52,\n * // replacement: 'function $$debug() { return console.log; }'\n * // }\n * ```\n *\n * @example Processing inline macro\n * ```ts\n * // Source: export const API_URL = $$inline(() => process.env.API);\n * await isVariableStatement(node, replacements, state);\n * // replacements contains: {\n * // start: 0,\n * // end: 59,\n * // replacement: 'export const API_URL = undefined;'\n * // }\n * ```\n *\n * @example Invalid macro (skipped)\n * ```ts\n * // Source: const $$bad = $$ifdef('DEV'); // Missing callback argument\n * await isVariableStatement(node, replacements, state);\n * // No replacement added (insufficient arguments)\n * ```\n *\n * @see {@link astProcess} for the calling context\n * @see {@link astInlineVariable} for inline macro transformation\n * @see {@link astDefineVariable} for conditional macro transformation\n *\n * @since 2.0.0\n */\n\nexport async function isVariableStatement(node: VariableStatement, replacements: Set<SubstInterface>, state: StateInterface): Promise<boolean> {\n let replacement: string | false = false;\n\n for (const decl of node.declarationList.declarations) {\n let suffix = '';\n let call: ts.CallExpression | undefined;\n const init = decl.initializer;\n if (!init) continue;\n\n if (ts.isCallExpression(init) && ts.isIdentifier(init.expression)) {\n // Plain: $$macro(...)\n call = init;\n } else if (\n ts.isCallExpression(init) &&\n ts.isCallExpression(init.expression) &&\n ts.isIdentifier(init.expression.expression)\n ) {\n // IIFE: $$macro(...)(...outerArgs)\n call = init.expression;\n const args = init.arguments.map(a => a.getText(state.sourceFile)).join(', ');\n suffix = `(${ args })`;\n } else if (\n ts.isAsExpression(init) &&\n ts.isCallExpression(init.expression) &&\n ts.isIdentifier(init.expression.expression)\n ) {\n call = init.expression;\n }\n\n if (!call) continue;\n\n const fnName = (call.expression as ts.Identifier).text;\n if (!MACRO_FUNCTIONS.includes(fnName)) continue;\n if (call.arguments.length !== expectedArgCount(fnName)) {\n const { line, character } = state.sourceFile.getLineAndCharacterOfPosition(call.getStart(state.sourceFile));\n throw new esBuildError({\n text: `Invalid macro call: ${ fnName } with ${ call.arguments.length } arguments`,\n location: {\n file: state.sourceFile.fileName,\n line: line + 1,\n column: character\n }\n });\n }\n\n const hasExport =\n node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;\n\n if (fnName === MACRO_FUNCTIONS[2]) replacement = await astInlineVariable(decl, node, call, hasExport, state);\n else if (suffix) replacement = astDefineCallExpression(call, state, decl, hasExport, suffix);\n else replacement = astDefineVariable(decl, call, hasExport, state);\n\n if (replacement !== false) {\n replacements.add({\n replacement,\n end: node.getEnd(),\n start: node.getStart(state.sourceFile)\n });\n }\n }\n\n return replacement !== false;\n}\n\n/**\n * Processes standalone macro call expressions and adds replacements to the replacement set.\n *\n * @param node - The expression statement containing the macro call\n * @param replacements - Set of code replacements to populate\n * @param state - The macro transformation state containing definitions and source file\n *\n * @returns A promise that resolves when the expression has been processed\n *\n * @remarks\n * This function handles standalone macro calls that appear as expression statements:\n * ```ts\n * $$ifdef('DEBUG', () => console.log('debug'));\n * $$inline(() => initialize());\n * ```\n *\n * The processing flow:\n * 1. Validates that the expression is a macro call with identifier\n * 2. Checks that the macro function name is recognized\n * 3. Validates argument count (2 for ifdef/ifndef, 1 for inline)\n * 4. Delegates to the appropriate transformer based on macro type\n * 5. Adds successful transformations to the replacement set\n *\n * **Macro type routing**:\n * - `$$inline`: Delegates to {@link astInlineCallExpression} (async evaluation)\n * - `$$ifdef`/`$$ifndef`: Delegates to {@link astDefineCallExpression} (conditional inclusion)\n *\n * **Note**: The define call expression handler currently doesn't return a replacement\n * (returns `false` implicitly), so only inline macros result in replacements at this level.\n *\n * @example Processing inline call\n * ```ts\n * // Source: $$inline(() => configureApp());\n * await isCallExpression(node, replacements, state);\n * // replacements contains: {\n * // start: 0,\n * // end: 35,\n * // replacement: 'undefined'\n * // }\n * ```\n *\n * @example Processing conditional call\n * ```ts\n * // Source: $$ifdef('DEBUG', () => enableDebugMode());\n * await isCallExpression(node, replacements, state);\n * // No replacement added (define expressions handle differently)\n * ```\n *\n * @see {@link astProcess} for the calling context\n * @see {@link astInlineCallExpression} for inline macro transformation\n * @see {@link astDefineCallExpression} for conditional macro transformation\n *\n * @since 2.0.0\n */\n\nexport async function isCallExpression(\n node: ExpressionStatement, replacements: Set<SubstInterface>, state: StateInterface\n): Promise<boolean> {\n const callExpr = <CallExpression> node.expression;\n if (!callExpr.expression || !ts.isIdentifier(callExpr.expression)) return false;\n\n const fnName = callExpr.expression.text;\n if (!MACRO_FUNCTIONS.includes(fnName)) return false;\n if (callExpr.arguments.length !== expectedArgCount(fnName)) {\n const { line, character } = state.sourceFile.getLineAndCharacterOfPosition(node.getStart(state.sourceFile));\n throw new esBuildError({\n text: `Invalid macro call: ${ fnName } with ${ callExpr.arguments.length } arguments`,\n location: {\n file: state.sourceFile.fileName,\n line: line + 1,\n column: character\n }\n });\n }\n\n let replacement: string | false = false;\n if (fnName == MACRO_FUNCTIONS[2]) {\n await astInlineCallExpression(callExpr.arguments, state);\n replacement = 'undefined';\n } else replacement = astDefineCallExpression(callExpr, state);\n\n if (replacement !== false) {\n replacements.add({\n replacement,\n end: callExpr.getEnd(),\n start: callExpr.getStart(state.sourceFile)\n });\n }\n\n return replacement !== false;\n}\n\n/**\n * Processes a `CallExpression` AST node that targets one of the supported macro functions and,\n * if possible, registers a text replacement.\n *\n * @param node - The AST node to process (must be a `CallExpression` to be meaningful)\n * @param replacements - Collection of replacements to apply later (sorted and spliced into the source)\n * @param state - Current macro processing state (includes `sourceFile`, `contents`, metadata, etc.)\n *\n * @returns `true` when a macro replacement was added; otherwise `false`.\n *\n * @remarks\n * This handler is used for *nested* macro call sites (i.e. `CallExpression` nodes that are not\n * expression statements or variable statements), for example:\n *\n * ```ts\n * const value = someFn($$inline(() => 123));\n * ```\n *\n * Routing:\n * - `$$inline(...)` \u2192 {@link astInlineCallExpression} (async)\n * - `$$ifdef(...)` / `$$ifndef(...)` \u2192 {@link astDefineCallExpression}\n *\n * The replacement range is based on the node\u2019s `[start, end]` positions in {@link StateInterface.sourceFile}.\n *\n * @see {@link astInlineCallExpression}\n * @see {@link astDefineCallExpression}\n *\n * @since 2.0.0\n */\n\nasync function macroCallExpression(node: ts.Node, replacements: Set<SubstInterface>, state: StateInterface): Promise<boolean> {\n if (!ts.isCallExpression(node)) return false;\n if (!nodeContainsMacro(node, state.sourceFile)) return false;\n\n const callNode = node as ts.CallExpression;\n if (!ts.isIdentifier(callNode.expression)) return false;\n\n const fnName = callNode.expression.text;\n\n if (fnName === MACRO_FUNCTIONS[2]) {\n // $$inline macro\n const replacement = await astInlineCallExpression(callNode.arguments, state);\n if (replacement === false) return false;\n\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement\n });\n\n return true;\n }\n\n // $$ifdef / $$ifndef macro\n const replacement = astDefineCallExpression(callNode, state);\n if (replacement === false) return false;\n\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement\n });\n\n return true;\n}\n\n/**\n * Recursively traverses the AST to find and transform all macro occurrences in the source file.\n *\n * @param state - The macro transformation state containing source file, definitions, and content\n * @param variant - The build variant name for tracking replacements (defaults to 'unknow')\n *\n * @returns A promise resolving to the transformed source code with all macro replacements applied\n *\n * @remarks\n * This is the main transformation function that orchestrates macro processing across the entire\n * source file. It performs a recursive AST traversal to locate and transform different macro patterns:\n *\n * **Macro patterns handled**:\n * 1. **Variable statements**: `const $$x = $$ifdef(...)` or `const x = $$inline(...)`\n * 2. **Expression statements**: Standalone `$$ifdef(...)` or `$$inline(...)` calls\n * 3. **Nested inline calls**: `$$inline(...)` within other expressions (not variable/expression statements)\n * 4. **Disabled macro calls**: Calls to macros marked as disabled in metadata\n * 5. **Disabled macro identifiers**: References to disabled macro names (replaced with `undefined`)\n *\n * @example Complete transformation\n * ```ts\n * // Original source:\n * const $$debug = $$ifdef('DEBUG', () => console.log);\n * const value = $$inline(() => 42);\n * $$debug();\n *\n * // With definitions: { DEBUG: false }\n * const result = await astProcess(state, 'production');\n *\n * // Transformed result:\n * const value = undefined;\n * undefined();\n *\n * // Tracked in state.stage.replacementInfo['production']\n * ```\n *\n * @example Handling disabled macros\n * ```ts\n * // Original source (with DEBUG=false):\n * const $$debug = $$ifdef('DEBUG', log);\n * if ($$debug) $$debug();\n *\n * // After processing:\n * if (undefined) undefined();\n * ```\n *\n * @example No macros (short circuit)\n * ```ts\n * const state = {\n * contents: 'const x = 1;',\n * sourceFile,\n * stage: { defineMetadata: { filesWithMacros: new Set(), disabledMacroNames: new Set() } }\n * };\n * const result = await astProcess(state);\n * // Returns original content unchanged immediately\n * ```\n *\n * @see {@link macroCallExpression} for nested inline calls\n * @see {@link isCallExpression} for expression statement handling\n * @see {@link isVariableStatement} for variable declaration handling\n * @see {@link MacrosStateInterface.replacementInfo} for replacement tracking\n *\n * @since 2.0.0\n */\n\nexport async function astProcess(state: StateInterface, variant: string = 'unknow'): Promise<string> {\n const fnToRemove = state.stage.defineMetadata.disabledMacroNames;\n const hasMacro = state.stage.defineMetadata.filesWithMacros.has(state.sourceFile.fileName);\n if (!hasMacro && fnToRemove.size === 0) return state.contents;\n\n const stack: Array<ts.Node> = [ state.sourceFile ];\n const replacements: Set<SubstInterface> = new Set();\n\n while (stack.length > 0) {\n const node = stack.pop();\n const kind = node?.kind;\n if (!node || !kind) continue;\n if (hasMacro) {\n if (kind === ts.SyntaxKind.VariableStatement) {\n if (await isVariableStatement(node as VariableStatement, replacements, state)) continue;\n }\n\n if (kind === ts.SyntaxKind.ExpressionStatement && nodeContainsMacro(node, state.sourceFile)) {\n if (await isCallExpression(node as ExpressionStatement, replacements, state)) continue;\n }\n\n if (kind === ts.SyntaxKind.CallExpression && nodeContainsMacro(node, state.sourceFile)) {\n if (await macroCallExpression(node as ExpressionStatement, replacements, state)) continue;\n }\n }\n\n if (fnToRemove.size > 0) {\n if (kind === ts.SyntaxKind.CallExpression) {\n const callNode = node as ts.CallExpression;\n if (ts.isIdentifier(callNode.expression) && fnToRemove.has(callNode.expression.text)) {\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement: 'undefined'\n });\n }\n } else if (kind === ts.SyntaxKind.Identifier) {\n const identifier = node as ts.Identifier;\n if (fnToRemove.has(identifier.text)) {\n const parent = node.parent ?? node;\n\n if (parent && !ts.isImportSpecifier(parent) && !ts.isExportSpecifier(parent)) {\n const parentText = parent?.getText(state.sourceFile);\n\n if (!ts.isCallExpression(parent) || parent.expression !== node) {\n if (!parentText || MACRO_FUNCTIONS.every(key => !parentText.includes(key))) {\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement: 'undefined'\n });\n }\n }\n }\n }\n }\n }\n\n const children = node.getChildren(state.sourceFile);\n for (let i = children.length - 1; i >= 0; i--) {\n stack.push(children[i]);\n }\n }\n\n if (replacements.size === 0) return state.contents;\n const replacementsArray = Array.from(replacements);\n replacementsArray.sort((a, b) => b.start - a.start);\n\n state.stage.replacementInfo ??= {};\n state.stage.replacementInfo[variant] ??= [];\n const replacementInfo = state.stage.replacementInfo[variant];\n\n for (const { start, end, replacement } of replacementsArray) {\n replacementInfo.push({\n source: highlightCode(state.contents.slice(start, end)),\n replacement: highlightCode(replacement)\n });\n\n state.contents = state.contents.slice(0, start) + replacement + state.contents.slice(end);\n }\n\n return state.contents;\n}\n\n/**\n * Main transformer directive that processes macro transformations for a build variant.\n *\n * @param variant - The build variant service containing configuration and TypeScript services\n * @param context - The load context containing file information, loader type, and build stage\n *\n * @returns A promise resolving to the transformed file result with processed macros, warnings, and errors\n *\n * @remarks\n * This is the entry point for macro transformation during the build process, integrated as\n * an esbuild plugin loader. It orchestrates the complete transformation pipeline:\n *\n * **Transformation pipeline**:\n * 1. **File filtering**: Validates file extension and content length\n * 2. **Source file acquisition**: Retrieves or creates TypeScript source file\n * 3. **State initialization**: Prepares transformation state with definitions and metadata\n * 4. **Macro processing**: Applies AST transformations via {@link astProcess}\n * 5. **Alias resolution**: Resolves TypeScript path aliases for non-bundled builds\n * 6. **Result assembly**: Returns transformed content with diagnostics\n *\n * **Early exits**:\n * - Non-TypeScript/JavaScript files: Returns content unchanged\n * - Empty files: Returns content unchanged\n * - Files without macros: Processes but no transformations occur\n *\n * **Alias resolution**:\n * When not bundling (`variant.config.esbuild.bundle === false`), path aliases are\n * resolved to relative paths with `.js` extensions for proper module resolution.\n *\n * **Source file handling**:\n * If the source file isn't in the language service program, it's touched (loaded)\n * to ensure the TypeScript compiler has current file information.\n *\n * @example Basic transformation flow\n * ```ts\n * const context = {\n * args: { path: 'src/index.ts' },\n * loader: 'ts',\n * stage: { defineMetadata: { ... } },\n * contents: 'const $$debug = $$ifdef(\"DEBUG\", log);'\n * };\n *\n * const result = await transformerDirective(variant, context);\n * // result.contents: transformed code\n * // result.warnings: macro warnings\n * // result.errors: transformation errors\n * ```\n *\n * @example Non-TypeScript file (skipped)\n * ```ts\n * const context = {\n * args: { path: 'styles.css' },\n * loader: 'css',\n * contents: '.class { color: red; }'\n * };\n *\n * const result = await transformerDirective(variant, context);\n * // result.contents === original content (unchanged)\n * ```\n *\n * @example With alias resolution\n * ```ts\n * // Source contains: import { utils } from '@utils/helpers';\n * // Non-bundled build\n * const result = await transformerDirective(variant, context);\n * // Import resolved: import { utils } from './utils/helpers.js';\n * ```\n *\n * @see {@link astProcess} for macro transformation logic\n * @see {@link LanguageHostService.resolveAliases} for alias resolution\n * @see {@link LoadContextInterface} for context structure\n *\n * @since 2.0.0\n */\n\nexport async function transformerDirective(variant: VariantService, context: LoadContextInterface): Promise<OnLoadResult | undefined> {\n const { args, loader, stage, contents, variantName, options, argv } = context;\n if (args.path.includes('node_modules')) return;\n\n if (contents.length < 1) return;\n if (!TS_JS_REGEX.test(args.path)) return;\n\n const languageService = variant.typescript.languageService;\n const sourceFile = languageService.getProgram()?.getSourceFile(args.path);\n if (!sourceFile) return;\n\n const state: StateInterface = {\n stage: stage as MacrosStateInterface,\n errors: [],\n contents: contents.toString(),\n warnings: [],\n defines: variant.config.define ?? {},\n sourceFile: sourceFile!,\n context: {\n argv,\n options,\n variantName\n }\n };\n\n let content = await astProcess(state, variant.name);\n if (!variant.config.esbuild.bundle) {\n const alias = variant.typescript.languageHostService.aliasRegex;\n if (alias) {\n content = variant.typescript.languageHostService.resolveAliases(content, args.path, '.js');\n }\n }\n\n return { loader, contents: content, warnings: state.warnings, errors: state.errors };\n}\n", "/**\n * Type imports (removed at compile time)\n */\n\nimport type { VariableDeclaration, CallExpression } from 'typescript';\nimport type { SourceFile, Node, ArrowFunction, FunctionExpression } from 'typescript';\nimport type { DefinesType, StateInterface } from './interfaces/macros-directive.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\n\n/**\n * The name of the conditional inclusion directive for checking if a definition is truthy.\n *\n * @remarks\n * Used to identify `$$ifdef` macro calls in the AST. Paired with `$$ifndef` (not-defined check),\n * this directive enables conditional compilation based on build-time definitions.\n *\n * @see {@link isDefinitionMet} for condition evaluation logic\n *\n * @since 2.0.0\n */\n\nconst IFDEF_DIRECTIVE = '$$ifdef';\n\n/**\n * Transforms an AST node into a function declaration or constant assignment.\n *\n * @param fnName - The name for the generated function or constant\n * @param node - The AST node to transform (typically a function or expression)\n * @param sourceFile - The source file containing the node (for text extraction)\n * @param hasExport - Whether to prepend `export` keyword; defaults to `false`\n *\n * @returns A string containing the transformed function declaration or constant assignment\n *\n * @remarks\n * This function handles transformation for conditional macro definitions by converting\n * the macro's callback argument into a named function or constant. The transformation\n * strategy depends on the node type:\n *\n * **For function-like nodes** (arrow functions and function expressions):\n * - Extracts parameters, return type, and body\n * - Generates a proper function declaration\n * - Preserves type annotations if present\n *\n * **For other node types** (expressions, literals, etc.):\n * - Generates a constant assignment\n * - Uses the node's text representation as the value\n *\n * The `hasExport` parameter controls whether the generated declaration is exported,\n * preserving the original export status of the macro variable.\n *\n * @example Arrow function transformation\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * const node = arrowFunctionNode; // () => console.log\n * const result = transformToFunction('$$debug', node, sourceFile, false);\n * // 'function $$debug() { return console.log; }'\n * ```\n *\n * @example Function expression with types\n * ```ts\n * // Source: export const $$getConfig = $$ifdef('DEV', function(): Config { return devConfig; });\n * const result = transformToFunction('$$getConfig', node, sourceFile, true);\n * // 'export function $$getConfig(): Config { return devConfig; }'\n * ```\n *\n * @example Non-function transformation\n * ```ts\n * // Source: const $$apiUrl = $$ifdef('PROD', 'https://api.example.com');\n * const node = stringLiteralNode;\n * const result = transformToFunction('$$apiUrl', node, sourceFile, false);\n * // 'const $$apiUrl = \"https://api.example.com\";'\n * ```\n *\n * @see {@link astDefineVariable} for the calling context\n * @see {@link transformFunctionLikeNode} for function-specific transformation\n *\n * @since 2.0.0\n */\n\nexport function transformToFunction(fnName: string, node: Node, sourceFile: SourceFile, hasExport = false): string {\n const prefix = hasExport ? 'export function ' : 'function ';\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node))\n return transformFunctionLikeNode(fnName, node, sourceFile, prefix);\n\n // Fallback for other node types\n const constPrefix = hasExport ? 'export const ' : 'const ';\n\n return `${ constPrefix }${ fnName } = ${ node.getText(sourceFile) };`;\n}\n\n/**\n * Transforms arrow functions and function expressions into proper function declarations.\n *\n * @param fnName - The name for the generated function\n * @param node - The arrow function or function expression to transform\n * @param sourceFile - The source file containing the node\n * @param prefix - The declaration prefix (e.g., `'function '` or `'export function '`)\n *\n * @returns A string containing the function declaration, prefixed with `async` if the\n * original node carried the `async` modifier\n *\n * @remarks\n * This function extracts the components of a function-like node and reconstructs them\n * as a proper function declaration:\n * - **Async**: Detected from the node's `modifiers` array via `ts.SyntaxKind.AsyncKeyword`\n * and prepended before the declaration prefix, yielding `async function name()` form\n * - **Parameters**: Extracted with full type annotations\n * - **Return type**: Preserved if present in the original\n * - **Body**: Transformed using {@link getFunctionBody} to handle arrow function syntax\n *\n * The transformation preserves all type information, making it suitable for TypeScript\n * projects that rely on type safety in conditional compilation scenarios.\n *\n * @example Async arrow function\n * ```ts\n * const node = parseExpression('async (x: number): Promise<number> => x * 2');\n * const result = transformFunctionLikeNode('double', node, sourceFile, 'export function ');\n * // 'async export function double(x: number): Promise<number> { return x * 2; }'\n * ```\n *\n * @example Arrow function with return type\n * ```ts\n * const node = parseExpression('(x: number): number => x * 2');\n * const result = transformFunctionLikeNode('double', node, sourceFile, 'export function ');\n * // 'export function double(x: number): number { return x * 2; }'\n * ```\n *\n * @example Function expression without types\n * ```ts\n * const node = parseExpression('function(a, b) { return a + b; }');\n * const result = transformFunctionLikeNode('add', node, sourceFile, 'function ');\n * // 'function add(a, b) { return a + b; }'\n * ```\n *\n * @see {@link getFunctionBody} for body extraction\n * @see {@link transformToFunction} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction transformFunctionLikeNode(\n fnName: string, node: ArrowFunction | FunctionExpression, sourceFile: SourceFile, prefix: string\n): string {\n const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;\n const asyncPrefix = isAsync ? 'async ' : '';\n const params = node.parameters.map(p => p.getText(sourceFile)).join(', ');\n const returnType = node.type ? `: ${ node.type.getText(sourceFile) }` : '';\n const body = getFunctionBody(node, sourceFile);\n\n return `${ asyncPrefix }${ prefix }${ fnName }(${ params })${ returnType } ${ body }`;\n}\n\n/**\n * Extracts and formats the function body, handling arrow function shorthand syntax.\n *\n * @param node - The arrow function or function expression to extract from\n * @param sourceFile - The source file containing the node\n *\n * @returns The formatted function body as a string\n *\n * @remarks\n * This function handles two body formats:\n * - **Block body**: Returns as-is (already wrapped in `{}`)\n * - **Expression body**: Wraps in block with `return` statement\n *\n * This ensures that all transformed functions have proper block bodies,\n * which is necessary for function declarations (they cannot have expression bodies).\n *\n * @example Arrow function with expression body\n * ```ts\n * const node = parseExpression('() => 42');\n * const body = getFunctionBody(node, sourceFile);\n * // '{ return 42; }'\n * ```\n *\n * @example Arrow function with block body\n * ```ts\n * const node = parseExpression('() => { console.log(\"test\"); return 42; }');\n * const body = getFunctionBody(node, sourceFile);\n * // '{ console.log(\"test\"); return 42; }'\n * ```\n *\n * @example Function expression (always has block body)\n * ```ts\n * const node = parseExpression('function() { return true; }');\n * const body = getFunctionBody(node, sourceFile);\n * // '{ return true; }'\n * ```\n *\n * @see {@link transformFunctionLikeNode} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction getFunctionBody(node: ArrowFunction | FunctionExpression, sourceFile: SourceFile): string {\n const bodyText = node.body.getText(sourceFile);\n if (ts.isArrowFunction(node) && !ts.isBlock(node.body)) {\n return `{ return ${ bodyText }; }`;\n }\n\n return bodyText;\n}\n\n/**\n * Transforms an AST node into an Immediately Invoked Function Expression (IIFE).\n *\n * @param node - The AST node to transform\n * @param sourceFile - The source file containing the node\n * @param prefix - The prefix to prepend before the IIFE; defaults to `''`\n * @param suffix - The suffix to append after the IIFE; defaults to `'();'`\n *\n * @returns A string containing the IIFE expression, prefixed with `async` when the\n * original function-like node carried the `async` modifier\n *\n * @remarks\n * This function wraps code in IIFE syntax for immediate execution in expression contexts.\n * The transformation strategy depends on the node type:\n *\n * **For function-like nodes** (arrow functions and function expressions):\n * - Detects the `async` modifier via `ts.SyntaxKind.AsyncKeyword` and prepends `async`\n * before `prefix` when present\n * - Wraps directly: `(function)()` or `(() => value)()`\n * - Preserves the function body as-is\n *\n * **For other node types** (expressions, statements):\n * - Wraps in a synchronous arrow function IIFE with explicit return\n * - Ensures the value is returned for use in expressions\n * - Applies `prefix` before and `suffix` after the IIFE\n *\n * The `prefix` and `suffix` parameters allow customization of the IIFE syntax, useful when\n * the IIFE needs additional context, chaining, or specific wrapping.\n *\n * Used when conditional macros appear in expression contexts where a function\n * declaration is not valid syntax.\n *\n * @example Async arrow function to IIFE\n * ```ts\n * const node = parseExpression('async () => await fetchData()');\n * const result = transformToIIFE(node, sourceFile);\n * // 'async (() => await fetchData())()'\n * ```\n *\n * @example Arrow function to IIFE\n * ```ts\n * const node = parseExpression('() => 42');\n * const result = transformToIIFE(node, sourceFile);\n * // '(() => 42)()'\n * ```\n *\n * @example Function expression to IIFE\n * ```ts\n * const node = parseExpression('function() { return \"hello\"; }');\n * const result = transformToIIFE(node, sourceFile);\n * // '(function() { return \"hello\"; })()'\n * ```\n *\n * @example Expression to IIFE\n * ```ts\n * const node = parseExpression('1 + 1');\n * const result = transformToIIFE(node, sourceFile);\n * // '(() => { return 1 + 1; })()'\n * ```\n *\n * @example Custom prefix and suffix\n * ```ts\n * const node = parseExpression('getValue()');\n * const result = transformToIIFE(node, sourceFile, 'await ', '.catch(handleError)');\n * // 'await (() => { return getValue(); })().catch(handleError)'\n * ```\n *\n * @see {@link astDefineCallExpression} for the calling context\n *\n * @since 2.0.0\n */\n\nexport function transformToIIFE(node: Node, sourceFile: SourceFile, prefix: string = '', suffix: string = '();'): string {\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;\n const asyncPrefix = isAsync ? 'async ' : '';\n\n return `${ asyncPrefix }${ prefix }(${ node.getText(sourceFile) })${ suffix }`;\n }\n\n if (prefix) return `${ prefix }${ node.getText(sourceFile) }`;\n\n return `(() => { return ${ node.getText(sourceFile) }; })${ suffix }`;\n}\n\n/**\n * Determines whether a conditional macro definition should be included based on build definitions.\n *\n * @param defineName - The definition name to check (e.g., `'DEBUG'`, `'PRODUCTION'`)\n * @param directiveName - The directive name (`'$$ifdef'` or `'$$ifndef'`)\n * @param defines - The build definitions object mapping names to boolean values\n *\n * @returns `true` if the definition condition is met, `false` otherwise\n *\n * @remarks\n * This function implements the core conditional logic for `$$ifdef` and `$$ifndef` macros:\n *\n * **For `$$ifdef`** (if defined):\n * - Returns `true` when the definition exists and is truthy\n * - Returns `false` when the definition is missing, `false`, `0`, `''`, etc.\n *\n * **For `$$ifndef`** (if not defined):\n * - Returns `true` when the definition is missing or falsy\n * - Returns `false` when the definition exists and is truthy\n *\n * The check uses JavaScript's truthiness rules via `!!defines[defineName]`.\n *\n * @example `$$ifdef` with true definition\n * ```ts\n * const defines = { DEBUG: true, PRODUCTION: false };\n * isDefinitionMet('DEBUG', '$$ifdef', defines); // true\n * isDefinitionMet('PRODUCTION', '$$ifdef', defines); // false\n * ```\n *\n * @example `$$ifndef` with false definition\n * ```ts\n * const defines = { DEBUG: true, PRODUCTION: false };\n * isDefinitionMet('DEBUG', '$$ifndef', defines); // false\n * isDefinitionMet('PRODUCTION', '$$ifndef', defines); // true\n * ```\n *\n * @example Missing definition\n * ```ts\n * const defines = { DEBUG: true };\n * isDefinitionMet('MISSING', '$$ifdef', defines); // false\n * isDefinitionMet('MISSING', '$$ifndef', defines); // true\n * ```\n *\n * @see {@link astDefineVariable} for usage context\n * @see {@link astDefineCallExpression} for usage context\n *\n * @since 2.0.0\n */\n\nfunction isDefinitionMet(defineName: string, directiveName: string, defines: DefinesType): boolean {\n const isDefined = defineName in defines && !!defines[defineName];\n\n return (directiveName === IFDEF_DIRECTIVE) === isDefined;\n}\n\n/**\n * Transforms a conditional macro variable declaration into a function or returns an empty string if excluded.\n *\n * @param decl - The variable declaration node containing the macro\n * @param init - The call expression node representing the macro call\n * @param hasExport - Whether the variable declaration has an `export` modifier\n * @param state - The macro transformation state containing definitions and source file\n *\n * @returns The transformed function/constant string, empty string if excluded, or `false` if invalid\n *\n * @remarks\n * This function processes conditional macro variable declarations of the form:\n * ```ts\n * const $$myFunc = $$ifdef('DEFINITION', callback);\n * const $$myFunc = $$ifndef('DEFINITION', callback);\n * ```\n *\n * The transformation process:\n * 1. Validates that the first argument is a string literal (the definition name)\n * 2. Checks if the definition condition is met using {@link isDefinitionMet}\n * 3. If included: transforms the callback into a function using {@link transformToFunction}\n * 4. If excluded: returns an empty string (macro is stripped from output)\n * 5. If invalid: returns `false` (non-string definition argument)\n *\n * The variable name from the declaration becomes the function name in the output.\n *\n * @example Included macro (DEBUG=true)\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * // With: { DEBUG: true }\n * const result = astDefineVariable(decl, init, false, state);\n * // 'function $$debug() { return console.log; }'\n * ```\n *\n * @example Excluded macro (DEBUG=false)\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * // With: { DEBUG: false }\n * const result = astDefineVariable(decl, init, false, state);\n * // ''\n * ```\n *\n * @example Exported macro\n * ```ts\n * // Source: export const $$feature = $$ifdef('FEATURE_X', () => true);\n * // With: { FEATURE_X: true }\n * const result = astDefineVariable(decl, init, true, state);\n * // 'export function $$feature() { return true; }'\n * ```\n *\n * @example Invalid macro (non-string definition)\n * ```ts\n * // Source: const $$bad = $$ifdef(DEBUG, () => {});\n * const result = astDefineVariable(decl, init, false, state);\n * // false\n * ```\n *\n * @see {@link isDefinitionMet} for condition evaluation\n * @see {@link transformToFunction} for transformation logic\n *\n * @since 2.0.0\n */\n\nexport function astDefineVariable(\n decl: VariableDeclaration, init: CallExpression, hasExport: boolean, state: StateInterface\n): string | false {\n const [ defineArg, callbackArg ] = init.arguments;\n\n if (!ts.isStringLiteral(defineArg)) return false;\n\n const fnName = (init.expression as ts.Identifier).text;\n const defineName = defineArg.text;\n\n if (!isDefinitionMet(defineName, fnName, state.defines)) {\n return 'undefined';\n }\n\n const varName = decl.name.getText(state.sourceFile);\n\n return transformToFunction(varName, callbackArg, state.sourceFile, hasExport);\n}\n\n/**\n * Transforms a conditional macro call expression into a constant assignment with an IIFE or returns empty string if excluded.\n *\n * @param decl - The variable declaration node containing the macro\n * @param init - The call expression node representing the macro call\n * @param hasExport - Whether the variable declaration has an `export` modifier\n * @param state - The macro transformation state containing definitions and source file\n * @param outerSuffix - Optional suffix to append after the IIFE invocation\n *\n * @returns The transformed constant assignment string, empty string if excluded, or `false` if invalid\n *\n * @remarks\n * This function processes conditional macro call expressions that are assigned to constants:\n * ```ts\n * const $$value = $$ifdef('DEBUG', () => \"debug mode\");\n * export const $$config = $$ifndef('PRODUCTION', () => devConfig);\n * ```\n *\n * Unlike {@link astDefineVariable}, which transforms macros into function declarations,\n * this handles macros that should remain as constant assignments with IIFE values.\n *\n * The transformation process:\n * 1. Validates that the first argument is a string literal (the definition name)\n * 2. Extracts the macro function name (`$$ifdef` or `$$ifndef`)\n * 3. Checks if the definition condition is met using {@link isDefinitionMet}\n * 4. If included: transforms the callback into a constant assignment with IIFE using {@link transformToIIFE}\n * 5. If excluded: returns an empty string (macro is stripped from output)\n * 6. If invalid: returns `false` (non-string definition argument)\n *\n * The variable name from the declaration becomes the constant name in the output,\n * and the `hasExport` parameter controls whether the constant is exported.\n *\n * @example Included expression (DEBUG=true)\n * ```ts\n * // Source: const $$debugMsg = $$ifdef('DEBUG', () => \"debugging\");\n * // With: { DEBUG: true }\n * const result = astDefineCallExpression(decl, init, false, state);\n * // 'const $$debugMsg = (() => { return \"debugging\"; })();'\n * ```\n *\n * @example Excluded expression (DEBUG=false)\n * ```ts\n * // Source: const $$debugMsg = $$ifdef('DEBUG', () => \"debugging\");\n * // With: { DEBUG: false }\n * const result = astDefineCallExpression(decl, init, false, state);\n * // ''\n * ```\n *\n * @example Exported constant\n * ```ts\n * // Source: export const $$apiUrl = $$ifndef('PRODUCTION', () => 'http://localhost');\n * // With: { PRODUCTION: false }\n * const result = astDefineCallExpression(decl, init, true, state);\n * // 'export const $$apiUrl = (() => { return \"http://localhost\"; })();'\n * ```\n *\n * @example With custom suffix\n * ```ts\n * // Source: const $$data = $$ifdef('FEATURE', () => fetchData());\n * // With: { FEATURE: true }\n * const result = astDefineCallExpression(decl, init, false, state, '.then(process)');\n * // 'const $$data = (() => { return fetchData(); })().then(process)'\n * ```\n *\n * @see {@link isDefinitionMet} for condition evaluation\n * @see {@link transformToIIFE} for transformation logic\n * @see {@link astDefineVariable} for function declaration handling\n *\n * @since 2.0.0\n */\n\nexport function astDefineCallExpression(\n init: CallExpression, state: StateInterface, decl?: VariableDeclaration, hasExport: boolean = false, outerSuffix?: string\n): string | false {\n const [ defineArg, callbackArg ] = init.arguments;\n\n if (!ts.isStringLiteral(defineArg)) return false;\n\n const defineName = defineArg.text;\n const fnName = (init.expression as ts.Identifier).text;\n if (!isDefinitionMet(defineName, fnName, state.defines)) return '';\n\n let constPrefix = '';\n const varName = decl?.name.getText(state.sourceFile);\n if(varName) {\n constPrefix = hasExport ? `export const ${ varName } = ` : `const ${ varName } = `;\n }\n\n return transformToIIFE(callbackArg, state.sourceFile, constPrefix, outerSuffix);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CallExpression, VariableDeclaration, Node } from 'typescript';\nimport type { SourceFile, NodeArray, Expression, VariableStatement } from 'typescript';\nimport type { StateInterface } from '@directives/interfaces/macros-directive.interface';\nimport type { FunctionNodeType, ModuleInterface } from '@directives/interfaces/inline-directive.interface';\nimport type { ExecutableInterface, VariableKeywordType } from '@directives/interfaces/inline-directive.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { createRequire } from 'module';\nimport { InlineError } from '@errors/inline.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { sandboxExecute } from '@services/vm.service';\nimport { dirname, relative } from '@components/path.component';\nimport { FrameworkService } from '@services/framework.service';\nimport { buildFromString } from '@services/transpiler.service';\n\n/**\n * Evaluates inline macro code in a sandboxed environment and returns the result as a string.\n *\n * @param code - The JavaScript code to execute (typically an IIFE wrapping a function or expression)\n * @param state - The current macro transformation state containing source file and error tracking\n * @param node - The AST node representing the inline macro call (used for error location tracking)\n *\n * @returns A promise resolving to the stringified result of the code execution, or `'undefined'` on error\n *\n * @remarks\n * This function performs the following steps:\n * 1. Transpiles and bundles the code using {@link buildFromString} in CommonJS format\n * 2. Creates a sandboxed execution context with access to Node.js globals and the file system\n * 3. Executes the code using {@link sandboxExecute} in an isolated VM context\n * 4. Captures and formats any errors using {@link InlineError} with source mapping\n * 5. Returns `'undefined'` on failure (errors are tracked in `state.errors`)\n *\n * The sandbox has access to:\n * - Global Node.js APIs (`Buffer`, `process`, `console`)\n * - Module system (`require`, `module`, `__dirname`, `__filename`)\n * - Timers (`setTimeout`, `setInterval`, and their clear counterparts)\n * - Standard JavaScript globals from `globalThis`\n *\n * Errors that occur during execution are enhanced with source maps to point back to the\n * original source code location, accounting for line offsets where the inline macro appears.\n *\n * @example Basic inline evaluation\n * ```ts\n * const code = '(() => { return 42; })()';\n * const result = await evaluateCode(code, state, node);\n * // result === 'undefined' (function executed but returns undefined as string)\n * ```\n *\n * @example Inline computation with imports\n * ```ts\n * const code = `(() => {\n * const fs = require('fs');\n * return fs.existsSync('./package.json') ? 'found' : 'missing';\n * })()`;\n *\n * const result = await evaluateCode(code, state, node);\n * // Executes in sandbox with require() support\n * ```\n *\n * @example Error handling with source mapping\n * ```ts\n * const code = '(() => { throw new Error(\"Test error\"); })()';\n * const result = await evaluateCode(code, state, node);\n * // Returns 'undefined'\n * // state.errors contains InlineError with mapped stack trace\n * ```\n *\n * @see {@link sandboxExecute} for VM execution\n * @see {@link InlineError} for error formatting\n * @see {@link createSandboxContext} for context creation\n * @see {@link handleExecutionError} for error processing\n * @see {@link buildFromString} for transpilation and bundling\n *\n * @since 2.0.0\n */\n\nexport async function evaluateCode(code: string, state: StateInterface, node: Node): Promise<string> {\n const [ map, data ] = (await buildFromString(code, state.sourceFile.fileName, {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n packages: 'external'\n })).outputFiles!;\n\n try {\n const module = { exports: {} };\n const require = createRequire(state.sourceFile.fileName);\n const context = createSandboxContext(state.sourceFile.fileName, module, require);\n context.context = state.context;\n\n const result = await sandboxExecute(data.text, context, {\n filename: state.sourceFile.fileName\n });\n\n if (result === null) return 'undefined';\n if (typeof result === 'number' || typeof result === 'boolean') return String(result);\n\n return JSON.stringify(result);\n } catch (err) {\n handleExecutionError(err, state, map.text, node);\n }\n\n return 'undefined';\n}\n\n/**\n * Creates a sandboxed execution context with Node.js globals and module system access.\n *\n * @param fileName - The absolute path to the source file (used for `__filename` and module resolution)\n * @param module - The CommonJS module object with `exports` property\n * @param require - The require function scoped to the source file's location\n *\n * @returns A context object containing all globals available during inline macro execution\n *\n * @remarks\n * The sandbox context provides a controlled environment for executing inline macros with:\n * - **Standard globals**: All properties from `globalThis` (including `RegExp` explicitly)\n * - **Node.js APIs**: `Buffer`, `process`, `console`\n * - **Module system**: `module`, `require`, `__dirname`, `__filename`\n * - **Timers**: `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`\n *\n * The context is designed to mimic a normal Node.js execution environment while maintaining\n * isolation from the build process. The `require` function is scoped to the source file's\n * directory, allowing relative imports to resolve correctly.\n *\n * @example Context structure\n * ```ts\n * const module = { exports: {} };\n * const require = createRequire('/project/src/config.ts');\n *\n * const context = createSandboxContext('/project/src/config.ts', module, require);\n *\n * // context contains:\n * // - process, Buffer, console\n * // - require (scoped to /project/src/)\n * // - __dirname === '/project/src'\n * // - __filename === '/project/src/config.ts'\n * // - setTimeout, setInterval, etc.\n * ```\n *\n * @example Usage in inline evaluation\n * ```ts\n * const context = createSandboxContext(state.sourceFile.fileName, module, require);\n *\n * await sandboxExecute(compiledCode, context, {\n * filename: state.sourceFile.fileName\n * });\n * ```\n *\n * @see {@link sandboxExecute} for execution\n * @see {@link evaluateCode} for usage context\n *\n * @since 2.0.0\n */\n\nexport function createSandboxContext(fileName: string, module: ModuleInterface, require: NodeJS.Require): Record<string, unknown> {\n return {\n ...globalThis,\n Error,\n RegExp,\n process,\n Buffer,\n module,\n require,\n console,\n setTimeout,\n setInterval,\n clearTimeout,\n clearInterval,\n ReferenceError,\n __dirname: dirname(fileName),\n __filename: fileName\n };\n}\n\n/**\n * Handles execution errors during inline macro evaluation and adds them to the transformation state.\n *\n * @param err - The error that occurred during execution\n * @param state - The macro transformation state to store the error in\n * @param mapText - The source map text for mapping error locations back to original source\n * @param node - The AST node representing the inline macro (used for calculating line offset)\n *\n * @remarks\n * This function processes errors that occur during {@link evaluateCode} by:\n * 1. Filtering out non-Error objects (ignores thrown primitives or undefined)\n * 2. Calculating the line offset where the inline macro appears in the source file\n * 3. Creating an {@link InlineError} with source map support and line offset adjustment\n * 4. Adding the formatted error to `state.errors` for build reporting\n *\n * The line offset is crucial for accurate error reporting because inline macros are extracted\n * from their original location, compiled separately, and executed in isolation. The offset\n * ensures that error locations point to the correct line in the original source file.\n *\n * @example Error handling flow\n * ```ts\n * try {\n * await sandboxExecute(code, context);\n * } catch (err) {\n * // err is a runtime error from the executed code\n * handleExecutionError(err, state, sourceMapText, node);\n * // state.errors now contains formatted error with correct source location\n * }\n * ```\n *\n * @example Error output\n * ```ts\n * // Original source at line 42: const x = $$inline(() => undefined.toString());\n * // After handling:\n * // state.errors === [{\n * // text: \"Cannot read property 'toString' of undefined\",\n * // detail: InlineError (with formatted stack pointing to line 42)\n * // }]\n * ```\n *\n * @see {@link evaluateCode} for execution context\n * @see {@link InlineError} for error formatting and source mapping\n *\n * @since 2.0.0\n */\n\nfunction handleExecutionError(err: unknown, state: StateInterface, mapText: string, node: Node): void {\n if (!err || (typeof err !== 'object') || !('stack' in err)) {\n err = new Error(String(err));\n }\n\n const start = node.getStart(state.sourceFile);\n const { line } = state.sourceFile.getLineAndCharacterOfPosition(start);\n\n inject(FrameworkService).setSource(mapText, state.sourceFile.fileName);\n const error = new InlineError(<Error> err, line);\n\n state.errors.push({\n text: error.message,\n detail: error\n });\n}\n\n/**\n * Searches for a function declaration or function variable by name in the source file.\n *\n * @param functionName - The name of the function to find\n * @param sourceFile - The TypeScript source file to search\n *\n * @returns The found function node (declaration, arrow function, or function expression), or `null` if not found\n *\n * @remarks\n * This function recursively traverses the AST to locate functions that match the given name.\n * It handles three types of function definitions:\n * - `function myFunction() {}` (function declarations)\n * - `const myFunction = () => {}` (arrow functions in variable declarations)\n * - `const myFunction = function() {}` (function expressions in variable declarations)\n *\n * The search stops at the first match found. This is used when an inline macro references\n * a function by name rather than providing an inline function expression.\n *\n * @example Finding a function declaration\n * ```ts\n * const sourceFile = ts.createSourceFile(\n * 'test.ts',\n * 'function myFunc() { return 42; }',\n * ts.ScriptTarget.Latest\n * );\n *\n * const func = findFunctionByName('myFunc', sourceFile);\n * // func is a FunctionDeclaration node\n * ```\n *\n * @example Finding an arrow function variable\n * ```ts\n * const sourceFile = ts.createSourceFile(\n * 'test.ts',\n * 'const myFunc = () => 42;',\n * ts.ScriptTarget.Latest\n * );\n *\n * const func = findFunctionByName('myFunc', sourceFile);\n * // func is an ArrowFunction node\n * ```\n *\n * @example Function not found\n * ```ts\n * const func = findFunctionByName('nonExistent', sourceFile);\n * // func === null\n * ```\n *\n * @see {@link extractFromIdentifier} for usage context\n * @see {@link findFunctionInVariableStatement} for variable extraction logic\n *\n * @since 2.0.0\n */\n\nfunction findFunctionByName(functionName: string, sourceFile: SourceFile): FunctionNodeType | null {\n let foundFunction: FunctionNodeType | null = null;\n\n const visit = (node: Node): void => {\n if (foundFunction) return;\n if (ts.isFunctionDeclaration(node) && node.name?.text === functionName) {\n foundFunction = node;\n\n return;\n }\n\n if (ts.isVariableStatement(node)) {\n foundFunction = findFunctionInVariableStatement(node, functionName);\n if (foundFunction) return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n\n return foundFunction;\n}\n\n/**\n * Extracts a function initializer from a variable statement if it matches the given name.\n *\n * @param node - The variable statement to search\n * @param functionName - The variable name to match\n *\n * @returns The arrow function or function expression initializer, or `null` if not found\n *\n * @remarks\n * This helper function is used by {@link findFunctionByName} to extract functions defined\n * as variables with arrow functions or function expressions as initializers.\n *\n * Only matches variables declared with simple identifiers (not destructured patterns)\n * that have arrow functions or function expressions as their initializer.\n *\n * @example Matching arrow function\n * ```ts\n * const statement = parseStatement('const myFunc = () => 42;');\n * const func = findFunctionInVariableStatement(statement, 'myFunc');\n * // func is the ArrowFunction node\n * ```\n *\n * @example Matching function expression\n * ```ts\n * const statement = parseStatement('const myFunc = function() { return 42; };');\n * const func = findFunctionInVariableStatement(statement, 'myFunc');\n * // func is the FunctionExpression node\n * ```\n *\n * @example No match\n * ```ts\n * const statement = parseStatement('const myFunc = 42;');\n * const func = findFunctionInVariableStatement(statement, 'myFunc');\n * // func === null (initializer is not a function)\n * ```\n *\n * @see {@link findFunctionByName} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction findFunctionInVariableStatement(node: VariableStatement, functionName: string): FunctionNodeType | null {\n for (const decl of node.declarationList.declarations) {\n if (\n ts.isIdentifier(decl.name) &&\n decl.name.text === functionName &&\n decl.initializer &&\n (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))\n ) {\n return decl.initializer;\n }\n }\n\n return null;\n}\n\n/**\n * Wraps JavaScript code in an Immediately Invoked Function Expression (IIFE).\n *\n * @param code - The code to wrap\n *\n * @returns The code wrapped in IIFE syntax: `module.exports = (code)();`\n *\n * @remarks\n * Converts function definitions or expressions into immediately executed forms for\n * inline evaluation. This is necessary when the inline macro contains a function\n * that should be executed and its return value used, rather than the function itself.\n *\n * The wrapping ensures that:\n * - Function declarations become function expressions (valid in expression context)\n * - Arrow functions and function expressions are immediately invoked\n * - The result of execution is captured rather than the function object\n *\n * @example Wrapping an arrow function\n * ```ts\n * const code = '() => 42';\n * const wrapped = wrapInIIFE(code);\n * // 'module.exports = (() => 42)();'\n * ```\n *\n * @example Wrapping a function expression\n * ```ts\n * const code = 'function() { return \"hello\"; }';\n * const wrapped = wrapInIIFE(code);\n * // 'module.exports = (function() { return \"hello\"; })();'\n * ```\n *\n * @example Wrapping a function declaration\n * ```ts\n * const code = 'function myFunc() { return 123; }';\n * const wrapped = wrapInIIFE(code);\n * // 'module.exports = (function myFunc() { return 123; })();'\n * ```\n *\n * @see {@link evaluateCode} for execution\n * @see {@link extractExecutableCode} for usage context\n *\n * @since 2.0.0\n */\n\nexport function wrapInIIFE(code: string): string {\n return `module.exports = (${ code })();`;\n}\n\n/**\n * Determines the variable keyword (`const`, `let`, or `var`) from TypeScript node flags.\n *\n * @param flags - TypeScript node flags from a variable declaration list\n *\n * @returns The appropriate variable keyword\n *\n * @remarks\n * Extracts the variable declaration keyword by checking TypeScript's node flags:\n * - Returns `'const'` if `NodeFlags.Const` is set\n * - Returns `'let'` if `NodeFlags.Let` is set\n * - Returns `'var'` as the default fallback\n *\n * This is used when transforming inline macro variable declarations to preserve\n * the original variable declaration style in the output.\n *\n * @example\n * ```ts\n * const flags = ts.NodeFlags.Const;\n * const keyword = getVariableKeyword(flags);\n * // 'const'\n * ```\n *\n * @example\n * ```ts\n * const flags = ts.NodeFlags.Let;\n * const keyword = getVariableKeyword(flags);\n * // 'let'\n * ```\n *\n * @example\n * ```ts\n * const flags = ts.NodeFlags.None;\n * const keyword = getVariableKeyword(flags);\n * // 'var'\n * ```\n *\n * @see {@link astInlineVariable} for usage context\n *\n * @since 2.0.0\n */\n\nfunction getVariableKeyword(flags: ts.NodeFlags): VariableKeywordType {\n if (flags & ts.NodeFlags.Const) return 'const';\n if (flags & ts.NodeFlags.Let) return 'let';\n\n return 'var';\n}\n\n/**\n * Extracts executable code from various AST node types for inline macro evaluation.\n *\n * @param node - The AST node to extract code from\n * @param state - The macro transformation state for error reporting and source file access\n *\n * @returns An object containing the extracted code and the source node, or `null` if extraction fails\n *\n * @remarks\n * This function handles multiple node types:\n * - **Identifiers**: Looks up function declarations by name and wraps them in IIFEs\n * - **Arrow functions**: Wraps them in IIFEs for immediate execution\n * - **Function expressions**: Wraps them in IIFEs for immediate execution\n * - **Other expressions**: Returns the code as-is for direct evaluation\n *\n * When a function is referenced by name (identifier), the function must be defined\n * in the same source file. If not found, a warning is added to the transformation state.\n *\n * The returned `ExecutableInterface` contains both the formatted executable code and\n * the original AST node for error location tracking during execution.\n *\n * @example Extracting from an identifier reference\n * ```ts\n * // Source contains: function myFunc() { return 42; }\n * const node = ts.factory.createIdentifier('myFunc');\n * const result = extractExecutableCode(node, state);\n * // result.data === '(function myFunc() { return 42; })()'\n * ```\n *\n * @example Extracting from an arrow function\n * ```ts\n * const node = parseExpression('() => 42');\n * const result = extractExecutableCode(node, state);\n * // result.data === '(() => 42)()'\n * ```\n *\n * @example Extracting from an expression\n * ```ts\n * const node = parseExpression('1 + 2');\n * const result = extractExecutableCode(node, state);\n * // result.data === '1 + 2'\n * ```\n *\n * @example Function not found (generates warning)\n * ```ts\n * const node = ts.factory.createIdentifier('nonExistent');\n * const result = extractExecutableCode(node, state);\n * // result.data === ''\n * // state.warnings contains: \"Function $$inline(nonExistent); not found in ...\"\n * ```\n *\n * @see {@link evaluateCode} for execution\n * @see {@link wrapInIIFE} for IIFE wrapping\n * @see {@link extractFromIdentifier} for identifier handling\n *\n * @since 2.0.0\n */\n\nexport function extractExecutableCode(node: Node, state: StateInterface): ExecutableInterface | null {\n if (!node) return null;\n\n // Handle identifier (function name reference)\n if (ts.isIdentifier(node)) {\n return extractFromIdentifier(node, state);\n }\n\n // Handle arrow functions and function expressions\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n return {\n node,\n data: wrapInIIFE(node.getText(state.sourceFile))\n };\n }\n\n // Handle other expressions\n return {\n node,\n data: node.getText(state.sourceFile)\n };\n}\n\n/**\n * Extracts executable code from a function identifier reference.\n *\n * @param node - The identifier node referencing a function name\n * @param state - The macro transformation state for function lookup and warnings\n *\n * @returns An object containing the wrapped function code and source node, or empty code with warning if not found\n *\n * @remarks\n * This function handles inline macros that reference functions by name rather than\n * defining them inline. It:\n * 1. Searches for the function declaration in the source file using {@link findFunctionByName}\n * 2. If found, wraps the function in an IIFE for immediate execution\n * 3. If not found, adds a warning to the transformation state and returns empty code\n *\n * The warning includes the relative path to help developers locate the issue quickly.\n *\n * @example Successful extraction\n * ```ts\n * // Source contains: function myFunc() { return 42; }\n * const identifier = ts.factory.createIdentifier('myFunc');\n * const result = extractFromIdentifier(identifier, state);\n * // result.data === '(function myFunc() { return 42; })()'\n * // result.node === FunctionDeclaration node\n * ```\n *\n * @example Function not found\n * ```ts\n * const identifier = ts.factory.createIdentifier('missing');\n * const result = extractFromIdentifier(identifier, state);\n * // result.data === ''\n * // result.node === identifier\n * // state.warnings contains a warning message\n * ```\n *\n * @see {@link findFunctionByName} for function lookup\n * @see {@link extractExecutableCode} for the calling context\n * @see {@link addFunctionNotFoundWarning} for warning generation\n *\n * @since 2.0.0\n */\n\nfunction extractFromIdentifier(node: ts.Identifier, state: StateInterface): ExecutableInterface {\n const functionDeclaration = findFunctionByName(node.text, state.sourceFile);\n\n if (!functionDeclaration) {\n addFunctionNotFoundWarning(node.text, state, node);\n\n return { data: '', node };\n }\n\n return {\n node: functionDeclaration,\n data: wrapInIIFE(functionDeclaration.getText(state.sourceFile))\n };\n}\n\n/**\n * Adds a warning to the transformation state when a referenced function is not found.\n *\n * @param functionName - The name of the function that was not found\n * @param state - The macro transformation state to add the warning to\n * @param node - The AST node representing the function reference (used for location tracking)\n *\n * @remarks\n * Generates a user-friendly warning message with the relative file path and precise location\n * information to help developers quickly identify and fix missing function references in inline macros.\n *\n * The warning includes:\n * - A descriptive message with the function name and file path\n * - Precise location information (line, column, file path)\n * - The source line text containing the reference\n *\n * The warning message format is:\n * ```\n * Function $$inline(functionName); not found in path/to/file.ts\n * ```\n *\n * @example\n * ```ts\n * // In file: /project/src/config.ts at line 42, column 15\n * // Code contains: const x = $$inline(missingFunc);\n *\n * const identifier = ts.factory.createIdentifier('missingFunc');\n * addFunctionNotFoundWarning('missingFunc', state, identifier);\n * // state.warnings === [{\n * // text: \"Function $$inline(missingFunc); not found in src/config.ts\",\n * // location: {\n * // line: 43, // 1-indexed\n * // column: 15,\n * // file: '/project/src/config.ts',\n * // lineText: 'asd'\n * // }\n * // }]\n * ```\n *\n * @see {@link extractFromIdentifier} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction addFunctionNotFoundWarning(functionName: string, state: StateInterface, node: Node): void {\n const start = node.getStart(state.sourceFile);\n const { line, character } = state.sourceFile.getLineAndCharacterOfPosition(start);\n const relativePath = relative('.', state.sourceFile.fileName);\n\n state.warnings.push({\n text: `Function $$inline(${ functionName }); not found in ${ relativePath }`,\n location: {\n line: line + 1,\n column: character,\n file: state.sourceFile.fileName,\n lineText: 'asd'\n }\n });\n}\n\n/**\n * Transforms an inline macro variable declaration into executable code with the evaluated result.\n *\n * @param decl - The variable declaration node containing the inline macro\n * @param node - The complete variable statement (needed for flags and export status)\n * @param init - The call expression node representing the `$$inline()` macro call\n * @param hasExport - Whether the variable declaration has an `export` modifier\n * @param state - The macro transformation state for code extraction and evaluation\n *\n * @returns A promise resolving to the transformed variable declaration string, or `false` if transformation fails\n *\n * @remarks\n * This function processes inline macro variable declarations of the form:\n * ```ts\n * const myVar = $$inline(...);\n * export const myVar = $$inline(...);\n * ```\n *\n * The transformation process:\n * 1. Extracts the executable code from the macro argument using {@link extractExecutableCode}\n * 2. Evaluates the code in a sandboxed environment using {@link evaluateCode}\n * 3. Replaces the macro call with the evaluated result\n * 4. Preserves the variable keyword (`const`, `let`, or `var`) and export status\n *\n * @example Basic inline variable\n * ```ts\n * // Input AST for: a const result = $$inline(() => 1 + 1);\n * const transformed = await astInlineVariable(decl, node, init, false, state);\n * // transformed === 'const result = undefined;'\n * // (actual evaluation would return the computed value)\n * ```\n *\n * @example Exported inline variable\n * ```ts\n * // Input AST for: export const API_URL = $$inline(() => process.env.API_URL);\n * const transformed = await astInlineVariable(decl, node, init, true, state);\n * // transformed === 'export const API_URL = undefined;'\n * ```\n *\n * @example With function reference\n * ```ts\n * // Input AST for: let config = $$inline(getConfig);\n * const transformed = await astInlineVariable(decl, node, init, false, state);\n * // transformed === 'let config = undefined;'\n * ```\n *\n * @see {@link evaluateCode} for code evaluation\n * @see {@link extractExecutableCode} for code extraction\n * @see {@link getVariableKeyword} for variable keyword detection\n *\n * @since 2.0.0\n */\n\nexport async function astInlineVariable(\n decl: VariableDeclaration, node: VariableStatement, init: CallExpression, hasExport: boolean, state: StateInterface\n): Promise<string | false> {\n const arg = init.arguments[0];\n const code = extractExecutableCode(arg, state);\n if (!code) return false;\n\n const result = await evaluateCode(code.data, state, code.node);\n const varKeyword = getVariableKeyword(node.declarationList.flags);\n const exportPrefix = hasExport ? 'export ' : '';\n const varName = decl.name.getText(state.sourceFile);\n\n return `${ exportPrefix }${ varKeyword } ${ varName } = ${ result };`;\n}\n\n/**\n * Transforms an inline macro call expression into its evaluated result.\n *\n * @param args - The arguments passed to the `$$inline()` call\n * @param state - The macro transformation state for code extraction and evaluation\n *\n * @returns A promise resolving to the evaluated result string, or `false` if transformation fails\n *\n * @remarks\n * This function processes standalone inline macro calls that appear in expression contexts:\n * ```ts\n * console.log($$inline(() => \"hello\"));\n * const x = someFunction($$inline(getValue));\n * ```\n *\n * Unlike {@link astInlineVariable}, this handles inline macros that are not part of\n * variable declarations but are used directly as expressions.\n *\n * The transformation process:\n * 1. Extracts the executable code from the first argument using {@link extractExecutableCode}\n * 2. Evaluates the code using {@link evaluateCode}\n * 3. Returns the stringified result to replace the macro call\n *\n * @example Inline function call\n * ```ts\n * // Input AST for: console.log($$inline(() => 42));\n * const transformed = await astInlineCallExpression(args, state);\n * // transformed === 'undefined'\n * // Original: console.log($$inline(() => 42));\n * // Result: console.log(undefined);\n * ```\n *\n * @example Inline with function reference\n * ```ts\n * // Input AST for: const result = compute($$inline(getValue));\n * const transformed = await astInlineCallExpression(args, state);\n * // transformed === 'undefined'\n * ```\n *\n * @example Extraction failure\n * ```ts\n * const transformed = await astInlineCallExpression([], state);\n * // transformed === false\n * ```\n *\n * @see {@link evaluateCode} for code evaluation\n * @see {@link extractExecutableCode} for code extraction\n * @see {@link astInlineVariable} for variable declaration handling\n *\n * @since 2.0.0\n */\n\nexport async function astInlineCallExpression(args: NodeArray<Expression>, state: StateInterface): Promise<string | false> {\n const arg = args[0];\n const code = extractExecutableCode(arg, state);\n\n if (!code) return false;\n\n return evaluateCode(code.data, state, code.node);\n}\n", "/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\nimport { getErrorMetadata, formatStack } from '@providers/stack.provider';\n\n/**\n * Custom error class for inline errors with enhanced formatting and source code context.\n *\n * @remarks\n * The `InlineError` class extends {@link xBuildBaseError} to provide specialized handling for\n * JavaScript/TypeScript errors with optional line offset adjustment. It automatically:\n * - Extracts and formats error metadata using {@link getErrorMetadata}\n * - Applies syntax highlighting to code context\n * - Generates enhanced stack traces with file locations\n * - Supports line offset adjustment for accurate error positioning\n * - Stores structured metadata in {@link StackInterface} format\n *\n * This class is designed to transform standard Error objects into human-readable, visually enhanced\n * output suitable for terminal display, making it easier to identify and fix errors in source code.\n *\n * **Key features:**\n * - Automatic error metadata extraction and formatting\n * - Contextual code display with configurable line offset\n * - Syntax highlighting with color-coded error indicators\n * - Enhanced stack trace generation\n * - Structured error metadata for programmatic access\n *\n * @example\n * ```ts\n * import { InlineError } from './inline.error';\n *\n * try {\n * // Some code that might throw an error\n * throw new Error('Unexpected token');\n * } catch (err) {\n * throw new InlineError(err as Error);\n * }\n * ```\n *\n * @example\n * ```ts\n * // Error with line offset adjustment\n * try {\n * // Code execution\n * } catch (err) {\n * // Adjust error line number by 2 lines\n * const error = new InlineError(err as Error, 2);\n * console.error(error); // Displays formatted error with adjusted line context\n * }\n * ```\n *\n * @see {@link StackInterface} for metadata structure\n * @see {@link xBuildBaseError} for base error functionality\n * @see {@link getErrorMetadata} for metadata extraction logic\n * @see {@link formatStack} for stack formatting logic\n *\n * @since 2.0.0\n */\n\nexport class InlineError extends xBuildBaseError {\n /**\n * Creates a new inline error with formatted output and metadata.\n *\n * @param error - The base Error object containing error details\n * @param lineOffset - Optional line number offset for adjusting error position (default: 0)\n *\n * @remarks\n * The constructor processes the error to:\n * 1. Extract the error message for the base Error\n * 2. Generate error metadata using {@link getErrorMetadata} with optional line offset\n * 3. Format the stack trace using {@link formatStack}\n * 4. Store structured metadata in {@link errorMetadata}\n *\n * The `lineOffset` parameter allows you to adjust the reported line number in the error output.\n * This is useful when the actual error location differs from the reported location due to\n * transpilation, code generation, or other transformations:\n * - Positive values shift the line number down\n * - Negative values shift the line number up\n * - Zero (default) uses the original line number\n *\n * The error name is always set to `'InlineError'` and the stack is replaced\n * with a custom formatted version that includes:\n * - Error name and message with color coding\n * - Highlighted code snippet showing the error location\n * - Enhanced stack trace with file path and position\n *\n * @example\n * ```ts\n * const error = new Error('Syntax error in file');\n * const inlineError = new InlineError(error);\n * // inlineError.stack contains formatted output with code context\n * // inlineError.metadata contains structured location data\n * ```\n *\n * @example\n * ```ts\n * // Adjust error line by -3 to account for wrapper code\n * const error = new Error('Type mismatch');\n * const inlineError = new InlineError(error, -3);\n * // Error will be displayed 3 lines higher than originally reported\n * ```\n *\n * @see {@link getErrorMetadata} for metadata extraction and formatting\n * @see {@link formatStack} for stack trace formatting\n *\n * @since 2.0.0\n */\n\n constructor(error: Error, lineOffset: number = 0) {\n super(error.message, 'InlineError');\n\n this.errorMetadata = getErrorMetadata(error, {}, lineOffset);\n this.stack = formatStack(this.errorMetadata, this.name, this.message);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Context, ScriptOptions } from 'vm';\n\n/**\n * Imports\n */\n\nimport { Script, createContext } from 'vm';\n\n/**\n * Executes arbitrary code inside a Node.js VM sandbox.\n *\n * @param code - The JavaScript source code to execute\n * @param sandbox - Optional {@link Context} object to inject into the VM environment\n * @param options - Optional {@link ScriptOptions} used when compiling the script\n *\n * @returns A promise resolving to the result of the executed code\n *\n * @throws Error - If the provided code fails to compile or runtime execution throws\n *\n * @remarks\n * This function uses Node.js's {@link Script} and {@link createContext} APIs to safely run code in\n * an isolated environment. Execution is configured with `breakOnSigint` enabled and `displayErrors` disabled.\n *\n * @example\n * ```ts\n * const result = await sandboxExecute(\"2 + 2\");\n * console.log(result); // 4\n * ```\n *\n * @example\n * ```ts\n * const result = await sandboxExecute(\"user.name\", { user: { name: \"Alice\" } });\n * console.log(result); // \"Alice\"\n * ```\n *\n * @see Context\n * @see ScriptOptions\n *\n * @since 1.0.0\n */\n\nexport async function sandboxExecute(code: string, sandbox: Context = {}, options: ScriptOptions = {}): Promise<unknown> {\n const script = new Script(code, options);\n const context = createContext(sandbox);\n\n return await script.runInContext(context, { breakOnSigint: true, displayErrors: false });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { VariantService } from '@services/variant.service';\nimport type { PartialMessage, Location, OnLoadResult } from 'esbuild';\nimport type { BuildContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { MacrosMetadataInterface } from '@directives/interfaces/analyze-directive.interface';\n\n/**\n * Imports\n */\n\nimport { inject } from '@symlinks/symlinks.module';\nimport { FilesModel } from '@typescript/models/files.model';\n\n/**\n * Constants\n */\n\nconst MACRO_PREFIX = '$$';\nconst IFDEF_REGEX = /(?:(?:export\\s+)?(?:const|let|var)\\s+([\\w$]+)\\s*=\\s*)?\\$\\$(ifdef|ifndef|inline)\\s*\\(\\s*(?:['\"]([^'\"]+)['\"])?/g;\n\n/**\n * Calculates the line and column position of a macro name within source text.\n *\n * @param text - The complete source file content\n * @param name - The macro name to locate\n * @param file - The file path for location reporting\n * @param index - The starting index in the text where the match was found\n * @returns A partial {@link Location} object containing file, line, and column information\n *\n * @since 2.0.0\n */\n\nexport function getLineAndColumn(text: string, name: string, file: string, index: number): Partial<Location> {\n let line = 1;\n for (let i = 0; i < index; i++) if (text[i] === '\\n') line++;\n const startLinePosition = text.lastIndexOf('\\n', index - 1) + 1;\n\n return {\n file,\n line,\n column: text.indexOf(name, startLinePosition) - startLinePosition\n };\n}\n\n/**\n * Determines whether a given position in source code is within a comment.\n *\n * @param content - The complete source file content\n * @param index - The position to check\n * @returns `true` if the position is within a single-line (`//`), multi-line (`\\/* *\\/`), or JSDoc comment, otherwise `false`\n *\n * @remarks\n * Scans backward from the given index to the start of the line, skipping whitespace.\n * Checks if the first non-whitespace characters form a comment start sequence.\n * This is used to avoid processing macros that appear in comments.\n *\n * @example Single-line comment detection\n * ```ts\n * const code = '// const $$debug = $$ifdef(\"DEBUG\");\\nconst $$prod = $$ifdef(\"PROD\");';\n *\n * const debugIndex = code.indexOf('$$debug');\n * console.log(isCommentLine(code, debugIndex)); // true\n *\n * const prodIndex = code.indexOf('$$prod');\n * console.log(isCommentLine(code, prodIndex)); // false\n * ```\n *\n * @example Multi-line comment detection\n * ```ts\n * const code = `/*\n * * const $$feature = $$ifdef(\"FEATURE\");\n * *\\/\n * const $$active = $$ifdef(\"ACTIVE\");`;\n *\n * const featureIndex = code.indexOf('$$feature');\n * console.log(isCommentLine(code, featureIndex)); // true\n *\n * const activeIndex = code.indexOf('$$active');\n * console.log(isCommentLine(code, activeIndex)); // false\n * ```\n *\n * @example Indented code\n * ```ts\n * const code = ' // Commented macro\\n const $$real = $$ifdef(\"REAL\");';\n * const index = code.indexOf('// Commented');\n * console.log(isCommentLine(code, index)); // true\n * ```\n *\n * @since 2.0.0\n */\n\nexport function isCommentLine(content: string, index: number): boolean {\n let lineStart = content.lastIndexOf('\\n', index - 1) + 1;\n\n while (lineStart < index && (content[lineStart] === ' ' || content[lineStart] === '\\t')) {\n lineStart++;\n }\n\n if (lineStart >= index) return false;\n\n const char1 = content[lineStart];\n const char2 = content[lineStart + 1];\n\n return (char1 === '/' && (char2 === '/' || char2 === '*')) || char1 === '*';\n}\n\n/**\n * Analyzes all project files for macro usage and generates metadata about disabled macros.\n *\n * @param variant - The current build variant containing define configurations\n * @param context - The build context to store metadata and configuration\n * @returns A promise resolving to an {@link AnalyzerMessageInterface} containing any warnings\n *\n * @remarks\n * Scans all entry point dependencies for `$$ifdef` and `$$ifndef` macro declarations.\n * Determines which macros should be disabled based on the variant's definition configuration.\n * Generates warnings for macros that don't follow the `$$` naming convention.\n * Stores results in `context.stage.defineMetadata` for use during the build process.\n *\n * @example Basic macro analysis with definitions\n * ```ts\n * const variant = {\n * config: {\n * define: {\n * DEBUG: true,\n * PRODUCTION: false\n * }\n * }\n * };\n *\n * const context = {\n * build: {\n * initialOptions: {\n * entryPoints: ['src/index.ts']\n * }\n * },\n * stage: {}\n * };\n *\n * const result = await analyzeMacroMetadata(variant, context);\n *\n * // context.stage.defineMetadata now contains:\n * // {\n * // disabledMacroNames: Set(['$$noProd']), // from $$ifndef('PRODUCTION')\n * // filesWithMacros: Set(['src/index.ts', 'src/config.ts'])\n * // }\n *\n * console.log(result.warnings); // Array of warnings for improperly named macros\n * ```\n *\n * @example Handling ifdef vs. ifndef\n * ```ts\n * // the Source file contains:\n * // const $$hasDebug = $$ifdef('DEBUG'); // enabled when DEBUG=true\n * // const $$noDebug = $$ifndef('DEBUG'); // enabled when DEBUG=false\n *\n * const variant = {\n * config: {\n * define: { DEBUG: true }\n * }\n * };\n *\n * await analyzeMacroMetadata(variant, context);\n * // disabledMacroNames will contain: Set(['$$noDebug'])\n * ```\n *\n * @example Warning generation for invalid macro names\n * ```ts\n * // Source contains: const myMacro = $$ifdef('FEATURE');\n * // (missing $$ prefix)\n *\n * const result = await analyzeMacroMetadata(variant, context);\n *\n * console.log(result.warnings);\n * // [{\n * // text: \"Macro function 'myMacro' not start with '$$' prefix to avoid conflicts\",\n * // location: { file: 'src/feature.ts', line: 10, column: 6 }\n * // }]\n * ```\n *\n * @see {@link MacrosMetadataInterface}\n *\n * @since 2.0.0\n */\n\nexport async function analyzeMacroMetadata(variant: VariantService, context: BuildContextInterface): Promise<OnLoadResult> {\n const metadata: MacrosMetadataInterface = {\n disabledMacroNames: new Set(),\n filesWithMacros: new Set()\n };\n\n context.stage.defineMetadata = metadata;\n\n const warnings: Array<PartialMessage> = [];\n const filesModel = inject(FilesModel);\n const defines = variant.config.define ?? {};\n const files = Object.values(variant.dependencies ?? {});\n\n for (const file of files) {\n const content = filesModel.getOrTouchFile(file)?.contentSnapshot?.text;\n if (!content) continue;\n\n const resolvedFile = filesModel.resolve(file);\n\n IFDEF_REGEX.lastIndex = 0;\n for (const match of content.matchAll(IFDEF_REGEX)) {\n const matchIndex = match.index!;\n if (isCommentLine(content, matchIndex)) continue;\n\n const [ , fn, directive, define ] = match;\n metadata.filesWithMacros.add(resolvedFile); // always register the file\n if (!fn) continue;\n\n if (!fn.startsWith(MACRO_PREFIX)) {\n warnings.push({\n text: `Macro function '${ fn }' not start with '${ MACRO_PREFIX }' prefix to avoid conflicts`,\n location: getLineAndColumn(content, fn, file, matchIndex)\n });\n }\n\n if(directive === 'inline') continue;\n const isDefined = !!defines[define];\n if ((directive === 'ifndef') === isDefined) {\n metadata.disabledMacroNames.add(fn);\n }\n }\n }\n\n return { warnings };\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OnLoadResult, Message, PartialMessage } from 'esbuild';\nimport type { BuildContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { OnEndType, OnStartType } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { ResultContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { BuildResultInterface } from '@providers/interfaces/esbuild-messages-provider.interface';\nimport type { BuildConfigInterface, PartialBuildConfigType } from '@interfaces/configuration.interface';\nimport type { DiagnosticInterface } from '@typescript/services/interfaces/typescript-service.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildError } from '@errors/xbuild.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { VariantService } from '@services/variant.service';\nimport { LifecycleProvider } from '@providers/lifecycle.provider';\nimport { transformerDirective } from '@directives/macros.directive';\nimport { analyzeMacroMetadata } from '@directives/analyze.directive';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { enhancedBuildResult, isBuildResultError } from '@providers/esbuild-messages.provider';\n\n/**\n * Orchestrates the build process across multiple variants with lifecycle management and configuration.\n *\n * @remarks\n * The `BuildService` is the primary service for managing multi-variant builds in xBuild.\n * It handles configuration changes, variant lifecycle, type checking, and build execution\n * with support for hot reloading and file watching.\n *\n * **Key responsibilities**:\n * - Manages multiple build variants (e.g., production, development, testing)\n * - Provides reactive configuration updates through subscription system\n * - Coordinates lifecycle hooks (onStart, onEnd) across all variants\n * - Handles macro transformation and directive processing\n * - Supports incremental builds and file touch notifications\n * - Aggregates build results and type checking diagnostics\n *\n * **Architecture**:\n * Each variant is managed by a {@link VariantService} instance with its own:\n * - esbuild configuration and context\n * - TypeScript language service\n * - Lifecycle provider for hooks and plugins\n * - Build state and watch mode support\n *\n * The service uses a subscription pattern to react to configuration changes,\n * automatically creating new variants or disposing removed ones.\n *\n * @example Basic usage\n * ```ts\n * const buildService = new BuildService({\n * variants: {\n * production: {\n * esbuild: { minify: true, sourcemap: false }\n * },\n * development: {\n * esbuild: { minify: false, sourcemap: true }\n * }\n * }\n * });\n *\n * // Build all variants\n * const results = await buildService.build();\n * console.log(results.production.errors);\n * ```\n *\n * @example With lifecycle hooks\n * ```ts\n * const buildService = new BuildService(config);\n *\n * buildService.onStart = (context) => {\n * console.log(`Building variant: ${context.variantName}`);\n * };\n *\n * buildService.onEnd = (context) => {\n * console.log(`Completed ${context.variantName}: ${context.result.errors.length} errors`);\n * };\n *\n * await buildService.build();\n * ```\n *\n * @example Configuration reload\n * ```ts\n * const buildService = new BuildService(initialConfig);\n *\n * // Reload with new configuration\n * buildService.reload({\n * variants: {\n * production: { esbuild: { target: 'es2020' } },\n * staging: { esbuild: { minify: true } }\n * }\n * });\n * // Old variants disposed, new ones created\n * ```\n *\n * @example Type checking\n * ```ts\n * const buildService = new BuildService(config);\n * const diagnostics = await buildService.typeChack();\n *\n * for (const [variant, errors] of Object.entries(diagnostics)) {\n * console.log(`${variant}: ${errors.length} type errors`);\n * }\n * ```\n *\n * @see {@link VariantService} for individual variant management\n * @see {@link ConfigurationService} for configuration handling\n * @see {@link LifecycleProvider} for hook management\n *\n * @since 2.0.0\n */\n\nexport class BuildService {\n /**\n * Callback invoked when a build completes for any variant.\n *\n * @remarks\n * Set via the `onEnd` setter. Called after each variant's build finishes,\n * providing access to build results, errors, warnings, and metadata.\n *\n * @since 2.0.0\n */\n\n private onEndCallback?: OnEndType;\n\n /**\n * Callback invoked when a build starts for any variant.\n *\n * @remarks\n * Set via the `onStart` setter. Called before each variant's build begins,\n * after macro metadata analysis completes.\n *\n * @since 2.0.0\n */\n\n private onStartCallback?: OnStartType;\n\n /**\n * Map of variant names to their service instances.\n *\n * @remarks\n * Contains all active build variants. Variants are created during construction\n * and updated when configuration changes via {@link reload} or {@link setConfiguration}.\n *\n * @since 2.0.0\n */\n\n private variants: { [variant: string]: VariantService } = {};\n\n /**\n * Configuration service managing build settings and variant definitions.\n *\n * @remarks\n * Injected singleton that provides reactive configuration updates through\n * its subscription system. Changes trigger automatic variant recreation.\n *\n * @since 2.0.0\n */\n\n private readonly configuration: ConfigurationService<BuildConfigInterface> = inject(ConfigurationService);\n\n /**\n * Creates a new BuildService instance with optional configuration and command-line arguments.\n *\n * @param argv - Command-line arguments passed to variant services (default: empty object)\n *\n * @remarks\n * The constructor:\n * 1. Accepts optional initial configuration\n * 2. Stores command-line arguments for variant initialization\n * 3. Subscribes to configuration changes via {@link parseVariants}\n * 4. Automatically creates variants defined in the configuration\n *\n * Configuration can be provided later via {@link reload} or {@link setConfiguration}\n * if not supplied during construction.\n *\n * @since 2.0.0\n */\n\n constructor(private argv: Record<string, unknown> = {}) {\n this.configuration.subscribe(this.parseVariants.bind(this));\n }\n\n /**\n * Gets the current complete build configuration.\n *\n * @returns The active build configuration including all variants and common settings\n *\n * @remarks\n * Retrieves the immutable snapshot of the current configuration from the\n * configuration service. Changes to the returned object do not affect\n * the actual configuration - use {@link setConfiguration} or {@link reload} instead.\n *\n * @since 2.0.0\n */\n\n get config(): BuildConfigInterface {\n return this.configuration.getValue();\n }\n\n /**\n * Sets the callback to invoke when any variant build completes.\n *\n * @param callback - Function receiving the result context with build output and metadata\n *\n * @remarks\n * The callback receives a {@link ResultContextInterface} containing:\n * - Variant name\n * - Build result (errors, warnings, outputs)\n * - Metadata files and outputs\n * - Timestamp and duration\n *\n * Called after the build finishes but before promises resolve.\n *\n * @example\n * ```ts\n * buildService.onEnd = (context) => {\n * const { variantName, result } = context;\n * console.log(`\u2713 ${variantName}: ${result.errors.length} errors`);\n * };\n * ```\n *\n * @since 2.0.0\n */\n\n set onEnd(callback: OnEndType) {\n this.onEndCallback = callback;\n }\n\n /**\n * Sets the callback to invoke when any variant build starts.\n *\n * @param callback - Function receiving the build context with file and variant information\n *\n * @remarks\n * The callback receives a {@link BuildContextInterface} containing:\n * - Variant name\n * - File path being processed\n * - Build stage and metadata\n * - Loader type\n *\n * Called after macro analysis but before transformation begins.\n *\n * @example\n * ```ts\n * buildService.onStart = (context) => {\n * console.log(`Building ${context.args.path} for ${context.variantName}`);\n * };\n * ```\n *\n * @since 2.0.0\n */\n\n set onStart(callback: OnStartType) {\n this.onStartCallback = callback;\n }\n\n /**\n * Reloads the build configuration and updates variants accordingly.\n *\n * @param config - Optional new configuration to replace the current one\n *\n * @remarks\n * The reload process:\n * 1. Replaces configuration if provided\n * 2. Compares new variant names with existing ones\n * 3. Disposes variants no longer in configuration\n * 4. Creates new variants from the updated configuration\n * 5. Existing variants with matching names continue unchanged\n *\n * This is useful for hot-reloading configuration files without restarting the build process.\n *\n * @example\n * ```ts\n * // Add a new staging variant\n * buildService.reload({\n * variants: {\n * ...buildService.config.variants,\n * staging: { esbuild: { minify: true } }\n * }\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n reload(config?: PartialBuildConfigType): void {\n if (config) this.configuration.reload(config);\n this.disposeVariants(this.compareKeys(this.config.variants, this.variants));\n this.parseVariants();\n }\n\n /**\n * Notifies all variants that specific files have been modified.\n *\n * @param files - Array of file paths that have changed\n *\n * @remarks\n * Propagates file change notifications to all variant services, triggering\n * incremental rebuilds in watch mode. Each variant's watch service handles\n * the actual rebuild logic.\n *\n * Typically used by file watchers or development servers to trigger hot reloads.\n *\n * @example\n * ```ts\n * // File watcher integration\n * watcher.on('change', (changedFiles) => {\n * buildService.touchFiles(changedFiles);\n * });\n * ```\n *\n * @see {@link VariantService.touchFiles}\n *\n * @since 2.0.0\n */\n\n touchFiles(files: Array<string>): void {\n for (const instance of Object.values(this.variants)) {\n instance.touchFiles(files);\n }\n }\n\n /**\n * Partially updates the build configuration without replacing it entirely.\n *\n * @param config - Partial configuration to merge with the current configuration\n *\n * @remarks\n * Performs a shallow merge of the provided configuration with the current one.\n * Use {@link reload} for deep configuration replacement or variant restructuring.\n *\n * Common use cases:\n * - Toggling minification\n * - Updating define constants\n * - Modifying common build options\n *\n * @example\n * ```ts\n * // Enable minification for all variants\n * buildService.setConfiguration({\n * common: { esbuild: { minify: true } }\n * });\n * ```\n *\n * @see {@link reload} for full configuration replacement\n *\n * @since 2.0.0\n */\n\n setConfiguration(config: Partial<BuildConfigInterface>): void {\n this.configuration.patch(config);\n }\n\n /**\n * Performs TypeScript type checking across all variants.\n *\n * @returns Promise resolving to a map of variant names to their diagnostic results\n *\n * @remarks\n * Runs the TypeScript compiler's diagnostic checker for each variant in parallel.\n * Returns all type errors, warnings, and suggestions without failing the build.\n *\n * **Note**: Method name has a typo - should be `typeCheck` but kept for backward compatibility.\n *\n * Useful for:\n * - Pre-build validation\n * - CI/CD type checking pipelines\n * - IDE integration and diagnostics display\n *\n * @example\n * ```ts\n * const diagnostics = await buildService.typeChack();\n *\n * for (const [variant, errors] of Object.entries(diagnostics)) {\n * if (errors.length > 0) {\n * console.error(`${variant} has ${errors.length} type errors`);\n * errors.forEach(err => console.error(err.messageText));\n * }\n * }\n * ```\n *\n * @see {@link DiagnosticInterface}\n * @see {@link VariantService.check}\n *\n * @since 2.0.0\n */\n\n async typeChack(): Promise<Record<string, DiagnosticInterface[]>> {\n const result: Record<string, Array<DiagnosticInterface>> = {};\n\n for(const variant of Object.values(this.variants)) {\n result[variant.name] = await variant.check();\n }\n\n return result;\n }\n\n /**\n * Executes the build process for all or specific variants.\n *\n * @param names - Optional array of variant names to build (builds all if omitted)\n *\n * @returns Promise resolving to a map of variant names to their enhanced build results\n *\n * @throws AggregateError - When any variant build fails, containing all error details\n *\n * @remarks\n * The build process:\n * 1. Filters variants if specific names are provided\n * 2. Builds all variants in parallel\n * 3. Collects results and errors from each variant\n * 4. Enhances build results with additional metadata\n * 5. Aggregates errors if any builds failed\n * 6. Throws AggregateError if errors occurred\n *\n * **Error handling**:\n * - Build failures don't stop other variants from building\n * - All errors are collected and thrown together after all builds are complete\n * - Supports both esbuild errors and generic JavaScript errors\n *\n * **Result enhancement**:\n * Build results are processed by {@link enhancedBuildResult} to provide\n * structured error and warning information.\n *\n * @example Build all variants\n * ```ts\n * try {\n * const results = await buildService.build();\n * console.log(`Built ${Object.keys(results).length} variants`);\n * } catch (error) {\n * if (error instanceof AggregateError) {\n * error.errors.forEach(err => console.error(err.message));\n * }\n * }\n * ```\n *\n * @example Build specific variants\n * ```ts\n * const results = await buildService.build(['production', 'staging']);\n * // Only production and staging variants are built\n * ```\n *\n * @example Handle individual variant errors\n * ```ts\n * try {\n * await buildService.build();\n * } catch (error) {\n * if (error instanceof AggregateError) {\n * console.error(`${error.errors.length} variants failed`);\n * }\n * }\n * ```\n *\n * @see {@link enhancedBuildResult}\n * @see {@link BuildResultInterface}\n * @see {@link VariantService.build}\n *\n * @since 2.0.0\n */\n\n async build(names?: Array<string>): Promise<Record<string, BuildResultInterface>> {\n const errorList: Array<Error> = [];\n const results: Record<string, BuildResultInterface> = {};\n const buildPromises = Object.entries(this.variants).map(async ([ variantName, variantInstance ]) => {\n if(names && !names.includes(variantName)) return;\n\n try {\n const result = await variantInstance.build();\n if(result) results[variantName] = enhancedBuildResult(result);\n } catch(error) {\n if (isBuildResultError(error) || error instanceof AggregateError) {\n const result = enhancedBuildResult({\n errors: error.errors as Array<Message>\n });\n\n errorList.push(...result.errors);\n } else if(error instanceof Error) {\n errorList.push(error);\n } else {\n errorList.push(new Error(String(error)));\n }\n }\n });\n\n await Promise.allSettled(buildPromises);\n if(errorList.length) throw new AggregateError(errorList, 'Build failed');\n\n return results;\n }\n\n /**\n * Triggers the onEnd callback when a variant build completes.\n *\n * @param context - The result context containing build output and metadata\n *\n * @remarks\n * Internal handler that safely invokes the user-provided onEnd callback if set.\n * Called by variant lifecycle providers after each build finishes.\n *\n * @since 2.0.0\n */\n\n private onEndTrigger(context: ResultContextInterface): void {\n if(this.onEndCallback) this.onEndCallback(context);\n }\n\n /**\n * Triggers the onStart callback and performs macro analysis before a variant build starts.\n *\n * @param context - The build context containing file and variant information\n *\n * @returns Promise resolving to the load result after macro metadata analysis\n *\n * @throws Error - Propagates errors from macro analysis that aren't AggregateErrors\n *\n * @remarks\n * Internal handler that:\n * 1. Analyzes macro metadata for the file being built\n * 2. Invokes the user-provided onStart callback if set\n * 3. Returns the analysis result to the build pipeline\n * 4. Converts AggregateErrors to esbuild-compatible error format\n *\n * The macro analysis prepares directive information ($$ifdef, $$inline, etc.)\n * that will be used during the transformation phase.\n *\n * @see {@link analyzeMacroMetadata}\n *\n * @since 2.0.0\n */\n\n private async onStartTrigger(context: BuildContextInterface): Promise<OnLoadResult> {\n try {\n const result = await analyzeMacroMetadata(this.variants[context.variantName], context);\n if(this.onStartCallback) this.onStartCallback(context);\n\n return result;\n } catch(error) {\n const errors: Array<PartialMessage> = [];\n if(error instanceof AggregateError) {\n for (const err of error.errors) {\n errors.push({\n detail: err,\n text: err.message\n });\n }\n\n return { errors };\n }\n\n throw error;\n }\n }\n\n /**\n * Disposes and removes variants by name.\n *\n * @param dispose - Array of variant names to dispose\n *\n * @remarks\n * Cleanly shuts down variant services and removes them from the internal map.\n * Called during configuration reload to remove variants no longer in config.\n *\n * Each variant's dispose method:\n * - Stops watch mode if active\n * - Cleans up esbuild contexts\n * - Releases TypeScript language service resources\n *\n * @since 2.0.0\n */\n\n private disposeVariants(dispose: Array<string>): void {\n if (dispose.length) {\n for (const variant of dispose) {\n this.variants[variant].dispose();\n delete this.variants[variant];\n }\n }\n }\n\n /**\n * Compares two objects and returns keys present in the second but not the first.\n *\n * @param obj1 - Reference object (usually new configuration)\n * @param obj2 - Comparison object (usually existing variants)\n *\n * @returns Array of keys present in obj2 but missing in obj1\n *\n * @remarks\n * Used to identify variants that should be disposed during configuration reload.\n * If a variant exists in the service but not in the new configuration, it's removed.\n *\n * @since 2.0.0\n */\n\n private compareKeys(obj1: object, obj2: object): Array<string> {\n const keys2 = Object.keys(obj2);\n const onlyInObj2 = keys2.filter(key => !(key in obj1));\n\n return [ ...onlyInObj2 ];\n }\n\n /**\n * Creates variant service instances from the current configuration.\n *\n * @throws xBuildError - When no variants are defined in the configuration\n *\n * @remarks\n * Invoked by the configuration subscription whenever configuration changes.\n * For each variant in the configuration:\n * 1. Skips if the variant already exists (prevents recreation)\n * 2. Creates a new LifecycleProvider with hooks\n * 3. Attaches onStart and onEnd listeners\n * 4. Creates VariantService with configuration\n * 5. Registers macro transformer directive\n *\n * The lifecycle hooks enable:\n * - Build start/end notifications\n * - Macro analysis and transformation\n * - Custom plugin integration\n *\n * @see {@link VariantService}\n * @see {@link LifecycleProvider}\n * @see {@link transformerDirective}\n *\n * @since 2.0.0\n */\n\n private parseVariants(): void {\n if(!this.config.variants)\n throw new xBuildError('Variants are not defined in the configuration');\n\n for (const name of Object.keys(this.config.variants)) {\n if (this.variants[name]) continue;\n const lifecycle = new LifecycleProvider(name, this.argv);\n lifecycle.onEnd(this.onEndTrigger.bind(this), 'build-service');\n lifecycle.onStart(this.onStartTrigger.bind(this), 'build-service');\n this.variants[name] = new VariantService(name, lifecycle, this.config.variants[name], this.argv);\n lifecycle.onLoad(transformerDirective.bind({}, this.variants[name]), 'build-service');\n }\n }\n}\n", "\n/**\n * Main entry point and public API for the xBuild build system.\n *\n * @remarks\n * This module serves as the primary interface for xBuild, providing:\n * - Type definitions for configuration and diagnostics\n * - Core services for building, watching, and serving\n * - Utility functions for configuration management\n * - Global macro function declarations for build-time transforms\n *\n * **Usage patterns**:\n * - **CLI usage**: Imported by {@link bash.ts} for command-line operations\n * - **Programmatic usage**: Imported by custom build scripts and tools\n * - **Configuration files**: Type exports used in `xbuild.config.ts`\n *\n * **Key exports**:\n * - `BuildService`: Main build orchestration service\n * - `WatchService`: File system monitoring for rebuilds\n * - `ServerModule`: Development HTTP server\n * - Configuration helper functions\n * - Global macro type declarations\n *\n * @example Programmatic build\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * production: {\n * esbuild: { minify: true, outdir: 'dist' }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n * await service.build('production');\n * ```\n *\n * @example Configuration file typing\n * ```ts\n * import type { xBuildConfig } from '@remotex-labs/xbuild';\n *\n * export default {\n * variants: {\n * dev: { esbuild: { minify: false } }\n * }\n * } satisfies xBuildConfig;\n * ```\n *\n * @packageDocumentation\n * @since 1.0.0\n */\n\n/**\n * Import will remove at compile time\n */\n\nimport type { PartialBuildConfigType } from '@interfaces/configuration.interface';\nimport type { xBuildConfigInterface } from '@providers/interfaces/config-file-provider.interface';\n\n/**\n * Imports\n */\n\nimport { inject } from '@symlinks/symlinks.module';\nimport { ConfigurationService } from '@services/configuration.service';\n\n/**\n * Export types\n */\n\nexport type * from '@providers/interfaces/lifecycle-provider.interface';\nexport type { ArgumentsInterface } from '@argv/interfaces/argv-module.interface';\nexport type { ServerConfigurationInterface } from '@server/interfaces/server.interface';\nexport type { MacroContextInterface } from '@directives/interfaces/macros-directive.interface';\nexport type { DiagnosticInterface } from '@typescript/services/interfaces/typescript-service.interface';\n\n/**\n * Export\n */\n\nexport * from '@components/glob.component';\nexport * from '@providers/esbuild-messages.provider';\nexport { ServerModule } from '@server/server.module';\nexport { WatchService } from '@services/watch.service';\n\n/**\n * Type alias for xBuild configuration objects.\n *\n * @remarks\n * Provides a shorter, more conventional name for the configuration interface.\n * Used primarily in configuration files to declare configuration object types\n * with TypeScript's `satisfies` operator or type annotations.\n *\n * **Properties include**:\n * - `variants`: Build variant configurations (dev, prod, etc.)\n * - `common`: Shared settings across all variants\n * - `serve`: Development server configuration\n * - `userArgv`: Custom CLI argument definitions\n * - `verbose`: Detailed logging flag\n *\n * @example Type annotation\n * ```ts\n * const config: xBuildConfig = {\n * variants: {\n * production: {\n * esbuild: { minify: true, outdir: 'dist' }\n * }\n * }\n * };\n * ```\n *\n * @example With satisfies operator (recommended)\n * ```ts\n * export default {\n * common: { esbuild: { platform: 'node' } },\n * variants: {\n * dev: { esbuild: { minify: false } },\n * prod: { esbuild: { minify: true } }\n * }\n * } satisfies xBuildConfig;\n * ```\n *\n * @see {@link xBuildConfigInterface} for detailed property documentation\n *\n * @since 2.0.0\n */\n\nexport type xBuildConfig = xBuildConfigInterface;\n\n/**\n * Global type declarations for xBuild's build-time macro system.\n *\n * @remarks\n * Declares globally available macro functions that are transformed at build time.\n * These functions provide conditional compilation and inline evaluation capabilities\n * without requiring explicit imports.\n *\n * **Macro functions**:\n * - `$$ifdef`: Include code when definition is truthy\n * - `$$ifndef`: Include code when definition is falsy/undefined\n * - `$$inline`: Evaluate expressions at build time\n *\n * All macro functions are:\n * - Prefixed with `$$` to avoid naming conflicts\n * - Transformed during the build process (not runtime functions)\n * - Available globally without imports\n * - Type-safe with TypeScript\n *\n * **DefineType**: String literal union representing common definition names,\n * extensible with custom strings via `| string`.\n *\n * @example Conditional compilation\n * ```ts\n * const logger = $$ifdef('DEBUG', () => console.log);\n * // In production (DEBUG=false), becomes: const logger = undefined;\n * // In development (DEBUG=true), becomes: function logger() { return console.log; }\n * ```\n *\n * @example Negated conditional\n * ```ts\n * const optimized = $$ifndef('DEBUG', () => fastImplementation());\n * // Included only when DEBUG is not defined or false\n * ```\n *\n * @example Inline evaluation\n * ```ts\n * const version = $$inline(() => process.env.VERSION);\n * // Evaluates at build time, replaces with actual value\n * ```\n *\n * @see {@link transformerDirective} for macro transformation implementation\n *\n * @since 2.0.0\n */\n\ndeclare global {\n /**\n * Type representing valid definition names for conditional macros.\n *\n * @remarks\n * Provides autocomplete for common definition names while allowing\n * custom strings. Definitions are typically set via:\n * - `config.variants[name].define` in configuration\n * - `--define` CLI flag\n * - Environment variables\n *\n * **Common definitions**:\n * - `DEBUG`: Development/debugging features\n * - `PRODUCTION`: Production-only optimizations\n * - `TEST`: Test environment features\n * - `DEV`: Development mode\n * - `CI`: Continuous integration environment\n * - `LOCAL`: Local development\n *\n * @example\n * ```ts\n * // With type checking\n * const fn = $$ifdef('DEBUG', log); // 'DEBUG' autocompletes\n * const custom = $$ifdef('MY_FEATURE', impl); // Custom string also allowed\n * ```\n *\n * @since 2.0.0\n */\n\n type DefineType = 'DEBUG' | 'PRODUCTION' | 'TEST' | 'DEV' | 'CI' | 'LOCAL' | string;\n\n /**\n * Conditional inclusion macro that includes code when a definition is truthy.\n *\n * @template T - The type of the callback return value\n * @param define - The definition name to check\n * @param callback - The code to include when definition is truthy\n *\n * @returns The callback value when condition is true, `undefined` when false\n *\n * @remarks\n * Transformed at build time based on the variant's `define` configuration.\n * When the specified definition is truthy, the callback is included in the\n * output; otherwise, the entire expression is replaced with `undefined`.\n *\n * **Transformation behavior**:\n * - Definition is truthy \u2192 Callback is included as-is\n * - Definition is falsy/undefined \u2192 Replaced with `undefined`\n * - Works with functions, objects, primitives, or any expression\n *\n * **Variable declarations**:\n * ```ts\n * const $$debug = $$ifdef('DEBUG', () => console.log);\n * // DEBUG=true \u2192 function $$debug() { return console.log; }\n * // DEBUG=false \u2192 undefined (entire declaration removed)\n * ```\n *\n * **Expression statements**:\n * ```ts\n * $$ifdef('DEBUG', () => initDebugTools());\n * // DEBUG=true \u2192 (() => initDebugTools())()\n * // DEBUG=false \u2192 (removed)\n * ```\n *\n * @example Function inclusion\n * ```ts\n * const logger = $$ifdef('DEBUG', () => console.log);\n *\n * // With DEBUG=true\n * logger('test'); // Works: logs 'test'\n *\n * // With DEBUG=false\n * logger('test'); // TypeError: logger is undefined\n * ```\n *\n * @example Object inclusion\n * ```ts\n * const config = {\n * apiUrl: 'https://api.example.com',\n * debug: $$ifdef('DEBUG', { verbose: true, logLevel: 'trace' })\n * };\n *\n * // With DEBUG=true\n * // config.debug = { verbose: true, logLevel: 'trace' }\n *\n * // With DEBUG=false\n * // config.debug = undefined\n * ```\n *\n * @example Guards in code\n * ```ts\n * if ($$ifdef('DEBUG', true)) {\n * console.log('Debug mode active');\n * }\n * // DEBUG=false \u2192 if (undefined) { ... } (block never executes)\n * ```\n *\n * @see {@link DefineType} for valid definition names\n * @since 2.0.0\n */\n\n function $$ifdef<T>(define: DefineType, callback: T):\n T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;\n\n /**\n * Conditional inclusion macro that includes code when a definition is falsy or undefined.\n *\n * @template T - The type of the callback return value\n * @param define - The definition name to check\n * @param callback - The code to include when definition is falsy/undefined\n *\n * @returns The callback value when condition is false, `undefined` when true\n *\n * @remarks\n * The inverse of `$$ifdef`. Transformed at build time based on the\n * variant's `define` configuration. When the specified definition is falsy\n * or undefined, the callback is included; otherwise, replaced with `undefined`.\n *\n * **Transformation behavior**:\n * - Definition is falsy/undefined \u2192 Callback is included as-is\n * - Definition is truthy \u2192 Replaced with `undefined`\n * - Works with functions, objects, primitives, or any expression\n *\n * **Use cases**:\n * - Development-only features (disabled in production)\n * - Fallback implementations (when optimized version unavailable)\n * - Debugging tools (removed in release builds)\n *\n * @example Development-only features\n * ```ts\n * const devTools = $$ifndef('PRODUCTION', () => initDevTools());\n *\n * // With PRODUCTION=false (dev mode)\n * devTools(); // Works: initializes dev tools\n *\n * // With PRODUCTION=true (production)\n * devTools(); // TypeError: devTools is undefined\n * ```\n *\n * @example Fallback implementation\n * ```ts\n * const optimizer = $$ifndef('NATIVE_OPTIMIZER', () => jsOptimizer());\n *\n * // With NATIVE_OPTIMIZER undefined\n * // Uses JavaScript fallback implementation\n *\n * // With NATIVE_OPTIMIZER=true\n * // optimizer is undefined, use native implementation elsewhere\n * ```\n *\n * @example Conditional exports\n * ```ts\n * export const debug = $$ifndef('PRODUCTION', {\n * log: console.log,\n * trace: console.trace\n * });\n *\n * // In development: exports debug object\n * // In production: export const debug = undefined;\n * ```\n *\n * @see {@link DefineType} for valid definition names\n * @since 2.0.0\n */\n\n function $$ifndef<T>(define: DefineType, callback: T):\n T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;\n\n /**\n * Inline evaluation macro that executes code at build time and replaces it with the result.\n *\n * @template T - The return type of the callback function\n * @param callback - Expression to evaluate at build time\n *\n * @returns The evaluated result with its original type, or `undefined` on evaluation failure\n *\n * @remarks\n * Executes the provided callback during the build process (not at runtime) and\n * replaces the macro call with the evaluated result. This enables:\n * - Injecting build-time environment variables\n * - Computing values during compilation\n * - Generating code from external sources\n * - Eliminating runtime overhead for static values\n *\n * **Execution context**:\n * - Runs in the Node.js build environment\n * - Has access to process.env and Node.js APIs\n * - Executes once per build, not per file or variant\n * - Errors during evaluation cause build failure\n *\n * **Return value handling**:\n * - The result preserves the original return type from the callback\n * - Primitives (string, number, boolean) are properly typed\n * - Objects and arrays maintain their structure and types\n * - Functions are toString()'d (use carefully)\n * - Returns `undefined` if evaluation fails or callback returns undefined\n *\n * **Common use cases**:\n * - Environment variable injection\n * - Build timestamp generation\n * - Package version embedding\n * - Configuration value computation\n *\n * @example Environment variable injection\n * ```ts\n * const apiUrl = $$inline(() => process.env.API_URL);\n * // Type: string | undefined\n * // Becomes: const apiUrl = \"https://api.example.com\";\n * ```\n *\n * @example Build metadata\n * ```ts\n * const buildInfo = {\n * version: $$inline(() => require('./package.json').version),\n * timestamp: $$inline(() => new Date().toISOString()),\n * commit: $$inline(() => process.env.GIT_COMMIT)\n * };\n * // Each value retains its type (string | undefined)\n * ```\n *\n * @example Computed configuration\n * ```ts\n * const maxWorkers = $$inline(() => {\n * const cpus = require('os').cpus().length;\n * return Math.max(1, cpus - 1);\n * });\n * // Type: number | undefined\n * // Computes optimal worker count during build\n * ```\n *\n * @example Feature flags from environment\n * ```ts\n * const features = {\n * betaFeatures: $$inline(() => process.env.ENABLE_BETA === 'true'),\n * debugMode: $$inline(() => process.env.NODE_ENV !== 'production')\n * };\n * // Boolean values computed at build time, typed as boolean | undefined\n * ```\n *\n * @see {@link astInlineCallExpression} for evaluation implementation\n *\n * @since 2.0.0\n */\n\n function $$inline<T>(callback: () => T): T | undefined;\n\n /**\n * Pre-configuration CLI arguments snapshot (bootstrap argv).\n *\n * @remarks\n * A globally accessible object used during early CLI bootstrap to store the result of\n * the *minimal* argument parse (typically just enough to locate the config file).\n *\n * This is useful when later stages need access to the initial argv values before the\n * full, enhanced parse (with user extensions) is performed.\n *\n * **Intended usage:**\n * - Set once at startup (e.g., right after parsing `--config`)\n * - Read later by services/modules that need bootstrap context\n *\n * **Shape:**\n * Uses `Record<string, unknown>` because the exact keys depend on the CLI parser and\n * configuration-defined options.\n *\n * @example\n * ```ts\n * // After minimal parsing\n * globalThis.$argv = { config: 'xbuild.config.ts', _: [], $0: 'xbuild' };\n *\n * // Later\n * const configPath = String($argv.config);\n * ```\n *\n * @since 2.0.0\n */\n\n var $argv: Record<string, unknown>;\n}\n\n/**\n * Core build orchestration service for managing multi-variant builds with lifecycle hooks.\n *\n * @remarks\n * The `BuildService` is the primary entry point for programmatic xBuild usage,\n * providing comprehensive build orchestration across multiple variants (e.g.,\n * production, development, staging) with reactive configuration management.\n *\n * **Key capabilities**:\n * - Multi-variant build execution with parallel processing\n * - Reactive configuration updates via subscription pattern\n * - TypeScript type checking across all variants\n * - Incremental builds with file touch notifications\n * - Lifecycle hooks (onStart, onEnd) for custom build logic\n * - Macro transformation and conditional compilation\n * - Hot-reloading configuration in watch mode\n *\n * **Variant management**:\n * Each variant is an isolated build configuration with its own:\n * - esbuild settings (minification, sourcemaps, platform, etc.)\n * - TypeScript compiler options and language service\n * - Output directory and entry points\n * - Define constants for conditional compilation\n * - Custom lifecycle hooks and plugins\n *\n * **Usage patterns**:\n * - **CLI mode**: Instantiated by {@link bash.ts} with command-line arguments\n * - **Programmatic mode**: Created in custom build scripts for automation\n * - **Watch mode**: Responds to file changes with incremental rebuilds\n * - **Testing**: Type-check only mode for CI/CD pipelines\n *\n * @example Programmatic build with single variant\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * // Configure build\n * overwriteConfig({\n * variants: {\n * production: {\n * esbuild: {\n * minify: true,\n * sourcemap: false,\n * outdir: 'dist',\n * platform: 'node'\n * }\n * }\n * }\n * });\n *\n * // Execute build\n * const service = new BuildService();\n * await service.build('production');\n * console.log('Build complete!');\n * ```\n *\n * @example Multi-variant build with lifecycle hooks\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * cjs: {\n * esbuild: { format: 'cjs', outdir: 'dist/cjs' }\n * },\n * esm: {\n * esbuild: { format: 'esm', outdir: 'dist/esm' }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n *\n * // Track build progress\n * service.onStart = (context) => {\n * console.log(`Building ${context.variantName}...`);\n * };\n *\n * service.onEnd = (context) => {\n * const { variantName, buildResult, duration } = context;\n * if (buildResult.errors.length === 0) {\n * console.log(`\u2713 ${variantName} completed in ${duration}ms`);\n * } else {\n * console.error(`\u2717 ${variantName} failed with ${buildResult.errors.length} errors`);\n * }\n * };\n *\n * // Build all variants in parallel\n * await service.build();\n * ```\n *\n * @example Type checking without building\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * main: {\n * esbuild: { entryPoints: ['src/**\\/*.ts'] },\n * types: { failOnError: true }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n * const diagnostics = await service.typeChack();\n *\n * for (const [variant, errors] of Object.entries(diagnostics)) {\n * if (errors.length > 0) {\n * console.error(`${variant}: ${errors.length} type errors`);\n * process.exit(1);\n * }\n * }\n * ```\n *\n * @example Configuration hot-reloading in watch mode\n * ```ts\n * import { BuildService } from '@remotex-labs/xbuild';\n * import { watch } from 'chokidar';\n *\n * const service = new BuildService();\n *\n * // Watch for configuration changes\n * watch('xbuild.config.ts').on('change', async () => {\n * const newConfig = await import('./xbuild.config.ts');\n * service.reload(newConfig.default);\n * console.log('Configuration reloaded, rebuilding...');\n * });\n *\n * // Watch for source file changes\n * watch('src/**\\/*.ts').on('change', (paths) => {\n * service.touchFiles([paths]);\n * });\n * ```\n *\n * @example Conditional compilation with defines\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * development: {\n * esbuild: { outdir: 'dev' },\n * define: {\n * DEBUG: true,\n * PRODUCTION: false\n * }\n * },\n * production: {\n * esbuild: { minify: true, outdir: 'dist' },\n * define: {\n * DEBUG: false,\n * PRODUCTION: true\n * }\n * }\n * }\n * });\n *\n * // Source code can use conditional macros:\n * // const logger = $$ifdef('DEBUG', () => console.log);\n * // logger?.('Debug message'); // Only included in development\n *\n * const service = new BuildService();\n * await service.build();\n * ```\n *\n * @example Custom arguments and metadata\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * userArgv: {\n * deploy: { type: 'boolean', description: 'Deploy after build' },\n * environment: { type: 'string', default: 'staging' }\n * },\n * variants: {\n * main: { esbuild: { outdir: 'dist' } }\n * }\n * });\n *\n * const service = new BuildService({\n * deploy: true,\n * environment: 'production'\n * });\n *\n * service.onEnd = async (context) => {\n * if (context.argv.deploy && context.buildResult.errors.length === 0) {\n * await deployToCDN(context.argv.environment);\n * }\n * };\n *\n * await service.build();\n * ```\n *\n * @see {@link OnEndType} for end hook signature\n * @see {@link OnStartType} for start hook signature\n * @see {@link WatchService} for file watching capabilities\n * @see {@link VariantService} for individual variant management\n * @see {@link patchConfig} for incremental configuration updates\n * @see {@link overwriteConfig} for full configuration replacement\n *\n * @since 2.0.0\n */\n\nexport { BuildService } from '@services/build.service';\n\n/**\n * Replaces the entire xBuild configuration with a new configuration.\n *\n * @param config - New configuration to apply\n *\n * @remarks\n * Completely overwrites the current configuration with the provided configuration.\n * This is a destructive operation that discards all existing settings, including:\n * - All variant configurations\n * - Common settings\n * - Server configuration\n * - User-defined CLI arguments\n *\n * **Use cases**:\n * - Programmatic build scripts that fully control configuration\n * - Testing scenarios requiring isolated configuration\n * - Dynamic configuration generation\n * - Configuration hot-reloading in watch mode\n *\n * **Timing considerations**:\n * - Must be called before creating `BuildService` instances\n * - In watch mode, triggers rebuild with new configuration\n * - Settings take effect immediately for subsequent builds\n *\n * **Difference from {@link patchConfig}**:\n * - `overwriteConfig`: Replaces entire configuration (destructive)\n * - `patchConfig`: Merges with existing configuration (additive)\n *\n * @example Programmatic configuration\n * ```ts\n * import { overwriteConfig, BuildService } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * production: {\n * esbuild: {\n * minify: true,\n * outdir: 'dist',\n * platform: 'node'\n * }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n * await service.build('production');\n * ```\n *\n * @example Dynamic configuration\n * ```ts\n * const isProd = process.env.NODE_ENV === 'production';\n *\n * overwriteConfig({\n * variants: {\n * main: {\n * esbuild: {\n * minify: isProd,\n * sourcemap: !isProd,\n * outdir: isProd ? 'dist' : 'dev'\n * }\n * }\n * }\n * });\n * ```\n *\n * @example Configuration reload in watch mode\n * ```ts\n * // In file change handler\n * if (changedFile === 'xbuild.config.ts') {\n * const newConfig = await loadConfig();\n * overwriteConfig(newConfig);\n * // Next build uses new configuration\n * }\n * ```\n *\n * @see {@link PartialBuildConfigType} for configuration structure\n * @see {@link patchConfig} for non-destructive configuration updates\n * @see {@link ConfigurationService.reload} for implementation details\n *\n * @since 2.0.0\n */\n\nexport function overwriteConfig(config: PartialBuildConfigType): void {\n inject(ConfigurationService).reload(config);\n}\n\n/**\n * Merges the provided configuration with the existing xBuild configuration.\n *\n * @param config - Partial configuration to merge\n *\n * @remarks\n * Performs a deep merge of the provided configuration with the current configuration,\n * preserving existing settings not specified in the patch. This is a non-destructive\n * operation that allows incremental configuration updates.\n *\n * **Merge behavior**:\n * - Object properties are deeply merged (not replaced)\n * - Array properties are replaced (not concatenated)\n * - Undefined values in patch are ignored (don't remove existing values)\n * - Null values in patch replace existing values\n *\n * **Use cases**:\n * - Adding new variants without affecting existing ones\n * - Updating specific settings while preserving others\n * - Applying conditional configuration overlays\n * - Plugin-based configuration extension\n *\n * **Timing considerations**:\n * - Can be called before or after creating `BuildService` instances\n * - Settings take effect immediately for subsequent builds\n * - Useful for progressive configuration in build scripts\n *\n * **Difference from {@link overwriteConfig}**:\n * - `patchConfig`: Merges with existing configuration (additive)\n * - `overwriteConfig`: Replaces entire configuration (destructive)\n *\n * @example Adding a new variant\n * ```ts\n * import { patchConfig } from '@remotex-labs/xbuild';\n *\n * // Existing config has 'dev' and 'prod' variants\n * patchConfig({\n * variants: {\n * staging: {\n * esbuild: {\n * minify: true,\n * outdir: 'staging'\n * }\n * }\n * }\n * });\n * // Now has 'dev', 'prod', and 'staging' variants\n * ```\n *\n * @example Updating specific settings\n * ```ts\n * // Update only output directory, preserve other settings\n * patchConfig({\n * variants: {\n * production: {\n * esbuild: {\n * outdir: 'build'\n * }\n * }\n * }\n * });\n * // Other production settings (minify, platform, etc.) unchanged\n * ```\n *\n * @example Conditional configuration\n * ```ts\n * if (process.env.ENABLE_SOURCE_MAPS === 'true') {\n * patchConfig({\n * common: {\n * esbuild: {\n * sourcemap: 'linked'\n * }\n * }\n * });\n * }\n * ```\n *\n * @example Plugin pattern\n * ```ts\n * function addTypeScriptPaths(paths: Record<string, string[]>) {\n * patchConfig({\n * common: {\n * esbuild: {\n * tsconfig: './tsconfig.json'\n * }\n * }\n * });\n * }\n *\n * addTypeScriptPaths({ '@/*': ['src/*'] });\n * ```\n *\n * @see {@link overwriteConfig} for full configuration replacement\n * @see {@link PartialBuildConfigType} for configuration structure\n * @see {@link ConfigurationService.patch} for implementation details\n *\n * @since 2.0.0\n */\n\nexport function patchConfig(config: PartialBuildConfigType): void {\n inject(ConfigurationService).patch(config);\n}\n", "/**\n * Maps terminal control codes to exit signal identifiers.\n *\n * @remarks\n * This constant object defines the ANSI escape sequences for common\n * terminal interrupt signals. These are used to detect when users\n * attempt to terminate the application via keyboard shortcuts.\n *\n * The signals are:\n * - `\\x03` (Ctrl+C) - SIGINT signal for interrupting the process\n * - `\\x04` (Ctrl+D) - SIGQUIT signal for quitting the process\n *\n * @example\n * ```ts\n * if (code === EXIT_SIGNALS.SIGINT) {\n * console.log('Caught Ctrl+C, exiting...');\n * process.exit(1);\n * }\n * ```\n *\n * @see WatchModule\n * @since 2.0.0\n */\n\n\nexport const EXIT_SIGNALS = {\n SIGINT: '\\x03', // Ctrl+C\n SIGQUIT: '\\x04' // Ctrl+D\n} as const;\n\n/**\n * Maps keyboard shortcuts to their corresponding action identifiers.\n *\n * @remarks\n * This constant object defines the single-character keys used for interactive terminal commands.\n * Each key triggers a specific development action such as restarting the server or clearing the console.\n *\n * The mappings are:\n * - `h` - Display help/shortcuts\n * - `q` - Quit the application\n * - `c` - Clear console\n * - `r` - Restart the server\n * - `u` - Show server URL\n * - `o` - Open in browser\n *\n * @example\n * ```ts\n * if (key.name === KEY_MAPPINGS.RELOAD) {\n * console.log('Restarting server...');\n * }\n * ```\n *\n * @see WatchModule\n * @since 2.0.0\n */\n\nexport const KEY_MAPPINGS = {\n HELP: 'h',\n QUIT: 'q',\n CLEAR: 'c',\n RELOAD: 'r',\n VERBOSE: 'v',\n SHOW_URL: 'u',\n OPEN_BROWSER: 'o'\n} as const;\n\n/**\n * Maps operating system platform identifiers to their browser-opening commands.\n *\n * @remarks\n * This constant object provides the appropriate shell command for opening\n * URLs in the default browser on different operating systems. It is used\n * by {@link openInBrowser} to ensure cross-platform compatibility.\n *\n * The platform commands are:\n * - `win32` - Windows: `start`\n * - `darwin` - macOS: `open`\n * - `linux` - Linux: `xdg-open`\n *\n * For unsupported platforms, `xdg-open` is used as a fallback.\n *\n * @example\n * ```ts\n * const platform = process.platform as keyof typeof COMMAND_MAP;\n * const command = COMMAND_MAP[platform] ?? 'xdg-open';\n * exec(`${command} http://localhost:3000`);\n * ```\n *\n * @see WatchModule\n * @since 2.0.0\n */\n\nexport const COMMAND_MAP = {\n win32: 'start',\n darwin: 'open',\n linux: 'xdg-open'\n} as const;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions } from 'esbuild';\nimport type { xBuildConfigInterface } from '@providers/interfaces/config-file-provider.interface';\n\n/**\n * Imports\n */\n\nimport { existsSync } from 'fs';\nimport { runInThisContext } from 'vm';\nimport { createRequire } from 'module';\nimport { inject } from '@symlinks/symlinks.module';\nimport { resolve } from '@components/path.component';\nimport { buildFiles } from '@services/transpiler.service';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { FrameworkService } from '@services/framework.service';\n\n/**\n * Transpilation options for configuration file compilation.\n *\n * @remarks\n * These esbuild options are used exclusively for transpiling TypeScript configuration\n * files (e.g., `config.xbuild.ts`) into executable JavaScript. The configuration\n * prioritizes correctness and simplicity over output size or performance.\n *\n * **Key settings:**\n * - **No bundling**: Dependencies are external to avoid conflicts\n * - **CommonJS output**: Enables `require()` and `module.exports` execution\n * - **Node.js platform**: Uses Node.js module resolution\n * - **Minimal minification**: Only syntax and whitespace for readability\n * - **Symbol preservation**: Maintains symlinks for monorepo support\n *\n * These options ensure configuration files can safely import types and utilities\n * without bundling their dependencies into the transpiled output.\n *\n * @since 2.0.0\n */\n\nconst transpileOptions: BuildOptions = {\n minify: false,\n format: 'cjs',\n platform: 'node',\n logLevel: 'silent',\n packages: 'external',\n minifySyntax: true,\n preserveSymlinks: true,\n minifyWhitespace: true,\n minifyIdentifiers: false\n};\n\n/**\n * Loads and executes a TypeScript configuration file, returning its exported configuration.\n *\n * @param path - Absolute or relative path to the configuration file\n * @returns Parsed configuration object, or empty object if file doesn't exist\n *\n * @template T - Configuration interface type (extends {@link xBuildConfigInterface})\n *\n * @remarks\n * This provider enables xBuild to load TypeScript configuration files with full type\n * safety and IDE support. It performs the following steps:\n *\n * 1. **Validation**: Checks if the file exists (returns an empty object if not)\n * 2. **Transpilation**: Compiles TypeScript to JavaScript using esbuild\n * 3. **Source map registration**: Registers the source map for error reporting\n * 4. **Environment setup**: Creates Node.js module context with `require()` support\n * 5. **Execution**: Runs the compiled code in an isolated VM context\n * 6. **Export extraction**: Retrieves the configuration from `module.exports`\n *\n * **Export resolution:**\n * - Prefers named export: `export const config = { ... }`\n * - Falls back to default export: `export default { ... }`\n * - Returns empty object if no valid export found\n *\n * **Module context:**\n * The function creates a temporary module context to execute the configuration file,\n * providing access to Node.js built-ins and the ability to import dependencies. This\n * allows configuration files to use dynamic imports, helper functions, and shared utilities.\n *\n * **Source map support:**\n * Source maps are registered with the framework service to ensure TypeScript error\n * locations are correctly mapped when errors occur in configuration files.\n *\n * @example\n * ```ts\n * // Load default configuration\n * const config = await configFileProvider<BuildConfigInterface>(\n * 'config.xbuild.ts'\n * );\n * ```\n *\n * @example\n * ```ts\n * // Load custom configuration with type safety\n * interface CustomConfig extends xBuildConfigInterface {\n * customField: string;\n * }\n *\n * const config = await configFileProvider<CustomConfig>(\n * 'custom.config.ts'\n * );\n *\n * console.log(config.customField); // Type-safe access\n * ```\n *\n * @example\n * ```ts\n * // Configuration file structure\n * // config.xbuild.ts\n * import { BuildConfigInterface } from '@xbuild/types';\n *\n * export const config: BuildConfigInterface = {\n * variants: {\n * esm: {\n * esbuild: {\n * entryPoints: ['src/index.ts'],\n * format: 'esm'\n * }\n * }\n * }\n * };\n * ```\n *\n * @example\n * ```ts\n * // Configuration with default export\n * // config.xbuild.ts\n * export default {\n * common: {\n * types: true\n * },\n * variants: { ... }\n * };\n * ```\n *\n * @see {@link buildFiles}\n * @see {@link xBuildConfigInterface}\n * @see {@link FrameworkService.setSource}\n *\n * @since 2.0.0\n */\n\nexport async function configFileProvider<T extends xBuildConfigInterface>(path: string): Promise<T> {\n if (!path || !existsSync(path)) return <T>{};\n inject(FilesModel).touchFile(path);\n\n const [ map, code ] = (await buildFiles([ path ], { ...transpileOptions, outdir: 'tmp' })).outputFiles!;\n inject(FrameworkService).setSource(map.text, path);\n\n globalThis.module = { exports: {} };\n globalThis.require = createRequire(resolve(path));\n\n await runInThisContext(code.text, { filename: path });\n const config = module.exports.config ?? module.exports.default;\n if (!config) return <T> {};\n\n return <T> config;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\n\n/**\n * Represents an error that occurs during VM runtime execution.\n *\n * Extends {@link xBuildBaseError} and adds support for wrapping native errors,\n * handling `AggregateError` instances, and preserving nested errors.\n *\n * @remarks\n * This class is designed to encapsulate runtime errors in a virtual machine context.\n * If the original error is already a `xJetBaseError`, it is returned as-is.\n * AggregateErrors are flattened into an array of `VMRuntimeError` instances.\n *\n * The formatted stack trace is automatically generated for both single and nested errors.\n *\n * @example\n * ```ts\n * try {\n * // Some VM execution code that throws\n * } catch (err) {\n * const vmError = new VMRuntimeError(err, { withFrameworkFrames: true });\n * console.error(vmError.formattedStack);\n * }\n * ```\n *\n * @since 2.0.0\n */\n\nexport class VMRuntimeError extends xBuildBaseError {\n /**\n * If the original error is an AggregateError, contains nested VMRuntimeError instances.\n *\n * @since 2.0.0\n */\n\n errors?: Array<VMRuntimeError> = [];\n\n /**\n * Creates a new `VMRuntimeError` instance from a native or xJetBaseError.\n *\n * @param originalError - The original error object thrown during execution.\n * @param options - Optional stack trace formatting options.\n *\n * @remarks\n * - If `originalError` is already an instance of `xJetBaseError`, it is returned as-is.\n * - If `originalError` is an `AggregateError`, each nested error is converted into a `VMRuntimeError`.\n * - The message and stack of the original error are preserved.\n * - The formatted stack trace is generated via {@link xBuildBaseError.reformatStack}.\n *\n * @since 2.0.0\n */\n\n constructor(private originalError: Error, options?: StackTraceInterface) {\n if (originalError instanceof xBuildBaseError) {\n return <VMRuntimeError> originalError;\n }\n\n // Pass the message to the base class Error\n super(originalError.message, 'VMRuntimeError');\n\n // Handle AggregateError\n if (this.originalError instanceof AggregateError && Array.isArray(this.originalError.errors)) {\n // Process nested errors\n this.errors = this.originalError.errors.map(error =>\n new VMRuntimeError(error, options)\n );\n }\n\n this.stack = this.originalError.stack;\n this.message = this.originalError.message;\n this.reformatStack(this.originalError, options);\n }\n\n /**\n * Custom Node.js inspect method for displaying the error in the console.\n *\n * @returns A string representation of the formatted stack trace, or\n * a concatenated list of nested errors if present.\n *\n * @remarks\n * Overrides the Node.js default inspection behavior.\n * If this instance contains nested errors, they are listed with their formatted stacks.\n *\n * @since 2.0.0\n */\n\n [Symbol.for('nodejs.util.inspect.custom')](): string | undefined {\n if (this.errors && this.errors.length > 0) {\n const errorList = this.errors.map(\n (error) => `${ error.formattedStack ?? error.stack }`\n ).join('');\n\n return `VMRuntimeError Contains ${ this.errors.length } nested errors:\\n${ errorList }\\n`;\n }\n\n return this.formattedStack || this.stack;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Metafile } from 'esbuild';\nimport type { IssueType } from '@components/interfaces/printer-component.interface';\nimport type { MacrosStateInterface } from '@directives/interfaces/analyze-directive.interface';\nimport type { DiagnosticInterface } from '@typescript/services/interfaces/typescript-service.interface';\nimport type { BuildContextInterface, ResultContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\n\n/**\n * Imports\n */\n\nimport { TypesError } from '@errors/types.error';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { xBuildBaseError } from '@errors/base.error';\nimport { prefix } from '@components/banner.component';\nimport { relative } from '@components/path.component';\nimport { VMRuntimeError } from '@errors/vm-runtime.error';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { mutedColor, pathColor, textColor, warnColor } from '@components/color.component';\nimport { errorColor, infoColor, keywordColor, okColor } from '@components/color.component';\nimport { enhancedBuildResult, isBuildResultError } from '@providers/esbuild-messages.provider';\n\n/**\n * Constants\n */\n\nexport const INDENT = ' ';\nexport const KILOBYTE = 1024;\nexport const MEGABYTE = KILOBYTE * 1024;\nexport const DASH_SYMBOL = '\u2014';\nexport const ARROW_SYMBOL = '\u2192';\nexport const ERROR_SYMBOL = '\u00D7';\nexport const WARNING_SYMBOL = '\u2022';\n\n/**\n * Creates a formatted prefix for action log messages.\n *\n * @remarks\n * Generates a standardized prefix combining the build banner prefix,\n * a symbol (typically an arrow), and a colored action name. This ensures\n * consistent formatting across all build action logs.\n *\n * @param action - The action name to display (e.g., 'build', 'completed')\n * @param symbol - The symbol to display, defaults to a dimmed arrow\n *\n * @returns A formatted string with prefix, symbol, and colored action name\n *\n * @example\n * ```ts\n * const buildPrefix = createActionPrefix('build');\n * // Output: \"[xBuild] \u2192 build\"\n *\n * const errorPrefix = createActionPrefix('completed', errorColor(ERROR_SYMBOL));\n * // Output: \"[xBuild] \u00D7 completed\"\n * ```\n *\n * @see {@link prefix}\n * @see {@link infoColor}\n *\n * @since 2.0.0\n */\n\nexport function createActionPrefix(action: string, symbol: string = infoColor.dim(ARROW_SYMBOL)): string {\n return `${ prefix() } ${ symbol } ${ infoColor(action) }`;\n}\n\n/**\n * Formats a byte size into a human-readable string with appropriate units.\n *\n * @remarks\n * Converts raw byte counts into formatted strings using B, KB, or MB units\n * depending on the size. Values are rounded to 2 decimal places for KB and MB.\n * This function is used primarily for displaying file sizes in build output.\n *\n * @param bytes - The number of bytes to format\n *\n * @returns A formatted string with the size and the appropriate unit (B, KB, or MB)\n *\n * @example\n * ```ts\n * formatByteSize(512); // \"512 B\"\n * formatByteSize(2048); // \"2.00 KB\"\n * formatByteSize(1572864); // \"1.50 MB\"\n * ```\n *\n * @since 2.0.0\n */\n\nexport function formatByteSize(bytes: number): string {\n if (bytes < KILOBYTE) return `${ bytes } B`;\n if (bytes < MEGABYTE) return `${ (bytes / KILOBYTE).toFixed(2) } KB`;\n\n return `${ (bytes / MEGABYTE).toFixed(2) } MB`;\n}\n\n/**\n * Formats a TypeScript diagnostic's file location into a readable string.\n *\n * @remarks\n * Creates a standardized location string in the format `file:line:column`,\n * similar to standard compiler output. Line and column numbers are 1-based\n * (incremented from TypeScript's 0-based values). The file path is made\n * relative to the current working directory for brevity.\n *\n * @param diagnostic - The TypeScript diagnostic containing location information\n *\n * @returns A formatted location string with colored path and position\n *\n * @example\n * ```ts\n * const diagnostic: DiagnosticInterface = {\n * file: '/project/src/index.ts',\n * line: 10,\n * column: 5,\n * code: 2304,\n * message: 'Cannot find name'\n * };\n *\n * formatDiagnosticLocation(diagnostic);\n * // Output: \"src/index.ts:11:6\"\n * ```\n *\n * @see {@link pathColor}\n * @see {@link warnColor}\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\nexport function formatDiagnosticLocation(diagnostic: DiagnosticInterface): string {\n const filePath = diagnostic.file ? relative(process.cwd(), diagnostic.file) : '(unknown)';\n const lineNumber = warnColor(String((diagnostic.line ?? 0) + 1));\n const columnNumber = warnColor(String((diagnostic.column ?? 0) + 1));\n\n return `${ pathColor(filePath) }:${ lineNumber }:${ columnNumber }`;\n}\n\n/**\n * Appends formatted error metadata to a buffer array.\n *\n * @remarks\n * Internal helper that adds formatted code snippets and enhanced stack traces\n * to the provided buffer. Only processes errors that have metadata with formatted\n * code. Used by {@link appendIssue} to include additional error context.\n *\n * @param buffer - Array to append formatted lines to\n * @param error - The xBuild error containing metadata to format\n *\n * @since 2.0.0\n */\n\nexport function appendErrorMetadata(buffer: Array<string>, error: xBuildBaseError): void {\n if (!error.metadata?.formatCode) return;\n\n const codeLines = error.metadata.formatCode.split('\\n');\n const stackTrace = error.metadata.stacks.join('\\n ');\n\n buffer.push('');\n for (const line of codeLines) {\n buffer.push(`${ INDENT }${ line }`);\n }\n buffer.push('');\n buffer.push(`${ INDENT }Enhanced Stack Trace:`);\n buffer.push(` ${ stackTrace }`);\n}\n\n/**\n * Logs formatted error metadata to the console.\n *\n * @remarks\n * Outputs formatted code snippets and enhanced stack traces for xBuild errors\n * that contain metadata. Used by {@link logError} to provide detailed error\n * context in the console output.\n *\n * @param error - The xBuild error containing metadata to log\n *\n * @example\n * ```ts\n * const error = new xBuildBaseError('Build failed', {\n * formatCode: 'const x = undefined;\\nx.toString();',\n * stacks: ['at build.ts:45:12', 'at main.ts:10:5']\n * });\n *\n * logErrorMetadata(error);\n * // Outputs formatted code and stack trace to console\n * ```\n *\n * @see {@link logError}\n * @see {@link xBuildBaseError}\n *\n * @since 2.0.0\n */\n\nexport function logErrorMetadata(error: xBuildBaseError): void {\n if (!error.metadata?.formatCode) return;\n\n const formattedCode = error.metadata.formatCode\n .split('\\n')\n .map(line => `${ INDENT }${ line }`)\n .join('\\n');\n\n const stackTrace = error.metadata.stacks.join('\\n ');\n\n console.log(`\\n${ formattedCode }\\n\\n${ INDENT }Enhanced Stack Trace:\\n ${ stackTrace }`);\n}\n\n/**\n * Formats a TypeScript diagnostic into a single-line string.\n *\n * @remarks\n * Internal helper that creates a formatted diagnostic string with location,\n * error code, and message. Used by {@link appendTypesError} to prepare\n * diagnostics for buffer output.\n *\n * @param diagnostic - The TypeScript diagnostic to format\n * @param symbol - The symbol to prefix the diagnostic with\n * @param codeColor - Color function for the error code\n *\n * @returns A formatted diagnostic string\n *\n * @since 2.0.0\n */\n\nexport function formatTypescriptDiagnostic(diagnostic: DiagnosticInterface, symbol: string, codeColor: typeof errorColor): string {\n const location = formatDiagnosticLocation(diagnostic);\n const diagnosticCode = codeColor(`TS${ diagnostic.code }`);\n const message = mutedColor(diagnostic.message);\n\n return `${ INDENT }${ symbol } ${ location } ${ textColor(ARROW_SYMBOL) } ${ diagnosticCode } ${ textColor(DASH_SYMBOL) } ${ message }`;\n}\n\n/**\n * Logs a formatted TypeScript diagnostic to the console.\n *\n * @remarks\n * Outputs a single TypeScript diagnostic with location, error code, and message\n * in a standardized format. Used internally for immediate console output of\n * diagnostics during type checking.\n *\n * @param diagnostic - The TypeScript diagnostic to log\n * @param symbol - The symbol to prefix the diagnostic with\n * @param codeColor - Color function for the error code, defaults to error color\n *\n * @since 2.0.0\n */\n\nexport function logTypescriptDiagnostic(diagnostic: DiagnosticInterface, symbol: string, codeColor: typeof errorColor = errorColor): void {\n const location = formatDiagnosticLocation(diagnostic);\n const diagnosticCode = codeColor(`TS${ diagnostic.code }`);\n const message = mutedColor(diagnostic.message);\n\n console.log(\n `${ INDENT }${ symbol } ${ location }`,\n textColor(ARROW_SYMBOL),\n `${ diagnosticCode } ${ textColor(DASH_SYMBOL) } ${ message }`\n );\n}\n\n/**\n * Appends formatted TypeScript type errors to a buffer array.\n *\n * @remarks\n * Internal helper that processes {@link TypesError} instances and adds their\n * diagnostics to the buffer. If no diagnostics exist, adds a generic warning\n * message. Returns the count of diagnostics processed.\n *\n * @param buffer - Array to append formatted lines to\n * @param error - The TypesError containing diagnostics to format\n * @param symbol - The symbol to prefix each diagnostic with\n *\n * @returns The number of diagnostics added to the buffer\n *\n * @since 2.0.0\n */\n\nexport function appendTypesError(buffer: Array<string>, error: TypesError, symbol: string): number {\n const diagnosticCount = error.diagnostics.length;\n\n if (diagnosticCount === 0) {\n buffer.push(`${ INDENT }${ warnColor(symbol) } ${ warnColor('TypesError') }: ${ mutedColor(error.message || 'Type checking warning') }`);\n\n return 1;\n }\n\n buffer.push('');\n for (const diagnostic of error.diagnostics) {\n buffer.push(formatTypescriptDiagnostic(diagnostic, warnColor(symbol), xterm.deepOrange));\n }\n\n return diagnosticCount;\n}\n\n/**\n * Appends a formatted generic issue to a buffer array.\n *\n * @remarks\n * Internal helper that processes non-TypesError issues and adds them to the buffer.\n * If the issue is an xBuildBaseError with metadata, also appends the error metadata.\n *\n * @param buffer - Array to append formatted lines to\n * @param issue - The issue to format and append\n * @param symbol - The symbol to prefix the issue with\n * @param color - Color function for the symbol and formatting\n *\n * @since 2.0.0\n */\n\nexport function appendGenericIssue(buffer: Array<string>, issue: IssueType, symbol: string, color: typeof errorColor): void {\n const title = `${ color(issue.name) }: ${ issue.message.slice(issue.name.length + 1) }`;\n buffer.push(`\\n${ INDENT }${ color(symbol) } ${ title }`);\n\n if (issue instanceof xBuildBaseError) {\n appendErrorMetadata(buffer, issue);\n }\n}\n\n/**\n * Appends a formatted build issue to a buffer array.\n *\n * @remarks\n * Processes different types of build issues (TypesError, xBuildBaseError, or\n * generic Error) and appends them to the provided buffer with appropriate\n * formatting. Returns the count of individual issues added, which may be\n * greater than 1 for TypesError containing multiple diagnostics.\n *\n * This function is used by {@link logBuildIssues} to prepare formatted issues\n * for batch console output.\n *\n * @param buffer - Array to append formatted issue lines to\n * @param issue - The build issue to format and append\n * @param symbol - The symbol to prefix the issue with (typically error or warning symbol)\n * @param color - Color function to apply to the symbol and formatting\n *\n * @returns The number of individual issues added to the buffer\n *\n * @example\n * ```ts\n * const buffer: string[] = [];\n * const error = new TypesError([diagnostic1, diagnostic2]);\n *\n * const count = appendIssue(buffer, error, ERROR_SYMBOL, errorColor);\n * // count = 2 (two diagnostics)\n * // buffer contains formatted diagnostic lines\n * ```\n *\n * @see {@link IssueType}\n * @see {@link TypesError}\n * @see {@link logBuildIssues}\n * @see {@link xBuildBaseError}\n *\n * @since 2.0.0\n */\n\nexport function appendIssue(buffer: Array<string>, issue: IssueType, symbol: string, color: typeof errorColor): number {\n if (issue instanceof TypesError) {\n return appendTypesError(buffer, issue, symbol);\n }\n\n appendGenericIssue(buffer, issue, symbol, color);\n\n return 1;\n}\n\n/**\n * Logs all build issues (errors or warnings) to the console in a formatted batch.\n *\n * @remarks\n * Processes an array of build issues and outputs them as a single formatted\n * block with a header showing the issue count. Uses buffering to prepare all\n * output before logging, ensuring clean and consistent console output.\n *\n * If no issues exist, this function returns early without logging anything.\n * The function handles different issue types (TypesError with multiple diagnostics,\n * xBuildBaseError with metadata, and generic errors) and formats them appropriately.\n *\n * @param issues - Array of build issues to log\n * @param issueType - Type label for the issues ('Errors' or 'Warnings')\n *\n * @example\n * ```ts\n * const errors = [\n * new xBuildBaseError('Build failed'),\n * new TypesError([diagnostic1, diagnostic2])\n * ];\n *\n * logBuildIssues(errors, 'Errors');\n * // Output:\n * // Errors (3)\n * // \u00D7 Build failed\n * // \u00D7 src/index.ts:10:5 \u2192 TS2304 \u2014 Cannot find name 'x'\n * // \u00D7 src/index.ts:15:3 \u2192 TS2322 \u2014 Type mismatch\n * ```\n *\n * @see {@link IssueType}\n * @see {@link appendIssue}\n *\n * @since 2.0.0\n */\n\nexport function logBuildIssues(issues: Array<IssueType>, issueType: 'Errors' | 'Warnings'): void {\n if (issues.length === 0) return;\n\n const isError = issueType === 'Errors';\n const symbol = isError ? ERROR_SYMBOL : WARNING_SYMBOL;\n const color = isError ? errorColor : warnColor;\n\n let totalIssueCount = 0;\n const buffer: Array<string> = [ '' ];\n\n for (const issue of issues) {\n totalIssueCount += appendIssue(buffer, issue, symbol, color);\n }\n\n buffer[0] = `\\n ${ color(issueType) } (${ totalIssueCount })`;\n console.log(buffer.join('\\n'));\n}\n\n/**\n * Logs build output files with their sizes to the console.\n *\n * @remarks\n * Processes the esbuild metafile to extract output file information and\n * displays each output file with its size in a formatted list. The output\n * includes a header with the total count of output files.\n *\n * File sizes are automatically formatted using appropriate units (B, KB, MB)\n * for readability.\n *\n * @param metafile - The esbuild metafile containing output information\n *\n * @example\n * ```ts\n * const metafile: Metafile = {\n * outputs: {\n * 'dist/index.js': { bytes: 1024, inputs: {} },\n * 'dist/utils.js': { bytes: 512, inputs: {} }\n * }\n * };\n *\n * logBuildOutputs(metafile);\n * // Output:\n * // Outputs (2)\n * // \u2192 dist/index.js: 1.00 KB\n * // \u2192 dist/utils.js: 512 B\n * ```\n *\n * @see {@link Metafile}\n * @see {@link formatByteSize}\n *\n * @since 2.0.0\n */\n\nexport function logBuildOutputs(metafile: Metafile): void {\n const outputEntries = Object.entries(metafile.outputs);\n const outputCount = outputEntries.length;\n\n const buffer: Array<string> = [];\n buffer.push(`\\n ${ okColor('Outputs') } (${ outputCount })`);\n\n for (const [ outputPath, info ] of outputEntries) {\n const size = warnColor.dim(formatByteSize(info.bytes));\n buffer.push(`${ INDENT }${ infoColor(ARROW_SYMBOL) } ${ pathColor(outputPath) }: ${ size }`);\n }\n\n buffer.push('');\n console.log(buffer.join('\\n'));\n}\n\n/**\n * Logs an error or issue to the console with appropriate formatting.\n *\n * @remarks\n * Provides unified error logging with special handling for different error types:\n * - {@link AggregateError}: Recursively logs all contained errors\n * - {@link TypesError}: Logs TypeScript diagnostics with file locations\n * - {@link xBuildBaseError}: Logs error with enhanced metadata and stack traces\n * - Generic {@link Error}: Wraps in {@link VMRuntimeError} before logging\n * - Other types: Converts to string, wraps in VMRuntimeError, and logs\n *\n * This is the primary function for error output throughout the build system,\n * ensuring consistent error formatting and the appropriate detail level.\n *\n * @param issue - The error or issue to log\n *\n * @example\n * ```ts\n * try {\n * await build();\n * } catch (error) {\n * logError(error);\n * }\n * ```\n *\n * @example\n * ```ts\n * // Logs multiple TypeScript errors\n * const typesError = new TypesError([diagnostic1, diagnostic2]);\n * logError(typesError);\n * // Output:\n * // \u00D7 src/index.ts:10:5 \u2192 TS2304 \u2014 Cannot find name 'x'\n * // \u00D7 src/main.ts:20:3 \u2192 TS2322 \u2014 Type mismatch\n * ```\n *\n * @see {@link TypesError}\n * @see {@link VMRuntimeError}\n * @see {@link xBuildBaseError}\n * @see {@link logErrorMetadata}\n *\n * @since 2.0.0\n */\n\nexport function logError(issue: unknown): void {\n if (issue instanceof xBuildBaseError) {\n const title = `${ errorColor(issue.name) }: ${ issue.message.slice(issue.name.length + 1) }`;\n console.log(`\\n${ INDENT }${ errorColor(ERROR_SYMBOL) } ${ title }`);\n logErrorMetadata(issue);\n } else if (isBuildResultError(issue)) {\n for (const error of issue.errors) {\n logError(error);\n }\n } else if (issue instanceof TypesError) {\n for (const diagnostic of issue.diagnostics) {\n logTypescriptDiagnostic(diagnostic, errorColor(ERROR_SYMBOL));\n }\n } else if (issue instanceof Error) {\n logError(new VMRuntimeError(issue));\n } else {\n logError(new xBuildError(String(issue)));\n }\n}\n\n/**\n * Logs TypeScript diagnostics for a single variant to the console.\n *\n * @remarks\n * Internal helper that outputs diagnostics for a named variant with a\n * completion status. Shows an error symbol if diagnostics exist, or\n * an arrow symbol for successful completion.\n *\n * @param name - The variant name\n * @param diagnostics - Array of TypeScript diagnostics for this variant\n *\n * @since 2.0.0\n */\n\nexport function logTypeDiagnostic(name: string, diagnostics: Array<DiagnosticInterface>): void {\n const hasErrors = diagnostics.length > 0;\n const nameColor = hasErrors ? warnColor(name) : keywordColor(name);\n const statusSymbol = hasErrors ? errorColor(ERROR_SYMBOL) : infoColor.dim(ARROW_SYMBOL);\n const status = createActionPrefix('completed', statusSymbol);\n\n console.log(`${ status } ${ nameColor }`);\n\n if (hasErrors) {\n console.log('');\n for (const diagnostic of diagnostics) {\n logTypescriptDiagnostic(diagnostic, errorColor(ERROR_SYMBOL));\n }\n console.log('');\n }\n}\n\n/**\n * Logs TypeScript type diagnostics for all variants to the console.\n *\n * @remarks\n * Processes a record of variant names to diagnostic arrays and outputs\n * each variant's type checking results. Used to provide feedback after\n * TypeScript type checking operations across multiple build variants.\n *\n * Each variant is logged with its completion status and any diagnostics\n * found during type checking.\n *\n * @param diagnostics - Record mapping variant names to their diagnostic arrays\n *\n * @example\n * ```ts\n * const diagnostics = {\n * 'production': [diagnostic1, diagnostic2],\n * 'development': []\n * };\n *\n * logTypeDiagnostics(diagnostics);\n * // Output:\n * // [xBuild] \u2192 completed production\n * // \u00D7 src/index.ts:10:5 \u2192 TS2304 \u2014 Cannot find name 'x'\n * // \u00D7 src/main.ts:15:3 \u2192 TS2322 \u2014 Type mismatch\n * //\n * // [xBuild] \u2192 completed development\n * ```\n *\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\nexport function logTypeDiagnostics(diagnostics: Record<string, Array<DiagnosticInterface>>): void {\n for (const [ name, errors ] of Object.entries(diagnostics)) {\n logTypeDiagnostic(name, errors);\n }\n}\n\n/**\n * Logs the start of a build operation for a variant.\n *\n * @remarks\n * Outputs a formatted message indicating that a build has started for the\n * specified variant. Used by the build lifecycle to provide feedback at\n * the beginning of build operations.\n *\n * @param context - Build context containing the variant name\n *\n * @example\n * ```ts\n * const context: BuildContextInterface = {\n * variantName: 'production',\n * // ... other properties\n * };\n *\n * logBuildStart(context);\n * // Output: [xBuild] \u2192 build production\n * ```\n *\n * @see {@link createActionPrefix}\n * @see {@link BuildContextInterface}\n *\n * @since 2.0.0\n */\n\nexport function logBuildStart({ variantName }: BuildContextInterface): void {\n console.log(`${ createActionPrefix('build') } ${ keywordColor(variantName) }`);\n}\n\n/**\n * Logs macro replacement information for a specific build variant.\n *\n * @remarks\n * Displays all macro transformations that occurred during the build process\n * for the specified variant. This function only outputs when verbose mode is enabled\n * in the configuration.\n *\n * Each replacement shows:\n * - The replacement value (if not 'undefined')\n * - The original source code as a comment\n *\n * Output is indented and color-coded for better readability.\n *\n * @param variant - The build variant name to retrieve replacements for\n * @param stage - The macro state interface containing replacement information\n *\n * @example\n * ```ts\n * const stage: MacrosStateInterface = {\n * defineMetadata: { ... },\n * replacementInfo: {\n * 'production': [\n * { source: \"$$ifdef('DEBUG', () => log())\", replacement: \"undefined\" },\n * { source: \"$$inline(() => 1 + 1)\", replacement: \"2\" }\n * ]\n * }\n * };\n *\n * logMacroReplacements('production', stage);\n * // Output (when verbose):\n * // [xBuild] macro replacement\n * // \u2192 2 // $$inline(() => 1 + 1)\n * // \u2192 // $$ifdef('DEBUG', () => log())\n * ```\n *\n * @see {@link MacrosStateInterface}\n * @see {@link MacroReplacementInterface}\n *\n * @since 2.1.5\n */\n\nexport function logMacroReplacements(variant: string, stage: MacrosStateInterface): void {\n if (!inject(ConfigurationService).getValue().verbose) return;\n const replaceInfo = stage?.replacementInfo?.[variant];\n if (!replaceInfo || !Array.isArray(replaceInfo) || replaceInfo.length === 0) return;\n\n const prefix = INDENT + pathColor(ARROW_SYMBOL);\n const buffer: Array<string> = [ createActionPrefix(`macro ${ warnColor('replacement') }`) ];\n\n for (const { source, replacement } of replaceInfo) {\n const code = xterm.dim('// ' + source).replaceAll('\\n', `\\n${ INDENT }`);\n\n if (replacement && replacement !== 'undefined') {\n const resultCode = replacement.replaceAll('\\n', `\\n${ INDENT }`);\n buffer.push(`\\n${ prefix } ${ resultCode } ${ code }`);\n } else {\n buffer.push(`\\n${ prefix } ${ code }`);\n }\n }\n\n console.log(buffer.join('\\n'));\n}\n\n/**\n * Logs the completion of a build operation with results summary.\n *\n * @remarks\n * Outputs a comprehensive build summary including\n * - Completion status with build duration\n * - All errors encountered during the build\n * - All warnings encountered during the build\n * - Macro replacements (if verbose mode is enabled)\n * - Output files with their sizes (if build succeeded)\n *\n * The completion status shows an error symbol if the build failed (no metafile),\n * or an arrow symbol for successful builds. Build duration is displayed in\n * milliseconds.\n *\n * This is the primary function for providing build feedback to users and is\n * called by the build lifecycle at the end of each build operation.\n *\n * @param context - Result context containing variant name, duration, build result, and stage\n *\n * @example\n * ```ts\n * const context: ResultContextInterface = {\n * variantName: 'production',\n * duration: 1523,\n * buildResult: {\n * errors: [],\n * warnings: [warning1],\n * metafile: { outputs: { ... } }\n * },\n * stage: macroStage\n * };\n *\n * logBuildEnd(context);\n * // Output:\n * // [xBuild] \u2192 completed production in 1523 ms\n * //\n * // Warnings (1)\n * // \u2022 Unused variable warning\n * //\n * // [xBuild] macro replacement\n * // \u2192 2 // $$inline(() => 1 + 1)\n * //\n * // Outputs (2)\n * // \u2192 dist/index.js: 45.23 KB\n * // \u2192 dist/utils.js: 12.45 KB\n * ```\n *\n * @see {@link logBuildIssues}\n * @see {@link logBuildOutputs}\n * @see {@link logMacroReplacements}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\nexport function logBuildEnd({ variantName, duration, buildResult, stage }: ResultContextInterface): void {\n const { errors, warnings, metafile } = enhancedBuildResult(buildResult);\n const isSuccess = !!metafile;\n\n const nameColor = isSuccess ? keywordColor(variantName) : warnColor(variantName);\n const statusSymbol = isSuccess ? infoColor.dim(ARROW_SYMBOL) : errorColor(ERROR_SYMBOL);\n const status = createActionPrefix('completed', statusSymbol);\n\n console.log(`${ status } ${ nameColor } ${ xterm.dim(`in ${ duration } ms`) }`);\n\n logBuildIssues(errors, 'Errors');\n logBuildIssues(warnings, 'Warnings');\n\n if(errors.length || warnings.length) console.log(''); // add space line\n logMacroReplacements(variantName, <MacrosStateInterface> stage);\n\n if (isSuccess) {\n logBuildOutputs(metafile);\n } else {\n console.log(''); // add space line\n }\n}\n", "/**\n * Imports\n */\n\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\n\n/**\n * Style token for successful/OK messages (green).\n *\n * @since 2.0.0\n */\n\nexport const okColor = xterm.hex('#80a36b');\n\n/**\n * Base text color token (neutral light).\n *\n * @since 2.0.0\n */\n\nexport const textColor = xterm.hex('#dcdfe4');\n\n/**\n * Style token for informational messages (blue).\n *\n * @since 2.0.0\n */\n\nexport const infoColor = xterm.hex('#5798cd');\n\n/**\n * Style token for warnings (yellow).\n *\n * @since 2.0.0\n */\n\nexport const warnColor = xterm.hex('#e5c07b');\n\n/**\n * Style token for file paths, URLs, and locations (cyan).\n *\n * @since 2.0.0\n */\n\nexport const pathColor = xterm.hex('#56b6c2');\n\n/**\n * Style token for errors and failures (red).\n *\n * @since 2.0.0\n */\n\nexport const errorColor = xterm.hex('#e06c75');\n\n/**\n * Style token for highlighted keywords and identifiers (purple).\n *\n * @since 2.0.0\n */\n\nexport const keywordColor = xterm.hex('#c678dd');\n\n/**\n * Style token for de-emphasized / secondary text (muted gray).\n *\n * @since 2.0.0\n */\n\nexport const mutedColor = xterm.hex('#a5a7ab');\n"],
|
|
6
|
-
"mappings": ";u4DAcA,OAAS,UAAAA,OAAc,KACvB,OAAS,OAAAC,OAAW,UCXpB,OAAOC,OAAa,eCeb,IAAMC,GAAa,IAAI,IAYjBC,GAAc,IAAI,IAYxB,SAASC,GAAmBC,EAA0D,CACzF,OAAO,OAAOA,GAAa,UAAYA,IAAa,MAAQ,aAAcA,CAC9E,CAYO,SAASC,GAAqBD,EAA4D,CAC7F,OAAO,OAAOA,GAAa,UAAYA,IAAa,MAAQ,eAAgBA,CAChF,CAYO,SAASE,GAAmBF,EAA0D,CACzF,OAAO,OAAOA,GAAa,UAAYA,IAAa,MAAQ,aAAcA,CAC9E,CAwHO,SAASG,EAAwDC,EAAyC,CAC7G,OAAO,SAAUC,EAAiB,CAC9BP,GAAY,IAAIO,EAAoCD,GAAW,CAAC,CAAC,CACrE,CACJ,CA4BO,SAASE,GAAkBC,EAA2BC,EAAuB,CAAC,EAAmB,CACpG,GAAI,CAACD,EAAW,OAAOC,EAEvB,IAAMC,EAA2BD,EACjC,QAAWR,KAAYO,EAAU,MAAME,EAAS,MAAM,EAClD,GAAIV,GAAmBC,CAAQ,EAC3BS,EAAS,KAAKC,EAAOV,EAAS,SAAU,GAAGM,GAAkBN,EAAS,SAAS,CAAC,CAAC,UAC1EC,GAAqBD,CAAQ,EACpCS,EAAS,KAAKT,EAAS,WAAW,GAAGM,GAAkBN,EAAS,SAAS,CAAC,CAAC,UACpEE,GAAmBF,CAAQ,EAClCS,EAAS,KAAKT,EAAS,QAAQ,UACxB,OAAOA,GAAa,WAC3BS,EAAS,KAAKC,EAAOV,CAAQ,CAAC,MAE9B,OAAM,IAAI,MAAM,0BAA2B,OAAOA,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bin/env node\n\n/**\n * Import will remove at compile time\n */\n\nimport type { ServerConfigurationInterface } from './index';\nimport type { ArgumentsInterface } from '@argv/interfaces/argv-module.interface';\nimport type { xBuildConfigInterface } from '@providers/interfaces/config-file-provider.interface';\n\n/**\n * Imports\n */\n\nimport { rmSync } from 'fs';\nimport { cwd } from 'process';\nimport '@errors/uncaught.error';\nimport { ArgvModule } from '@argv/argv.module';\nimport { join } from '@components/path.component';\nimport { inject } from '@symlinks/symlinks.module';\nimport { init } from '@components/interactive.component';\nimport { collectFilesFromGlob } from '@components/glob.component';\nimport { configFileProvider } from '@providers/config-file.provider';\nimport { bannerComponent, prefix } from '@components/banner.component';\nimport { BuildService, overwriteConfig, ServerModule, WatchService } from './index';\nimport { logError, logTypeDiagnostics, logBuildEnd } from '@components/printer.component';\nimport { errorColor, keywordColor, mutedColor, pathColor } from '@components/color.component';\nimport { logBuildStart, createActionPrefix, ERROR_SYMBOL } from '@components/printer.component';\n\n/**\n * Default glob patterns for excluding common non-source directories from entry point collection.\n *\n * @remarks\n * Applied when `--entryPoints` CLI flag is provided to filter out:\n * - `node_modules`: Third-party dependencies\n * - `dist`: Build output directory\n * - `bundle`: Alternative build output\n * - `**\\/*.d.ts`: TypeScript declaration files\n *\n * These patterns are prepended with `!` to indicate exclusion in glob syntax.\n *\n * @example\n * ```ts\n * const patterns = [...args.entryPoints, ...DEFAULT_IGNORE_PATTERNS];\n * // Result: ['src/**\\/*.ts', '!node_modules/**', '!dist/**', ...]\n * ```\n *\n * @see {@link configureEntryPoints} for usage context\n *\n * @since 2.0.0\n */\n\nconst DEFAULT_IGNORE_PATTERNS = [\n '!node_modules/**',\n '!dist/**',\n '!bundle/**',\n '!**/*.d.ts'\n] as const;\n\n/**\n * Glob patterns for directories excluded from watch mode file monitoring.\n *\n * @remarks\n * Prevents unnecessary rebuilds when files change in:\n * - `dist`: Build output (avoids rebuild loops)\n * - `.git`: Version control metadata\n * - `.idea`: IDE configuration files\n * - `node_modules`: Third-party dependencies (rarely change during development)\n *\n * Does not use `!` prefix as these are used directly with the watch service's\n * ignore configuration, not glob pattern matching.\n *\n * @example\n * ```ts\n * const watchService = new WatchService(WATCH_IGNORE_PATTERNS);\n * // Ignores changes in dist/, .git/, .idea/, node_modules/\n * ```\n *\n * @see {@link WatchService} for file monitoring implementation\n * @see {@link collectWatchIgnorePatterns} for dynamic pattern collection\n *\n * @since 2.0.0\n */\n\nconst WATCH_IGNORE_PATTERNS = [\n 'dist',\n 'dist/**',\n '.git/**',\n '.idea/**',\n 'node_modules/**'\n] as const;\n\n/**\n * Configures entry points from CLI glob patterns and injects them as a special \"argv\" build variant.\n *\n * @param config - The xBuild configuration object to modify\n * @param args - Parsed command-line arguments containing entry point patterns\n *\n * @remarks\n * When the `--entryPoints` CLI flag is provided, this function:\n * 1. Combines user patterns with default exclusion patterns\n * 2. Excludes custom output directories from config (both CLI and config file)\n * 3. Resolves glob patterns to actual file paths\n * 4. Creates an \"argv\" variant containing the collected entry points\n *\n * The \"argv\" variant is a special build variant that merges with other configured\n * variants or serves as the sole variant if none are defined in the config file.\n *\n * **Output directory exclusion**:\n * - Checks `args.outdir` (CLI flag)\n * - Checks `config.common.esbuild.outdir` (config file)\n * - Adds both as exclusion patterns to prevent output files from being processed as source\n *\n * @example With entry points CLI flag\n * ```ts\n * const args = { entryPoints: ['src/**\\/*.ts'], outdir: 'build' };\n * configureEntryPoints(config, args);\n *\n * // config.variants.argv now contains:\n * // {\n * // esbuild: {\n * // entryPoints: ['src/index.ts', 'src/utils.ts', ...]\n * // }\n * // }\n * ```\n *\n * @example Without entry points (no-op)\n * ```ts\n * const args = {};\n * configureEntryPoints(config, args);\n * // config unchanged\n * ```\n *\n * @see {@link ArgumentsInterface.entryPoints}\n * @see {@link DEFAULT_IGNORE_PATTERNS} for default exclusions\n * @see {@link collectFilesFromGlob} for glob pattern resolution\n *\n * @since 2.0.0\n */\n\nfunction configureEntryPoints(config: xBuildConfigInterface, args: ArgumentsInterface): void {\n if (!args.entryPoints) return;\n\n const ignorePatterns = [\n ...args.entryPoints,\n ...DEFAULT_IGNORE_PATTERNS\n ];\n\n if (args.outdir) {\n ignorePatterns.push(`!${ args.outdir }/**`, `!${ args.outdir }`);\n }\n\n if (config.common?.esbuild?.outdir) {\n ignorePatterns.push(`!${ config.common.esbuild.outdir }/**`, `!${ config.common.esbuild.outdir }`);\n }\n\n config.variants = {\n argv: {\n esbuild: {\n entryPoints: collectFilesFromGlob(cwd(), ignorePatterns)\n }\n }\n };\n}\n\n/**\n * Applies command-line argument overrides to all build variant configurations.\n *\n * @param config - The xBuild configuration object to modify\n * @param args - Parsed command-line arguments containing override values\n *\n * @remarks\n * Iterates through all configured variants and applies CLI flag overrides for:\n * - `--verbose`: Enable detailed logging\n * - `--types`: Enable/disable TypeScript type generation\n * - `--outdir`: Override output directory\n * - `--bundle`: Enable bundling and minification\n * - `--minify`: Enable code minification\n * - `--tsconfig`: Specify custom TypeScript configuration file\n * - `--platform`: Target platform (node, browser, neutral)\n * - `--declaration`: Enable/disable `.d.ts` generation\n * - `--failOnError`: Fail build on type errors\n *\n * **Precedence**: CLI flags take precedence over config file settings, allowing\n * temporary overrides without modifying the configuration file.\n *\n * **Top-level vs. variant settings**:\n * - `verbose` is set at the top level (affects all variants)\n * - Other settings are applied to each variant's configuration individually\n *\n * **Conditional application**: Only defined CLI arguments are applied, allowing\n * partial overrides while preserving other config file settings.\n *\n * @example Override output directory\n * ```ts\n * const args = { outdir: 'build' };\n * applyCommandLineOverrides(config, args);\n *\n * // All variants now have:\n * // variant.esbuild.outdir = 'build'\n * ```\n *\n * @example Multiple overrides\n * ```ts\n * const args = {\n * minify: true,\n * platform: 'node',\n * declaration: false\n * };\n * applyCommandLineOverrides(config, args);\n *\n * // All variants updated with these settings\n * ```\n *\n * @see {@link ArgumentsInterface} for available CLI flags\n * @see {@link xBuildConfigInterface} for configuration structure\n *\n * @since 2.0.0\n */\n\nfunction applyCommandLineOverrides(config: xBuildConfigInterface, args: ArgumentsInterface): void {\n if (args.verbose !== undefined) {\n config.verbose = args.verbose;\n }\n\n const variants = Object.values(config.variants ?? {});\n\n for (const variant of variants) {\n if (args.types !== undefined) variant.types = args.types;\n if (args.outdir !== undefined) variant.esbuild.outdir = args.outdir;\n if (args.bundle !== undefined) variant.esbuild.minify = args.bundle;\n if (args.minify !== undefined) variant.esbuild.minify = args.minify;\n if (args.tsconfig !== undefined) variant.esbuild.tsconfig = args.tsconfig;\n if (args.platform !== undefined) variant.esbuild.platform = args.platform;\n if (args.declaration !== undefined) variant.declaration = args.declaration;\n\n if (args.failOnError !== undefined) {\n variant.types = { failOnError: args.failOnError };\n }\n }\n}\n\n/**\n * Collects all directories that should be ignored by the file watcher.\n *\n * @param config - The xBuild configuration containing output directory settings\n *\n * @returns Array of directory patterns to exclude from watch monitoring\n *\n * @remarks\n * Combines default ignore patterns with dynamic output directories to create\n * a comprehensive exclusion list for the watch service. This prevents:\n * - Rebuild loops (watching build output directories)\n * - Unnecessary rebuild triggers from IDE/VCS file changes\n * - Performance issues from monitoring large node_modules directories\n *\n * **Dynamic pattern collection**:\n * 1. Starts with {@link WATCH_IGNORE_PATTERNS} (static patterns)\n * 2. Adds `config.common.esbuild.outdir` if present\n * 3. Adds each variant's `esbuild.outdir` if present\n * 4. For each directory, adds both the directory itself and a recursive pattern\n *\n * **Pattern format**:\n * - `dist`: Ignore the directory\n * - `dist/**`: Ignore all files within the directory recursively\n *\n * @example With common and variant output directories\n * ```ts\n * const config = {\n * common: { esbuild: { outdir: 'dist' } },\n * variants: {\n * prod: { esbuild: { outdir: 'build' } },\n * dev: { esbuild: { outdir: 'tmp' } }\n * }\n * };\n *\n * const patterns = collectWatchIgnorePatterns(config);\n * // Returns: [\n * // 'dist', '.git/**', 'node_modules/**', ...,\n * // 'dist', 'dist/**',\n * // 'build', 'build/**',\n * // 'tmp', 'tmp/**'\n * // ]\n * ```\n *\n * @example With no custom output directories\n * ```ts\n * const config = { variants: {} };\n * const patterns = collectWatchIgnorePatterns(config);\n * // Returns: ['dist', 'dist/**', '.git/**', '.idea/**', 'node_modules/**']\n * ```\n *\n * @see {@link WATCH_IGNORE_PATTERNS} for default exclusions\n * @see {@link WatchService} for watch service implementation\n *\n * @since 2.0.0\n */\n\nfunction collectWatchIgnorePatterns(config: xBuildConfigInterface): Array<string> {\n const ignorePatterns: Array<string> = [ ...WATCH_IGNORE_PATTERNS ];\n\n if (config.common?.esbuild?.outdir) {\n ignorePatterns.push(config.common.esbuild.outdir, `${ config.common.esbuild.outdir }/**`);\n }\n\n const variants = Object.values(config.variants ?? {});\n for (const variant of variants) {\n if (variant.esbuild.outdir) {\n ignorePatterns.push(variant.esbuild.outdir, `${ variant.esbuild.outdir }/**`);\n }\n }\n\n return ignorePatterns;\n}\n\n/**\n * Starts the development HTTP server if requested via CLI or configuration.\n *\n * @param config - The xBuild configuration containing server settings\n * @param args - Parsed command-line arguments containing serve flag\n *\n * @returns Promise resolving to the server URL string if started, otherwise undefined\n *\n * @remarks\n * The server is started when either:\n * - `--serve [dir]` CLI flag is provided (optionally with directory)\n * - `config.serve.start` is set to `true` in configuration file\n *\n * **Server directory resolution**:\n * 1. `config.serve.dir` (config file setting, highest priority)\n * 2. `args.serve` (CLI flag value, if string)\n * 3. `'dist'` (default fallback)\n *\n * **Configuration merging**:\n * - Merges config file server settings with CLI overrides\n * - Wraps the `onStart` callback to capture server URL and log startup message\n * - Preserves user-defined `onStart` callback if present\n *\n * **Startup logging**:\n * Displays formatted startup message:\n * ```\n * [serve] dist http://localhost:3000\n * ```\n *\n * @example Start server with CLI flag\n * ```ts\n * const args = { serve: 'public' };\n * const url = await startServer(config, args);\n * // Server started at http://localhost:3000\n * // Serving: public\n * ```\n *\n * @example Start server from config\n * ```ts\n * const config = {\n * serve: {\n * start: true,\n * dir: 'dist',\n * port: 8080\n * }\n * };\n * const url = await startServer(config, {});\n * // Server started at http://localhost:8080\n * ```\n *\n * @example No server (returns undefined)\n * ```ts\n * const config = { serve: { start: false } };\n * const url = await startServer(config, {});\n * // url === undefined\n * ```\n *\n * @see {@link ServerModule} for server implementation\n * @see {@link ServerConfigurationInterface} for configuration options\n *\n * @since 2.0.0\n */\n\nasync function startServer(config: xBuildConfigInterface, args: ArgumentsInterface): Promise<string | undefined> {\n const shouldStartServer = (args.serve ?? false) !== false || config.serve?.start;\n if (!shouldStartServer) return;\n\n let urlString = undefined;\n const serveDir = config.serve?.dir || args.serve || 'dist';\n const serverConfig: ServerConfigurationInterface = {\n ...config.serve,\n onStart({ host, port, url }): void {\n urlString = url;\n console.log(`${ createActionPrefix('serve') } ${ keywordColor(serveDir) } ${ pathColor(url) }\\n`);\n config.serve?.onStart?.({ host, port, url });\n }\n };\n\n const server = new ServerModule(serverConfig, serveDir);\n await server.start();\n\n return urlString;\n}\n\n/**\n * Executes a single build pass, handling clean, type checking, and build operations.\n *\n * @param buildService - The build service instance to execute\n * @param args - Parsed command-line arguments controlling build behavior\n *\n * @returns Promise that resolves when the build completes or fails\n *\n * @remarks\n * Orchestrates a complete build cycle with the following steps:\n * 1. **Clean**: Removes the `dist` directory (forced, recursive)\n * 2. **Type check or build**: Executes type checking if `--typeCheck` flag is set, otherwise performs full build\n * 3. **Error handling**: Catches and logs any build errors\n *\n * **Operational modes**:\n * - **Type check mode** (`--typeCheck`): Runs TypeScript compiler diagnostics without emitting files\n * - **Build mode**: Executes full build with optional build name parameter\n *\n * **Clean behavior**:\n * - Always removes `dist` directory before building\n * - Uses `{ recursive: true, force: true }` for safe deletion\n * - Errors during clean are silently ignored (directory may not exist)\n *\n * **Error handling**:\n * - All errors are caught and logged via {@link logError}\n * - Errors do not throw (suitable for watch mode)\n *\n * @example Standard build\n * ```ts\n * const args = { build: 'production' };\n * await executeBuild(buildService, args);\n * // 1. Removes dist/\n * // 2. Builds with 'production' configuration\n * ```\n *\n * @example Type check only\n * ```ts\n * const args = { typeCheck: true };\n * await executeBuild(buildService, args);\n * // 1. Removes dist/\n * // 2. Runs TypeScript diagnostics\n * // 3. Logs diagnostics (no files emitted)\n * ```\n *\n * @example Error during build\n * ```ts\n * await executeBuild(buildService, args);\n * // If build fails, error is logged but function doesn't throw\n * ```\n *\n * @see {@link logError} for error formatting\n * @see {@link BuildService.typeChack} for type checking\n * @see {@link BuildService.build} for build implementation\n * @see {@link logTypeDiagnostics} for diagnostic output formatting\n *\n * @since 2.0.0\n */\n\nasync function executeBuild(buildService: BuildService, args: ArgumentsInterface): Promise<void> {\n try {\n const distPath = join(process.cwd(), 'dist');\n rmSync(distPath, { recursive: true, force: true });\n\n if (args.typeCheck) {\n const diagnostics = await buildService.typeChack();\n logTypeDiagnostics(diagnostics);\n } else {\n const result = await buildService.build(args.build);\n Object.entries(result).forEach(([ name, variant ]) => {\n const errors = variant.errors.filter(\n (error: Error & { id?: string }) => error?.id === 'endHook'\n );\n\n if(!errors.length) return;\n const status = createActionPrefix('onEnd-hook', errorColor(ERROR_SYMBOL));\n console.log(status, name);\n\n errors.forEach((error: Error) => logError(error));\n console.log('');\n });\n }\n } catch (error) {\n logError(error);\n }\n}\n\n/**\n * Enters watch mode for continuous rebuilding on file changes.\n *\n * @param buildService - The build service instance to trigger rebuilds\n * @param config - The xBuild configuration containing watch patterns\n * @param args - Parsed command-line arguments controlling watch behavior\n * @param url - Optional server URL to display in interactive UI\n *\n * @returns Promise that resolves when watch mode is set up (never resolves in watch mode)\n *\n * @remarks\n * Watch mode is enabled when:\n * - `--watch` CLI flag is provided, OR\n * - `--serve` CLI flag is provided (implies watching), OR\n * - `config.serve.start` is `true` (implies watching)\n *\n * **Watch mode flow**:\n * 1. Collects ignore patterns from configuration\n * 2. Initializes watch service with ignore patterns\n * 3. Sets up interactive terminal UI (if applicable)\n * 4. Executes initial build\n * 5. Starts file system watcher\n * 6. On file changes:\n * - Touches changed files in TypeScript language service\n * - Reloads configuration if config file changed\n * - Logs rebuild trigger\n * - Executes rebuild\n *\n * **Configuration reloading**:\n * If the configuration file itself changes, the config is reloaded and\n * the build service is updated with the new configuration, allowing\n * configuration changes without restarting the process.\n *\n * **Interactive UI**:\n * Initializes an interactive terminal interface displaying:\n * - Server URL (if provided)\n * - Build status\n * - Keyboard shortcuts for manual actions\n *\n * **Early exit**:\n * If watch mode is not requested, the function returns immediately\n * without starting the watcher.\n *\n * @example Watch mode with server\n * ```ts\n * const args = { watch: true, serve: 'dist' };\n * await startWatchMode(buildService, config, args, 'http://localhost:3000');\n * // 1. Executes initial build\n * // 2. Starts watching files\n * // 3. Rebuilds on changes\n * // (Never returns)\n * ```\n *\n * @example Serve mode (implicit watch)\n * ```ts\n * const args = { serve: 'dist' };\n * await startWatchMode(buildService, config, args, url);\n * // Watch mode automatically enabled\n * ```\n *\n * @example No watch mode\n * ```ts\n * const args = {};\n * await startWatchMode(buildService, config, args);\n * // Returns immediately (no watching)\n * ```\n *\n * @see {@link WatchService} for file system monitoring\n * @see {@link BuildService.reload} for configuration reloading\n * @see {@link BuildService.touchFiles} for incremental compilation\n * @see {@link collectWatchIgnorePatterns} for ignore pattern collection\n *\n * @since 2.0.0\n */\n\nasync function startWatchMode(\n buildService: BuildService, config: xBuildConfigInterface, args: ArgumentsInterface, url?: string\n): Promise<void> {\n const shouldWatch = args.watch || args.serve !== undefined || config.serve?.start;\n if (!shouldWatch) return;\n\n const ignorePatterns = collectWatchIgnorePatterns(config);\n const watchService = new WatchService(ignorePatterns);\n\n init(async () => {\n await executeBuild(buildService, args);\n }, url);\n\n await executeBuild(buildService, args);\n await watchService.start(async (changedFiles: Array<string>): Promise<void> => {\n buildService.touchFiles(changedFiles);\n\n if(changedFiles.includes(args.config!)) {\n const config = await configFileProvider(args.config!);\n buildService.reload(config);\n }\n\n console.log(`\\n${ prefix() } ${ mutedColor('Rebuilding') }: files (${ changedFiles.length })\\n`);\n await executeBuild(buildService, args);\n });\n\n return;\n}\n\n/**\n * Main CLI entry point that orchestrates the complete xBuild execution lifecycle.\n *\n * @returns Promise that resolves when execution completes (or never in watch mode)\n *\n * @throws Errors are caught and logged internally, function does not throw\n *\n * @remarks\n * This is the primary entry point executed when the xBuild CLI is invoked.\n * It orchestrates the complete build lifecycle from configuration loading to\n * build execution, with support for watch mode, development server, and various\n * build configurations.\n *\n * **Execution flow**:\n * 1. **Banner**: Display xBuild version and branding\n * 2. **Configuration parsing**:\n * - Parse config file path from CLI args\n * - Load configuration file (if exists)\n * - Parse full CLI arguments with config context\n * - Extract user-defined arguments\n * 3. **Configuration setup**:\n * - Configure entry points from glob patterns\n * - Apply CLI overrides to variant configurations\n * - Finalize and validate configuration\n * 4. **Build service initialization**:\n * - Create build service instance with user args\n * - Register lifecycle callbacks (onStart, onEnd)\n * 5. **Server startup** (if requested):\n * - Start development HTTP server\n * - Capture server URL for UI display\n * 6. **Execution mode**:\n * - Enter watch mode if `--watch` or `--serve` flags present\n * - Otherwise, execute single build pass\n *\n * **Configuration precedence**:\n * 1. CLI flags (highest priority)\n * 2. Configuration file settings\n * 3. Built-in defaults (lowest priority)\n *\n * **User arguments**:\n * Custom CLI arguments defined in `config.userArgv` are parsed separately\n * and passed to the build service, allowing custom build scripts to extend\n * the CLI with additional flags.\n *\n * **Lifecycle callbacks**:\n * - `onStart`: Logs build start with timing information\n * - `onEnd`: Logs build completion with duration and status\n *\n * @example Standard build invocation\n * ```bash\n * xbuild\n * # 1. Displays banner\n * # 2. Loads xbuild.config.ts\n * # 3. Executes build\n * # 4. Exits\n * ```\n *\n * @example Watch mode with server\n * ```bash\n * xbuild --watch --serve dist --port 8080\n * # 1. Displays banner\n * # 2. Loads configuration\n * # 3. Starts server on port 8080\n * # 4. Executes initial build\n * # 5. Watches for changes\n * # (Runs indefinitely)\n * ```\n *\n * @example Custom configuration file\n * ```bash\n * xbuild --config custom.config.ts --minify\n * # Loads custom.config.ts instead of default\n * ```\n *\n * @see {@link startWatchMode} for watch mode\n * @see {@link executeBuild} for build execution\n * @see {@link startServer} for development server\n * @see {@link ArgvModule} for CLI argument parsing\n * @see {@link BuildService} for build orchestration\n * @see {@link configFileProvider} for configuration loading\n *\n * @since 2.0.0\n */\n\nasync function main(): Promise<void> {\n // Display banner\n console.log(bannerComponent());\n\n // Parse configuration\n const argvService = inject(ArgvModule);\n const preConfig = argvService.parseConfigFile(process.argv);\n\n globalThis.$argv = preConfig;\n const config = await configFileProvider(preConfig.config);\n const args = argvService.enhancedParse(process.argv, config.userArgv);\n const userArgs = argvService.parseUserArgv(process.argv, config.userArgv);\n\n // Configure build\n configureEntryPoints(config, args);\n applyCommandLineOverrides(config, args);\n overwriteConfig(config);\n\n // Initialize build service\n const buildService = new BuildService(userArgs);\n buildService.onEnd = logBuildEnd;\n buildService.onStart = logBuildStart;\n\n // Execute build pipeline\n const url = await startServer(config, args);\n await startWatchMode(buildService, config, args, url);\n await executeBuild(buildService, args);\n}\n\nmain();\n", "/**\n * Imports\n */\n\nimport process from 'node:process';\nimport { xBuildBaseError } from '@errors/base.error';\nimport { formatStack, getErrorMetadata } from '@providers/stack.provider';\n\n/**\n * Formats and logs error output in a standardized way.\n *\n * @remarks\n * This utility is designed for use in global error handlers such as\n * `uncaughtException` and `unhandledRejection`.\n * - If the error is an {@link AggregateError}, all individual errors are iterated and logged.\n * - Errors extending {@link xBuildBaseError} are logged directly without stack formatting.\n * - Standard {@link Error} instances are logged using {@link formatStack}, with both\n * framework and native frames included.\n * - Non-error values are logged as-is.\n *\n * @param reason - The error, aggregate error, or arbitrary value to log.\n *\n * @example\n * ```ts\n * formatErrors(new Error(\"Something went wrong\"));\n * ```\n *\n * @see formatStack\n * @see xJetBaseError\n * @see AggregateError\n *\n * @since 2.0.0\n */\n\nexport function formatErrors(reason: unknown): void {\n if (reason instanceof AggregateError) {\n console.error('AggregateError:', reason.message);\n for (const err of reason.errors) {\n if (err instanceof Error && !(err instanceof xBuildBaseError)) {\n const metadata = getErrorMetadata(err, { withFrameworkFrames: true, withNativeFrames: true });\n console.error(formatStack(metadata, err.name, err.message));\n } else {\n console.error(err);\n }\n }\n\n return;\n }\n\n if (reason instanceof Error && !(reason instanceof xBuildBaseError)) {\n const metadata = getErrorMetadata(reason, { withFrameworkFrames: true, withNativeFrames: true });\n console.error(formatStack(metadata, reason.name, reason.message));\n } else {\n console.error(reason);\n }\n}\n\n/**\n * Global handler for uncaught exceptions in Node.js.\n *\n * @param reason - The value or error object representing the uncaught exception\n *\n * @throws This handler does not throw, but catches uncaught exceptions\n *\n * @remarks\n * When an uncaught exception occurs, this handler logs the error using {@link formatStack}\n * with both framework and native frames included, and then terminates the process\n * with exit code `2`, signaling failure.\n *\n * @example\n * ```ts\n * // Automatically registered when this file is loaded,\n * throw new Error('This error will be logged and exit the process');\n * ```\n *\n * @see formatStack\n * @see process.exit\n * @see {@link https://nodejs.org/api/process.html#event-uncaughtexception | Node.js documentation on 'uncaughtException'}\n *\n * @since 2.0.0\n */\n\nprocess.on('uncaughtException', (reason: unknown) => {\n formatErrors(reason);\n process.exit(2);\n});\n\n/**\n * Global handler for unhandled promise rejections in Node.js.\n *\n * @param reason - The value or error object representing the reason for the unhandled promise rejection\n *\n * @throws This handler does not throw, but catches unhandled promise rejections\n *\n * @remarks\n * When an unhandled promise rejection occurs, this handler logs the error using {@link formatStack}\n * with both framework and native frames included, and then terminates the process\n * with exit code `2`. Using a distinct exit code allows differentiating between uncaught exceptions\n * and unhandled promise rejections.\n *\n * @example\n * ```ts\n * // Automatically registered when this file is loaded\n * Promise.reject(new Error('This rejection will be logged and exit the process'));\n * ```\n *\n * @see formatStack\n * @see process.exit\n * @see {@link https://nodejs.org/api/process.html#process_event_unhandledrejection | Node.js documentation on 'unhandledRejection'}\n *\n * @since 2.0.0\n */\n\nprocess.on('unhandledRejection', (reason: unknown) => {\n formatErrors(reason);\n process.exit(2);\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { InjectableOptionsInterface, ProvidersType } from './interfaces/symlinks.interface';\nimport type { ProviderUseFactoryInterface, ProviderUseValueInterface } from './interfaces/symlinks.interface';\nimport type { ProviderUseClassInterface, ConstructorType, ConstructorLikeType } from './interfaces/symlinks.interface';\n\n/**\n * A collection of singleton instances for injectable classes.\n *\n * @remarks\n * This map stores instances of classes marked as `singleton` in `@Injectable` metadata.\n * It ensures that only one instance exists for the lifetime of the application.\n *\n * @see ConstructorType\n * @since 2.0.0\n */\n\nexport const SINGLETONS = new Map<ConstructorType, unknown>();\n\n/**\n * Stores metadata for all classes marked with the `@Injectable` decorator.\n *\n * @remarks\n * The metadata includes scope, factory function, and provider dependencies.\n *\n * @see Injectable\n * @since 2.0.0\n */\n\nexport const INJECTABLES = new Map<ConstructorType, InjectableOptionsInterface>();\n\n/**\n * Type guard to check if a provider uses a class.\n *\n * @param provider - The provider to check.\n * @returns True if the provider is a {@link ProviderUseClassInterface}.\n *\n * @see ProviderUseClassInterface\n * @since 2.0.0\n */\n\nexport function isProviderUseClass(provider: unknown): provider is ProviderUseClassInterface {\n return typeof provider === 'object' && provider !== null && 'useClass' in provider;\n}\n\n/**\n * Type guard to check if a provider uses a factory function.\n *\n * @param provider - The provider to check.\n * @returns True if the provider is a {@link ProviderUseFactoryInterface}.\n *\n * @see ProviderUseFactoryInterface\n * @since 2.0.0\n */\n\nexport function isProviderUseFactory(provider: unknown): provider is ProviderUseFactoryInterface {\n return typeof provider === 'object' && provider !== null && 'useFactory' in provider;\n}\n\n/**\n * Type guard to check if a provider uses a value.\n *\n * @param provider - The provider to check.\n * @returns True if the provider is a {@link ProviderUseValueInterface}.\n *\n * @see ProviderUseValueInterface\n * @since 2.0.0\n */\n\nexport function isProviderUseValue(provider: unknown): provider is ProviderUseValueInterface {\n return typeof provider === 'object' && provider !== null && 'useValue' in provider;\n}\n\n/**\n * Marks a class as injectable, optionally providing metadata.\n *\n * @param options - Optional configuration for the injectable class.\n *\n * @remarks\n * The `@Injectable` decorator allows classes to be automatically instantiated\n * and injected with dependencies using the `inject` function.\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n *\n * const instance = inject(MyService);\n * ```\n *\n * ```ts\n * @Injectable()\n * class Database {\n * }\n *\n * @Injectable({\n * providers: [ Database ]\n * })\n * class UserService {\n * constructor(private db: Database) {\n * console.log(db); // db instance\n * }\n * }\n *\n * const userService = inject(UserService);\n * ```\n *\n * ```ts\n * @Injectable()\n * class Cache {}\n *\n * @Injectable({\n * providers: [{ useClass: Cache }]\n * })\n * class UserService {\n * constructor(cache: Cache) {\n * console.log(cache); // cache instance\n * }\n * }\n *\n * const userService = inject(UserService);\n * ```\n *\n * ```ts\n * @Injectable({\n * providers: [\n * {\n * useFactory(): Date {\n * return new Date();\n * }\n * }\n * ]\n * })\n * class ClockService {\n * constructor(now: Date) {\n * console.log(now.toLocaleTimeString()); // get time from the factory\n * }\n * }\n *\n * const clockService = inject(ClockService);\n * ```\n *\n * ```ts\n * @Injectable({\n * providers: [\n * {\n * useValue: 'https://api.example.com'\n * }\n * ]\n * })\n * class ApiService {\n * constructor(baseUrl: string) {\n * console.log(baseUrl);\n * }\n * }\n *\n *\n * const apiService = inject(ApiService); // log https://api.example.com\n * const apiService2 = inject(ApiService, 'https://api2.example.com'); // log https://api2.example.com\n * ```\n *\n * ```ts\n * @Injectable()\n * class Logger {\n * }\n *\n * @Injectable({\n * providers: [\n * Logger,\n * { useValue: 10 },\n * { useFactory: (): string => 'prod' }\n * ]\n * })\n * class AppService {\n * constructor(\n * logger: Logger,\n * retries: number,\n * env: string\n * ) {\n * console.log(logger, retries, env);\n * }\n * }\n *\n * const appService = inject(AppService); // log Logger {} 10 prod\n * const appService2 = inject(AppService, inject(Logger), 50, 'test'); // log Logger {} 50 test\n * ```\n *\n * @see InjectableOptionsInterface\n * @since 2.0.0\n */\n\nexport function Injectable<T extends ConstructorType = ConstructorType>(options?: InjectableOptionsInterface<T>) {\n return function (target: T): void {\n INJECTABLES.set(target, <InjectableOptionsInterface>options || {});\n };\n}\n\n/**\n * Converts an array of providers into constructor arguments for injection.\n *\n * @param providers - An optional array of providers to resolve.\n * @param args - Optional initial arguments to prepend before resolving providers.\n * @returns An array of resolved arguments including the results from providers.\n *\n * @remarks\n * This function iterates over the provided `ProvidersType` array and converts each provider\n * into its resolved value. It supports class providers, factory providers, value providers,\n * and direct constructor functions. The returned array can be used to construct instances\n * with dependencies injected in the correct order.\n *\n * @example\n * ```ts\n * const args = providersIntoArgs([{ useValue: 42 }, { useFactory: () => 'hello' }]);\n * // args = [42, 'hello']\n * ```\n *\n * @see isProviderUseClass\n * @see isProviderUseValue\n * @see isProviderUseFactory\n *\n * @since 2.0.0\n */\n\nexport function providersIntoArgs(providers?: ProvidersType, args: Array<unknown> = []): Array<unknown> {\n if (!providers) return args;\n\n const scopeAgs: Array<unknown> = args;\n for (const provider of providers.slice(scopeAgs.length)) {\n if (isProviderUseClass(provider)) {\n scopeAgs.push(inject(provider.useClass, ...providersIntoArgs(provider.providers)));\n } else if (isProviderUseFactory(provider)) {\n scopeAgs.push(provider.useFactory(...providersIntoArgs(provider.providers)));\n } else if (isProviderUseValue(provider)) {\n scopeAgs.push(provider.useValue);\n } else if (typeof provider === 'function') {\n scopeAgs.push(inject(provider));\n } else {\n throw new Error(`Unknown provider type: ${ typeof provider }`);\n }\n }\n\n return scopeAgs;\n}\n\n/**\n * Resolves and instantiates a class with its dependencies.\n *\n * @param token - The constructor function or class to instantiate.\n * @param args - Optional arguments to pass to the constructor, which can override\n * or supplement provider-resolved values.\n * @returns An instance of the class with all dependencies injected.\n *\n * @remarks\n * The `inject` function looks up metadata for the class marked with `@Injectable`.\n * It resolves all providers recursively using `providersIntoArgs`. If the class is\n * marked as a `singleton`, the same instance will be returned on further calls.\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n *\n * const instance = inject(MyService);\n * ```\n *\n * @see Injectable\n * @see providersIntoArgs\n *\n * @since 2.0.0\n */\n\nexport function inject<T, Args extends Array<unknown>>(token: ConstructorLikeType<T, Args>, ...args: Partial<Args>): T {\n if (SINGLETONS.has(token)) return <T>SINGLETONS.get(token);\n\n const metadata = INJECTABLES.get(token);\n if (!metadata) throw new Error(`Cannot inject ${ token.name } \u2013 not marked @Injectable`);\n\n const scopeAgs = providersIntoArgs(metadata.providers, args);\n const instance: T = metadata.factory\n ? <T>metadata.factory(...scopeAgs)\n : new token(...scopeAgs as Args);\n\n if (metadata?.scope === 'singleton') {\n SINGLETONS.set(token, instance);\n }\n\n return instance;\n}\n\n/**\n * Forces the instantiation of a class bypassing any existing singleton instance.\n *\n * @param token - The constructor function or class to instantiate.\n * @param args - Optional arguments to pass to the constructor, which can override\n * or supplement provider-resolved values.\n * @returns A new instance of the class, even if a singleton instance already exists.\n *\n * @remarks\n * Unlike the `inject` function, `forceInject` will delete any existing singleton\n * instance for the given class before creating a new one. This is useful when you\n * need a fresh instance regardless of the singleton scope.\n *\n * @example\n * ```ts\n * @Injectable({ scope: 'singleton' })\n * class MyService {}\n *\n * const freshInstance = forceInject(MyService);\n * ```\n *\n * @see inject\n * @since 2.0.0\n */\n\nexport function forceInject<T, Args extends Array<unknown>>(token: ConstructorLikeType<T, Args>, ...args: Partial<Args>): T {\n if (SINGLETONS.has(token)) SINGLETONS.delete(token);\n\n return inject<T, Args>(token, ...args);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PartialMessage } from 'esbuild';\nimport type { SourceService } from '@remotex-labs/xmap';\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\nimport type { ParsedStackTraceInterface, StackFrameInterface } from '@remotex-labs/xmap/parser.component';\nimport type { StackInterface, StackContextInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { inject } from '@symlinks/symlinks.module';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { FrameworkService } from '@services/framework.service';\nimport { relative, dirname, join } from '@components/path.component';\nimport { parseErrorStack } from '@remotex-labs/xmap/parser.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { highlightCode } from '@remotex-labs/xmap/highlighter.component';\nimport { type PositionWithCodeInterface, Bias } from '@remotex-labs/xmap';\nimport { type SourceOptionsInterface, formatErrorCode } from '@remotex-labs/xmap/formatter.component';\n\n/**\n * Regular expression to match multiple consecutive spaces.\n *\n * @remarks\n * Used to normalize spacing in formatted strings by replacing sequences\n * of two or more spaces with a single space.\n *\n * @since 2.0.0\n */\n\nconst MULTIPLE_SPACES = /\\s{2,}/g;\n\n/**\n * Regular expression to detect HTTP or HTTPS URLs.\n *\n * @remarks\n * Used to identify URL-based source paths in stack traces or source maps.\n *\n * @since 2.0.0\n */\n\nconst URL_PATTERN = /^https?:\\/\\//;\n\n/**\n * Regular expression to detect file:// protocol URLs.\n *\n * @remarks\n * Used to identify and strip file protocol prefixes from file paths.\n *\n * @since 2.0.0\n */\n\nconst FILE_PROTOCOL = /^file:\\/\\//;\n\n/**\n * Extracts a parsed stack trace from either an Error object or an esbuild PartialMessage.\n *\n * @param raw - Either an {@link Error} object or an esbuild {@link PartialMessage}\n * @returns A {@link ParsedStackTraceInterface} containing structured stack frame data\n *\n * @remarks\n * - If `raw` is an Error instance, parses it directly using {@link parseErrorStack}.\n * - If `raw.detail` is an Error, parses that instead.\n * - For esbuild messages without location info, returns a minimal parsed stack.\n * - For esbuild messages with location, creates a single-frame stack from the location data.\n *\n * @example\n * ```ts\n * const error = new Error(\"Something went wrong\");\n * const parsed = getErrorStack(error);\n * console.log(parsed.stack); // Array of stack frames\n * ```\n *\n * @see parseErrorStack\n * @see ParsedStackTraceInterface\n *\n * @since 2.0.0\n */\n\nexport function getErrorStack(raw: Partial<PartialMessage> | Error): ParsedStackTraceInterface {\n if (raw instanceof Error) return parseErrorStack(raw);\n if (raw.detail instanceof Error) return parseErrorStack(raw.detail);\n\n if (!raw.location) {\n return { stack: [], name: 'esBuildMessage', message: raw.text ?? '', rawStack: '' };\n }\n\n return {\n name: 'esBuildMessage',\n message: raw.text ?? '',\n rawStack: '',\n stack: [\n {\n source: `@${ raw.location.file }`,\n line: raw.location.line,\n column: raw.location.column,\n fileName: raw.location.file,\n eval: false,\n async: false,\n native: false,\n constructor: false\n }\n ]\n };\n}\n\n/**\n * Retrieves a source service for a given stack frame, either from source maps or file snapshots.\n *\n * @param frame - The stack frame containing file information\n * @returns A {@link SourceService} if the source can be resolved, otherwise null\n *\n * @remarks\n * - First attempts to retrieve a mapped source using {@link FrameworkService.getSourceMap}.\n * - Falls back to file snapshots via {@link FilesModel.getSnapshot} if no source map exists.\n * - Creates a minimal {@link SourceService} implementation for snapshot-based sources.\n * - Returns null if neither a source map nor snapshot is available.\n * - The created service implements `getPositionWithCode` to extract code snippets with context lines.\n *\n * @example\n * ```ts\n * const source = getSource.call(context, frame);\n * if (source) {\n * const position = source.getPositionWithCode(10, 5, Bias.LOWER_BOUND);\n * }\n * ```\n *\n * @see SourceService\n * @see StackFrameInterface\n * @see StackContextInterface\n * @see FilesModel.getSnapshot\n * @see FrameworkService.getSourceMap\n *\n * @since 2.0.0\n */\n\nexport function getSource(this: StackContextInterface, frame: StackFrameInterface): SourceService | null {\n const fileName = frame.fileName ?? '';\n const mapped = this.framework.getSourceMap(fileName);\n if (mapped) return mapped;\n\n const snapshot = this.files.getOrTouchFile(fileName);\n const code = snapshot?.contentSnapshot?.text;\n\n if (!snapshot || !code) return null;\n const lines = code.split('\\n');\n\n return {\n getPositionWithCode: (line, column, _bias, options) => {\n const before = options?.linesBefore ?? 3;\n const after = options?.linesAfter ?? 3;\n\n const startLine = Math.max(line - before, 0);\n const endLine = Math.min(line + after, lines.length);\n\n return {\n line,\n column: column + 1,\n code: lines.slice(startLine, endLine).join('\\n'),\n source: fileName,\n name: null,\n startLine,\n endLine,\n sourceRoot: null,\n sourceIndex: -1,\n generatedLine: -1,\n generatedColumn: -1\n };\n }\n } as SourceService;\n}\n\n\n/**\n * Highlights code at a specific position with syntax coloring.\n *\n * @param position - The position object containing the code to highlight\n * @returns The code string with applied syntax highlighting and formatting\n *\n * @remarks\n * - Uses {@link highlightCode} to apply syntax highlighting to the `position.code`.\n * - Wraps the highlighted code with {@link formatErrorCode} for additional formatting.\n * - Default highlight color is {@link xterm.brightPink}.\n *\n * @example\n * ```ts\n * const highlighted = highlightPositionCode({ code: 'const x = 1;', line: 1, column: 0 });\n * console.log(highlighted); // Outputs syntax-highlighted code string\n * ```\n *\n * @see highlightCode\n * @see formatErrorCode\n * @see xterm.brightPink\n *\n * @since 2.0.0\n */\n\nexport function highlightPositionCode(position: PositionWithCodeInterface): string {\n return formatErrorCode(\n { ...position, code: highlightCode(position.code) },\n { color: xterm.brightPink }\n );\n}\n\n/**\n * Formats a stack frame into a human-readable string with colorized output.\n *\n * @param frame - The stack frame to format\n * @returns A formatted string representation of the stack frame\n *\n * @remarks\n * - Converts absolute file paths to relative paths based on {@link FrameworkService.rootPath}.\n * - Displays function name, file name, line number, and column number.\n * - Uses {@link xterm} color utilities for enhanced readability.\n * - Normalizes multiple consecutive spaces using {@link MULTIPLE_SPACES} regex.\n * - Falls back to `frame.source` if no file name is available.\n *\n * @example\n * ```ts\n * const formatted = formatStackFrame.call(context, frame);\n * console.log(formatted); // \"at myFunction src/utils.ts [10:5]\"\n * ```\n *\n * @see xterm\n * @see StackFrameInterface\n * @see StackContextInterface\n *\n * @since 2.0.0\n */\n\nexport function formatStackFrame(this: StackContextInterface, frame: StackFrameInterface): string {\n let fileName = frame.fileName;\n if (fileName?.includes(this.framework.rootPath)) {\n fileName = relative(this.framework.rootPath, fileName);\n }\n\n if (!fileName) return frame.source ?? '';\n\n const position =\n frame.line && frame.column\n ? xterm.gray(`[${ frame.line }:${ frame.column }]`)\n : '';\n\n return `at ${ frame.functionName ?? '' } ${ xterm.darkGray(fileName) } ${ position }`\n .replace(MULTIPLE_SPACES, ' ')\n .trim();\n}\n\n/**\n * Constructs a location string for a stack frame, suitable for links or display.\n *\n * @param frame - The stack frame being processed\n * @param position - The resolved source position with code\n * @returns A string representing the source location, including line number\n *\n * @remarks\n * - Handles HTTP/HTTPS URLs by appending `#L` line number format.\n * - Searches for embedded HTTP/HTTPS URLs within the source path.\n * - Prepends the source root if available and normalizes path separators.\n * - Appends the line number using `#L` format for all location strings.\n * - Falls back to the frame's fileName if no source is provided, stripping `file://` prefixes.\n *\n * @example\n * ```ts\n * const location = getSourceLocation.call(context, frame, position);\n * console.log(location); // \"src/utils/file.js#L12\"\n * ```\n *\n * @see URL_PATTERN\n * @see FILE_PROTOCOL\n * @see StackFrameInterface\n * @see PositionWithCodeInterface\n *\n * @since 2.0.0\n */\n\nexport function getSourceLocation(this: StackContextInterface, frame: StackFrameInterface, position: Required<PositionWithCodeInterface>): string {\n const { source, sourceRoot, line } = position;\n\n if (!source) {\n return frame.fileName ? frame.fileName.replace(FILE_PROTOCOL, '') : '';\n }\n\n const httpIndex = Math.max(source.lastIndexOf('http://'), source.lastIndexOf('https://'));\n if (httpIndex > 0) return `${ source.substring(httpIndex) }#L${ line }`;\n if (URL_PATTERN.test(source)) return `${ source }#L${ line }`;\n\n if (sourceRoot) {\n const path = relative(dirname(this.framework.distPath), join(this.framework.distPath, source));\n\n return `${ sourceRoot }${ path }#L${ line }`;\n }\n\n return `${ source }#L${ line }`;\n}\n\n/**\n * Formats a stack frame with enhanced position information from source maps.\n *\n * @param frame - The original stack frame\n * @param position - The resolved source position with code context\n * @returns A formatted string representing the enhanced stack frame\n *\n * @remarks\n * - Caches the first encountered code snippet in the context for later display.\n * - Stores highlighted code in {@link StackContextInterface.formatCode} on first call.\n * - Uses {@link highlightPositionCode} to generate syntax-highlighted code snippets.\n * - Delegates to {@link formatStackFrame} with updated position and location information.\n * - Updates frame properties with mapped source location via {@link getSourceLocation}.\n *\n * @example\n * ```ts\n * const formatted = formatFrameWithPosition.call(context, frame, position);\n * console.log(formatted); // Enhanced stack frame with source-mapped location\n * ```\n *\n * @see formatStackFrame\n * @see getSourceLocation\n * @see StackFrameInterface\n * @see StackContextInterface\n * @see highlightPositionCode\n * @see PositionWithCodeInterface\n *\n * @since 2.0.0\n */\n\nexport function formatFrameWithPosition(this: StackContextInterface, frame: StackFrameInterface, position: Required<PositionWithCodeInterface>): string {\n if (!this.code) {\n this.code = position.code;\n this.source = position.source;\n this.formatCode = highlightPositionCode(position);\n }\n\n return formatStackFrame.call(this, {\n ...frame,\n line: position.line,\n column: position.column,\n functionName: position.name ?? frame.functionName,\n fileName: getSourceLocation.call(this, frame, position)\n });\n}\n\n/**\n * Processes a single stack frame and formats it for display, optionally including source map information.\n *\n * @param frame - The stack frame to process\n * @param options - Optional {@link SourceOptionsInterface} for retrieving source positions\n * @returns A formatted string representing the stack frame, or an empty string if filtered out\n *\n * @remarks\n * - Skips native frames if {@link StackContextInterface.withNativeFrames} is false.\n * - Skips frames without any location information (line, column, fileName, or functionName).\n * - Attempts to resolve source positions using {@link getSource} and {@link SourceService.getPositionWithCode}.\n * - Filters out framework files if {@link StackContextInterface.withFrameworkFrames} is false.\n * - Applies line offset adjustments if {@link StackContextInterface.lineOffset} is set.\n * - Stores the resolved line and column in the context for reference.\n * - Delegates formatting to {@link formatFrameWithPosition} or {@link formatStackFrame} based on position availability.\n *\n * @example\n * ```ts\n * const formatted = stackEntry.call(context, frame, { linesBefore: 3, linesAfter: 3 });\n * console.log(formatted);\n * ```\n *\n * @see getSource\n * @see formatStackFrame\n * @see StackContextInterface\n * @see formatFrameWithPosition\n * @see SourceService.getPositionWithCode\n *\n * @since 2.0.0\n */\n\nexport function stackEntry(this: StackContextInterface, frame: StackFrameInterface, options?: SourceOptionsInterface): string {\n if (!this.withNativeFrames && frame.native) return '';\n if (!frame.line && !frame.column && !frame.fileName && !frame.functionName) return '';\n\n const source = getSource.call(this, frame);\n if (!source) return formatStackFrame.call(this, frame);\n\n const position = source.getPositionWithCode(\n frame.line ?? 0,\n frame.column ?? 0,\n Bias.LOWER_BOUND,\n options\n );\n\n if (!position) return formatStackFrame.call(this, frame);\n if (!this.withFrameworkFrames && this.framework.isFrameworkFile(position)) return '';\n if (this.lineOffset) {\n position.line += this.lineOffset;\n position.startLine += this.lineOffset;\n position.endLine += this.lineOffset;\n }\n\n this.line = position.line;\n this.column = position.column;\n\n return formatFrameWithPosition.call(this, frame, position);\n}\n\n\n/**\n * Parses error metadata into a structured stack representation with enhanced source information.\n *\n * @param raw - Either an esbuild {@link PartialMessage} or an {@link Error} object\n * @param options - Optional {@link StackTraceInterface} configuration for controlling stack parsing\n * @param lineOffset - Optional line number offset to apply to all positions (default: 0)\n * @returns A {@link StackInterface} object containing formatted stack frames and code context\n *\n * @remarks\n * - Creates a {@link StackContextInterface} using injected services for file and framework resolution.\n * - Respects the `verbose` configuration setting to control native and framework frame visibility.\n * - Uses {@link getErrorStack} to parse the raw error into stack frames.\n * - Processes each frame via {@link stackEntry}, filtering out empty results.\n * - Returns structured metadata including formatted code, line/column positions, and stack traces.\n * - Line offsets are applied to all resolved positions for alignment with external systems.\n *\n * @example\n * ```ts\n * try {\n * throw new Error(\"Something went wrong\");\n * } catch (error) {\n * const metadata = getErrorMetadata(error, { linesBefore: 5, linesAfter: 5 });\n * console.log(metadata.stacks); // Array of formatted stack lines\n * console.log(metadata.formatCode); // Highlighted code snippet\n * }\n * ```\n *\n * @see stackEntry\n * @see getErrorStack\n * @see StackInterface\n * @see StackTraceInterface\n * @see StackContextInterface\n * @see ConfigurationService\n *\n * @since 2.0.0\n */\n\nexport function getErrorMetadata(raw: PartialMessage | Error, options?: StackTraceInterface, lineOffset: number = 0): StackInterface {\n const verbose = inject(ConfigurationService).getValue(c => c.verbose) ?? false;\n const context: StackContextInterface = {\n code: '',\n line: 0,\n column: 0,\n source: '',\n formatCode: '',\n lineOffset,\n files: inject(FilesModel),\n framework: inject(FrameworkService),\n withNativeFrames: verbose,\n withFrameworkFrames: verbose,\n ...options\n };\n\n const parsed = getErrorStack(raw);\n const stacks = parsed.stack\n .map(frame => stackEntry.call(context, frame, options))\n .filter(Boolean);\n\n return {\n stacks,\n code: context.code,\n line: context.line ?? 0,\n column: context.column ?? 0,\n source: context.source,\n formatCode: context.formatCode\n };\n}\n\n/**\n * Formats error metadata into a human-readable string with enhanced styling.\n *\n * @param metadata - The {@link StackInterface} object containing parsed stack trace information\n * @param name - The error name (e.g., \"TypeError\", \"ReferenceError\")\n * @param message - The error message describing what went wrong\n * @param notes - Optional array of esbuild {@link PartialMessage} notes to display\n * @returns A string containing the formatted error output with colorized text, code snippet, and stack trace\n *\n * @remarks\n * - Constructs a formatted error output from pre-parsed stack metadata.\n * - Displays the error name and message at the top with {@link xterm.lightCoral} highlighting.\n * - Includes any additional notes in gray text below the error message.\n * - Appends syntax-highlighted code snippet if available in metadata.\n * - Appends formatted stack trace frames with proper indentation under \"Enhanced Stack Trace\".\n * - All formatting and syntax highlighting should be pre-applied in the metadata.\n *\n * @example\n * ```ts\n * const metadata: StackInterface = {\n * code: \"const x = undefined;\\nx.toString();\",\n * line: 2,\n * column: 1,\n * source: \"/path/to/file.ts\",\n * stacks: [\"at Object.<anonymous> (/path/to/file.ts:2:1)\"],\n * formatCode: \"1 | const x = undefined;\\n2 | x.toString();\\n ^\"\n * };\n *\n * const notes = [{ text: \"Did you forget to check for null?\" }];\n * console.log(formatStack(metadata, \"TypeError\", \"Cannot read property 'toString' of undefined\", notes));\n * ```\n *\n * @see xterm\n * @see PartialMessage\n * @see StackInterface\n * @see getErrorMetadata\n *\n * @since 2.0.0\n */\n\nexport function formatStack(metadata: StackInterface, name: string, message: string, notes: PartialMessage['notes'] = []): string {\n const parts = [ `\\n${ name }: ${ xterm.lightCoral(message) }` ];\n for (const note of notes ?? []) {\n if(note.text) parts.push('\\n ' + xterm.gray(note.text));\n }\n\n if (metadata.formatCode) parts.push(`\\n\\n${ metadata.formatCode }`);\n if (metadata.stacks.length) {\n parts.push(`\\n\\nEnhanced Stack Trace:\\n ${ metadata.stacks.join('\\n ') }\\n`);\n }\n\n return parts.join('');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { FileSnapshotInterface, ScriptSnapshotType } from './interfaces/files-model.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { resolve } from '@components/path.component';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { closeSync, fstatSync, openSync, readFileSync } from 'fs';\n\n/**\n * In-memory cache that maintains lightweight snapshots of file contents (as TypeScript `IScriptSnapshot`)\n * together with modification time and version counters.\n *\n * Primarily used by language servers, transpiler, and incremental build systems to avoid unnecessary\n * file system reads and snapshot recreation when files have not changed.\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class FilesModel {\n /**\n * Cache that maps original (possibly relative) paths \u2192 normalized absolute paths with forward slashes\n * @since 2.0.0\n */\n\n private readonly resolvedPathCache = new Map<string, string>();\n\n /**\n * Main storage: resolved absolute path \u2192 current file snapshot state\n * @since 2.0.0\n */\n\n private readonly snapshotsByPath = new Map<string, FileSnapshotInterface>();\n\n /**\n * Removes all cached paths and snapshots.\n * @since 2.0.0\n */\n\n clear(): void {\n this.snapshotsByPath.clear();\n this.resolvedPathCache.clear();\n }\n\n /**\n * Returns the current known snapshot state for the given file path, or `undefined`\n * if the file has never been touched/observed by this cache.\n *\n * @param path - filesystem path (relative or absolute)\n * @returns current snapshot data or `undefined` if not tracked yet\n *\n * @since 2.0.0\n */\n\n getSnapshot(path: string): FileSnapshotInterface | undefined {\n return this.snapshotsByPath.get(this.resolve(path));\n }\n\n /**\n * Returns an existing snapshot entry for the given file path, or creates/updates it if not tracked yet.\n *\n * @param path - Filesystem path (relative or absolute).\n * @returns The current snapshot entry for the file (existing or newly created).\n *\n * @remarks\n * This is a convenience method combining:\n * - {@link getSnapshot} (fast path when already tracked), and\n * - {@link touchFile} (tracks the file, reads content if needed, updates version/mtime).\n *\n * Use this when you need a snapshot entry and don't want to handle the `undefined` case.\n *\n * @see {@link touchFile}\n * @see {@link getSnapshot}\n *\n * @since 2.0.0\n */\n\n getOrTouchFile(path: string): FileSnapshotInterface {\n return this.snapshotsByPath.get(this.resolve(path)) ?? this.touchFile(path);\n }\n\n /**\n * Returns array containing all currently tracked resolved absolute paths.\n *\n * @returns list of normalized absolute paths (using forward slashes)\n *\n * @since 2.0.0\n */\n\n getTrackedFilePaths(): Array<string> {\n return [ ...this.snapshotsByPath.keys() ];\n }\n\n /**\n * Ensures the file is tracked and returns an up-to-date snapshot state.\n *\n * @param path - Filesystem path (relative or absolute)\n * @returns Shallow copy of the current (possibly just updated) snapshot entry\n *\n * @remarks\n * This method implements incremental file tracking with three possible outcomes:\n *\n * **Fast path (no changes):**\n * - mtime hasn't changed \u2192 returns existing state without I/O\n *\n * **Update path (file changed):**\n * - mtime changed or file is new \u2192 reads content and creates fresh `ScriptSnapshot`\n * - Increments version number for TypeScript language service invalidation\n *\n * **Error path (file unavailable):**\n * - File cannot be read (deleted/permission denied) \u2192 clears snapshot and bumps version\n * - Version increment only occurs if there was previous content (prevents silent no-ops)\n *\n * Always returns a shallow copy to prevent accidental mutation of internal state.\n *\n * Typically used in watch mode to notify TypeScript of file changes without full rebuilds.\n *\n * @example\n * ```ts\n * const snapshot = filesModel.touchFile('./src/index.ts');\n *\n * if (snapshot.contentSnapshot) {\n * languageServiceHost.getScriptSnapshot = () => snapshot.contentSnapshot;\n * languageServiceHost.getScriptVersion = () => String(snapshot.version);\n * }\n * ```\n *\n * @see {@link getSnapshot}\n * @see {@link FileSnapshotInterface}\n *\n * @since 2.0.0\n */\n\n touchFile(path: string): FileSnapshotInterface {\n const resolvedPath = this.resolve(path);\n const entry = this.snapshotsByPath.get(resolvedPath) ?? this.createEntry(resolvedPath);\n\n try {\n this.syncEntry(resolvedPath, entry);\n } catch {\n /**\n * Currently, the catch block only increments the version if the snapshot exists, otherwise silently ignores errors.\n * Suggestion: always increase the version if the file cannot be read, so TS will treat it as changed.\n */\n\n if(entry.contentSnapshot !== undefined || entry.version > 0) {\n entry.version++;\n entry.mtimeMs = 0;\n entry.contentSnapshot = undefined;\n }\n }\n\n return { ...entry };\n }\n\n /**\n * Normalizes the given path to an absolute path using forward slashes.\n * Results are cached to avoid repeated `path.resolve` + replace calls.\n *\n * @param path - any filesystem path\n * @returns normalized absolute path (always `/` separators)\n *\n * @since 2.0.0\n */\n\n resolve(path: string): string {\n const cached = this.resolvedPathCache.get(path);\n if (cached) return cached;\n\n const resolved = resolve(path);\n this.resolvedPathCache.set(path, resolved);\n\n return resolved;\n }\n\n /**\n * Creates a new snapshot entry for a resolved file path and registers it in the cache.\n *\n * @param resolvedPath - Normalized absolute file path\n * @returns A new {@link FileSnapshotInterface} with initial state (version 0, no content)\n *\n * @remarks\n * This method initializes a new file tracking entry with default values:\n * - `version`: 0 (will increment on first read)\n * - `mtimeMs`: 0 (will update on first sync)\n * - `contentSnapshot`: undefined (will populate on first sync)\n *\n * The entry is immediately added to {@link snapshotsByPath} to prevent duplicate creation.\n *\n * Called internally by {@link touchFile} when encountering a previously unseen file path.\n *\n * @since 2.1.5\n */\n\n private createEntry(resolvedPath: string): FileSnapshotInterface {\n const entry: FileSnapshotInterface = { version: 0, mtimeMs: 0, contentSnapshot: undefined };\n this.snapshotsByPath.set(resolvedPath, entry);\n\n return entry;\n }\n\n /**\n * Synchronizes a snapshot entry with the current file system state.\n *\n * @param resolvedPath - Normalized absolute path to the file\n * @param entry - The snapshot entry to update\n *\n * @remarks\n * This method performs efficient incremental updates:\n *\n * **Optimization check:**\n * - Compares current mtime with cached mtime\n * - Returns immediately if file hasn't changed (fast path)\n *\n * **Update logic:**\n * - Reads file content only when mtime differs\n * - Increments version for TypeScript invalidation\n * - Updates mtime to current value\n * - Creates TypeScript `ScriptSnapshot` from content\n *\n * **File descriptor handling:**\n * - Opens file in read mode (`'r'`)\n * - Ensures file descriptor closure via `finally` block\n * - Throws on read errors (handled by caller)\n *\n * Empty file content results in `undefined` snapshot rather than empty snapshot,\n * signaling that the file has no compilable content.\n *\n * @throws Will propagate file system errors (ENOENT, EACCES, etc.) to caller\n *\n * @since 2.1.5\n */\n\n private syncEntry(resolvedPath: string, entry: FileSnapshotInterface): void {\n const fd = openSync(resolvedPath, 'r');\n\n try {\n const { mtimeMs } = fstatSync(fd);\n if (mtimeMs === entry.mtimeMs) return;\n const content = readFileSync(fd, 'utf-8');\n\n entry.version++;\n entry.mtimeMs = mtimeMs;\n entry.contentSnapshot = content\n ? <ScriptSnapshotType> ts.ScriptSnapshot.fromString(content)\n : undefined;\n } finally {\n closeSync(fd);\n }\n }\n}\n", "/**\n * Import\n */\n\nimport * as path from 'path';\nimport * as pathPosix from 'path/posix';\n\n/**\n * Regular expression to match backslashes in file paths.\n *\n * @remarks\n * Used by {@link toPosix} to convert Windows-style backslash path separators\n * to POSIX-style forward slashes for cross-platform path normalization.\n *\n * Matches: `\\`\n *\n * @since 2.0.0\n */\n\nconst BACKSLASH_RE = /\\\\/g;\n\n/**\n * Regular expression to match consecutive forward slashes in file paths.\n *\n * @remarks\n * Used by {@link toPosix} to normalize paths by collapsing multiple consecutive\n * forward slashes into a single slash. This ensures consistent path formatting\n * across different platforms and input sources.\n *\n * Matches: Two or more forward slashes (`//`, `///`, etc.)\n *\n * @since 2.0.0\n */\n\nconst DUPLICATE_SLASH_RE = /\\/+/g;\n\n/**\n * Converts a file path to POSIX format by normalizing backslashes and duplicate slashes.\n *\n * @param input - The file path to convert (can be null or undefined)\n *\n * @returns The path in POSIX format with forward slashes, or an empty string if input is falsy\n *\n * @remarks\n * This function performs the following transformations:\n * 1. Converts all backslashes (`\\`) to forward slashes (`/`)\n * 2. Collapses consecutive forward slashes into a single slash\n * 3. Returns an empty string for null, undefined, or empty input\n *\n * This is useful for normalizing Windows-style paths to POSIX-style paths for\n * cross-platform compatibility in build tools and file processing.\n *\n * @example Converting Windows path\n * ```ts\n * const windowsPath = 'C:\\\\Users\\\\Documents\\\\file.txt';\n * const posixPath = toPosix(windowsPath);\n * // 'C:/Users/Documents/file.txt'\n * ```\n *\n * @example Normalizing duplicate slashes\n * ```ts\n * const messyPath = 'src//components///Button.tsx';\n * const cleanPath = toPosix(messyPath);\n * // 'src/components/Button.tsx'\n * ```\n *\n * @example Handling falsy values\n * ```ts\n * toPosix(null); // ''\n * toPosix(undefined); // ''\n * toPosix(''); // ''\n * ```\n *\n * @since 2.0.0\n */\n\nexport function toPosix(input: string | null | undefined): string {\n if (!input) return '';\n\n let p = String(input);\n p = p.replace(BACKSLASH_RE, '/');\n p = p.replace(DUPLICATE_SLASH_RE, '/');\n\n return p;\n}\n\n/**\n * Normalizes a file path to POSIX format and resolves `.` and `..` segments.\n *\n * @param path - The file path to normalize\n *\n * @returns The normalized POSIX path with resolved relative segments\n *\n * @remarks\n * This function:\n * 1. Converts the path to POSIX format using {@link toPosix}\n * 2. Applies `path.posix.normalize()` to resolve `.` and `..` segments\n * 3. Removes trailing slashes (except for root `/`)\n *\n * @example Resolving relative segments\n * ```ts\n * const path = 'src/components/../utils/./helper.ts';\n * const normalized = normalize(path);\n * // 'src/utils/helper.ts'\n * ```\n *\n * @example Normalizing Windows path\n * ```ts\n * const windowsPath = 'C:\\\\Users\\\\..\\\\Documents\\\\file.txt';\n * const normalized = normalize(windowsPath);\n * // 'C:/Documents/file.txt'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function normalize(path: string): string {\n return pathPosix.normalize(toPosix(path));\n}\n\n/**\n * Joins multiple path segments into a single POSIX path.\n *\n * @param paths - Path segments to join\n *\n * @returns The joined path in POSIX format with normalized separators\n *\n * @remarks\n * This function:\n * 1. Converts each path segment to POSIX format using {@link toPosix}\n * 2. Joins them using `path.posix.join()`\n * 3. Normalizes the result (resolves `.` and `..`, removes duplicate slashes)\n *\n * @example Joining path segments\n * ```ts\n * const fullPath = join('src', 'components', 'Button.tsx');\n * // 'src/components/Button.tsx'\n * ```\n *\n * @example Joining mixed-format paths\n * ```ts\n * const fullPath = join('C:\\\\Users', 'Documents', '../Pictures/photo.jpg');\n * // 'C:/Users/Pictures/photo.jpg'\n * ```\n *\n * @example Joining with empty segments\n * ```ts\n * const fullPath = join('src', '', 'utils');\n * // 'src/utils'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function join(...paths: Array<string>): string {\n return pathPosix.join(...paths.map(toPosix));\n}\n\n/**\n * Resolves a sequence of paths into an absolute POSIX path.\n *\n * @param paths - Path segments to resolve (processed right-to-left until an absolute path is found)\n *\n * @returns The resolved absolute path in POSIX format\n *\n * @remarks\n * This function:\n * 1. Uses Node.js `path.resolve()` to compute the absolute path\n * 2. Converts the result to POSIX format using {@link toPosix}\n * 3. Processes paths right-to-left, stopping at the first absolute path\n *\n * The resolution process:\n * - If no absolute path is found, prepends the current working directory\n * - Relative segments (`.` and `..`) are resolved\n * - The result is always an absolute path\n *\n * @example Resolving relative paths\n * ```ts\n * // Current directory: /home/user/project\n * const absolutePath = resolve('src', 'components', 'Button.tsx');\n * // '/home/user/project/src/components/Button.tsx'\n * ```\n *\n * @example Resolving with an absolute path\n * ```ts\n * const absolutePath = resolve('/var/www', 'html', 'index.html');\n * // '/var/www/html/index.html'\n * ```\n *\n * @example Resolving on Windows\n * ```ts\n * // Current directory: C:\\Users\\project\n * const absolutePath = resolve('src\\\\utils', '../components/Button.tsx');\n * // 'C:/Users/project/src/components/Button.tsx'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function resolve(...paths: Array<string>): string {\n return toPosix(path.resolve(...paths));\n}\n\n/**\n * Returns the directory name of a path in POSIX format.\n *\n * @param p - The file path\n *\n * @returns The directory portion of the path, or `.` for paths without a directory component\n *\n * @remarks\n * This function:\n * 1. Converts the path to POSIX format using {@link toPosix}\n * 2. Extracts the directory portion using `path.posix.dirname()`\n * 3. Removes the last segment (file or final directory name)\n *\n * @example Getting directory name\n * ```ts\n * const dir = dirname('/home/user/file.txt');\n * // '/home/user'\n * ```\n *\n * @example Windows path\n * ```ts\n * const dir = dirname('C:\\\\Users\\\\Documents\\\\file.txt');\n * // 'C:/Users/Documents'\n * ```\n *\n * @example Path without directory\n * ```ts\n * const dir = dirname('file.txt');\n * // '.'\n * ```\n *\n * @example Root path\n * ```ts\n * const dir = dirname('/file.txt');\n * // '/'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function dirname(p: string): string {\n return toPosix(path.dirname(p));\n}\n\n/**\n * Calculates the relative path from one location to another in POSIX format.\n *\n * @param from - The source path (starting point)\n * @param to - The destination path (target)\n *\n * @returns The relative path from `from` to `to`, or `.` if paths are identical\n *\n * @remarks\n * This function:\n * 1. Converts both paths to POSIX format using {@link toPosix}\n * 2. Computes the relative path using `path.posix.relative()`\n * 3. Returns `.` when the result is empty (indicating the same location)\n *\n * The relative path uses `..` to navigate up directories and includes only\n * the necessary segments to reach the destination from the source.\n *\n * @example Basic relative path\n * ```ts\n * const rel = relative('/home/user/project', '/home/user/docs/file.txt');\n * // '../docs/file.txt'\n * ```\n *\n * @example Same directory\n * ```ts\n * const rel = relative('/home/user', '/home/user');\n * // '.'\n * ```\n *\n * @example Windows paths\n * ```ts\n * const rel = relative('C:\\\\Users\\\\project\\\\src', 'C:\\\\Users\\\\project\\\\dist\\\\bundle.js');\n * // '../dist/bundle.js'\n * ```\n *\n * @example Sibling directories\n * ```ts\n * const rel = relative('/app/src/components', '/app/src/utils');\n * // '../utils'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function relative(from: string, to: string): string {\n return pathPosix.relative(toPosix(from), toPosix(to)) || '.';\n}\n\n/**\n * Returns the last portion of a path (filename or directory name) in POSIX format.\n *\n * @param p - The file path\n * @param suffix - Optional file extension to remove from the result\n *\n * @returns The base name of the path, optionally with the suffix removed\n *\n * @remarks\n * This function:\n * 1. Converts the path to POSIX format using {@link toPosix}\n * 2. Extracts the final segment using `path.posix.basename()`\n * 3. Optionally removes the specified suffix if it matches the end of the basename\n *\n * The suffix parameter is useful for extracting filenames without extensions.\n *\n * @example Getting filename\n * ```ts\n * const name = basename('/home/user/documents/report.pdf');\n * // 'report.pdf'\n * ```\n *\n * @example Removing extension\n * ```ts\n * const name = basename('/home/user/documents/report.pdf', '.pdf');\n * // 'report'\n * ```\n *\n * @example Windows path\n * ```ts\n * const name = basename('C:\\\\Users\\\\Documents\\\\file.txt');\n * // 'file.txt'\n * ```\n *\n * @example Directory name\n * ```ts\n * const name = basename('/home/user/documents/');\n * // 'documents'\n * ```\n *\n * @example Suffix doesn't match\n * ```ts\n * const name = basename('file.txt', '.md');\n * // 'file.txt'\n * ```\n *\n * @see {@link toPosix} for path conversion\n *\n * @since 2.0.0\n */\n\nexport function basename(p: string, suffix?: string): string {\n return toPosix(path.basename(p, suffix));\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PositionInterface } from '@remotex-labs/xmap';\n\n/**\n * Imports\n */\n\nimport { readFileSync } from 'fs';\nimport { SourceService } from '@remotex-labs/xmap';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { resolve, toPosix } from '@components/path.component';\n\n/**\n * Provides access to the framework's file paths and associated source maps.\n *\n * @remarks\n * This service manages the framework's source map files, including the main framework\n * file and any additional source files. It caches initialized {@link SourceService}\n * instances for performance.\n *\n * @example\n * ```ts\n * const frameworkService = new FrameworkService();\n * console.log(frameworkService.rootPath);\n * const sourceMap = frameworkService.sourceMap(frameworkService.filePath);\n * ```\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class FrameworkService {\n /**\n * Absolute path to the current file.\n *\n * @readonly\n * @since 2.0.0\n */\n\n readonly filePath: string;\n\n /**\n * Absolute path to the distribution directory.\n *\n * @readonly\n * @since 2.0.0\n */\n\n readonly distPath: string;\n\n /**\n * Absolute path to the project root directory.\n *\n * @readonly\n * @since 2.0.0\n */\n\n readonly rootPath: string;\n\n /**\n * Cached {@link SourceService} instances for additional source files.\n * @since 2.0.0\n */\n\n private readonly sourceMaps = new Map<string, SourceService>();\n\n /**\n * Initializes a new {@link FrameworkService} instance.\n *\n * @remarks\n * Sets up the main framework source map, as well as root and distribution paths.\n *\n * @since 2.0.0\n */\n\n constructor() {\n this.filePath = import.meta.filename;\n this.setSourceFile(this.filePath);\n\n this.rootPath = this.getRootDir();\n this.distPath = this.getDistDir();\n }\n\n /**\n * Determines whether a given {@link PositionInterface} refers to a framework file.\n *\n * @param position - The position information to check\n * @returns `true` if the position is from the framework (contains \"xJet\"), otherwise `false`\n *\n * @see PositionInterface\n * @since 1.0.0\n */\n\n isFrameworkFile(position: PositionInterface): boolean {\n const { source, sourceRoot } = position;\n const lowerCaseSource = source?.toLowerCase();\n\n return Boolean(\n (source && lowerCaseSource.includes('xbuild') && !lowerCaseSource.includes('xbuild.config')) ||\n (sourceRoot && sourceRoot.includes('xBuild'))\n );\n }\n\n /**\n * Retrieves a cached {@link SourceService} for a given file path.\n *\n * @param path - Absolute path to the file\n * @returns A {@link SourceService} instance if found, otherwise `undefined`\n *\n * @remarks\n * Paths are normalized before lookup. Only previously initialized source maps\n * (via {@link setSource} or {@link setSourceFile}) are available in the cache.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n getSourceMap(path: string): SourceService | undefined {\n path = resolve(path);\n if (this.sourceMaps.has(path))\n return this.sourceMaps.get(path)!;\n\n return undefined;\n }\n\n /**\n * Registers and initializes a new {@link SourceService} for a provided source map string.\n *\n * @param source - The raw source map content\n * @param path - Absolute file path associated with the source map\n * @returns A new or cached {@link SourceService} instance\n *\n * @throws Error if initialization fails\n *\n * @remarks\n * If a source map for the given path is already cached, the cached instance is returned.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n setSource(source: string, path: string): void {\n const key = resolve(path);\n\n try {\n return this.initializeSourceMap(source, key);\n } catch (error) {\n throw new Error(\n `Failed to initialize SourceService: ${ key }\\n${ error instanceof Error ? error.message : String(error) }`\n );\n }\n }\n\n /**\n * Loads and initializes a {@link SourceService} for a file and its `.map` companion.\n *\n * @param path - Absolute path to the file\n * @returns A new or cached {@link SourceService} instance\n *\n * @throws Error if the `.map` file cannot be read or parsed\n *\n * @remarks\n * This method attempts to read the `.map` file located next to the provided file.\n * If already cached, returns the existing {@link SourceService}.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n setSourceFile(path: string): void {\n if(!path) return;\n\n const key = resolve(path);\n const map = `${ path }.map`;\n\n if (this.sourceMaps.has(key))\n return;\n\n try {\n const sourceMapData = readFileSync(map, 'utf-8');\n\n return this.initializeSourceMap(sourceMapData, key);\n } catch (error) {\n throw new Error(\n `Failed to initialize SourceService: ${ key }\\n${ error instanceof Error ? error.message : String(error) }`\n );\n }\n }\n\n /**\n * Retrieves the project root directory.\n * @returns Absolute path to the project root\n *\n * @since 2.0.0\n */\n\n private getRootDir(): string {\n return toPosix(process.cwd());\n }\n\n /**\n * Retrieves the distribution directory.\n * @returns Absolute path to the distribution folder\n *\n * @since 2.0.0\n */\n\n private getDistDir(): string {\n return toPosix(import.meta.dirname);\n }\n\n /**\n * Creates and caches a new {@link SourceService} instance for a given source map.\n *\n * @param source - Raw source map content\n * @param path - Normalized file path used as the cache key\n * @returns The newly created {@link SourceService} instance\n *\n * @remarks\n * This method is only used internally by {@link setSource} and {@link setSourceFile}.\n * The instance is cached in {@link sourceMaps} for reuse.\n *\n * @see SourceService\n * @since 2.0.0\n */\n\n private initializeSourceMap(source: string, path: string): void {\n if(source?.includes('\"mappings\": \"\"'))\n return;\n\n const sourceMap = new SourceService(source, path);\n this.sourceMaps.set(path, sourceMap);\n }\n}\n", "/**\n * Imports\n */\n\nimport { Observable } from '@observable/observable.module';\n\n/**\n * Transforms each emitted value using the provided transformation function.\n *\n * @template T - The input value type.\n * @template R - The output value type after transformation.\n *\n * @param project - Function that transforms each input value to an output value.\n * @returns An operator function that creates a new observable with transformed values.\n *\n * @throws Error - If the project function throws, the error is caught and emitted to the observer.\n *\n * @remarks\n * The `map` operator applies a transformation function to every value emitted by the source\n * observable and emits the transformed values. Errors thrown by the project function are\n * automatically caught and passed to the observer's error handler.\n *\n * Common use cases:\n * - Converting data formats (string to number, object property extraction)\n * - Mathematical transformations (doubling, negation)\n * - Type conversions and casting\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>((observer) => {\n * observer.next?.(5);\n * observer.next?.(10);\n * });\n *\n * const doubled = numbers.pipe(map((x) => x * 2));\n *\n * doubled.subscribe((value) => console.log(value)); // Outputs: 10, 20\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function map<T, R>(project: (value: T) => R) {\n return (source: Observable<T>): Observable<R> => {\n return new Observable<R>((observer) => {\n return source.subscribe({\n next: (value) => {\n try {\n const result = project(value);\n observer.next?.(result);\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n\n/**\n * Emits only values that are different from the previously emitted value.\n *\n * @template T - The type of values being compared.\n *\n * @param compareFn - Optional comparison function to determine equality. Defaults to strict equality (`===`).\n * @returns An operator function that creates a new observable with only distinct consecutive values.\n *\n * @remarks\n * The `distinctUntilChanged` operator filters out consecutive duplicate values using the provided\n * comparison function. Only values that differ from the last emitted value are passed through.\n * This is particularly useful for reducing redundant emissions when state changes are minimal.\n *\n * The comparison function receives the previous and current values and should return `true`\n * if they are considered equal (and thus should be filtered), or `false` if they are different\n * (and thus should be emitted).\n *\n * Errors thrown by the comparison function are caught and emitted to the observer's error handler.\n *\n * Common use cases:\n * - Avoiding redundant updates (e.g., state management)\n * - Filtering out echoed or repeated sensor data\n * - Preventing unnecessary re-renders in UI frameworks\n *\n * @example\n * ```ts\n * const values = new Observable<number>((observer) => {\n * observer.next?.(1);\n * observer.next?.(1);\n * observer.next?.(2);\n * observer.next?.(2);\n * observer.next?.(3);\n * });\n *\n * const distinct = values.pipe(distinctUntilChanged());\n *\n * distinct.subscribe((value) => console.log(value)); // Outputs: 1, 2, 3\n * ```\n *\n * @example\n * ```ts\n * // Custom comparison for objects\n * interface User { id: number; name: string; }\n *\n * const users = new Observable<User>((observer) => {\n * observer.next?.({ id: 1, name: 'Alice' });\n * observer.next?.({ id: 1, name: 'Alice' });\n * observer.next?.({ id: 2, name: 'Bob' });\n * });\n *\n * const distinctUsers = users.pipe(\n * distinctUntilChanged((prev, curr) => prev.id === curr.id)\n * );\n *\n * distinctUsers.subscribe((user) => console.log(user.name));\n * // Outputs: \"Alice\", \"Bob\"\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function distinctUntilChanged<T>(\n compareFn: (previous: T, current: T) => boolean = (a, b) => a === b\n) {\n return (source: Observable<T>): Observable<T> => {\n return new Observable<T>((observer) => {\n let hasPrevious = false;\n let previous: T;\n\n return source.subscribe({\n next: (value) => {\n try {\n if(!hasPrevious) {\n previous = value;\n hasPrevious = true;\n observer.next?.(value);\n\n return;\n }\n\n if (!compareFn(previous, value)) {\n previous = value;\n observer.next?.(value);\n }\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n\n/**\n * Filters emitted values based on a predicate function.\n *\n * @template T - The type of values being filtered.\n *\n * @param predicate - Function that returns `true` if the value should pass through, `false` otherwise.\n * @returns An operator function that creates a new observable with only filtered values.\n *\n * @remarks\n * The `filter` operator only emits values that satisfy the predicate condition. Values that\n * do not match the condition are silently skipped. All other events (error, complete) are\n * passed through unchanged.\n *\n * Errors thrown by the predicate function are caught and passed to the observer's error handler.\n *\n * Common use cases:\n * - Filtering by value range (e.g., only positive numbers)\n * - Filtering by type or property (e.g., only objects with specific properties)\n * - Conditional emission based on complex logic\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>((observer) => {\n * observer.next?.(1);\n * observer.next?.(2);\n * observer.next?.(3);\n * observer.next?.(4);\n * observer.next?.(5);\n * });\n *\n * const evens = numbers.pipe(filter((x) => x % 2 === 0));\n *\n * evens.subscribe((value) => console.log(value)); // Outputs: 2, 4\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function filter<T>(predicate: (value: T) => boolean) {\n return (source: Observable<T>): Observable<T> => {\n return new Observable<T>((observer) => {\n return source.subscribe({\n next: (value) => {\n try {\n if (predicate(value)) {\n observer.next?.(value);\n }\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n\n/**\n * Performs a side effect for each emitted value without modifying the value.\n *\n * @template T - The type of values being processed.\n *\n * @param sideEffect - Function to execute for each emitted value. The return value is ignored.\n * @returns An operator function that creates a new observable with the side effect applied.\n *\n * @remarks\n * The `tap` operator is used for debugging, logging, or triggering side effects without\n * altering the data flow. The provided function is called for each emitted value, and the\n * original value is passed through unchanged to the resulting observable.\n *\n * Errors thrown by the side effect function are caught and passed to the observer's error handler.\n * The original value is NOT emitted if the side effect throws an error.\n *\n * Common use cases:\n * - Logging values for debugging\n * - Triggering analytics or tracking events\n * - Updating external state or UI without changing the stream\n * - Performance monitoring\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>((observer) => {\n * observer.next?.(5);\n * observer.next?.(10);\n * });\n *\n * const logged = numbers.pipe(\n * tap((x) => console.log(`Processing: ${x}`))\n * );\n *\n * logged.subscribe((value) => console.log(`Received: ${value}`));\n * // Outputs:\n * // Processing: 5\n * // Received: 5\n * // Processing: 10\n * // Received: 10\n * ```\n *\n * @see Observable\n * @see OperatorFunctionType\n *\n * @since 2.0.0\n */\n\nexport function tap<T>(sideEffect: (value: T) => void) {\n return (source: Observable<T>): Observable<T> => {\n return new Observable<T>((observer) => {\n return source.subscribe({\n next: (value) => {\n try {\n sideEffect(value);\n observer.next?.(value);\n } catch (err) {\n observer.error?.(err);\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.()\n });\n });\n };\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ObserverInterface, UnsubscribeType } from '@observable/observable.module';\nimport type { NextType, ErrorType, CompleteType, OperatorFunctionType } from '@observable/observable.module';\n\n/**\n * Represents a push-based collection of values that can be observed over time\n *\n * This is the core type of lightweight observable implementation.\n * It allows subscription, safe error handling and operator chaining via pipe.\n *\n * @template T - Type of values emitted by this observable\n *\n * @example\n * ```ts\n * const numbers = new Observable<number>(observer => {\n * [1, 2, 3].forEach(v => observer.next?.(v));\n * observer.complete?.();\n * return () => console.log('cleaned up');\n * });\n *\n * const sub = numbers.subscribe({\n * next: v => console.log(v),\n * complete: () => console.log('done')\n * });\n *\n * sub(); // triggers cleanup\n * ```\n *\n * @see {@link pipe}\n * @see {@link ObserverInterface}\n * @see {@link OperatorFunctionType}\n *\n * @since 2.0.0\n */\n\nexport class ObservableService<T = unknown> {\n /**\n * Creates a new observable service with a subscription handler.\n *\n * @param handler - Function called when someone subscribes.\n * It receives an observer and returns an optional cleanup function.\n *\n * @remarks\n * The handler function is called immediately when {@link subscribe} is invoked.\n * It receives the observer object and is responsible for:\n * - Calling `observer.next()` to emit values\n * - Calling `observer.error()` to emit errors\n * - Calling `observer.complete()` to signal completion\n * - Returning an optional cleanup function for resource management\n *\n * This design pattern allows for lazy initialization, external event binding and\n * fine-grained control over subscription lifecycle.\n *\n * @example\n * ```ts\n * const timerObservable = new ObservableService<number>((observer) => {\n * let count = 0;\n * const intervalId = setInterval(() => {\n * observer.next?.(count++);\n * }, 1000);\n *\n * // Return cleanup function\n * return () => clearInterval(intervalId);\n * });\n * ```\n *\n * @see ObserverInterface\n * @since 2.0.0\n */\n\n constructor(\n private readonly handler: (observer: ObserverInterface<T>) => UnsubscribeType | void\n ) {}\n\n /**\n * Subscribes to this observable and receives values, errors and completion\n *\n * @param observerOrNext - Either a full observer object or just the next handler\n * @param error - Optional error handler\n * @param complete - Optional completion handler\n * @returns Unsubscribe function \u2014 call it to stop receiving values and clean up\n *\n * @remarks\n * Supports three overload styles:\n * 1. Single observer object\n * 2. Separate next/error/complete callbacks\n * 3. Only the next callback (error and complete are optional)\n *\n * @example\n * ```ts\n * // Object style\n * subscription = source.subscribe({\n * next: v => console.log(v),\n * error: e => console.error(e),\n * complete: () => console.log('completed')\n * });\n *\n * // Callback style\n * subscription = source.subscribe(\n * v => console.log(v),\n * e => console.error(e),\n * () => console.log('completed')\n * );\n * ```\n *\n * @since 2.0.0\n */\n\n subscribe(\n observerOrNext?: ObserverInterface<T> | NextType<T>,\n error?: ErrorType,\n complete?: CompleteType\n ): UnsubscribeType {\n const observer = this.createSafeObserver(observerOrNext, error, complete);\n let cleanup: UnsubscribeType | void;\n\n try {\n cleanup = this.handler(observer);\n } catch (err) {\n observer.error?.(err);\n\n return () => {};\n }\n\n return () => {\n try {\n cleanup?.();\n } catch (err) {\n observer.error?.(err);\n }\n };\n }\n\n /**\n * Chains zero or more operators to transform this observable\n *\n * When called without arguments returns the same observable (identity).\n * Each operator receives the previous observable and returns a new one.\n *\n * @remarks\n * Type signatures are overloaded up to 5 explicit operators for best type inference.\n * After that, a rest version is used with weaker type information (the result is `Observable<T>`).\n *\n * @returns New observable (or same when no operators given)\n *\n * @since 2.0.0\n */\n\n pipe(): this;\n\n /**\n * Chains one observable operator to transform the observable.\n *\n * @template A - The output type of the first operator.\n *\n * @param op1 - First operator function to apply.\n * @returns An observable transformed by the operator.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A>(\n op1: OperatorFunctionType<T, A>\n ): ObservableService<A>;\n\n /**\n * Chains two observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @returns An observable transformed by both operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B>(\n op1: OperatorFunctionType<T, A>, op2: OperatorFunctionType<A, B>\n ): ObservableService<B>;\n\n /**\n * Chains three observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @returns An observable transformed by all three operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>\n ): ObservableService<C>;\n\n /**\n * Chains four observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n * @template D - The output type of the fourth operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @param op4 - Fourth operator function to apply.\n * @returns An observable transformed by all four operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C, D>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>,\n op4: OperatorFunctionType<C, D>\n ): ObservableService<D>;\n\n /**\n * Chains five observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n * @template D - The output type of the fourth operator.\n * @template E - The output type of the fifth operator.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @param op4 - Fourth operator function to apply.\n * @param op5 - Fifth operator function to apply.\n * @returns An observable transformed by all five operators in sequence.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C, D, E>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>,\n op4: OperatorFunctionType<C, D>,\n op5: OperatorFunctionType<D, E>\n ): ObservableService<E>;\n\n /**\n * Chains five or more observable operators to transform the observable.\n *\n * @template A - The output type of the first operator.\n * @template B - The output type of the second operator.\n * @template C - The output type of the third operator.\n * @template D - The output type of the fourth operator.\n * @template E - The output type of the fifth operator.\n * @template Ops - Tuple type of additional operator functions beyond the first five.\n *\n * @param op1 - First operator function to apply.\n * @param op2 - Second operator function to apply.\n * @param op3 - Third operator function to apply.\n * @param op4 - Fourth operator function to apply.\n * @param op5 - Fifth operator function to apply.\n * @param operations - Additional operator functions to apply sequentially.\n * @returns An observable transformed by all operators in sequence with the output type inferred from the final operator.\n *\n * @see {@link pipe} for implementation details\n * @since 2.0.0\n */\n\n pipe<A, B, C, D, E, Ops extends Array<OperatorFunctionType>>(\n op1: OperatorFunctionType<T, A>,\n op2: OperatorFunctionType<A, B>,\n op3: OperatorFunctionType<B, C>,\n op4: OperatorFunctionType<C, D>,\n op5: OperatorFunctionType<D, E>,\n ...operations: Ops\n ): ObservableService<\n Ops extends [...Array<unknown>, OperatorFunctionType<unknown, infer R>] ? R : T\n >;\n\n /**\n * Internal implementation of the pipe operator chain.\n *\n * @param operators - Array of operator functions to be reduced over the observable.\n * @returns The final transformed observable, or the original observable if no operators are provided.\n *\n * @remarks\n * This is the concrete implementation that executes the operator chain using a reducer pattern.\n * Each operator receives the current observable and returns a transformed observable, which becomes\n * the input for the next operator. The chain begins with the current observable instance.\n *\n * If the operator array is empty, the method returns the current observable unchanged, allowing\n * for safe calling of `pipe()` without arguments.\n *\n * Operators are applied sequentially from left to right, enabling composition of multiple\n * transformations such as mapping, filtering, debouncing and other value manipulations.\n *\n * @example\n * ```ts\n * const source = new ObservableService<number>((observer) => {\n * observer.next?.(10);\n * observer.next?.(20);\n * });\n *\n * // With operators\n * const doubled = source.pipe(\n * (obs) => new ObservableService((observer) =>\n * obs.subscribe((v) => observer.next?.(v * 2))\n * )\n * );\n *\n * // Without operators\n * const same = source.pipe();\n * ```\n *\n * @see OperatorFunctionType\n * @since 2.0.0\n */\n\n pipe<R = ObservableService<T>>(...operators: Array<OperatorFunctionType>): R {\n if (operators.length === 0) {\n return this as unknown as R;\n }\n\n return <R> operators.reduce<ObservableService>(\n (prev, op) => op(prev),\n this as ObservableService\n );\n }\n\n /**\n * Converts subscribe arguments into a consistent ObserverInterface shape\n *\n * @remarks Internal helper \u2013 not meant to be called directly\n *\n * @since 2.0.0\n */\n\n protected createSafeObserver(\n observerOrNext?: ObserverInterface<T> | NextType<T>,\n error?: ErrorType,\n complete?: CompleteType\n ): ObserverInterface<T> {\n return typeof observerOrNext === 'function'\n ? { next: observerOrNext, error, complete }\n : observerOrNext || {};\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ObserverInterface } from '@observable/observable.module';\n\n/**\n * Imports\n */\n\nimport { ObservableService } from '@observable/services/observable.service';\n\n/**\n * A subject that acts as both an observable and an observer.\n *\n * @template T - The type of values emitted by the subject.\n *\n * @remarks\n * The `SubjectService` extends {@link Observable} to provide a multicast observable\n * that maintains a collection of active observers. Unlike a regular observable that executes\n * its handler once per subscription, a subject allows multiple subscribers to share the same\n * emission sequence and receive values emitted directly via {@link next}, {@link error},\n * and {@link complete} methods.\n *\n * This is particularly useful for:\n * - Event buses where multiple listeners need the same events\n * - Sharing a single data source across multiple subscribers\n * - Implementing pub-sub patterns\n *\n * When a subscriber unsubscribes, they are automatically removed from the observer's collection.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * // Multiple subscribers\n * subject.subscribe((value) => console.log('Observer 1:', value));\n * subject.subscribe((value) => console.log('Observer 2:', value));\n *\n * // Emit values to all subscribers\n * subject.next(42); // Both observers receive 42\n * subject.next(100); // Both observers receive 100\n *\n * // Complete the subject\n * subject.complete();\n * ```\n *\n * @see ObservableService\n * @see ObserverInterface\n *\n * @since 2.0.0\n */\n\nexport class SubjectService<T> extends ObservableService<T> {\n /**\n * Tracks whether the subject has completed.\n *\n * @remarks\n * Once the subject is completed, no further values or errors can be emitted,\n * and new subscribers will immediately receive the complete notification.\n *\n * @since 2.0.0\n */\n\n protected isCompleted = false;\n\n /**\n * Collection of all active observers subscribed to this subject.\n *\n * @remarks\n * This set maintains references to all current observers. When {@link next}, {@link error},\n * or {@link complete} is called, all observers in this collection are notified.\n *\n * @see ObserverInterface\n * @since 2.0.0\n */\n\n private observers = new Set<ObserverInterface<T>>();\n\n /**\n * Creates a new subject service with a shared observer management handler.\n *\n * @template T - The type of values emitted by the subject.\n *\n * @remarks\n * The subject initializes with a handler function that manages the observer's collection.\n * When a new subscriber is added via {@link subscribe}, the observer is added to the\n * collection and a cleanup function is returned that removes the observer when unsubscribed.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<string>();\n * const unsub = subject.subscribe((value) => console.log(value));\n * subject.next('hello'); // Observer receives 'hello'\n * unsub(); // Remove observer from a subject\n * ```\n *\n * @since 2.0.0\n */\n\n constructor() {\n super((observer) => {\n if (this.isCompleted) {\n observer.complete?.();\n\n return;\n }\n\n this.observers.add(observer);\n\n return (): boolean => this.observers.delete(observer);\n });\n }\n\n /**\n * Emits a new value to all active observers.\n *\n * @template T - The type of values emitted by the subject.\n *\n * @param value - The value to emit to all observers.\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `next` handler throws an error.\n *\n * @remarks\n * This method calls the `next` handler on all current observers with the provided value.\n * If an observer's next handler throws an error, it is caught and passed to that observer's\n * error handler (if provided). All errors from handlers are collected and thrown together\n * as an {@link AggregateError} after all observers have been notified.\n *\n * The observers are iterated over a snapshot of the collection to allow observers to\n * unsubscribe during emission without affecting iteration.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * subject.subscribe((value) => console.log('A:', value));\n * subject.subscribe((value) => {\n * if (value === 0) throw new Error('Zero not allowed');\n * console.log('B:', value);\n * });\n *\n * try {\n * subject.next(0); // Observer B throws, wrapped in AggregateError\n * } catch (err) {\n * if (err instanceof AggregateError) {\n * console.log(`${err.errors.length} observer(s) failed`);\n * }\n * }\n * ```\n *\n * @see AggregateError\n * @since 2.0.0\n */\n\n next(value: T): void {\n if (this.isCompleted) return;\n const errors: Array<unknown> = [];\n\n for (const o of [ ...this.observers ]) {\n try {\n o.next?.(value);\n } catch (err) {\n errors.push(err);\n try {\n o.error?.(err);\n } catch {}\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, `${ errors.length } observer(s) failed in next()`);\n }\n }\n\n /**\n * Emits an error to all active observers.\n *\n * @param err - The error to emit to all observers.\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `error` handler throws an error.\n *\n * @remarks\n * This method calls the `error` handler on all current observers with the provided error.\n * If an observer's error handler throws an error, it is caught and collected. All errors\n * from handlers are thrown together as an {@link AggregateError} after all observers\n * have been notified.\n *\n * If an observer does not provide an error handler, it is skipped without any effect.\n *\n * The observers are iterated over a snapshot of the collection to allow observers to\n * unsubscribe during emission without affecting iteration.\n *\n * After an error is emitted, the subject behaves as completed (no further emissions allowed).\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * subject.subscribe({\n * error: (err) => console.log('Observer A error:', err)\n * });\n *\n * subject.subscribe({\n * error: () => { throw new Error('Handler failed'); }\n * });\n *\n * try {\n * subject.error(new Error('Something went wrong'));\n * } catch (err) {\n * if (err instanceof AggregateError) {\n * console.log(`${err.errors.length} observer(s) failed`);\n * }\n * }\n * ```\n *\n * @see AggregateError\n * @since 2.0.0\n */\n\n error(err: unknown): void {\n if (this.isCompleted) return;\n const errors: Array<unknown> = [];\n\n for (const o of [ ...this.observers ]) {\n try {\n o.error?.(err);\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, `${ errors.length } observer(s) failed in error()`);\n }\n }\n\n /**\n * Signals completion to all observers and clears all subscriptions.\n *\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `complete` handler throws an error.\n *\n * @remarks\n * This method calls the `complete` handler on all current observers, then clears the\n * observers collection to prevent further emissions. If an observer's complete handler\n * throws an error, it is caught and collected. All errors from handlers are thrown\n * together as an {@link AggregateError} after all observers have been notified.\n *\n * If an observer does not provide a complete handler, it is skipped without any effect.\n *\n * The observers are iterated over a snapshot of the collection to allow safe completion.\n * After completion, the subject will accept no further emissions and new subscribers\n * will immediately receive the complete notification.\n *\n * @example\n * ```ts\n * const subject = new SubjectService<number>();\n *\n * subject.subscribe({\n * complete: () => console.log('Observer A completed')\n * });\n *\n * subject.subscribe({\n * complete: () => { throw new Error('Handler failed'); }\n * });\n *\n * try {\n * subject.complete();\n * } catch (err) {\n * if (err instanceof AggregateError) {\n * console.log(`${err.errors.length} observer(s) failed`);\n * }\n * }\n * ```\n *\n * @see AggregateError\n * @since 2.0.0\n */\n\n complete(): void {\n if (this.isCompleted) return;\n const errors: Array<unknown> = [];\n\n\n for (const o of [ ...this.observers ]) {\n try {\n o.complete?.();\n } catch (err) {\n errors.push(err);\n }\n }\n\n this.observers.clear();\n this.isCompleted = true;\n if (errors.length > 0) {\n throw new AggregateError(errors, `${ errors.length } observer(s) failed in complete()`);\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CompleteType, NextType, ErrorType } from '@observable/observable.module';\nimport type { ObserverInterface, UnsubscribeType } from '@observable/observable.module';\n\n/**\n * Imports\n */\n\nimport { SubjectService } from '@observable/services/subject.service';\n\n/**\n * A subject that emits the most recent value to new subscribers immediately upon subscription.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @remarks\n * The `BehaviorSubject` extends {@link Subject} to maintain and replay the\n * latest emitted value to all new subscribers. Unlike a regular subject where new subscribers\n * only receive values emitted after subscription, behavior subjects guarantee that every new\n * subscriber immediately receives the current value.\n *\n * This is particularly useful for:\n * - State management where new subscribers need the current state\n * - Configuration or preference storage\n * - Real-time data feeds where latecomers need the latest snapshot\n *\n * The behavior subject always has a value available, even before any emission occurs, using\n * the initial value provided at construction.\n *\n * @example\n * ```ts\n * const count = new BehaviorSubject<number>(0);\n * count.subscribe((value) => console.log('Observer 1:', value)); // Immediately logs: 0\n * count.next(5);\n * count.subscribe((value) => console.log('Observer 2:', value)); // Immediately logs: 5\n * ```\n *\n * @see SubjectService\n * @see ObserverInterface\n *\n * @since 2.0.0\n */\n\nexport class BehaviorSubjectService<T> extends SubjectService<T> {\n /**\n * The most recently emitted value or the initial value.\n *\n * @remarks\n * This property stores the latest value that will be replayed to new subscribers.\n * It is initialized with the value provided to the constructor and updated whenever\n * {@link next} is called.\n *\n * @since 2.0.0\n */\n\n private lastValue: T;\n\n /**\n * Creates a new behavior subject with an initial or lazily-computed value.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @param initialValue - Either an initial value or a factory function that computes it.\n *\n * @remarks\n * The behavior subject requires an initial value at construction time. This value can be\n * provided in two ways:\n *\n * 1. **Direct value**: Pass the value directly (e.g., `new BehaviorSubject(0)`)\n * 2. **Factory function**: Pass a function that returns the value (e.g., `new BehaviorSubject(() => getInitialState())`)\n *\n * Using a factory function allows for lazy initialization and computation of the initial value,\n * which is useful when the initial state depends on side effects or is expensive to compute.\n *\n * @example\n * ```ts\n * // Direct value\n * const subject1 = new BehaviorSubject<number>(42);\n *\n * // Factory function for lazy initialization\n * const subject2 = new BehaviorSubject<string>(() => {\n * return localStorage.getItem('savedState') ?? 'default';\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(initialValue: T | (() => T)) {\n super();\n this.lastValue = typeof initialValue === 'function'\n ? (initialValue as () => T)()\n : initialValue;\n }\n\n /**\n * Retrieves the current value of the behavior subject.\n *\n * @template T - The type of the value.\n *\n * @returns The most recently emitted value or the initial value.\n *\n * @remarks\n * This getter provides read-only access to the current state of the behavior subject.\n * The value is always available and represents either the last emitted value or the\n * initial value if no emissions have occurred.\n *\n * @example\n * ```ts\n * const subject = new BehaviorSubject<number>(10);\n * console.log(subject.value); // Output: 10\n *\n * subject.next(20);\n * console.log(subject.value); // Output: 20\n * ```\n *\n * @since 2.0.0\n */\n\n get value(): T {\n return this.lastValue;\n }\n\n /**\n * Subscribes to the behavior subject with immediate replay of the current value.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @param observerOrNext - Either an observer object or a callback function for the `next` event.\n * @param error - Optional error handler callback.\n * @param complete - Optional completion handler callback.\n * @returns An unsubscribe function that removes the subscription.\n *\n * @remarks\n * This override adds behavior-specific subscription logic: immediately after the observer\n * is registered with the parent {@link SubjectService}, the current value is emitted to\n * the new observer. This ensures all subscribers, even those who join late, receive the\n * most recent value.\n *\n * The subscription follows the same modes as the parent:\n * 1. **Observer mode**: Pass a full {@link ObserverInterface}\n * 2. **Callback mode**: Pass a `next` callback with optional error and complete handlers\n * 3. **Empty mode**: Pass nothing to subscribe without any handlers\n *\n * @example\n * ```ts\n * const subject = new BehaviorSubject<number>(5);\n *\n * // Observer mode\n * const unsub1 = subject.subscribe({\n * next: (value) => console.log('A:', value)\n * }); // Immediately logs: \"A: 5\"\n *\n * subject.next(10);\n *\n * // Callback mode (late subscriber)\n * const unsub2 = subject.subscribe(\n * (value) => console.log('B:', value)\n * ); // Immediately logs: \"B: 10\"\n *\n * subject.next(15); // Both log their respective updates\n * ```\n *\n * @see ObserverInterface\n * @see SubjectService.subscribe\n *\n * @since 2.0.0\n */\n\n override subscribe(\n observerOrNext?: ObserverInterface<T> | NextType<T>,\n error?: ErrorType,\n complete?: CompleteType\n ): UnsubscribeType {\n if(this.isCompleted) return () => {};\n\n const observer = this.createSafeObserver(observerOrNext, error, complete);\n const unsub = super.subscribe(observer);\n observer.next?.(this.lastValue);\n\n return unsub;\n }\n\n /**\n * Emits a new value and updates the current state.\n *\n * @template T - The type of values emitted by the behavior subject.\n *\n * @param value - The new value to emit to all observers.\n * @returns void\n *\n * @throws AggregateError - If one or more observer's `next` handler throws an error.\n *\n * @remarks\n * This override extends the parent {@link SubjectService.next} method by storing the\n * emitted value as the current state before broadcasting to all observers. This ensures\n * that any new subscribers added after this emission will receive this value.\n *\n * Error handling follows the parent behavior: if an observer's next handler throws,\n * the error is passed to that observer's error handler (if provided), and all errors\n * are collected and thrown together as an {@link AggregateError}.\n *\n * @example\n * ```ts\n * const subject = new BehaviorSubject<number>(0);\n *\n * subject.subscribe((value) => console.log('Observer 1:', value));\n *\n * subject.next(42); // Updates internal state and notifies observers\n *\n * subject.subscribe((value) => console.log('Observer 2:', value));\n * // Immediately logs: \"Observer 2: 42\" (receives the updated state)\n * ```\n *\n * @see AggregateError\n * @see SubjectService.next\n *\n * @since 2.0.0\n */\n\n override next(value: T): void {\n if (this.isCompleted) return;\n\n this.lastValue = value;\n super.next(value);\n }\n}\n", "/**\n * Checks whether a value is a plain object (not null, not an array, but an object).\n *\n * @param item - The value to check\n *\n * @returns `true` if the value is a plain object, `false` otherwise\n *\n * @remarks\n * This type guard function narrows the type to `Record<string, unknown>` when it returns `true`.\n * A value is considered a plain object if it meets all criteria:\n * - Is truthy (not `null`, `undefined`, `false`, `0`, `''`, etc.)\n * - Has type `'object'`\n * - Is not an array\n *\n * This function treats class instances, dates, and other object types as plain objects since\n * they satisfy the criteria. Use more specific checks if you need to exclude these.\n *\n * @example\n * ```ts\n * isObject({}); // true\n * isObject({ key: 'value' }); // true\n * isObject(null); // false\n * isObject([]); // false\n * isObject('string'); // false\n * isObject(new Date()); // true (it's an object, not an array)\n * ```\n *\n * @see {@link deepMerge}\n *\n * @since 2.0.0\n */\n\nexport function isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === 'object' && !Array.isArray(item);\n}\n\n/**\n * Recursively merges multiple source objects into a target object with deep property merging.\n *\n * @template T - The type of the target object must extend `object`\n *\n * @param target - The target object to merge into\n * @param sources - One or more source objects to merge from\n *\n * @returns The target object with all sources merged into it\n *\n * @remarks\n * This function performs a deep merge with the following behavior:\n * - Primitive values in sources overwrite values in target\n * - Arrays are concatenated (target items first, then source items)\n * - Objects are recursively merged\n * - Sources are processed left-to-right, with later sources overwriting earlier ones\n * - The target object is mutated and returned\n *\n * Merge strategy by type:\n * - **Both arrays**: Concatenates `[...targetValue, ...sourceValue]`\n * - **Both objects**: Recursively merges properties\n * - **Source is object, target is not**: Creates a new object with source properties\n * - **Other cases**: Source value overwrites target value\n *\n * @example\n * ```ts\n * const target = { a: 1, b: { x: 10 } };\n * const source = { b: { y: 20 }, c: 3 };\n *\n * const result = deepMerge(target, source);\n * // { a: 1, b: { x: 10, y: 20 }, c: 3 }\n * ```\n *\n * @example\n * ```ts\n * // Array concatenation\n * const target = { items: [1, 2] };\n * const source = { items: [3, 4] };\n *\n * deepMerge(target, source);\n * // { items: [1, 2, 3, 4] }\n * ```\n *\n * @example\n * ```ts\n * // Multiple sources\n * const result = deepMerge(\n * { a: 1 },\n * { b: 2 },\n * { c: 3 }\n * );\n * // { a: 1, b: 2, c: 3 }\n * ```\n *\n * @see {@link isObject}\n *\n * @since 2.0.0\n */\nexport function deepMerge<T extends object>(target: T, ...sources: Array<object>): T {\n if (!sources.length) return target;\n const source = sources.shift();\n\n if (isObject(target) && isObject(source)) {\n for (const key in source) {\n const sourceValue = source[key];\n const targetValue = target[key];\n\n if (Array.isArray(sourceValue) && Array.isArray(targetValue)) {\n Object.assign(target, { [key]: [ ...targetValue, ...sourceValue ] });\n } else if (isObject(sourceValue)) {\n Object.assign(target, {\n [key]: deepMerge(\n isObject(targetValue) ? targetValue : {},\n sourceValue\n )\n });\n } else {\n Object.assign(target, { [key]: sourceValue });\n }\n }\n\n return deepMerge(target, ...sources);\n }\n\n return target;\n}\n\n/**\n * Performs deep equality comparison between two values with support for primitives, objects, arrays, and special types.\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param strictCheck - When `true`, requires arrays and objects to have the same length/key count; defaults to `true`\n *\n * @returns `true` if values are deeply equal, `false` otherwise\n *\n * @remarks\n * This function performs comprehensive equality checking with special handling for:\n * - **Primitives**: Uses strict equality (`===`) and `Object.is()` for `NaN` and `-0` handling\n * - **Dates**: Compares timestamps using `getTime()`\n * - **RegExp**: Compares source patterns and flags\n * - **URLs**: Compares full `href` strings\n * - **Arrays**: Recursively compares elements\n * - **Objects**: Recursively compares properties\n *\n * The `strictCheck` parameter controls comparison behavior:\n * - `true` (default): Arrays must have the same length, objects must have the same key count.\n * - `false`: Allows partial matches (subset comparison)\n *\n * **Null handling**:\n * Returns `false` if either value is `null` (unless both are `null`, caught by `===` check).\n *\n * @example\n * ```ts\n * equals(1, 1); // true\n * equals('test', 'test'); // true\n * equals(NaN, NaN); // true (via Object.is)\n * equals(null, null); // true\n * ```\n *\n * @example\n * ```ts\n * // Date comparison\n * const date1 = new Date('2024-01-01');\n * const date2 = new Date('2024-01-01');\n * equals(date1, date2); // true\n * ```\n *\n * @example\n * ```ts\n * // Deep object comparison\n * equals(\n * { a: 1, b: { c: 2 } },\n * { a: 1, b: { c: 2 } }\n * ); // true\n * ```\n *\n * @example\n * ```ts\n * // Strict vs non-strict array comparison\n * equals([1, 2], [1, 2, 3], true); // false (different lengths)\n * equals([1, 2], [1, 2, 3], false); // true (subset match)\n * ```\n *\n * @see {@link deepEquals}\n * @see {@link hasKey}\n *\n * @since 2.0.0\n */\n\nexport function equals(a: unknown, b: unknown, strictCheck = true): boolean {\n if (a === b) return true;\n if (Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n\n if (URL && a instanceof URL && b instanceof URL)\n return a.href === b.href;\n\n if (typeof a === 'object' && typeof b === 'object') {\n return deepEquals(a, b, strictCheck);\n }\n\n return false;\n}\n\n/**\n * Checks whether an object or function has a specific property key.\n *\n * @param obj - The object or function to check\n * @param key - The property key to search for (string or symbol)\n *\n * @returns `true` if the key exists on the object, `false` otherwise\n *\n * @remarks\n * This function performs two checks to determine the key existence:\n * 1. Uses the `in` operator to check the prototype chain\n * 2. Uses `Object.prototype.hasOwnProperty.call()` for own properties\n *\n * Returns `false` if the value is:\n * - `null` or `undefined`\n * - Not an object or function (primitives like strings, numbers, booleans)\n *\n * This function is safer than direct property access when dealing with unknown objects,\n * as it handles `null` and `undefined` gracefully without throwing errors.\n *\n * @example\n * ```ts\n * const obj = { name: 'test' };\n * hasKey(obj, 'name'); // true\n * hasKey(obj, 'age'); // false\n * hasKey(null, 'key'); // false\n * hasKey('string', 'length'); // true\n * ```\n *\n * @example\n * ```ts\n * // Symbol keys\n * const sym = Symbol('key');\n * const obj = { [sym]: 'value' };\n * hasKey(obj, sym); // true\n * ```\n *\n * @see {@link deepEquals}\n *\n * @since 2.0.0\n */\n\nexport function hasKey(obj: unknown, key: string | symbol): boolean {\n if (obj == null || (typeof obj !== 'object' && typeof obj !== 'function'))\n return false;\n\n return key in obj || Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Performs deep equality comparison on objects and arrays with configurable strictness.\n *\n * @param a - The first object to compare\n * @param b - The second object to compare\n * @param strictCheck - When `true`, requires same length/key count; defaults to `true`\n *\n * @returns `true` if objects are deeply equal, `false` otherwise\n *\n * @remarks\n * This internal helper function is called by {@link equals} to handle object and array comparisons.\n * It recursively compares nested structures using the following logic:\n *\n * **Array comparison**:\n * - In strict mode: Arrays must have identical length\n * - Compares elements by index using {@link equals}\n * - Order matters (different order means not equal)\n *\n * **Object comparison**:\n * - In strict mode: Objects must have same number of keys\n * - Iterates through keys of the first object\n * - Checks if each key exists in the second object\n * - Recursively compares property values using {@link equals}\n *\n * **Non-strict mode** allows partial matches where the first value can be a subset of the second.\n *\n * @example\n * ```ts\n * // Arrays\n * deepEquals([1, 2, 3], [1, 2, 3], true); // true\n * deepEquals([1, 2], [1, 2, 3], false); // true (subset)\n * deepEquals([1, 2], [1, 2, 3], true); // false (different lengths)\n * ```\n *\n * @example\n * ```ts\n * // Nested objects\n * deepEquals(\n * { user: { name: 'Alice', age: 30 } },\n * { user: { name: 'Alice', age: 30 } },\n * true\n * ); // true\n * ```\n *\n * @see {@link equals}\n * @see {@link hasKey}\n *\n * @since 2.0.0\n */\n\nfunction deepEquals(a: object, b: object, strictCheck: boolean = true): boolean {\n if (Array.isArray(a) && Array.isArray(b)) {\n if(strictCheck && a.length !== b.length) return false;\n\n return a.every((val, i) => equals(val, b[i], strictCheck));\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (strictCheck && aKeys.length !== bKeys.length) return false;\n\n for (const key of aKeys) {\n if (!hasKey(b, key)) return false;\n if (!equals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], strictCheck)) {\n return false;\n }\n }\n\n return true;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PartialBuildConfigType } from '@interfaces/configuration.interface';\n\n/**\n * Default build configuration shared across all variants.\n * Provides sensible defaults for common build settings including TypeScript compilation and esbuild options.\n *\n * @remarks\n * This frozen configuration object serves as the foundation for all builds when no custom\n * common configuration is provided. It establishes defaults for:\n * - Type checking enabled\n * - Declaration file generation enabled\n * - Bundle mode with minification\n * - CommonJS output format\n * - Browser platform target\n * - Output to `dist` directory\n *\n * All nested objects are deeply frozen using `Object.freeze()` to prevent accidental mutation\n * and ensure configuration immutability. This makes the defaults safe to reference without\n * defensive copying.\n *\n * These defaults are merged with user-provided configuration, with user values taking precedence.\n * Individual variants can override any of these settings for their specific build targets.\n *\n * @example\n * ```ts\n * // User config merges with defaults\n * const userConfig: BuildConfigInterface = {\n * ...DEFAULTS_COMMON_CONFIG,\n * common: {\n * ...DEFAULTS_COMMON_CONFIG.common,\n * esbuild: {\n * ...DEFAULTS_COMMON_CONFIG.common?.esbuild,\n * format: 'esm', // Override default 'cjs'\n * minify: false // Override default true\n * }\n * },\n * variants: { ... }\n * };\n * ```\n *\n * @example\n * ```ts\n * // Accessing default values\n * const defaultFormat = DEFAULTS_COMMON_CONFIG.common?.esbuild?.format;\n * // 'cjs'\n *\n * const defaultOutDir = DEFAULTS_COMMON_CONFIG.common?.esbuild?.outdir;\n * // 'dist'\n * ```\n *\n * @see {@link PartialBuildConfigType}\n *\n * @since 2.0.0\n */\n\nexport const DEFAULTS_COMMON_CONFIG: PartialBuildConfigType = Object.freeze({\n verbose: false,\n common: Object.freeze({\n types: true,\n declaration: true,\n esbuild: Object.freeze({\n write: true,\n bundle: true,\n minify: true,\n format: 'cjs',\n outdir: 'dist',\n platform: 'browser',\n absWorkingDir: process.cwd()\n })\n })\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { UnsubscribeType, Observable } from '@observable/observable.module';\nimport type { BuildConfigInterface, DeepPartialType } from '@interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { BehaviorSubject } from '@observable/observable.module';\nimport { deepMerge, equals } from '@components/object.component';\nimport { map, distinctUntilChanged } from '@observable/observable.module';\nimport { DEFAULTS_COMMON_CONFIG } from '@constants/configuration.constant';\n\n/**\n * Provides a centralized service for managing and observing configuration state.\n *\n * @template T - The configuration object type must extend {@link BuildConfigInterface}\n *\n * @remarks\n * Configuration changes are deeply merged with existing values, preserving unmodified properties.\n * Type-safe selectors enable reactive access to nest or derived configuration properties.\n *\n * @example\n * ```ts\n * // Initialize with default or custom configuration\n * const configService = new ConfigurationService({ name: 'myApp' });\n *\n * // Get current configuration value\n * const config = configService.getValue();\n *\n * // Get a specific configuration property\n * const name = configService.getValue(cfg => cfg.name);\n *\n * // Subscribe to configuration changes\n * const unsubscribe = configService.subscribe((config) => {\n * console.log('Config updated:', config);\n * });\n *\n * // Select and observe specific properties reactively\n * configService.select(cfg => cfg.name)\n * .subscribe(name => console.log('Name changed:', name));\n *\n * // Update configuration (deep merge)\n * configService.patch({ name: 'newApp' });\n *\n * // Cleanup subscription\n * unsubscribe();\n * ```\n *\n * @see {@link BuildConfigInterface} for the configuration contract\n * @see {@link BehaviorSubject} for the underlying reactive implementation\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class ConfigurationService<T extends BuildConfigInterface> {\n /**\n * Internal configuration state managed by a {@link BehaviorSubject}.\n *\n * @remarks\n * This private property holds the current configuration and emits changes\n * to all active subscribers. All public methods delegate state access through this subject.\n *\n * @see {@link BehaviorSubject}\n *\n * @since 2.0.0\n */\n\n private readonly config$: BehaviorSubject<T>;\n\n /**\n * Initializes a new {@link ConfigurationService} instance.\n *\n * @param initialConfig - The initial configuration object (defaults to {@link DEFAULTS_COMMON_CONFIG})\n *\n * @remarks\n * - Creates a deep copy of the provided configuration to prevent external mutations\n * - If no configuration is provided, uses the default configuration\n * - The configuration is wrapped in a {@link BehaviorSubject} for reactive updates\n *\n * @example\n * ```ts\n * // With default configuration\n * const service = new ConfigurationService();\n *\n * // With custom configuration\n * const service = new ConfigurationService({ name: 'customApp' });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(private initialConfig: T = DEFAULTS_COMMON_CONFIG as T) {\n this.config$ = new BehaviorSubject<T>(deepMerge({}, initialConfig) as T);\n }\n\n /**\n * Retrieves the current configuration value synchronously.\n *\n * @overload\n * @returns The complete current configuration object\n *\n * @example\n * ```ts\n * const config = configService.getValue();\n * console.log(config.name);\n * ```\n *\n * @since 2.0.0\n */\n\n getValue(): T;\n\n /**\n * Retrieves a computed value derived from the current configuration.\n *\n * @overload\n * @typeParam R - The return type of the selector function\n * @param selector - A function that extracts or transforms a value from the configuration\n * @returns The computed value returned by the selector function\n *\n * @remarks\n * This overload allows synchronous extraction of specific configuration properties\n * or computed values without creating an Observable subscription.\n *\n * @example\n * ```ts\n * const name = configService.getValue(cfg => cfg.name);\n * const nameLength = configService.getValue(cfg => cfg.name?.length ?? 0);\n * ```\n *\n * @since 2.0.0\n */\n\n getValue<R>(selector: (config: T) => R): R;\n\n /**\n * Implementation of getValue that handles both overloads.\n *\n * @param selector - Optional selector function for computed values\n * @returns The current configuration or a computed value derived from it\n *\n * @remarks\n * When no selector is provided, it returns the complete configuration.\n * When a selector is provided, applies it to the current configuration value\n * and returns the result.\n *\n * @since 2.0.0\n */\n\n getValue<R>(selector?: (config: T) => R): T | R {\n if (!selector)\n return this.config$.value;\n\n return selector(this.config$.value);\n }\n\n /**\n * Subscribes to configuration changes and executes a callback for each update.\n *\n * @param observer - A callback function invoked with the new configuration value on each change\n * @returns An unsubscribe function that removes this subscription when called\n *\n * @remarks\n * - The observer is immediately called with the current configuration value\n * - Subsequent calls occur whenever the configuration is updated via {@link patch}\n * - Returns an unsubscribe function for cleanup; it should be called to prevent memory leaks\n * - For more sophisticated reactive operations, consider using {@link select} instead\n *\n * @example\n * ```ts\n * const unsubscribe = configService.subscribe((config) => {\n * console.log('Configuration changed:', config);\n * });\n *\n * // Later, stop listening to changes\n * unsubscribe();\n * ```\n *\n * @see {@link select} for reactive selector-based subscriptions\n *\n * @since 1.0.0\n */\n\n subscribe(observer: (value: T) => void): UnsubscribeType {\n return this.config$.subscribe(observer);\n }\n\n /**\n * Creates an Observable that emits selected configuration values whenever they change.\n *\n * @typeParam R - The return type of the selector function\n * @param selector - A function that extracts or transforms a value from the configuration\n * @returns An Observable that emits distinct selector results on configuration changes\n *\n * @remarks\n * - Uses the provided selector to extract a computed value from the configuration\n * - Only emits values that are distinct from the previous emission (via {@link distinctUntilChanged})\n * - Distinction is determined using the {@link equals} utility for deep equality comparison\n * - Allows reactive composition using RxJS operators and subscriptions\n * - Ideal for observing nested properties or computed values without pollution from unchanged properties\n *\n * @example\n * ```ts\n * // Observe a specific property\n * configService.select(cfg => cfg.name)\n * .subscribe(name => console.log('Name is now:', name));\n *\n * // Observe a derived value\n * configService.select(cfg => cfg.name?.toUpperCase() ?? '')\n * .subscribe(uppercaseName => console.log('Upper name:', uppercaseName));\n *\n * // Compose with other RxJS operators\n * configService.select(cfg => cfg.name)\n * .pipe(\n * filter(name => name?.length > 0),\n * map(name => name.toUpperCase())\n * )\n * .subscribe(uppercaseName => console.log('Valid uppercase name:', uppercaseName));\n * ```\n *\n * @see {@link equals} for equality comparison logic\n * @see {@link distinctUntilChanged} for deduplication behavior\n * @see {@link subscribe} for simple subscription-based value access\n *\n * @since 2.0.0\n */\n\n select<R>(selector: (config: T) => R): Observable<R> {\n return this.config$.pipe(\n map(selector),\n distinctUntilChanged((prev, curr) => equals(prev, curr))\n ) as Observable<R>;\n }\n\n /**\n * Updates the configuration with partial changes, performing a deep merge.\n *\n * @param partial - A partial configuration object containing the properties to update\n *\n * @remarks\n * - Performs a deep merge of the provided partial configuration with the current configuration\n * - Unmodified properties are preserved from the current configuration\n * - The merge operation uses {@link deepMerge} to ensure nested objects are properly merged\n * - After merging, emits the updated configuration to all active subscribers via the BehaviorSubject\n * - For complete replacement rather than merging, create a new ConfigurationService instance\n *\n * @example\n * ```ts\n * // Update a single property\n * configService.patch({ name: 'updatedApp' });\n *\n * // Update multiple properties (existing properties are preserved)\n * configService.patch({\n * name: 'newApp',\n * // other properties remain unchanged\n * });\n *\n * // Patch with nested updates\n * configService.patch({\n * name: 'app',\n * // nested properties would be merged deeply if they existed\n * });\n * ```\n *\n * @see {@link subscribe} to observe changes\n * @see {@link deepMerge} for the merging implementation\n * @see {@link select} to observe specific properties reactively\n *\n * @since 1.0.0\n */\n\n patch(partial: DeepPartialType<T>): void {\n const mergedConfig = deepMerge<T>(\n {} as T,\n this.config$.value,\n partial\n );\n\n this.config$.next(mergedConfig);\n }\n\n /**\n * Replaces the entire configuration with a new configuration object.\n *\n * @param config - The complete configuration object to set\n *\n * @remarks\n * - Performs a complete replacement of the configuration (unlike {@link patch} which merges)\n * - The provided configuration object is used directly without deep cloning\n * - Emits the new configuration to all active subscribers via the BehaviorSubject\n * - Useful when you need to reset or swap the entire configuration state\n * - No properties are preserved from the previous configuration\n *\n * @example\n * ```ts\n * // Replace entire configuration\n * configService.reload({\n * verbose: true,\n * variants: { production: { esbuild: { minify: true } } },\n * common: { esbuild: { write: true } }\n * });\n *\n * // Reset to default configuration\n * configService.reload(DEFAULTS_COMMON_CONFIG);\n *\n * // Swap between different configuration profiles\n * const prodConfig = loadProductionConfig();\n * configService.reload(prodConfig);\n * ```\n *\n * @see {@link patch} for partial configuration updates with deep merging\n * @see {@link subscribe} to observe configuration changes\n * @see {@link select} to observe specific configuration properties reactively\n *\n * @since 2.0.0\n */\n\n reload(config: Partial<T>): void {\n this.config$.next(deepMerge({}, this.initialConfig, config) as T);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StackTraceInterface, StackInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { formatStack, getErrorMetadata } from '@providers/stack.provider';\n\n/**\n * A base class for custom errors with enhanced stack trace formatting and source code information.\n *\n * @remarks\n * The `xBuildBaseError` class extends the native `Error` class, adding functionality to:\n * - Parse and store structured stack trace metadata via {@link StackInterface}\n * - Format stack traces with syntax highlighting and source mapping\n * - Provide enhanced console output through custom Node.js inspection\n *\n * This is particularly useful for debugging errors in compiled or transpiled code by providing\n * clearer information about the original source of the error, including\n * - Original source file paths (from source maps)\n * - Highlighted code snippets showing the error location\n * - Enhanced stack frame formatting with proper indentation\n *\n * @example\n * ```ts\n * class ValidationError extends xBuildBaseError {\n * constructor(message: string, field: string) {\n * super(message, 'ValidationError');\n * this.reformatStack(this, { withFrameworkFrames: false });\n * }\n * }\n *\n * throw new ValidationError('Invalid email format', 'email');\n * ```\n *\n * @see {@link formatStack} for stack formatting\n * @see {@link getErrorMetadata} for stack parsing\n * @see {@link StackInterface} for the metadata structure\n * @see {@link StackTraceInterface} for formatting options\n *\n * @since 2.0.0\n */\n\nexport abstract class xBuildBaseError extends Error {\n /**\n * Structured metadata from the parsed stack trace.\n *\n * @remarks\n * Contains the parsed stack information including\n * - Original source code snippet\n * - Line and column numbers\n * - Source file path (from source maps)\n * - Formatted stack frames\n * - Syntax-highlighted code\n *\n * This property is populated by calling {@link reformatStack}.\n *\n * @since 2.0.0\n */\n\n protected errorMetadata: StackInterface | undefined;\n\n /**\n * Pre-formatted stack trace string ready for display.\n *\n * @remarks\n * Contains the complete formatted output including\n * - Error name and message\n * - Syntax-highlighted code snippet (if available)\n * - Enhanced stack trace with proper indentation\n *\n * This is generated by {@link formatStack} and used by the custom\n * Node.js inspector for console output.\n *\n * @since 2.0.0\n */\n\n protected formattedStack: string | undefined;\n\n /**\n * Creates a new instance of the base error class.\n *\n * @param message - The error message describing the problem\n * @param name - The error type name; defaults to `'xBuildBaseError'`\n *\n * @remarks\n * This constructor:\n * - Properly sets up the prototype chain to ensure `instanceof` checks work for derived classes\n * - Captures the stack trace if supported by the runtime environment\n * - Sets the error name for identification\n *\n * **Important:** This is a protected constructor and should only be called by derived classes.\n * Subclasses should call {@link reformatStack} after construction to enable enhanced formatting.\n *\n * @example\n * ```ts\n * class DatabaseError extends xBuildBaseError {\n * constructor(message: string, public readonly query: string) {\n * super(message, 'DatabaseError');\n * this.reformatStack(this);\n * }\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n protected constructor(message: string, name: string = 'xBuildBaseError') {\n super(message);\n\n // Ensure a correct prototype chain (important for `instanceof`)\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Gets the structured stack trace metadata.\n *\n * @returns The parsed stack metadata, or `undefined` if {@link reformatStack} has not been called\n *\n * @remarks\n * Provides read-only access to the error's structured stack information,\n * which can be used for:\n * - Custom error logging\n * - Error reporting services\n * - Debugging tools\n * - Stack analysis\n *\n * @example\n * ```ts\n * try {\n * throw new ValidationError('Invalid input');\n * } catch (error) {\n * if (error instanceof xBuildBaseError) {\n * const meta = error.metadata;\n * console.log(`Error at ${meta?.source}:${meta?.line}:${meta?.column}`);\n * }\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n get metadata(): StackInterface | undefined {\n return this.errorMetadata;\n }\n\n /**\n * Custom inspect behavior for Node.js console output.\n *\n * @returns The enhanced formatted stack trace if available, otherwise falls back to the raw stack trace\n *\n * @remarks\n * This method is automatically called by Node.js when the error is logged to the console\n * using `console.log()`, `console.error()`, or `util.inspect()`.\n *\n * The formatted output includes:\n * - Colored and styled error name and message\n * - Syntax-highlighted code snippet showing the error location\n * - Enhanced stack frames with source-mapped paths\n *\n * @example\n * ```ts\n * const error = new ValidationError('Invalid data');\n * console.log(error); // Automatically uses this method for formatting\n * ```\n *\n * @see {@link https://nodejs.org/api/util.html#custom-inspection-functions-on-objects | Node.js Custom Inspection}\n *\n * @since 2.0.0\n */\n\n [Symbol.for('nodejs.util.inspect.custom')](): string | undefined {\n return this.formattedStack || this.stack;\n }\n\n /**\n * Parses the error stack trace and generates enhanced formatting with metadata.\n *\n * @param error - The error object to parse and format\n * @param options - Optional configuration for stack trace parsing and formatting\n *\n * @remarks\n * This method performs two operations:\n * 1. Parses the error's stack trace using {@link getErrorMetadata} to extract structured metadata\n * 2. Formats the metadata using {@link formatStack} to create a styled, human-readable output\n *\n * The parsed metadata is stored in {@link errorMetadata} and the formatted string in {@link formattedStack}.\n *\n * **Typical usage:** Call this method in the constructor of derived error classes to enable\n * enhanced stack trace formatting.\n *\n * @example\n * ```ts\n * class NetworkError extends xBuildBaseError {\n * constructor(message: string, public readonly statusCode: number) {\n * super(message, 'NetworkError');\n * // Enable enhanced formatting without framework frames\n * this.reformatStack(this, {\n * withFrameworkFrames: false,\n * withNativeFrames: true\n * });\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * class CustomError extends xBuildBaseError {\n * constructor(message: string) {\n * super(message, 'CustomError');\n * // Use default options\n * this.reformatStack(this);\n * }\n * }\n * ```\n *\n * @see {@link formatStack} for formatting logic\n * @see {@link getErrorMetadata} for parsing logic\n * @see {@link StackTraceInterface} for available options\n *\n * @since 2.0.0\n */\n\n protected reformatStack(error: Error, options?: StackTraceInterface): void {\n this.errorMetadata = getErrorMetadata(error, options);\n this.formattedStack = formatStack(this.errorMetadata, error.name, error.message);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Argv, Options } from 'yargs';\nimport type { BaseArgumentsInterface } from '@argv/interfaces/argv-module.interface';\nimport type { UserExtensionInterface, ArgumentsInterface } from '@argv/interfaces/argv-module.interface';\n\n/**\n * Imports\n */\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { CLI_DEFAULT_OPTIONS, CLI_USAGE_EXAMPLES } from '@argv/constants/argv.constant';\n\n/**\n * Command-line argument parser and processor for xBuild.\n *\n * @remarks\n * This module provides three levels of argument parsing to support different stages\n * of the build tool's initialization and execution:\n *\n * - **Configuration file parsing**: Early-stage parsing to locate custom config files\n * - **User extension parsing**: Parses custom options defined in configuration files\n * - **Enhanced parsing**: Full-featured CLI with help, version, examples, and validation\n *\n * The module is designed as a singleton service, ensuring consistent argument parsing\n * across the entire application lifecycle. It integrates with yargs to provide a\n * comprehensive command-line interface with:\n * - Automatic help generation with custom branding\n * - Usage examples and documentation links\n * - Type-safe argument validation\n * - Support for custom user-defined options\n * - Strict mode to catch typos and invalid options\n *\n * **Parsing Strategy:**\n *\n * The three-stage parsing approach allows xBuild to:\n * 1. First, parse just the `--config` flag to locate a configuration file\n * 2. Load configuration and discover user-defined CLI options\n * 3. Reparse all arguments with a complete option set for full validation\n *\n * This strategy enables configuration files to extend the CLI dynamically while\n * maintaining type safety and proper error handling.\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n *\n * // Parse config path only\n * const { config } = parseConfigFile(process.argv);\n *\n * // Load config and get user extensions\n * const userOptions = await configFileProvider(config);\n *\n * // Full parse with all options\n * const args = argvModule.enhancedParse(process.argv, userOptions.userArgv);\n *\n * // User argv\n * const userArgs = argvService.parseUserArgv(process.argv, userOptions.userArgv);\n * ```\n *\n * @see {@link bannerComponent}\n * @see {@link CLI_USAGE_EXAMPLES}\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class ArgvModule {\n /**\n * Parses command-line arguments to extract the configuration file path.\n *\n * @param argv - Raw command-line arguments array\n * @returns Parsed arguments containing the config file path\n *\n * @remarks\n * This method performs minimal parsing focused solely on extracting the `--config`\n * option. It's used during the initial bootstrap phase before the configuration\n * file is loaded, enabling xBuild to locate and load custom configuration files.\n *\n * **Parsing behavior:**\n * - Only processes the `config` option\n * - Disables help and version flags to prevent premature exit\n * - Returns a default config path if not specified\n * - Ignores all other arguments for performance\n *\n * The returned config path is used to load the build configuration file,\n * which may define additional CLI options that require reparsing with\n * the complete option set.\n *\n * This is the first step in a multi-stage parsing strategy that allows\n * configuration files to extend the CLI dynamically.\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n * const result = argvModule.parseConfigFile(process.argv);\n *\n * console.log(result.config);\n * // Output: 'config.xbuild.ts' (default)\n * // Or: 'custom.xbuild.ts' (if --config custom.xbuild.ts was passed)\n * ```\n *\n * @example\n * ```ts\n * // Command: xBuild --config build/prod.xbuild.ts src/index.ts\n * const { config } = argvModule.parseConfigFile(process.argv);\n * // Result: { config: 'build/prod.xbuild.ts', _: [...], $0: '...' }\n * ```\n *\n * @see {@link enhancedParse}\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\n parseConfigFile(argv: Array<string>): BaseArgumentsInterface & { config: string } {\n return yargs(argv)\n .help(false)\n .version(false)\n .options({\n config: CLI_DEFAULT_OPTIONS.config\n }).parseSync() as BaseArgumentsInterface & { config: string };\n }\n\n /**\n * Parses user-defined command-line options from configuration files.\n *\n * @param argv - Raw command-line arguments array\n * @param argvOptions - Optional user-defined CLI options from configuration\n * @returns Parsed arguments containing user-defined option values\n *\n * @remarks\n * This method parses custom CLI options defined in the build configuration file,\n * allowing users to extend xBuild's command-line interface with project-specific\n * arguments. It's used after loading the configuration file but before the final\n * enhanced parse.\n *\n * **Parsing behavior:**\n * - Only processes user-defined options (not xBuild defaults)\n * - Returns an empty object if no user options are provided\n * - Disables help and version to prevent premature exit\n * - Maintains type safety with generic return type\n *\n * User-defined options can include custom flags for:\n * - Build environment selection (staging, production)\n * - Feature flags and conditional compilation\n * - Custom output paths or naming schemes\n * - Integration with other build tools\n *\n * The parsed values are available in lifecycle hooks and configuration functions,\n * enabling dynamic build behavior based on CLI arguments.\n *\n * @example\n * ```ts\n * // In config.xbuild.ts\n * export default {\n * cliOptions: {\n * env: {\n * describe: 'Build environment',\n * type: 'string',\n * choices: ['dev', 'staging', 'prod']\n * }\n * }\n * };\n * ```\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n * const userArgs = argvModule.parseUserArgv<{ env: string }>(\n * process.argv,\n * config.cliOptions\n * );\n *\n * console.log(userArgs.env);\n * // Output: 'prod' (if --env prod was passed)\n * ```\n *\n * @example\n * ```ts\n * // No user options defined\n * const userArgs = argvModule.parseUserArgv(process.argv);\n * // Returns: {}\n * ```\n *\n * @see {@link enhancedParse}\n * @see {@link parseConfigFile}\n *\n * @since 2.0.0\n */\n\n parseUserArgv<T extends BaseArgumentsInterface>(argv: Array<string>, argvOptions?: Record<string, Options>): T {\n if (!argvOptions) return <T>{};\n\n return yargs(argv)\n .help(false)\n .version(false)\n .options(argvOptions).parseSync() as T;\n }\n\n /**\n * Performs comprehensive argument parsing with full CLI features and validation.\n *\n * @param argv - Raw command-line arguments array\n * @param userExtensions - Optional user-defined CLI options from configuration\n * @returns Fully parsed and validated arguments with all xBuild and user options\n *\n * @remarks\n * This method provides the complete command-line interface experience with all\n * features enabled. It combines xBuild's default options with user-defined extensions\n * to create a unified, fully validated CLI.\n *\n * **Enhanced features:**\n * - **Custom help formatting**: Displays xBuild banner and grouped options\n * - **Usage examples**: Shows common command patterns with descriptions\n * - **Strict validation**: Catches unknown options and invalid values\n * - **Help and version**: Standard `--help` and `--version` flags\n * - **Documentation links**: Provides epilogue with documentation URL\n * - **Positional arguments**: Supports file paths as positional parameters\n *\n * **Help output structure:**\n * 1. xBuild ASCII banner\n * 2. Usage syntax\n * 3. Commands section\n * 4. xBuild Options (grouped)\n * 5. User Options (grouped, if any)\n * 6. Examples\n * 7. Documentation link\n *\n * **Option grouping:**\n * - Separates xBuild core options from user-defined options\n * - Improves help readability for complex configurations\n * - Makes custom options clearly identifiable\n *\n * The method overrides yargs' `showHelp` to inject custom branding and option\n * grouping, providing a polished CLI experience consistent with xBuild's design.\n *\n * This is the final parsing stage and should be called after configuration loading\n * is complete and all user extensions have been discovered.\n *\n * @example\n * ```ts\n * const argvModule = inject(ArgvModule);\n * const args = argvModule.enhancedParse(process.argv, {\n * env: {\n * describe: 'Build environment',\n * type: 'string',\n * choices: ['dev', 'prod']\n * }\n * });\n *\n * console.log(args.entryPoints); // ['src/index.ts']\n * console.log(args.minify); // true\n * console.log(args.env); // 'prod'\n * ```\n *\n * @example\n * ```ts\n * // Command: xBuild src/app.ts --bundle --minify --env prod\n * const args = argvModule.enhancedParse(process.argv, userOptions);\n * // Result: {\n * // entryPoints: ['src/app.ts'],\n * // bundle: true,\n * // minify: true,\n * // ...\n * // }\n * ```\n *\n * @example\n * ```ts\n * // Displaying help\n * // Command: xBuild --help\n * // Shows:\n * // - ASCII banner\n * // - Usage: xBuild [files..] [options]\n * // - xBuild Options: (--bundle, --minify, etc.)\n * // - User Options: (--env, custom options)\n * // - Examples: Common usage patterns\n * // - Documentation link\n * ```\n *\n * @see {@link parseUserArgv}\n * @see {@link parseConfigFile}\n * @see {@link bannerComponent}\n * @see {@link CLI_USAGE_EXAMPLES}\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\n enhancedParse(argv: Array<string>, userExtensions: UserExtensionInterface = {}): ArgumentsInterface {\n const parser = yargs(hideBin(argv)).locale('en');\n const originalShowHelp = parser.showHelp;\n parser.showHelp = function (consoleFunction?: string | ((s: string) => void)): Argv<unknown> {\n this.group(Object.keys(CLI_DEFAULT_OPTIONS), 'xBuild Options:');\n this.group(Object.keys(userExtensions), 'user Options:');\n\n return originalShowHelp.call(this, consoleFunction as (s: string) => void);\n };\n\n parser\n .usage('Usage: xBuild [files..] [options]')\n .command('* [entryPoints..]', 'Specific files to build (supports glob patterns)', (yargs) => {\n return yargs.positional('entryPoints', {\n describe: 'Specific files to build (supports glob patterns)',\n type: 'string',\n array: true\n });\n })\n .options(userExtensions)\n .options(CLI_DEFAULT_OPTIONS)\n .epilogue('For more information, check the documentation https://remotex-labs.github.io/xBuild/')\n .help()\n .alias('help', 'h')\n .strict()\n .version();\n\n CLI_USAGE_EXAMPLES.forEach(([ command, description ]) => {\n parser.example(command, description);\n });\n\n return parser.parseSync();\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Options } from 'yargs';\n\n/**\n * Default path to the xBuild configuration file.\n *\n * @remarks\n * This constant defines the standard location for xBuild's build configuration.\n * Used as the default value for the `--config` CLI option when no custom path is provided.\n *\n * The configuration file contains:\n * - Build variant definitions (production, development, etc.)\n * - Common build settings shared across variants\n * - esbuild compiler options\n * - TypeScript integration settings\n * - Custom lifecycle hooks\n * - Define replacements and injections\n *\n * The file is a TypeScript module that exports build configuration, enabling\n * type-safe configuration with IDE autocomplete support.\n *\n * @example\n * ```ts\n * // Default usage\n * xBuild src/index.ts\n * // Automatically looks for: config.xbuild.ts\n * ```\n *\n * @example\n * ```ts\n * // Custom config path\n * xBuild src/index.ts --config build/custom.xbuild.ts\n * ```\n *\n * @since 2.0.0\n */\n\nexport const CLI_CONFIG_PATH = 'config.xbuild.ts' as const;\n\n/**\n * Default command-line interface options and their configurations.\n *\n * @remarks\n * This constant defines all available CLI flags and arguments for the xBuild tool,\n * providing comprehensive build customization from the command line. Each option\n * includes type validation, aliases, descriptions, and default values.\n *\n * **Option Categories:**\n *\n * **Input/Output:**\n * - `entryPoints`: Source files to compile (supports glob patterns)\n * - `outdir`: Output directory for compiled files\n *\n * **Build Modes:**\n * - `watch`: Enable watch mode for automatic rebuilds\n * - `serve`: Start development server\n * - `typeCheck`: Type check only without output\n *\n * **Build Configuration:**\n * - `bundle`: Bundle dependencies into output\n * - `minify`: Minify output code\n * - `format`: Module format (cjs, esm, iife)\n * - `platform`: Target platform (browser, node, neutral)\n *\n * **TypeScript:**\n * - `declaration`: Generate .d.ts files\n * - `types`: Enable type checking during build\n * - `failOnError`: Fail build on type errors\n * - `tsconfig`: Custom tsconfig.json path\n *\n * **Configuration:**\n * - `config`: Custom build configuration file path\n * - `verbose`: Enable detailed error messages\n *\n * All options can be used individually or combined to create complex build workflows.\n * Options specified on the command line override configuration file settings.\n *\n * @example\n * ```ts\n * // Single file build with defaults\n * xBuild src/index.ts\n * ```\n *\n * @example\n * ```ts\n * // Production build with bundling and minification\n * xBuild src/app.ts --bundle --minify --format esm\n * ```\n *\n * @example\n * ```ts\n * // Development mode with watch and server\n * xBuild src/app.ts --watch --serve dist\n * ```\n *\n * @example\n * ```ts\n * // Library build with type definitions\n * xBuild src/lib.ts --declaration --format esm --outdir dist\n * ```\n *\n * @example\n * ```ts\n * // Type checking only (no output)\n * xBuild --typeCheck\n * ```\n *\n * @see {@link TSCONFIG_PATH}\n * @see {@link CLI_CONFIG_PATH}\n * @see {@link CLI_USAGE_EXAMPLES}\n *\n * @since 2.0.0\n */\n\nexport const CLI_DEFAULT_OPTIONS: Record<string, Options> = {\n entryPoints: {\n describe: 'Source files to build (supports glob patterns)',\n type: 'string',\n array: true\n },\n typeCheck: {\n describe: 'Perform type checking without building output',\n alias: 'tc',\n type: 'boolean'\n },\n platform: {\n describe: 'Target platform for the build output',\n alias: 'p',\n type: 'string',\n choices: [ 'browser', 'node', 'neutral' ] as const\n },\n serve: {\n describe: 'Start server to the <folder>',\n alias: 's',\n type: 'string'\n },\n outdir: {\n describe: 'Directory for build output files',\n alias: 'o',\n type: 'string'\n },\n declaration: {\n describe: 'Generate TypeScript declaration files (.d.ts)',\n alias: 'de',\n type: 'boolean'\n },\n watch: {\n describe: 'Watch mode - rebuild on file changes',\n alias: 'w',\n type: 'boolean'\n },\n config: {\n describe: 'Path to build configuration file',\n alias: 'c',\n type: 'string',\n default: CLI_CONFIG_PATH\n },\n tsconfig: {\n describe: 'Path to TypeScript configuration file',\n alias: 'tsc',\n type: 'string'\n },\n minify: {\n describe: 'Minify the build output',\n alias: 'm',\n type: 'boolean'\n },\n bundle: {\n describe: 'Bundle dependencies into output files',\n alias: 'b',\n type: 'boolean'\n },\n types: {\n describe: 'Enable type checking during build process',\n alias: 'btc',\n type: 'boolean'\n },\n failOnError: {\n describe: 'Fail build when TypeScript errors are detected',\n alias: 'foe',\n type: 'boolean'\n },\n format: {\n describe: 'Output module format',\n alias: 'f',\n type: 'string',\n choices: [ 'cjs', 'esm', 'iife' ]\n },\n verbose: {\n describe: 'Verbose error stack traces',\n alias: 'v',\n type: 'boolean'\n },\n build: {\n describe: 'Select an build configuration variant by names (as defined in your config file)',\n alias: 'xb',\n type: 'string',\n array: true\n }\n} as const;\n\n/**\n * Example command-line usage patterns demonstrating common build scenarios.\n *\n * @remarks\n * This constant provides a curated collection of practical CLI usage examples\n * that demonstrate how to combine xBuild options for common development workflows.\n * Each example includes the complete command and a description of its purpose.\n *\n * **Example Categories:**\n *\n * **Basic Builds:**\n * - Single file compilation with defaults\n * - Multi-file bundling with optimization\n *\n * **Development Workflows:**\n * - Watch mode with development server\n * - Custom server directory configuration\n *\n * **Library Publishing:**\n * - ESM library with type definitions\n * - Platform-specific builds\n *\n * **Validation:**\n * - Type checking without output\n * - Custom configuration files\n *\n * These examples are displayed in CLI help output and serve as quick-start\n * templates for developers learning the tool.\n *\n * @example\n * ```ts\n * // Displayed when running: xBuild --help\n * // Shows all usage examples with descriptions\n * ```\n *\n * @example\n * ```ts\n * // Example: Production library build\n * xBuild src/lib.ts --format esm --declaration\n * // Generates: dist/lib.js and dist/lib.d.ts as ESM\n * ```\n *\n * @example\n * ```ts\n * // Example: Development with hot reload\n * xBuild src/app.ts -s dist\n * // Starts: Watch mode + dev server serving from dist/\n * ```\n *\n * @see {@link CLI_DEFAULT_OPTIONS}\n *\n * @since 2.0.0\n */\n\nexport const CLI_USAGE_EXAMPLES = [\n [ 'xBuild src/index.ts', 'Build a single file with default settings' ],\n [ 'xBuild src/**/*.ts --bundle --minify', 'Bundle and minify all TypeScript files' ],\n [ 'xBuild src/app.ts -s', 'Development mode with watch and dev server' ],\n [ 'xBuild src/app.ts -s dist', 'Development mode with watch and dev server from dist folder' ],\n [ 'xBuild src/lib.ts --format esm --declaration', 'Build ESM library with type definitions' ],\n [ 'xBuild src/server.ts --platform node --outdir dist', 'Build Node.js application to dist folder' ],\n [ 'xBuild --typeCheck', 'Type check only without generating output' ],\n [ 'xBuild --config custom.xbuild.ts', 'Use custom configuration file' ]\n] as const;\n", "/**\n * Imports\n */\n\nimport readline from 'readline';\nimport { exec } from 'child_process';\nimport { patchConfig } from '../index';\nimport { inject } from '@symlinks/symlinks.module';\nimport { prefix } from '@components/banner.component';\nimport { platform, exit, stdin, stdout } from 'process';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { EXIT_SIGNALS, KEY_MAPPINGS, COMMAND_MAP } from '@components/constants/interactive.constant';\n\n/**\n * Generates a formatted help message displaying available keyboard shortcuts.\n *\n * @param activeUrl - Whether to include URL-related shortcuts (show/open in browser)\n * @returns A formatted multi-line string containing all available shortcuts\n *\n * @remarks\n * Dynamically builds a help menu based on the current context. When a server is active\n * (indicated by `activeUrl`), additional shortcuts for URL display and browser opening are included.\n *\n * The output uses ANSI styling via {@link xterm} for visual hierarchy:\n * - Dimmed prefix text \"press\"\n * - Bold key name\n * - Dimmed action description\n *\n * **Shortcuts included**:\n * - `u` - Show server URL (when `activeUrl` is true)\n * - `o` - Open in browser (when `activeUrl` is true)\n * - `v` - Toggle verbose mode\n * - `r` - Reload/restart build\n * - `c` - Clear console\n * - `q` - Quit application\n *\n * @example\n * ```ts\n * const helpText = generateHelp(true);\n * console.log(helpText);\n * // Output:\n * // \uD83D\uDE80 Shortcuts\n * // press u to show server url\n * // press o to open in browser\n * // press v to enable / disable verbose mode\n * // ...\n * ```\n *\n * @see {@link xterm} for ANSI styling\n * @see {@link KEY_MAPPINGS} for key definitions\n *\n * @since 2.0.0\n */\n\nexport function generateHelp(activeUrl: boolean = false): string {\n const shortcuts: Array<string> = [ '\uD83D\uDE80 Shortcuts' ];\n const prefix = xterm.dim(' press ');\n\n const addShortcut = (key: string, description: string): void => {\n shortcuts.push(`${ prefix }${ xterm.bold(key) }${ xterm.dim(description) }`);\n };\n\n if (activeUrl) {\n addShortcut(KEY_MAPPINGS.SHOW_URL, ' to show server url');\n addShortcut(KEY_MAPPINGS.OPEN_BROWSER, ' to open in browser');\n }\n\n addShortcut(KEY_MAPPINGS.VERBOSE, ' to enable / disable verbose mode');\n addShortcut(KEY_MAPPINGS.RELOAD, ' to reload');\n addShortcut(KEY_MAPPINGS.CLEAR, ' to clear console');\n addShortcut(KEY_MAPPINGS.QUIT, ' to quit\\n');\n\n return shortcuts.join('\\n');\n}\n\n/**\n * Clears the terminal screen without scrollback, moving the cursor to the top.\n *\n * @remarks\n * Performs a visual clear by:\n * 1. Calculating available terminal rows (minus 2 for buffer)\n * 2. Printing newlines to push content out of view\n * 3. Moving cursor to position (0, 0)\n * 4. Clearing all content from the cursor downward\n *\n * This approach ensures a clean visual reset without modifying scrollback history.\n * The function is safe to call regardless of terminal size; it handles small terminals\n * gracefully by ensuring `repeatCount` is never negative.\n *\n * @example\n * ```ts\n * // User presses 'c' to clear console\n * clearScreen();\n * // Terminal is cleared, cursor at top-left\n * ```\n *\n * @see {@link handleKeypress} for usage in keypress handling\n *\n * @since 2.0.0\n */\n\nexport function clearScreen(): void {\n const repeatCount = Math.max(0, stdout.rows - 2);\n if (repeatCount > 0) {\n console.log('\\n'.repeat(repeatCount));\n }\n\n readline.cursorTo(stdout, 0, 0);\n readline.clearScreenDown(stdout);\n}\n\n/**\n * Opens the specified URL in the system's default browser.\n *\n * @param url - The URL to open in the browser\n *\n * @remarks\n * Provides cross-platform browser opening by executing the appropriate shell command\n * for the current operating system:\n * - **Windows**: `start <url>`\n * - **macOS**: `open <url>`\n * - **Linux**: `xdg-open <url>` (also used as fallback)\n *\n * The function uses Node.js {@link exec} to spawn the command asynchronously.\n * No error handling is performed; if the command fails, it silently continues.\n *\n * @example\n * ```ts\n * // User presses 'o' to open server URL\n * openInBrowser('http://localhost:3000');\n * // Browser opens with the specified URL\n * ```\n *\n * @see {@link COMMAND_MAP} for platform-to-command mapping\n * @see {@link handleKeypress} for usage in keypress handling\n *\n * @since 2.0.0\n */\n\nexport function openInBrowser(url: string): void {\n const command = COMMAND_MAP[<keyof typeof COMMAND_MAP> platform] ?? 'xdg-open';\n exec(`${ command } ${ url }`);\n}\n\n/**\n * Handles keyboard input events and executes corresponding actions.\n *\n * @param code - The raw character code from the keypress event\n * @param key - The parsed key information including name, sequence, and modifiers\n * @param reload - Callback function to trigger a build reload/restart\n * @param help - Pre-generated help text to display when help key is pressed\n * @param url - Optional server URL for URL display and browser opening features\n *\n * @remarks\n * Acts as the central dispatcher for interactive terminal commands. Processes both\n * exit signals (Ctrl+C, Ctrl+D) and single-key shortcuts, executing appropriate actions\n * for each recognized input.\n *\n * **Processing flow**:\n * 1. Validates key information exists\n * 2. Checks for exit signals \u2192 exits with code 1\n * 3. Matches key name against {@link KEY_MAPPINGS}\n * 4. Executes corresponding action (clear, reload, toggle verbose, etc.)\n *\n * **Available actions**:\n * - **Clear** (`c`): Clears the terminal screen\n * - **Verbose** (`v`): Toggles verbose/debug mode via {@link ConfigurationService}\n * - **Reload** (`r`): Clears screen and invokes the reload callback\n * - **Help** (`h`): Displays the help menu\n * - **Show URL** (`u`): Prints the server URL (if provided)\n * - **Open Browser** (`o`): Opens the server URL in browser (if provided)\n * - **Quit** (`q`): Exits the process with a goodbye message\n *\n * The function safely handles cases where `url` is undefined by checking existence\n * before executing URL-dependent actions.\n *\n * @example Basic usage\n * ```ts\n * handleKeypress('r', { name: 'r' }, async () => rebuild(), helpText);\n * // Clears screen and triggers rebuild\n * ```\n *\n * @example Exit signal\n * ```ts\n * handleKeypress('\\x03', { name: 'c', sequence: '\\x03' }, reload, help);\n * // Prints \"\uD83D\uDC4B Exiting...\" and exits with code 1\n * ```\n *\n * @example Toggle verbose\n * ```ts\n * // Current verbose: false\n * handleKeypress('v', { name: 'v' }, reload, help);\n * // Prints: \"\uD83D\uDC1E Debug mode: ENABLED\"\n * // Updates config: { verbose: true }\n * ```\n *\n * @see {@link init} for event listener setup\n * @see {@link EXIT_SIGNALS} for exit signal codes\n * @see {@link KEY_MAPPINGS} for recognized key names\n *\n * @since 2.0.0\n */\n\nexport function handleKeypress(code: string, key: readline.Key, reload: () => void, help: string, url?: string): void {\n if (!key?.name) return;\n if (key.sequence === KEY_MAPPINGS.QUIT || code === EXIT_SIGNALS.SIGINT || code === EXIT_SIGNALS.SIGQUIT) {\n console.log('\\n\uD83D\uDC4B Exiting...');\n exit(1);\n }\n\n switch (key.name) {\n case KEY_MAPPINGS.CLEAR:\n clearScreen();\n break;\n case KEY_MAPPINGS.VERBOSE:\n const verbose = inject(ConfigurationService).getValue(cfg => cfg.verbose);\n console.log(`\uD83D\uDC1E Debug mode: ${ !verbose ? 'ENABLED' : 'DISABLED' }`);\n patchConfig({ verbose: !verbose });\n break;\n case KEY_MAPPINGS.RELOAD:\n clearScreen();\n reload();\n break;\n case KEY_MAPPINGS.HELP:\n clearScreen();\n console.log(help);\n break;\n case KEY_MAPPINGS.SHOW_URL:\n if (url) {\n console.log(`${ prefix() } ${ xterm.canaryYellow(url) }`);\n }\n break;\n case KEY_MAPPINGS.OPEN_BROWSER:\n if (url) {\n openInBrowser(url);\n }\n break;\n }\n}\n\n/**\n * Initializes the interactive terminal interface for watch mode.\n *\n * @param reload - Callback function to trigger a build reload/restart when requested\n * @param url - Optional server URL to enable URL-related shortcuts and functionality\n *\n * @remarks\n * Sets up the interactive development environment by configuring the terminal for raw\n * input mode and registering keypress event handlers. This function should be called\n * once during watch mode initialization.\n *\n * **Initialization flow**:\n * 1. **TTY check**: Exits early if stdin is not a TTY (e.g., piped input, CI environment)\n * 2. **Help generation**: Creates context-aware help text based on URL availability\n * 3. **Help display**: Prints the shortcuts menu immediately\n * 4. **Raw mode**: Enables character-by-character input without requiring Enter\n * 5. **Event setup**: Configures keypress event emission and registers handler\n *\n * **TTY requirement**:\n * Interactive mode is disabled when stdin is not a TTY. This prevents issues in:\n * - CI/CD pipelines\n * - Piped/redirected input scenarios\n * - Non-interactive shells\n *\n * **Raw mode implications**:\n * - Characters are processed immediately without buffering\n * - Standard terminal line editing (backspace, etc.) is disabled\n * - Allows single-key shortcuts without an Enter key\n *\n * The function keeps the process alive by registering an event listener, which should\n * persist for the duration of the watch session.\n *\n * @example Basic initialization\n * ```ts\n * // In watch mode without server\n * init(async () => {\n * await rebuild();\n * });\n * // Displays shortcuts without URL options\n * ```\n *\n * @example With server URL\n * ```ts\n * // In watch mode with dev server\n * init(async () => {\n * await rebuild();\n * }, 'http://localhost:3000');\n * // Displays all shortcuts including 'u' and 'o'\n * ```\n *\n * @example Non-TTY environment (CI)\n * ```ts\n * // stdin.isTTY === false\n * init(reload, url);\n * // Function returns immediately without setup\n * ```\n *\n * @see {@link generateHelp} for help text generation\n * @see {@link handleKeypress} for keypress handling logic\n *\n * @since 2.0.0\n */\n\nexport function init(reload: () => void, url?: string): void {\n if (!stdin.isTTY) return;\n const helpString = generateHelp(!!url);\n console.log(helpString);\n\n stdin.setRawMode(true);\n readline.emitKeypressEvents(stdin);\n stdin.on('keypress', (code, key) => {\n handleKeypress(code, key, reload, helpString, url);\n });\n}\n\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ParseGlobInterface } from '@components/interfaces/glob-component.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { readdirSync } from 'fs';\nimport { matchesGlob } from 'path';\nimport { join } from '@components/path.component';\n\n/**\n * Separates glob patterns into include and exclude arrays.\n *\n * @param globs - Array of glob patterns (patterns starting with '!' are treated as excludes)\n * @returns Object containing separate include and exclude pattern arrays\n *\n * @example\n * ```ts\n * const { include, exclude } = parseGlobs([\n * '**\\/*.ts',\n * '!**\\/*.test.ts',\n * '**\\/*.js',\n * '!node_modules/**'\n * ]);\n * // include: ['**\\/*.ts', '**\\/*.js']\n * // exclude: ['**\\/*.test.ts', 'node_modules/**']\n * ```\n *\n * @since 2.0.0\n */\n\nexport function parseGlobs(globs: Array<string>): ParseGlobInterface {\n const include: Array<string> = [];\n const exclude: Array<string> = [];\n\n for (const g of globs) {\n if (g.startsWith('!')) {\n exclude.push(g.slice(1));\n } else {\n include.push(g);\n }\n }\n\n return { include, exclude };\n}\n\n/**\n * Checks if a path matches any pattern in the provided array.\n *\n * @param p - Path to test against patterns\n * @param patterns - Array of glob patterns to match against\n * @returns True if a path matches at least one pattern, false otherwise\n *\n * @remarks\n * Uses early exit optimization - stops checking as soon as a match is found.\n * A pattern is treated as a match when either:\n * - The pattern string ends with the provided path\n * - `matchesGlob(p, pattern)` returns true\n *\n * @example\n * ```ts\n * matchesAny('src/app.ts', ['**\\/*.ts', '**\\/*.js']); // true\n * matchesAny('src/app.ts', ['prefix/src/app.ts']); // true (suffix check)\n * matchesAny('README.md', ['**\\/*.ts', '**\\/*.js']); // false\n * ```\n *\n * @see matchesGlob\n * @since 2.0.0\n */\n\nexport function matchesAny(p: string, patterns: Array<string>): boolean {\n for (const pattern of patterns) {\n if (pattern.endsWith(p) || matchesGlob(p, pattern)) return true;\n }\n\n return false;\n}\n\n/**\n * Determines if a directory should be excluded from traversal.\n *\n * @param relativePath - Relative path of the directory to check\n * @param exclude - Array of glob patterns for exclusion\n * @returns True if directory matches any exclude pattern, false otherwise\n *\n * @remarks\n * Checks both the directory path itself and the directory with `/**` appended\n * to properly handle patterns like `node_modules/**`.\n *\n * @example\n * ```ts\n * isDirectoryExcluded('node_modules', ['node_modules/**']); // true\n * isDirectoryExcluded('src', ['node_modules/**']); // false\n * ```\n *\n * @see matchesGlob\n * @since 2.0.0\n */\n\nexport function isDirectoryExcluded(relativePath: string, exclude: Array<string>): boolean {\n const dirWithGlob = relativePath + '/**';\n\n for (const pattern of exclude) {\n if (matchesGlob(relativePath, pattern) || matchesGlob(dirWithGlob, pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n\n/**\n * Determines if a file should be included based on include and exclude patterns.\n *\n * @param relativePath - Relative path of the file to check\n * @param include - Array of glob patterns for inclusion\n * @param exclude - Array of glob patterns for exclusion\n * @returns True if file matches include patterns and not exclude patterns, false otherwise\n *\n * @remarks\n * A file must match at least one include pattern AND not match any exclude pattern\n * to be considered for inclusion.\n *\n * @example\n * ```ts\n * shouldIncludeFile('src/app.ts', ['**\\/*.ts'], ['**\\/*.test.ts']); // true\n * shouldIncludeFile('src/app.test.ts', ['**\\/*.ts'], ['**\\/*.test.ts']); // false\n * ```\n *\n * @see matchesAny\n * @since 2.0.0\n */\n\nexport function shouldIncludeFile(relativePath: string, include: Array<string>, exclude: Array<string>): boolean {\n // Must match at least one an include pattern\n if (!matchesAny(relativePath, include)) return false;\n\n // Must NOT match any exclude pattern\n return !matchesAny(relativePath, exclude);\n}\n\n/**\n * Collects files matching glob patterns from a directory tree.\n *\n * @param baseDir - Base directory to start searching from\n * @param globs - Array of glob patterns (use '!' prefix to exclude)\n * @returns Record mapping file paths without extension to full file paths\n *\n * @remarks\n * This function performs a depth-first traversal with several optimizations:\n * - Separates include/exclude patterns once upfront\n * - Early exits on excluded directories to avoid unnecessary traversal\n * - Returns Record instead of Array for O(1) lookups\n * - Keys are relative to baseDir (without extension)\n * - Values are relative to process.cwd() (with extension)\n * - Optimized with cached length calculations and index-based loops\n * - Avoids unnecessary string allocations\n *\n * @example\n * ```ts\n * // If baseDir is 'src' and file is at <cwd>/src/errors/uncaught-error.spec.ts\n * const files = collectFilesFromGlob('src', ['**\\/*.ts']);\n * // Returns: { 'errors/uncaught-error.spec': 'src/errors/uncaught-error.spec.ts' }\n * ```\n *\n * @since 2.0.0\n */\n\nexport function collectFilesFromGlob(baseDir: string, globs: Array<string>): Record<string, string> {\n const { include, exclude } = parseGlobs(globs);\n const collected: Record<string, string> = Object.create(null);\n const cwdPath = cwd();\n const rootDirLength = cwdPath.length + 1; // +1 for trailing slash\n const baseDirLength = baseDir.length + 1; // +1 for trailing slash\n const hasExcludes = exclude.length > 0;\n\n function walk(dir: string): void {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n const len = entries.length;\n for (let i = 0; i < len; i++) {\n const entry = entries[i];\n const fullPath = join(dir, entry.name);\n const relativeFromBase = fullPath.slice(baseDirLength);\n\n if (entry.isDirectory()) {\n if (!hasExcludes || !isDirectoryExcluded(relativeFromBase, exclude)) walk(fullPath);\n continue;\n }\n\n if (hasExcludes && matchesAny(relativeFromBase, exclude)) continue;\n if (matchesAny(relativeFromBase, include)) {\n const relativeFromRoot = fullPath.slice(rootDirLength);\n const lastDotIndex = relativeFromBase.lastIndexOf('.');\n const keyPath = lastDotIndex > 0 ? relativeFromBase.slice(0, lastDotIndex) : relativeFromBase;\n\n collected[keyPath] = relativeFromRoot;\n }\n }\n }\n\n walk(baseDir);\n\n return collected;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DiagnosticInterface } from '@typescript/typescript.module';\n\n/**\n * Represents a TypeScript type checking error with associated diagnostic information.\n *\n * @remarks\n * The `TypesError` class extends the native `Error` class to provide enhanced error reporting\n * for TypeScript type checking failures. It captures and preserves diagnostic information\n * from TypeScript's type checker, allowing structured access to individual diagnostics.\n *\n * **Error context**:\n * Each `TypesError` can contain zero or more {@link DiagnosticInterface} objects that provide:\n * - Source file location (file path, line, column)\n * - Diagnostic code for error identification\n * - Detailed error messages\n *\n * @example\n * ```ts\n * import { TypesError } from '@errors/types.error';\n * import type { DiagnosticInterface } from '@typescript/interfaces/typescript.interface';\n *\n * // Create error with diagnostics from type checker\n * const diagnostics: DiagnosticInterface[] = [\n * {\n * file: 'src/index.ts',\n * line: 10,\n * column: 5,\n * code: 2322,\n * message: 'Type \"string\" is not assignable to type \"number\"'\n * }\n * ];\n *\n * throw new TypesError('Type checking failed', diagnostics);\n * ```\n *\n * @see {@link Typescript.check} for type checking context\n * @see {@link DiagnosticInterface} for diagnostic structure\n *\n * @since 2.0.0\n */\n\nexport class TypesError extends Error {\n\n /**\n * Array of diagnostic information from TypeScript type checking.\n *\n * @remarks\n * Contains all diagnostics collected during type checking that led to this error.\n * May be empty if the error is not directly related to specific diagnostics.\n *\n * Each diagnostic includes:\n * - **file**: Source file path relative to project root\n * - **line**: 1-based line number where the issue occurred\n * - **column**: 1-based column number where the issue occurred\n * - **code**: TypeScript error code for identifying error type\n * - **message**: Human-readable error description\n *\n * Read-only to prevent modification after error creation.\n *\n * @example\n * ```ts\n * const error = new TypesError('Type check failed', diagnostics);\n * for (const diag of error.diagnostics) {\n * console.log(`${diag.file}:${diag.line}:${diag.column} - ${diag.message}`);\n * }\n * ```\n *\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\n readonly diagnostics: Array<DiagnosticInterface>;\n\n /**\n * Creates a new instance of `TypesError`.\n *\n * @param message - Optional error message describing the type checking failure\n * @param diagnostics - Optional array of diagnostic information (defaults to an empty array)\n *\n * @remarks\n * Initializes the error with:\n * 1. Message passed to parent `Error` class\n * 2. Error name set to `'TypesError'` for identification\n * 3. Stored diagnostics array for later inspection\n * 4. Prototype chain properly configured for instanceof checks\n *\n * **Prototype chain setup**:\n * Sets the prototype explicitly to ensure `instanceof` checks work correctly\n * across different execution contexts and transpilation scenarios.\n *\n * @example\n * ```ts\n * // Create error with message and diagnostics\n * const error = new TypesError('Type checking failed', [{\n * file: 'src/app.ts',\n * line: 42,\n * column: 15,\n * code: 2339,\n * message: 'Property \"config\" does not exist'\n * }]);\n *\n * // Create error with a message only\n * const simple = new TypesError('Type checking failed');\n *\n * // Create error with diagnostics only\n * const diag = new TypesError(undefined, diagnostics);\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(message?: string, diagnostics: Array<DiagnosticInterface> = []) {\n super(message);\n this.name = 'TypesError';\n this.diagnostics = diagnostics;\n\n Object.setPrototypeOf(this, TypesError.prototype);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\n\n/**\n * Represents a generic xBuild framework error.\n *\n * Extends {@link xBuildBaseError} and automatically formats the stack trace\n * according to the provided options.\n *\n * @remarks\n * This class is intended for general-purpose errors within the xBuild framework.\n * The stack trace is formatted automatically during construction, with\n * framework-specific frames included by default.\n *\n * @example\n * ```ts\n * throw new xBuildError('An unexpected error occurred');\n * ```\n *\n * @since 1.0.0\n */\n\nexport class xBuildError extends xBuildBaseError {\n\n /**\n * Creates a new instance of `xBuildError`.\n *\n * @param message - The error message to display\n * @param options - Optional stack trace formatting options (default includes framework frames)\n *\n * @remarks\n * The constructor passes the message to the base `xBuildBaseError` class,\n * then reformats the stack trace using {@link xBuildBaseError.reformatStack}.\n *\n * @since 1.0.0\n */\n\n constructor(message: string, options: StackTraceInterface = { withFrameworkFrames: true }) {\n super(message);\n this.reformatStack(this, options);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { PartialMessage } from 'esbuild';\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\nimport { getErrorMetadata, formatStack } from '@providers/stack.provider';\n\n/**\n * Normalized runtime error wrapper for esbuild diagnostics.\n *\n * @remarks\n * `esBuildError` converts an esbuild {@link PartialMessage} into an {@link xBuildBaseError}\n * with framework-aware metadata and a formatted stack string.\n *\n * Construction behavior:\n * - Uses `message.text` as the runtime error message (defaults to empty string)\n * - Copies `message.id` to {@link id} (defaults to empty string)\n * - Builds structured metadata via {@link getErrorMetadata}\n * - Replaces `stack` using {@link formatStack}, including any diagnostic notes\n *\n * @example\n * ```ts\n * const message = {\n * id: 'transform',\n * text: 'Unexpected token',\n * location: { file: 'src/index.ts', line: 1, column: 5 },\n * notes: [{ text: 'Check syntax near this token' }]\n * };\n *\n * const error = new esBuildError(message);\n * console.error(error.id); // \"transform\"\n * console.error(error.stack);\n * ```\n *\n * @see {@link xBuildBaseError}\n * @see {@link getErrorMetadata}\n * @see {@link formatStack}\n *\n * @since 2.0.0\n */\n\nexport class esBuildError extends xBuildBaseError {\n /**\n * Optional esbuild diagnostic identifier copied from `PartialMessage.id`.\n *\n * @remarks\n * This value is useful for categorizing diagnostics by producer (for example,\n * plugin- or phase-specific IDs). When absent in the source message, it defaults\n * to an empty string.\n *\n * @since 2.0.0\n */\n\n readonly id: string;\n\n /**\n * Creates a new esbuild error with formatted output and metadata.\n *\n * @param message - The esbuild {@link PartialMessage} containing diagnostic details\n * @param options - Optional stack parsing/formatting options used when deriving metadata\n *\n * @remarks\n * The constructor:\n * 1. Initializes the base error with `message.text ?? ''`\n * 2. Persists `message.id ?? ''` on {@link id}\n * 3. If `message.detail` is an `Error`, uses its `message` and `stack` as runtime values\n * 4. Builds structured metadata from either the original message or `detail` error\n * 5. Produces formatted output (stack replacement for message-based diagnostics, or\n * formatted inspector output for `detail`-based diagnostics)\n *\n * The error name is always set to `'esBuildError'`. Formatted output includes:\n * - Error name and message with color coding\n * - Any diagnostic notes from esbuild\n * - Highlighted code snippet showing the error location\n * - Enhanced stack trace with file path and position\n *\n * @see {@link getErrorMetadata} for formatting logic\n * @see {@link PartialMessage} for esbuild message structure\n *\n * @since 2.0.0\n */\n\n constructor(message: PartialMessage, options?: StackTraceInterface) {\n super(message.text ?? '', 'esBuildError');\n\n this.id = message.id ?? '';\n if(message.detail instanceof Error) {\n this.stack = message.detail.stack;\n this.message = message.detail.message;\n this.reformatStack(message.detail, options);\n } else {\n this.errorMetadata = getErrorMetadata(message, { withFrameworkFrames: true });\n this.stack = formatStack(this.errorMetadata, this.name, this.message, message.notes);\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildResult, Message } from 'esbuild';\nimport type { BuildResultInterface } from './interfaces/esbuild-messages-provider.interface';\n\n/**\n * Imports\n */\n\nimport { TypesError } from '@errors/types.error';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { xBuildBaseError } from '@errors/base.error';\nimport { esBuildError } from '@errors/esbuild.error';\n\n/**\n * Converts an esbuild message to a normalized Error instance.\n *\n * @param msg - The esbuild message object containing error or warning details\n * @returns A normalized Error instance appropriate for the message type\n *\n * @remarks\n * This function handles different types of esbuild messages and converts them to the appropriate\n * error classes used throughout the xBuild system. It prioritizes preserving existing error\n * instances while wrapping raw messages in appropriate error types.\n *\n * **Conversion priority**:\n * 1. If `msg.detail` is already an `xBuildBaseError` or `TypesError`, return it unchanged\n * 2. If `msg.detail` is any other Error, wrap it in `VMRuntimeError` with framework frames\n * 3. If `msg.location` exists, create an `esBuildError` with a formatted code snippet\n * 4. Otherwise, wrap the message text in a `VMRuntimeError`\n *\n * This normalization ensures consistent error handling and reporting throughout the build\n * pipeline, with appropriate context and formatting for each error type.\n *\n * @example\n * ```ts\n * // Message with location information\n * const msg: Message = {\n * text: 'Unexpected token',\n * location: { file: 'src/index.ts', line: 10, column: 5 }\n * };\n * const error = normalizeMessageToError(msg);\n * // Returns esBuildError with formatted code snippet\n *\n * // Message with existing error detail\n * const msgWithError: Message = {\n * text: 'Build failed',\n * detail: new TypesError('Type checking failed', [])\n * };\n * const error2 = normalizeMessageToError(msgWithError);\n * // Returns the TypesError unchanged\n * ```\n *\n * @see {@link TypesError}\n * @see {@link esBuildError}\n * @see {@link VMRuntimeError}\n * @see {@link xBuildBaseError}\n *\n * @since 2.0.0\n */\n\nexport function normalizeMessageToError(msg: Message | esBuildError): Error | undefined {\n if (msg instanceof xBuildBaseError)\n return msg;\n\n if (msg.detail instanceof xBuildBaseError || msg.detail instanceof TypesError)\n return msg.detail;\n\n if (msg.detail instanceof Error)\n return new esBuildError(msg, { withFrameworkFrames: true });\n\n if (msg.location)\n return new esBuildError(msg);\n\n if(msg.text)\n return new xBuildError(msg.text);\n}\n\n/**\n * Processes an array of esbuild messages and converts them to normalized errors.\n *\n * @param messages - Array of esbuild message objects to process\n * @param target - Array to populate with normalized error instances\n *\n * @remarks\n * This function iterates through esbuild messages and converts each one to a normalized\n * Error instance using {@link normalizeMessageToError}, appending the results to the\n * target array.\n *\n * The target array is modified in place, allowing errors and warnings from different\n * sources to be aggregated into the same collection.\n *\n * **Processing behavior**:\n * - Each message is converted independently\n * - Conversion failures do not stop processing of remaining messages\n * - a Target array is modified in place (no return value)\n * - Empty message arrays are handled gracefully\n *\n * Common use cases:\n * - Converting esbuild error arrays to normalized errors\n * - Converting esbuild warning arrays to normalized errors\n * - Aggregating messages from multiple build results\n *\n * @example\n * ```ts\n * const buildResult: BuildResult = await build({ ... });\n * const errors: Array<Error> = [];\n * const warnings: Array<Error> = [];\n *\n * // Process errors and warnings\n * processEsbuildMessages(buildResult.errors, errors);\n * processEsbuildMessages(buildResult.warnings, warnings);\n *\n * console.log(`Build completed with ${errors.length} errors and ${warnings.length} warnings`);\n * ```\n *\n * @see {@link enhancedBuildResult}\n * @see {@link normalizeMessageToError}\n *\n * @since 2.0.0\n */\n\nexport function processEsbuildMessages(messages: Array<Message> = [], target: Array<Error>): void {\n for (const msg of messages) {\n const error = normalizeMessageToError(msg);\n if(error) target.push(error);\n }\n}\n\n/**\n * Converts esbuild's BuildResult into xBuild's BuildResultInterface with normalized errors.\n *\n * @param source - Partial esbuild BuildResult containing build artifacts and messages\n * @returns A BuildResultInterface with normalized errors and warnings\n *\n * @remarks\n * This function transforms esbuild's build result into the xBuild-specific result interface,\n * converting all error and warning messages to normalized Error instances while preserving\n * build artifacts like metafiles, output files, and mangle cache.\n *\n * **Transformation process**:\n * 1. Creates a new BuildResultInterface with empty error/warning arrays\n * 2. Copies build artifacts (metafile, outputFiles, mangleCache) directly\n * 3. Processes errors array through {@link processEsbuildMessages}\n * 4. Processes warnings array through {@link processEsbuildMessages}\n * 5. Returns the fully populated result object\n *\n * **Preserved artifacts**:\n * - `metafile`: Build metadata including inputs, outputs, and dependencies\n * - `outputFiles`: Generated file contents when `write: false`\n * - `mangleCache`: Identifier mangling cache for consistent minification\n *\n * All esbuild Message objects are converted to Error instances, providing consistent\n * error handling throughout the xBuild system with proper stack traces, formatting,\n * and error classification.\n *\n * @example\n * ```ts\n * const esbuildResult = await build({\n * entryPoints: ['src/index.ts'],\n * write: false,\n * metafile: true\n * });\n *\n * const result = enhancedBuildResult(esbuildResult);\n * // result.errors: Array<Error> (normalized)\n * // result.warnings: Array<Error> (normalized)\n * // result.metafile: Metafile (preserved)\n * // result.outputFiles: OutputFile[] (preserved)\n *\n * console.log(`Build produced ${result.errors.length} errors`);\n * ```\n *\n * @see {@link BuildResultInterface}\n * @see {@link processEsbuildMessages}\n * @see {@link normalizeMessageToError}\n *\n * @since 2.0.0\n */\n\nexport function enhancedBuildResult(source: Partial<BuildResult>): BuildResultInterface {\n const target: BuildResultInterface = {\n errors: [],\n warnings: [],\n metafile: source.metafile,\n outputFiles: source.outputFiles,\n mangleCache: source.mangleCache\n };\n\n processEsbuildMessages(source.errors, target.errors);\n processEsbuildMessages(source.warnings, target.warnings);\n\n return target;\n}\n\n/**\n * Type guard that checks if an unknown value is an esbuild BuildResult error object.\n *\n * @param error - The value to check, typically from a catch block\n * @returns `true` if the value is a BuildResult with errors property, `false` otherwise\n *\n * @remarks\n * This type guard validates that an error object follows the esbuild BuildResult structure,\n * which includes an `errors` property. It's useful for distinguishing between esbuild-specific\n * errors and other error types during error handling.\n *\n * The function performs two checks:\n * 1. Verifies the value is an object (not null)\n * 2. Checks for the presence of an `errors` property\n *\n * When the function returns `true`, TypeScript will narrow the type of the parameter to\n * `BuildResult`, allowing type-safe access to BuildResult properties like `errors`,\n * `warnings`, `metafile`, etc.\n *\n * Common use cases:\n * - Catch block error type discrimination\n * - Conditional error handling based on an error source\n * - Type narrowing for BuildResult-specific error processing\n *\n * @example\n * ```ts\n * try {\n * await build({ entryPoints: ['src/index.ts'] });\n * } catch (error) {\n * if (isBuildResultError(error)) {\n * // TypeScript knows error is BuildResult here\n * console.error(`Build failed with ${error.errors.length} errors`);\n * processEsbuildMessages(error.errors, errorList);\n * } else if (error instanceof Error) {\n * // Handle generic errors\n * console.error(error.message);\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // In error aggregation\n * const errors: Array<Error> = [];\n *\n * if (isBuildResultError(caughtError)) {\n * const result = enhancedBuildResult(caughtError);\n * errors.push(...result.errors);\n * } else {\n * errors.push(new Error(String(caughtError)));\n * }\n * ```\n *\n * @see {@link BuildResult}\n * @see {@link enhancedBuildResult}\n * @see {@link processEsbuildMessages}\n *\n * @since 2.0.0\n */\n\nexport function isBuildResultError(error: unknown): error is BuildResult {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { ServerConfigurationInterface } from '@server/interfaces/server.interface';\n\n/**\n * Imports\n */\n\nimport * as http from 'http';\nimport * as https from 'https';\nimport { extname } from 'path';\nimport { readFileSync } from 'fs';\nimport html from './html/server.html';\nimport { inject } from '@symlinks/symlinks.module';\nimport { prefix } from '@components/banner.component';\nimport { readdir, stat, readFile } from 'fs/promises';\nimport { resolve, join } from '@components/path.component';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { FrameworkService } from '@services/framework.service';\n\n/**\n * Provides a basic HTTP/HTTPS server module with static file serving\n * and directory listing capabilities.\n *\n * @remarks\n * The `ServerModule` supports serving static files, directories, and\n * optional HTTPS configuration. It handles request logging and error\n * responses and can invoke user-defined hooks via the configuration.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * server.start();\n * ```\n *\n * @see ServerConfigurationInterface\n * @since 2.0.0\n */\n\nexport class ServerModule {\n\n /**\n * The underlying HTTP or HTTPS server instance.\n *\n * @remarks\n * This property holds the active server instance created by either {@link startHttpServer}\n * or {@link startHttpsServer}. It remains undefined until {@link start} is called.\n * The server instance is used to manage the lifecycle of the HTTP/HTTPS server,\n * including stopping and restarting operations.\n *\n * @see start\n * @see stop\n * @see restart\n * @see startHttpServer\n * @see startHttpsServer\n *\n * @since 2.0.0\n */\n\n private server?: http.Server;\n\n /**\n * Normalized absolute root directory for serving files.\n *\n * @readonly\n * @since 2.0.0\n */\n\n private readonly rootDir: string;\n\n /**\n * Injected {@link FrameworkService} instance used for path resolution and framework assets.\n *\n * @readonly\n * @see FrameworkService\n *\n * @since 2.0.0\n */\n\n private readonly framework = inject(FrameworkService);\n\n /**\n * Initializes a new {@link ServerModule} instance.\n *\n * @param config - Server configuration including host, port, HTTPS options, and hooks.\n * @param dir - Root directory from which files will be served.\n *\n * @example\n * ```ts\n * import { ServerProvider } from './server-provider';\n *\n * const serverConfig = {\n * port: 8080,\n * keyfile: './path/to/keyfile',\n * certfile: './path/to/certfile',\n * onRequest: (req, res, next) => { /* custom request handling *\\/ }\n * };\n * const provider = new ServerProvider(serverConfig, './public');\n * provider.start();\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(readonly config: ServerConfigurationInterface, dir: string) {\n this.rootDir = resolve(dir);\n this.config.port ||= 0;\n this.config.host ||= 'localhost';\n }\n\n /**\n * Starts the HTTP or HTTPS server based on configuration.\n *\n * @returns A promise that resolves when the server is fully started and listening.\n *\n * @remarks\n * This method performs the following steps:\n * 1. Invokes the optional {@link ServerConfigurationInterface.onStart} hook if provided.\n * 2. Determines whether to start an HTTPS or HTTP server based on the {@link ServerConfigurationInterface.https} flag.\n * 3. Calls {@link startHttpsServer} if HTTPS is enabled, otherwise calls {@link startHttpServer}.\n *\n * @example\n * ```ts\n * const server = new ServerModule({\n * port: 3000,\n * host: 'localhost',\n * https: true,\n * onStart: () => console.log('Server starting...')\n * }, '/var/www');\n * await server.start();\n * ```\n *\n * @see stop\n * @see restart\n * @see startHttpServer\n * @see startHttpsServer\n * @see ServerConfigurationInterface\n *\n * @since 2.0.0\n */\n\n async start(): Promise<void> {\n if (this.config.https)\n return await this.startHttpsServer();\n\n await this.startHttpServer();\n }\n\n /**\n * Stops the running HTTP or HTTPS server.\n *\n * @returns A promise that resolves when the server is fully stopped.\n *\n * @remarks\n * This method gracefully shuts down the server by closing all active connections.\n * If no server is currently running, it logs a message and returns early.\n * Once stopped, the {@link server} instance is set to `undefined`.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * server.start();\n * // Later...\n * await server.stop();\n * ```\n *\n * @see start\n * @see server\n * @see restart\n *\n * @since 2.0.0\n */\n\n async stop(): Promise<void> {\n if (!this.server) {\n console.log(prefix(), xterm.gray('No server is currently running.'));\n\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n this.server!.close(err => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n console.log(prefix(), xterm.dim('Server stopped.'));\n this.server = undefined;\n }\n\n /**\n * Restarts the HTTP or HTTPS server.\n *\n * @returns A promise that resolves when the server has been stopped and restarted.\n *\n * @remarks\n * This method performs a graceful restart by first calling {@link stop} to shut down\n * the current server instance, then calling {@link start} to create a new server\n * with the same configuration. This is useful when configuration changes need to be\n * applied or when recovering from errors.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * server.start();\n * // Later, restart the server...\n * await server.restart();\n * ```\n *\n * @see stop\n * @see start\n *\n * @since 2.0.0\n */\n\n async restart(): Promise<void> {\n console.log(prefix(), xterm.burntOrange('Restarting server...'));\n await this.stop();\n await this.start();\n }\n\n /**\n * Updates the configuration with the actual port assigned by the system.\n *\n * @remarks\n * This method is called after the server starts listening to retrieve and store the\n * actual port number when port `0` was specified in the configuration. When port `0`\n * is used, the operating system automatically assigns an available port, and this\n * method captures that assigned port for use throughout the application.\n *\n * **When this method is needed**:\n * - {@link ServerConfigurationInterface.port} is set to `0` (dynamic port allocation)\n * - The server has started and bound to a port\n * - The actual port needs to be known for logging, testing, or external configuration\n *\n * **Behavior**:\n * 1. Checks if the configured port is `0` (indicating dynamic allocation request)\n * 2. Retrieves the address information from the active server using {@link Server.address}\n * 3. Validates that the address is an object containing a port property\n * 4. Updates {@link config.port} with the system-assigned port number\n *\n * This is particularly useful in:\n * - Testing environments where multiple servers run simultaneously\n * - CI/CD pipelines where port conflicts must be avoided\n * - Containerized deployments with dynamic port mapping\n * - Development tools that spawn multiple server instances\n *\n * The method safely handles cases where the server address might not be available\n * or might not be in the expected format, preventing runtime errors.\n *\n * @example\n * ```ts\n * // Configuration with dynamic port\n * const config = { port: 0, host: 'localhost' };\n * const server = new ServerModule(config, '/var/www');\n *\n * await server.start();\n * // After start, setActualPort() is called internally\n *\n * console.log(config.port); // Now shows actual assigned port, e.g., 54321\n *\n * // Use case: Testing with dynamic ports\n * async function createTestServer() {\n * const config = { port: 0, host: 'localhost' };\n * const server = new ServerModule(config, './public');\n * await server.start();\n * // setActualPort() has updated config.port\n * return { server, port: config.port }; // Return actual port for tests\n * }\n *\n * const { server, port } = await createTestServer();\n * console.log(`Test server running on port ${port}`);\n * ```\n *\n * @see Server.address\n * @see startHttpServer\n * @see startHttpsServer\n * @see ServerConfigurationInterface.port\n *\n * @since 2.0.0\n */\n\n private setActualPort(): void {\n if (this.config.port === 0) {\n const address = this.server!.address();\n if(address && typeof address === 'object' && address.port)\n this.config.port = address.port;\n }\n }\n\n /**\n * Starts an HTTP server.\n *\n * @returns A promise that resolves when the server is listening and ready to accept connections.\n *\n * @remarks\n * Creates an HTTP server instance using Node.js's built-in {@link http} module.\n * All incoming requests are passed to {@link handleRequest}, which routes them to\n * {@link defaultResponse} for serving static files or directories.\n *\n * The server listens on the configured {@link ServerConfigurationInterface.host} and\n * {@link ServerConfigurationInterface.port} from the {@link config}.\n *\n * @example\n * ```ts\n * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');\n * await server.start(); // Internally calls startHttpServer if HTTPS is not configured\n * ```\n *\n * @see start\n * @see handleRequest\n * @see defaultResponse\n * @see ServerConfigurationInterface\n *\n * @since 2.0.0\n */\n\n private startHttpServer(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.server = http.createServer((req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n this.server.listen(this.config.port, this.config.host, () => {\n this.setActualPort();\n this.config.onStart?.({\n host: this.config.host!,\n port: this.config.port!,\n url: `http://${ this.config.host }:${ this.config.port }`\n });\n resolve();\n });\n });\n }\n\n /**\n * Starts an HTTPS server using configured certificate and key files.\n *\n * @returns A promise that resolves when the server is listening and ready to accept connections.\n *\n * @remarks\n * Creates an HTTPS server instance using Node.js's built-in {@link https} module.\n * If {@link ServerConfigurationInterface.key} or {@link ServerConfigurationInterface.cert}\n * are not provided in the configuration, defaults are loaded from the framework's\n * distribution path at `certs/server.key` and `certs/server.crt`.\n *\n * All incoming requests are passed to {@link handleRequest}, which routes them to\n * {@link defaultResponse} for serving static files or directories.\n *\n * The server listens on the configured {@link ServerConfigurationInterface.host} and\n * {@link ServerConfigurationInterface.port} from the {@link config}.\n *\n * @example\n * ```ts\n * const server = new ServerModule({\n * port: 3000,\n * host: 'localhost',\n * https: true,\n * key: './path/to/key.pem',\n * cert: './path/to/cert.pem'\n * }, '/var/www');\n * await server.start(); // Internally calls startHttpsServer\n * ```\n *\n * @see start\n * @see handleRequest\n * @see defaultResponse\n * @see FrameworkService\n * @see ServerConfigurationInterface\n *\n * @since 2.0.0\n */\n\n private startHttpsServer(): Promise<void> {\n return new Promise((resolve) => {\n const options = {\n key: readFileSync(this.config.key ?? join(this.framework.distPath, '..', 'certs', 'server.key')),\n cert: readFileSync(this.config.cert ?? join(this.framework.distPath, '..', 'certs', 'server.crt'))\n };\n\n this.server = https.createServer(options, (req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n this.server.listen(this.config.port, this.config.host, () => {\n this.setActualPort();\n this.config.onStart?.({\n host: this.config.host!,\n port: this.config.port!,\n url: `https://${ this.config.host }:${ this.config.port }`\n });\n resolve();\n });\n });\n }\n\n /**\n * Handles incoming HTTP/HTTPS requests, optionally invoking user-defined hooks.\n *\n * @param req - Incoming HTTP request.\n * @param res - Server response object.\n * @param defaultHandler - Callback for default request handling.\n *\n * @remarks\n * If `config.verbose` is true, logs requests to the console.\n * Errors during handling are forwarded to {@link sendError}.\n *\n * @see sendError\n * @since 2.0.0\n */\n\n private handleRequest(req: IncomingMessage, res: ServerResponse, defaultHandler: () => void): void {\n try {\n if(this.config.verbose) {\n console.log(\n `${ prefix() } Request ${ xterm.lightCoral(req.url?.toString() ?? '') }`\n );\n }\n\n if (this.config.onRequest) {\n this.config.onRequest(req, res, defaultHandler);\n } else {\n defaultHandler();\n }\n } catch (error) {\n this.sendError(res, <Error> error);\n }\n }\n\n /**\n * Returns the MIME content type for a given file extension.\n *\n * @param ext - File extension without the leading dot.\n * @returns MIME type string for the provided extension.\n *\n * @since 2.0.0\n */\n\n private getContentType(ext: string): string {\n const contentTypes: Record<string, string> = {\n html: 'text/html',\n css: 'text/css',\n js: 'application/javascript',\n cjs: 'application/javascript',\n mjs: 'application/javascript',\n ts: 'text/plain',\n map: 'application/json',\n json: 'application/json',\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n txt: 'text/plain'\n };\n\n return contentTypes[ext] || 'application/octet-stream';\n }\n\n /**\n * Handles default responses for requests by serving files or directories.\n *\n * @param req - Incoming HTTP request.\n * @param res - Server response.\n *\n * @remarks\n * Ensures the requested path is within the server root.\n * Calls {@link handleDirectory} or {@link handleFile} depending on resource type.\n *\n * @see handleFile\n * @see sendNotFound\n * @see handleDirectory\n *\n * @since 2.0.0\n */\n\n private async defaultResponse(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const requestPath = req.url === '/' ? '' : req.url?.replace(/^\\/+/, '') || '';\n const fullPath = join(this.rootDir, requestPath);\n\n if (!fullPath.startsWith(this.rootDir)) {\n res.statusCode = 403;\n res.end();\n\n return;\n }\n\n try {\n const stats = await stat(fullPath);\n\n if (stats.isDirectory()) {\n await this.handleDirectory(fullPath, requestPath, res);\n } else if (stats.isFile()) {\n await this.handleFile(fullPath, res);\n }\n } catch (error) {\n const msg = (<Error> error).message;\n if (!msg.includes('favicon')) {\n console.log(prefix(), msg);\n }\n\n this.sendNotFound(res);\n }\n }\n\n /**\n * Handles directory listing for a request path.\n *\n * @param fullPath - Absolute directory path.\n * @param requestPath - Relative path from the server root.\n * @param res - Server response.\n *\n * @remarks\n * Generates an HTML listing with icons\n * Invalid filenames are skipped.\n *\n * @see fileIcons\n * @since 2.0.0\n */\n\n private async handleDirectory(fullPath: string, requestPath: string, res: ServerResponse): Promise<void> {\n const files = await readdir(fullPath);\n let fileList = files.map(file => {\n const fullPath = join(requestPath, file);\n const ext = extname(file).slice(1) || 'folder';\n\n if(ext === 'folder') {\n return `\n <a href=\"/${ fullPath }\" class=\"folder-row\">\n <div class=\"icon\"><i class=\"fa-solid fa-folder\"></i></div>\n <div class=\"meta\"><div class=\"name\">${ file }</div><div class=\"sub\">Folder</div></div>\n </a>\n `;\n }\n\n return `\n <a href=\"/${ fullPath }\" class=\"file-row\">\n <div class=\"icon\"><i class=\"fa-solid fa-file-code\"></i></div>\n <div class=\"meta\"><div class=\"name\">${ file }</div><div class=\"sub\">${ ext }</div></div>\n </a>\n `;\n }).join('');\n\n if(!fileList) {\n fileList = '<div class=\"empty\">No files or folders here.</div>';\n } else {\n fileList = `<div class=\"list\">${ fileList }</div>`;\n }\n\n let activePath = '/';\n const segments = requestPath.split('/').map(path => {\n activePath += `${ path }/`;\n\n return `<li><a href=\"${ activePath }\">${ path }</a></li>`;\n }).join('');\n\n const htmlResult = html.replace('${ fileList }', fileList)\n .replace('${ paths }', '<li><a href=\"/\">root</a></li>' + segments)\n .replace('${ up }', '/' + requestPath.split('/').slice(0, -1).join('/'));\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(htmlResult);\n }\n\n /**\n * Serves a static file.\n *\n * @param fullPath - Absolute path to the file.\n * @param res - Server response.\n *\n * @remarks\n * Determines MIME type using {@link getContentType}.\n *\n * @see getContentType\n * @since 2.0.0\n */\n\n private async handleFile(fullPath: string, res: ServerResponse): Promise<void> {\n const ext = extname(fullPath).slice(1) || 'txt';\n const contentType = this.getContentType(ext);\n\n const data = await readFile(fullPath);\n res.writeHead(200, { 'Content-Type': contentType });\n res.end(data);\n }\n\n /**\n * Sends a 404 Not Found response.\n *\n * @param res - Server response.\n *\n * @since 2.0.0\n */\n\n private sendNotFound(res: ServerResponse): void {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n\n /**\n * Sends a 500 Internal Server Error response and logs the error.\n *\n * @param res - Server response.\n * @param error - Error object to log.\n *\n * @since 2.0.0\n */\n\n private sendError(res: ServerResponse, error: Error): void {\n console.error(prefix(), error.toString());\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end('Internal Server Error');\n }\n}\n", "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/><title>Dark File Browser \u2014 FTP-like</title><link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css\" integrity=\"sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class=\"app\"><aside class=\"sidebar\"><div class=\"brand\"><div class=\"logo\">F</div><div><h1>xBuildFTP</h1><div class=\"muted\">Browse & serve files</div></div></div><div class=\"search\"><input placeholder=\"Search files & folders...\"/></div><div class=\"quick-list\"><a href=\"/\">\uD83C\uDFE0 Home</a><a href=\"${ up }\">\u2B06\uFE0F Up</a></div></aside><main class=\"main\"><div class=\"topbar\"><div class=\"topbar\"><ul class=\"breadcrumbs\"> ${ paths } </ul></div></div> ${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>", "/**\n * Imports\n */\n\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\n\n/**\n * ASCII Logo and Version Information\n *\n * @remarks\n * The `asciiLogo` constant stores an ASCII representation of the project logo\n * that will be displayed in the banner. This banner is rendered in a formatted\n * string in the `bannerComponent` function.\n *\n * The `cleanScreen` constant contains an ANSI escape code to clear the terminal screen.\n */\n\nexport const asciiLogo = `\n ______ _ _ _\n | ___ \\\\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\\\ \\\\/ / ___ \\\\ | | | | |/ _\\` |\n > <| |_/ / |_| | | | (_| |\n/_/\\\\_\\\\____/ \\\\__,_|_|_|\\\\__,_|\n`;\n\n/**\n * Renders the banner with the ASCII logo and version information.\n *\n * @returns A formatted string containing the ASCII logo and version number with color formatting\n *\n * @remarks\n * This function constructs and returns a formatted banner string that includes:\n * - An ASCII logo rendered in burnt orange\n * - The current version number displayed in bright pink\n *\n * The function uses ANSI color codes through the xterm utility to create visually\n * distinct elements in the banner. The version number is retrieved from the global\n * `__VERSION` variable.\n *\n * The banner is designed with appropriate spacing and carriage returns to ensure\n * a consistent display across different terminal environments.\n *\n * @example\n * ```ts\n * // Display the banner in the console.\n * console.log(bannerComponent());\n * ```\n *\n * @since 1.0.0\n */\n\nexport function bannerComponent(): string {\n return `\n \\r${ xterm.burntOrange(asciiLogo) }\n \\rVersion: ${ xterm.brightPink(__VERSION) }\n \\r`;\n}\n\n/**\n * Returns a formatted prefix string for xBuild log messages.\n *\n * @returns A string containing the xBuild prefix formatted in light coral color\n *\n * @remarks\n * This function creates a consistent, visually distinct prefix for all xBuild\n * logging output. The prefix is formatted with light coral coloring using the\n * xterm color utility to make xBuild logs easily identifiable in console output.\n *\n * The function is used throughout the build system to maintain consistent\n * log formatting and improve readability when multiple tools or processes\n * are outputting to the same console.\n *\n * @example\n * ```ts\n * // Basic usage in log messages\n * console.log(`${prefix()} Starting build process...`);\n * // Output: \"[xBuild] Starting build process...\" (with \"[xBuild]\" in light coral)\n *\n * // In a logger utility\n * function log(message: string): void {\n * console.log(`${prefix()} ${message}`);\n * }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function prefix(): string {\n return xterm.lightCoral('[xBuild]');\n}\n", "/**\n * Imports\n */\n\nimport { matchesGlob } from 'path';\nimport { stat, watch } from 'fs/promises';\nimport { inject } from '@symlinks/symlinks.module';\nimport { normalize, join } from '@components/path.component';\nimport { FrameworkService } from '@services/framework.service';\n\n/**\n * Provides a file-watching service that tracks changes in the framework's root directory.\n *\n * @remarks\n * This service sets up a recursive file system watcher, filters excluded files,\n * and debounces changes to optimize performance. It is mainly used for monitoring\n * source files or test files and triggering callbacks on changes.\n *\n * @example\n * ```ts\n * const watcher = new WatchService(['**\\/node_modules\\/**']);\n * await watcher.start((changedFiles) => {\n * console.log('Changed files:', changedFiles);\n * });\n * ```\n *\n * @see FrameworkService\n * @since 2.0.0\n */\n\nexport class WatchService {\n /**\n * Glob patterns that **exclude** paths from being emitted.\n *\n * @remarks\n * Patterns use **Node.js native glob semantics** via `matchesGlob`.\n * Negation syntax (`!pattern`) is **not supported** and must be expressed\n * through explicit include/exclude separation.\n *\n * Typical examples:\n *\n * - `**\\/node_modules\\/**`\n * - `**\\/dist\\/**`\n * - `**\\/*.spec.ts`\n *\n * @since 2.0.0\n */\n\n readonly excludes: Array<string>;\n\n /**\n * Glob patterns that **allow** paths to be emitted.\n *\n * @remarks\n * A file must match **at least one** an include pattern to be considered.\n * Defaults to `['**\\/*']`, meaning all files are eligible unless excluded.\n *\n * @since 2.0.0\n */\n\n readonly include: Array<string>;\n\n\n /**\n * Timer used for debouncing file change events.\n *\n * @remarks\n * When multiple file changes occur in quick succession, this timer ensures that\n * the `handleChangedFiles` method is called only once after a short delay,\n * preventing redundant executions and improving performance.\n *\n * @since 2.0.0\n */\n\n private debounceTimer: NodeJS.Timeout | null = null;\n\n /**\n * Reference to the core {@link FrameworkService}.\n *\n * @remarks\n * Injected via the {@link inject} helper, this service provides access to\n * framework-level configuration such as the project root path, runtime\n * environment, and shared utilities.\n * It is used here for resolving relative paths and coordinating with the\n * broader testing infrastructure.\n *\n * @see inject\n * @see FrameworkService\n *\n * @since 2.0.0\n */\n\n private readonly framework: FrameworkService = inject(FrameworkService);\n\n /**\n * Creates a new {@link WatchService}.\n *\n * @param excludes - Glob patterns to ignore.\n * @param include - Glob patterns to allow. Defaults to `['**\\/*']`.\n *\n * @remarks\n * Include and exclude rules are evaluated as:\n *\n * ```\n * included AND NOT excluded\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(excludes: Array<string> = [], include: Array<string> = [ '**/*' ]) {\n this.include = include;\n this.excludes = excludes;\n }\n\n /**\n * Start the file watcher.\n *\n * @param callback - Function to call with the changed file paths.\n * Expects a callback that accepts an array of files.\n * @returns A promise that resolves when the watcher is ready.\n *\n * @remarks\n * This method performs the following steps:\n * 1. Sets up a recursive file system watcher on the framework's root directory.\n * 2. On file changes, normalizes paths, filters excluded files, and schedules\n * handling of changed files with a debouncing to avoid excessive executions.\n *\n * @example\n * ```ts\n * const watcher = new WatchService();\n * await watcher.start((changedFiles) => {\n * console.log('Files changed:', changedFiles);\n * });\n * ```\n *\n * @see handleChangedFiles\n *\n * @since 2.0.0\n */\n\n async start(callback: (files: Array<string>) => void): Promise<void> {\n const changedFilesSet = new Set<string>();\n const watcher = watch(this.framework.rootPath, { recursive: true });\n for await (const { filename } of watcher) {\n if (!filename) continue;\n\n const fullPath = normalize(filename);\n if (fullPath.endsWith('~')) continue;\n\n if (!this.include.some((pattern) => matchesGlob(fullPath, pattern))) continue;\n if (this.excludes.some((pattern) => matchesGlob(fullPath, pattern))) continue;\n\n // Check if the path is a file (not a directory)\n const absolutePath = join(this.framework.rootPath, fullPath);\n try {\n const stats = await stat(absolutePath);\n if (!stats.isFile()) continue;\n } catch {\n // File might have been deleted or doesn't exist yet\n }\n\n changedFilesSet.add(fullPath);\n this.debounce(() => this.handleChangedFiles(callback, changedFilesSet));\n }\n }\n\n /**\n * Handles the changed files after debouncing.\n *\n * @param callback - Function to call with the changed file paths. Expects a callback that accepts an array of files.\n * @param changedFilesSet - Set of changed file paths containing normalized paths of modified files.\n *\n * @remarks\n * Executes the callback with a copy of the changed files and then clears the set\n * for the next batch of changes.\n *\n * @see start\n * @see debounce\n *\n * @since 2.0.0\n */\n\n private async handleChangedFiles(callback: (files: Array<string>) => void, changedFilesSet: Set<string>): Promise<void> {\n callback?.([ ...changedFilesSet ]);\n changedFilesSet.clear();\n }\n\n /**\n * Debounce the execution of a function to limit how frequently it runs.\n *\n * @param fn - The function to execute after the debounced delay.\n * @param delay - Optional debounce delay in milliseconds (default is 150 ms).\n *\n * @remarks\n * If multiple calls are made within the delay period, only the last one will execute.\n * This is used in the file watcher to prevent excessive calls to handle file changes\n * when multiple filesystem events occur in quick succession.\n *\n * @see debounceTimer\n * @see handleChangedFiles\n *\n * @since 2.0.0\n */\n\n private debounce(fn: () => void, delay = 150): void {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(fn, delay);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LifecycleProvider } from '@providers/lifecycle.provider';\nimport type { BuildOptions, OnStartResult, BuildResult } from 'esbuild';\nimport type { DiagnosticInterface } from '@typescript/typescript.module';\nimport type { VariantBuildInterface } from '@interfaces/configuration.interface';\nimport type { UnsubscribeType } from '@observable/interfaces/observable.interface';\nimport type { ResultContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { ConfigSubscriptionInterface } from '@services/interfaces/variant-service.interface';\nimport type { CommonBuildInterface, LifecycleHooksInterface } from '@interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { build } from 'esbuild';\nimport { writeFile, mkdir } from 'fs/promises';\nimport { TypesError } from '@errors/types.error';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { deepMerge } from '@components/object.component';\nimport { Typescript } from '@typescript/typescript.module';\nimport { analyzeDependencies } from '@services/transpiler.service';\nimport { relative, resolve, join } from '@components/path.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { extractEntryPoints } from '@components/entry-points.component';\nimport { isBuildResultError } from '@providers/esbuild-messages.provider';\n\n/**\n * Manages a single build \u201Cvariant\u201D (e.g. `dev`, `prod`) end-to-end.\n *\n * @remarks\n * A variant combines:\n * - Variant-specific configuration (esbuild options, hooks, define/banner/footer)\n * - Common configuration shared across variants\n *\n * Responsibilities:\n * - Merge and normalize configuration (`initializeConfig`)\n * - Register lifecycle hooks (core + user-defined)\n * - Keep a TypeScript service instance in sync (type-checking + declaration emission)\n * - Build using esbuild\n * - Hot-reload on configuration changes (temporarily deactivating builds during updates)\n *\n * @example\n * ```ts\n * const variant = new VariantService('production', lifecycle, variantConfig, { watch: true });\n *\n * // Build once\n * await variant.build();\n *\n * // Access computed dependency entry points (only meaningful when bundle=false)\n * console.log(Object.keys(variant.dependencies));\n *\n * // Cleanup\n * variant.dispose();\n * ```\n *\n * @since 2.0.0\n */\n\nexport class VariantService {\n /**\n * Dependency-to-entry-point map produced by {@link buildDependencyMap}.\n *\n * @remarks\n * This map is always refreshed before each build. When `esbuild.bundle === false`,\n * it is assigned to `esbuild.entryPoints` so that every discovered input becomes an entry point.\n *\n * Keys are output-like paths (relative to `rootDir`) **without** file extensions.\n * Values are source file paths.\n *\n * @example\n * ```ts\n * // Example shape:\n * // {\n * // \"index\": \"/abs/path/src/index.ts\",\n * // \"utils/math\": \"/abs/path/src/utils/math.ts\"\n * // }\n * console.log(variant.dependencies);\n * ```\n *\n * @since 2.0.0\n */\n\n private dependenciesFile: undefined | Record<string, string>;\n\n /**\n * Indicates whether this variant is currently active and should execute builds.\n *\n * @remarks\n * Set to `false` temporarily during configuration updates to prevent builds from running\n * with stale configuration. Re-enabled after configuration is successfully reloaded.\n *\n * @since 2.0.0\n */\n\n private active: boolean = true;\n\n /**\n * Path of the TypeScript configuration file currently in use.\n *\n * @remarks\n * Tracks the tsconfig file for this variant. When configuration changes and a different\n * tsconfig is specified, the old TypeScript instance is disposed and a new one is created.\n *\n * @since 2.0.0\n */\n\n private tsConfigPath: string;\n\n /**\n * TypeScript language service instance for type checking and declaration generation.\n *\n * @remarks\n * Manages the TypeScript compiler for this variant, providing type checking diagnostics\n * and declaration file emission. Recreated when tsconfig changes.\n *\n * @since 2.0.0\n */\n\n private typescriptModule: Typescript;\n\n /**\n * Unsubscribe function for configuration change subscription.\n *\n * @remarks\n * Called during disposal to stop listening to configuration updates and prevent memory leaks.\n *\n * @since 2.0.0\n */\n\n private readonly configUnsubscribe: UnsubscribeType;\n\n /**\n * Configuration service instance providing reactive configuration access.\n *\n * @remarks\n * Injected dependency for accessing and subscribing to build configuration changes.\n *\n * @since 2.0.0\n */\n\n private readonly configService = inject(ConfigurationService);\n\n /**\n * Creates a new variant service instance.\n *\n * @param name - Variant name (used for configuration lookup and hook identification)\n * @param lifecycle - Lifecycle provider used to register build hooks/plugins\n * @param buildConfig - Initial variant build configuration\n * @param argv - Optional CLI/extra arguments passed to dynamic config functions\n *\n * @remarks\n * During construction this service:\n * - Initializes the TypeScript module using `esbuild.tsconfig` (default: `\"tsconfig.json\"`)\n * - Merges variant configuration with common configuration\n * - Normalizes/expands entry points\n * - Registers core lifecycle hooks (`start`/`end`)\n * - Subscribes to configuration changes for hot-reload\n *\n * @example\n * ```ts\n * const variant = new VariantService(\n * 'dev',\n * lifecycle,\n * config,\n * { watch: true }\n * );\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(\n readonly name: string,\n private lifecycle: LifecycleProvider,\n private buildConfig: VariantBuildInterface,\n private argv: Record<string, unknown> = {}\n ) {\n if (!this.buildConfig?.esbuild) {\n throw new xBuildError(`Variant '${ this.name }' not found configuration`);\n }\n\n this.tsConfigPath = this.buildConfig.esbuild.tsconfig ?? 'tsconfig.json';\n this.typescriptModule = new Typescript(this.tsConfigPath);\n this.buildConfig = this.initializeConfig(\n this.getConfig(this.buildConfig, this.configService.getValue().common)!\n );\n\n this.typescriptModule.languageHostService.touchFiles(\n Object.values(<Record<string, string>> this.buildConfig.esbuild.entryPoints)\n );\n\n this.lifecycle.onEnd(this.end.bind(this), `${ this.name }-core`);\n this.lifecycle.onStart(this.start.bind(this), `${ this.name }-core`);\n\n this.configUnsubscribe = this.configService.select(config => ({\n variantConfig: config.variants?.[this.name],\n commonConfig: config.common\n })).subscribe(\n this.handleConfigChange.bind(this),\n error => {\n throw error;\n }\n );\n }\n\n /**\n * Provides access to the TypeScript language service instance for this variant.\n *\n * @returns The TypeScript module instance used for type checking and declaration generation\n *\n * @remarks\n * This getter exposes the variant's TypeScript language service, which provides:\n * - Type checking and diagnostics\n * - Declaration file generation\n * - File change tracking\n * - TypeScript compiler integration\n *\n * The TypeScript module is initialized during construction with the variant's `tsconfig.json`\n * configuration and is recreated when the TypeScript configuration file path changes during\n * hot-reload. The instance is disposed when the variant service is disposed.\n *\n * Use this getter to access TypeScript functionality externally, such as\n * - Manually triggering type checks\n * - Accessing diagnostics without building\n * - Integrating with IDE tooling\n * - Custom declaration file processing\n *\n * @example\n * ```ts\n * const service = new VariantService('production', lifecycle);\n * const typescript = service.typescript;\n *\n * // Check for type errors\n * const diagnostics = typescript.check();\n * console.log(`Found ${diagnostics.length} type errors`);\n *\n * // Emit declarations manually\n * await typescript.emit('types');\n * ```\n *\n * @see {@link dispose}\n * @see {@link Typescript}\n * @see {@link touchFiles}\n *\n * @since 2.0.0\n */\n\n get typescript(): Typescript {\n return this.typescriptModule;\n }\n\n /**\n * Provides access to the merged build configuration for this variant.\n *\n * @returns The complete variant build configuration including esbuild options, TypeScript settings, and lifecycle hooks\n *\n * @remarks\n * This getter exposes the variant's fully merged configuration, which combines:\n * - Common configuration shared across all variants\n * - Variant-specific configuration overrides\n * - Applied to define replacements\n * - Configured lifecycle hooks\n * - TypeScript and declaration settings\n *\n * The configuration is automatically updated when hot-reload detects changes to the\n * configuration file. The returned object reflects the current active configuration\n * used for builds.\n *\n * Configuration structure includes:\n * - `esbuild`: esbuild compiler options (entry points, output, format, minification)\n * - `types`: TypeScript type checking settings\n * - `declaration`: Declaration file generation settings\n * - `define`: Compile-time constant replacements\n * - `banner`: Text to prepend to output files\n * - `footer`: Text to append to output files\n * - `lifecycle`: Custom build lifecycle hooks\n *\n * Use this getter to:\n * - Inspect current build settings\n * - Debug configuration merging\n * - Access configuration in custom lifecycle hooks\n * - Validate variant settings\n *\n * @example\n * ```ts\n * const service = new VariantService('production', lifecycle);\n * const config = service.config;\n *\n * console.log(`Minification: ${config.esbuild.minify}`);\n * console.log(`Output format: ${config.esbuild.format}`);\n * console.log(`Type checking: ${config.types !== false}`);\n * ```\n *\n * @example\n * ```ts\n * // Access in lifecycle hook\n * lifecycle.onStart(async (context) => {\n * const config = variantService.config;\n * if (config.esbuild.minify) {\n * console.log('Building minified output');\n * }\n * });\n * ```\n *\n * @see {@link getConfig}\n * @see {@link handleConfigChange}\n * @see {@link VariantBuildInterface}\n *\n * @since 2.0.0\n */\n\n get config(): VariantBuildInterface {\n return this.buildConfig;\n }\n\n /**\n * Returns the latest dependency entry-point map computed for this variant.\n *\n * @remarks\n * Mainly useful when `esbuild.bundle === false`, because in that mode the build\n * rewrites `esbuild.entryPoints` to this map.\n *\n * @example\n * ```ts\n * await variant.build();\n * for (const [outPath, sourcePath] of Object.entries(variant.dependencies)) {\n * console.log(outPath, '->', sourcePath);\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n get dependencies(): Record<string, string> {\n return this.dependenciesFile ?? {};\n }\n\n /**\n * Disposes this variant service instance and releases resources.\n *\n * @remarks\n * Disposal performs two cleanup steps:\n * 1. Unsubscribes from configuration updates (stops hot-reload notifications)\n * 2. Releases the underlying TypeScript service resources for the current `tsconfig` path\n *\n * Call this when the variant is no longer needed to avoid keeping subscriptions alive and\n * to prevent TypeScript language service instances from lingering in memory.\n *\n * @example\n * ```ts\n * const variant = new VariantService('dev', lifecycle, config);\n *\n * // ... run builds, watch, etc. ...\n *\n * variant.dispose();\n * ```\n *\n * @since 2.0.0\n */\n\n dispose(): void {\n this.configUnsubscribe();\n this.typescriptModule.dispose(this.tsConfigPath);\n }\n\n /**\n * Notifies the TypeScript language service that files have been modified.\n *\n * @param files - Array of file paths that have been modified\n *\n * @remarks\n * This method updates the TypeScript language service's internal state to reflect\n * file changes, ensuring type checking and diagnostics remain accurate. Typically\n * called by file watchers when source files are modified.\n *\n * The TypeScript module will invalidate cached diagnostics for the touched files\n * and recalculate them on the next type check.\n *\n * @example\n * ```ts\n * // In a file watcher\n * watcher.on('change', (filePath) => {\n * service.touchFiles([filePath]);\n * });\n * ```\n *\n * @see {@link Typescript.touchFiles}\n *\n * @since 2.0.0\n */\n\n touchFiles(files: Array<string>): void {\n this.typescriptModule.touchFiles(files);\n }\n\n /**\n * Performs TypeScript type checking for all files in the variant's dependency graph.\n *\n * @returns Array of diagnostic information containing errors, warnings, and suggestions\n *\n * @remarks\n * This method executes type checking on all source files discovered through dependency\n * analysis. It ensures the dependency map is built before checking, building it lazily\n * on the first invocation if not already available.\n *\n * The type checking process:\n * 1. Builds the dependency map if not already cached (first invocation only)\n * 2. Extracts all source file paths from the dependency map\n * 3. Passes the file list to the TypeScript module for semantic analysis\n * 4. Returns diagnostics for all type errors, warnings, and suggestions\n *\n * This method can be called independently of the build process to perform\n * type checking without compilation. It's also used internally by the `start`\n * lifecycle hook during builds when type checking is enabled.\n *\n * The dependency file map is cached after the first build, so subsequent\n * type checks reuse the same file list unless the variant is rebuilt or\n * dependencies change.\n *\n * @example\n * ```ts\n * const service = new VariantService('production', lifecycle, config);\n *\n * // Check types without building\n * const diagnostics = await service.check();\n *\n * if (diagnostics.length > 0) {\n * console.error(`Found ${diagnostics.length} type issues`);\n * diagnostics.forEach(d => {\n * console.error(`${d.file}:${d.line}:${d.column} - ${d.message}`);\n * });\n * }\n * ```\n *\n * @example\n * ```ts\n * // Used in CI pipeline\n * const errors = (await service.check()).filter(\n * d => d.category === DiagnosticCategory.Error\n * );\n *\n * if (errors.length > 0) {\n * process.exit(1);\n * }\n * ```\n *\n * @see {@link start}\n * @see {@link Typescript.check}\n * @see {@link buildDependencyMap}\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\n async check(): Promise<DiagnosticInterface[]> {\n if(!this.dependenciesFile)\n this.dependenciesFile = await this.buildDependencyMap();\n\n return this.typescriptModule.check(Object.values(this.dependenciesFile!));\n }\n\n /**\n * Executes a build for this variant.\n *\n * @returns The esbuild {@link BuildResult}, or `undefined` if the variant is inactive.\n *\n * @remarks\n * High-level steps:\n * 1. Skip if inactive (used during configuration hot-reload)\n * 2. Apply banner/footer injections\n * 3. Compute dependency map\n * 4. If `bundle === false`, replace `entryPoints` with the computed dependency map\n * 5. Run esbuild\n * 6. Write `package.json` with the correct `\"type\"` for the output format\n *\n * @example\n * ```ts\n * const result = await variant.build();\n * if (result) {\n * console.log('warnings:', result.warnings.length);\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n async build(): Promise<BuildResult | undefined> {\n if (!this.active) return;\n this.applyInjections();\n\n const config = Object.assign({}, this.buildConfig.esbuild);\n this.dependenciesFile = await this.buildDependencyMap();\n if (this.buildConfig.esbuild.bundle === false) {\n Object.assign(config, { entryPoints: this.dependenciesFile });\n }\n\n try {\n const result = await build(config);\n await this.packageTypeComponent();\n\n return result;\n } catch (error: unknown) {\n if (isBuildResultError(error)) {\n const errors = error.errors.filter(error => error.location);\n if (errors.length > 0) throw error;\n\n return {\n errors: error?.errors ?? [],\n warnings: error?.warnings ?? []\n } as BuildResult;\n }\n }\n }\n\n /**\n * Merges variant-specific configuration with common configuration.\n *\n * @param config - Variant-specific build configuration\n * @param common - Common build configuration shared across variants\n * @returns Merged configuration, or null if variant config is undefined\n *\n * @remarks\n * This method performs a deep merge where variant-specific settings override\n * common settings. The merge is performed using the `deepMerge` utility, which\n * recursively combines nested objects and arrays.\n *\n * Merge priority (highest to lowest):\n * 1. Variant-specific configuration\n * 2. Common configuration\n * 3. Empty object (default base)\n *\n * If the variant configuration is undefined, it returns null to signal that the\n * variant doesn't exist.\n *\n * @example\n * ```ts\n * const common = { esbuild: { minify: false } };\n * const variant = { esbuild: { minify: true, sourcemap: true } };\n * const merged = getConfig(variant, common);\n * // Result: { esbuild: { minify: true, sourcemap: true } }\n * ```\n *\n * @see {@link deepMerge}\n *\n * @since 2.0.0\n */\n\n private getConfig(config?: VariantBuildInterface, common: CommonBuildInterface = {}): VariantBuildInterface | null {\n if (!config) return null;\n\n return deepMerge<VariantBuildInterface>(\n {} as VariantBuildInterface,\n common,\n config\n );\n }\n\n /**\n * Core start hook handler that runs type checking and declaration generation.\n *\n * @returns Start result containing any type errors and warnings\n *\n * @remarks\n * This private method is registered as an onStart hook during construction and executes\n * at the beginning of each build. It runs two tasks concurrently:\n * 1. **Type checking**: Validates TypeScript types and reports diagnostics\n * 2. **Declaration generation**: Emits .d.ts declaration files\n *\n * Both tasks run in parallel using `Promise.all` for optimal performance.\n *\n * Type checking behavior depends on the `types` configuration:\n * - If `types.failOnError` is false, type errors become warnings\n * - If `types.failOnError` is true (default), type errors fail the build\n *\n * Declaration generation behavior depends on the `declaration` configuration:\n * - If `declaration.bundle` is true (default), declarations are bundled\n * - If `declaration.bundle` is false, individual declarations are emitted\n * - Custom output directory can be specified with `declaration.outDir`\n *\n * @since 2.0.0\n */\n\n private async start(): Promise<OnStartResult | undefined> {\n const result: OnStartResult = { errors: [], warnings: [] };\n if (!this.buildConfig.types) return result;\n\n const diagnostics = this.typescriptModule.check(\n Object.values(this.dependenciesFile ?? {})\n );\n\n if (diagnostics.length === 0) return result;\n const buildOnError = typeof this.buildConfig.types === 'object' &&\n !this.buildConfig.types.failOnError;\n\n if (buildOnError) {\n const error = new TypesError('Type checking failed', diagnostics);\n result.warnings?.push({ detail: error, location: undefined });\n } else {\n const errors: Array<DiagnosticInterface> = [];\n const warnings: Array<DiagnosticInterface> = [];\n const error = new TypesError('Type checking failed', errors);\n const warning = new TypesError('Type checking failed', warnings);\n\n for (const d of diagnostics) {\n (d.category === ts.DiagnosticCategory.Error ? errors : warnings).push(d);\n }\n\n if(errors.length)\n result.errors?.push({ detail: error, location: undefined });\n\n if(warnings.length)\n result.warnings?.push({ detail: warning, location: undefined });\n }\n\n return result;\n }\n\n /**\n * Core end hook handler that generates declaration files after a successful build.\n *\n * @param context - The result context containing build results and metadata\n *\n * @returns Start result containing any declaration generation warnings, or undefined if build has errors\n *\n * @remarks\n * This private method is registered as an onEnd hook during construction and executes\n * at the end of each build. It performs declaration file generation only if the build is\n * completed successfully without errors.\n *\n * The method follows this execution flow:\n * 1. Checks if the build produced any errors\n * 2. Returns early (undefined) if errors exist, skipping declaration generation\n * 3. Creates a new result object for collecting warnings\n * 4. Executes declaration file emission\n * 5. Returns the result with any warnings from the emission process\n *\n * Declaration generation only runs for successful builds to avoid creating declaration\n * files for code that failed to compile. This ensures type definitions remain consistent\n * with the compiled JavaScript output.\n *\n * Any errors during declaration generation are captured as warnings and included in the\n * returned result, allowing the build to complete while reporting the issue.\n *\n * @example\n * ```ts\n * // Registered during construction\n * this.lifecycle.onEnd(this.end.bind(this), `${this.name}-core`);\n *\n * // Called automatically by lifecycle provider after build\n * // If build succeeded: generates declarations\n * // If build failed: skips declaration generation\n * ```\n *\n * @see {@link ResultContextInterface}\n * @see {@link start} for the corresponding start hook\n *\n * @since 2.0.0\n */\n\n private async end(context: ResultContextInterface): Promise<OnStartResult | undefined> {\n if (context.buildResult.errors?.length > 0) return;\n\n const result: OnStartResult = { errors: [], warnings: [] };\n if (!this.buildConfig.declaration) return;\n\n const decl = this.buildConfig.declaration;\n const shouldBundle = typeof decl === 'object' ? decl.bundle !== false : true;\n const outDir = typeof decl === 'object' ? decl.outDir : undefined;\n\n try {\n if (shouldBundle) {\n await this.typescriptModule.emitBundle(\n <Record<string, string>> this.buildConfig.esbuild.entryPoints, outDir\n );\n } else {\n await this.typescriptModule.emit(outDir);\n }\n } catch (err) {\n result.warnings?.push({ detail: err, location: undefined });\n }\n\n return result;\n }\n\n /**\n * Registers lifecycle hooks from configuration with the lifecycle provider.\n *\n * @param hooks - Lifecycle hooks interface containing hook handlers\n *\n * @remarks\n * This method extracts individual hook handlers from the configuration and\n * registers them with the variant's lifecycle provider. Hooks are registered\n * using the default variant name identifier.\n *\n * Only defined hooks are registered; undefined hooks are skipped. This allows\n * partial hook configuration where only specific lifecycle stages need custom logic.\n *\n * Hook registration order:\n * 1. onStart\n * 2. onResolve\n * 3. onLoad\n * 4. onEnd\n * 5. onSuccess\n *\n * If no hooks are provided in the configuration, the method returns early\n * without registering anything.\n *\n * @example\n * ```ts\n * // In build configuration\n * {\n * lifecycle: {\n * onStart: async (context) => {\n * console.log('Custom start hook');\n * },\n * onSuccess: async (context) => {\n * console.log('Build succeeded!');\n * }\n * }\n * }\n * ```\n *\n * @see {@link LifecycleProvider.onStart}\n * @see {@link LifecycleProvider.onResolve}\n * @see {@link LifecycleProvider.onLoad}\n * @see {@link LifecycleProvider.onEnd}\n * @see {@link LifecycleProvider.onSuccess}\n *\n * @since 2.0.0\n */\n\n private registerConfigHooks(hooks?: LifecycleHooksInterface): void {\n if (!hooks) return;\n const { onStart, onResolve, onLoad, onEnd, onSuccess } = hooks;\n\n if (onStart) this.lifecycle.onStart(onStart);\n if (onResolve) this.lifecycle.onResolve(onResolve);\n if (onLoad) this.lifecycle.onLoad(onLoad);\n if (onEnd) this.lifecycle.onEnd(onEnd);\n if (onSuccess) this.lifecycle.onSuccess(onSuccess);\n }\n\n /**\n * Generates a `package.json` file with the appropriate `type` field\n * based on the format specified in the configuration.\n *\n * - If the format is `esm`, the `type` will be set to `\"module\"`.\n * - If the format is `cjs`, the `type` will be set to `\"commonjs\"`.\n *\n * The function will ensure that the specified output directory exists, and if it doesn't,\n * it will create the necessary directories before writing the `package.json` file.\n *\n * @throws Error - throw an error if there is a problem creating the directory or writing the file.\n *\n * @example\n * ```ts\n * const config = {\n * esbuild: {\n * format: 'esm'\n * }\n * };\n * packageTypeComponent(config);\n * // This will create 'dist/package.json' with the content: {\"type\": \"module\"}\n * ```\n *\n * @since 2.0.0\n */\n\n private async packageTypeComponent(): Promise<void> {\n const outDir = this.buildConfig.esbuild.outdir ?? 'dist';\n const type = this.buildConfig.esbuild.format === 'esm' ? 'module' : 'commonjs';\n\n await mkdir(outDir, { recursive: true });\n await writeFile(join(outDir, 'package.json'), `{\"type\": \"${ type }\"}`);\n }\n\n /**\n * Validates and normalizes the merged variant configuration.\n *\n * @param config - Merged variant configuration (common + variant)\n * @returns The normalized configuration used internally for builds.\n *\n * @remarks\n * This method:\n * - Ensures required config fields exist (e.g. `esbuild.entryPoints`)\n * - Registers configured lifecycle hooks\n * - Normalizes `esbuild.tsconfig` (default: `\"tsconfig.json\"`)\n * - Expands entry points relative to `rootDir`\n * - Applies computed esbuild options (`define`, `logLevel`, and lifecycle plugin)\n *\n * @example\n * ```ts\n * // Called internally during construction and config hot-reload.\n * // You typically don't call this directly.\n * ```\n *\n * @since 2.0.0\n */\n\n private initializeConfig(config: VariantBuildInterface): VariantBuildInterface {\n if (!config) {\n throw new xBuildError(`Variant '${ this.name }' not found configuration`);\n }\n\n if (!config.esbuild.entryPoints) {\n throw new xBuildError('Entry points are required in esbuild configuration');\n }\n\n const defineFromConfig = config.define;\n const define: Record<string, string> | undefined = defineFromConfig\n ? Object.fromEntries(\n Object.entries(defineFromConfig).map(\n ([ key, value ]) => [ key, JSON.stringify(value) ]\n )\n )\n : undefined;\n\n this.registerConfigHooks(config.lifecycle);\n config.esbuild.entryPoints = extractEntryPoints(\n this.typescriptModule.config.options.rootDir ?? process.cwd(), config.esbuild.entryPoints\n );\n\n config.esbuild = Object.assign({}, config.esbuild, {\n define,\n logLevel: 'silent',\n plugins: [ this.lifecycle.create() ]\n }) as BuildOptions;\n\n return config;\n }\n\n /**\n * Handles configuration change events and updates variant settings.\n *\n * @param variantConfig - Updated variant-specific configuration\n * @param commonConfig - Updated common configuration\n *\n * @remarks\n * This method is called whenever the configuration service detects changes to the\n * variant's configuration. It performs a hot-reload of all variant settings without\n * requiring a restart.\n *\n * The reload process:\n * 1. Temporarily deactivates the variant (prevents builds during reload)\n * 2. Merges new variant and common configuration\n * 3. Validates that the variant still exists (returns if removed)\n * 4. Reactivates the variant\n * 5. Updates the build configuration\n * 6. Recreates TypeScript module if tsconfig changed\n * 7. Re-registers lifecycle hooks from a new configuration\n * 8. Reapplies define replacements and esbuild options\n * 9. Rebuilds entry points mapping\n *\n * TypeScript module recreation logic:\n * - Disposes old TypeScript instance if tsconfig path changed\n * - Creates new instance with updated tsconfig\n * - Preserves TypeScript instance if tsconfig unchanged\n *\n * This enables configuration changes to take effect immediately without stopping\n * watch mode or restarting the build process.\n *\n * @example\n * ```ts\n * // Configuration changes from:\n * { minify: false, tsconfig: 'tsconfig.json' }\n * // To:\n * { minify: true, tsconfig: 'tsconfig.prod.json' }\n * // TypeScript module is recreated with new tsconfig\n * // All other settings are updated\n * ```\n *\n * @see {@link getConfig}\n * @see {@link registerConfigHooks}\n *\n * @since 2.0.0\n */\n\n private async handleConfigChange({ variantConfig, commonConfig }: ConfigSubscriptionInterface): Promise<void> {\n this.active = false;\n const config = this.getConfig(variantConfig, commonConfig);\n if (!config) return;\n\n this.active = true;\n this.buildConfig = this.initializeConfig(config);\n\n if(config.esbuild.outdir && config.esbuild.outfile)\n this.buildConfig.esbuild.outdir = undefined;\n\n if (config.esbuild.tsconfig && config.esbuild.tsconfig !== this.tsConfigPath) {\n this.typescriptModule.dispose(this.tsConfigPath);\n this.tsConfigPath = config.esbuild.tsconfig;\n this.typescriptModule = new Typescript(this.tsConfigPath);\n }\n }\n\n /**\n * Removes file extension from a path.\n *\n * @param filePath - Path with extension\n * @returns Path without extension\n *\n * @since 2.0.0\n */\n\n private stripExtension(filePath: string): string {\n const lastDotIndex = filePath.lastIndexOf('.');\n\n return lastDotIndex > 0 ? filePath.substring(0, lastDotIndex) : filePath;\n }\n\n /**\n * Analyzes build dependencies and maps all source files to their output paths.\n *\n * @returns Record mapping output paths (without extensions) to source file paths\n *\n * @remarks\n * This method performs the following steps:\n * - Analyzes the dependency graph using esbuild's metafile\n * - Extracts configured entry points\n * - Discovers all transitive dependencies from the build\n * - Maps each file to its relative output path based on rootDir\n *\n * Entry points are preserved as-is, while dependencies are mapped relative to the\n * TypeScript root directory with extensions removed for output path calculation.\n *\n * @example\n * ```ts\n * const fileMap = await this.buildDependencyMap();\n * // {\n * // 'index': 'src/index.ts',\n * // 'utils/helper': 'src/utils/helper.ts',\n * // 'components/button': 'src/components/button.ts'\n * // }\n * ```\n *\n * @since 2.0.0\n */\n\n private async buildDependencyMap(): Promise<Record<string, string>> {\n const { esbuild } = this.buildConfig;\n const { metafile } = await analyzeDependencies(esbuild.entryPoints, {\n loader: esbuild.loader,\n platform: esbuild.platform\n });\n\n const result: Record<string, string> = {};\n for (const file of Object.keys(metafile.inputs)) {\n const relativePath = relative(this.typescriptModule.config.options.rootDir!, resolve(file));\n const path = this.stripExtension(relativePath);\n result[path] = file;\n }\n\n return result;\n }\n\n /**\n * Injects banner or footer text into esbuild output configuration.\n *\n * @param type - Type of text block to inject ('banner' or 'footer')\n *\n * @remarks\n * This method processes banner or footer configuration and injects the resulting\n * text into esbuild options. The configuration can specify text for different\n * output types (js, CSS).\n *\n * Text can be specified in two ways:\n * - **Static string**: Used directly as the banner/footer text\n * - **Function**: Called with variant name and argv, returns the text\n *\n * The function form allows dynamic text generation based on build context.\n *\n * If no banner/footer is configured for this variant, the method returns early\n * without modifying esbuild options.\n *\n * @example\n * ```ts\n * // Static banner\n * {\n * banner: {\n * js: '// Copyright 2024'\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // Dynamic banner with function\n * {\n * banner: {\n * js: (variantName, argv) => `// Build: ${variantName} at ${new Date()}`\n * }\n * }\n * ```\n *\n * @since 2.0.0\n */\n\n private injectTextBlock(type: 'banner' | 'footer'): void {\n const content = this.buildConfig[type];\n if (!content) return;\n\n const esbuild: BuildOptions = this.buildConfig.esbuild;\n esbuild[type] ??= {};\n\n for (const [ target, value ] of Object.entries(content)) {\n esbuild[type][target] = typeof value === 'function'\n ? value(this.name, this.argv)\n : value;\n }\n }\n\n /**\n * Applies banner and footer text injections before build execution.\n *\n * @remarks\n * This method injects custom text into the build output by calling `injectTextBlock`\n * for both 'banner' and 'footer' configuration options. Banners are prepended to\n * output files, while footers are appended.\n *\n * This is called at the start of each build to ensure injections reflect the\n * current configuration state.\n *\n * @see {@link injectTextBlock}\n *\n * @since 2.0.0\n */\n\n private applyInjections(): void {\n this.injectTextBlock('banner');\n this.injectTextBlock('footer');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LanguageService, SourceFile } from 'typescript';\nimport type { LanguageHostService } from '@typescript/services/hosts.service';\nimport type { FileNodeInterface, ModuleInfoInterface } from '@typescript/models/interfaces/graph-model.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { inject, Injectable } from '@symlinks/symlinks.module';\nimport { cleanContent, removeExportModifiers } from '@typescript/components/transformer.component';\n\n/**\n * Builds a simplified, declaration-only dependency graph for TypeScript files.\n *\n * Analyzes source files to extract internal dependencies, named/default/namespace imports & exports,\n * and produces cleaned `.d.ts`-like content with imports and export keywords removed.\n *\n * Primarily used for module federation analysis, tree-shaking verification, public API extraction,\n * or generating documentation / type-only bundles.\n *\n * @since 2.0.0\n */\n\n@Injectable({\n scope: 'singleton'\n})\nexport class GraphModel {\n /**\n * Active TypeScript language service instance used to emit declaration files.\n *\n * Set temporarily during the ` scan () ` call via `Object.assign` trick\n * because we want to avoid passing it through every private method signature.\n *\n * @remarks\n * The `!` assertion is safe because `scan()` always assigns both services\n * before any method that uses them is called.\n *\n * @since 2.0.0\n */\n\n private languageService!: LanguageService;\n\n /**\n * Language host providing module resolution, file system access, and version tracking.\n *\n * Like `languageService`, it is temporarily attached during `scan()` execution.\n *\n * @remarks\n * The definite assignment assertion (`!`) is valid only because `scan()`\n * guarantees both fields are set before private methods are invoked.\n *\n * @since 2.0.0\n */\n\n private languageHostService!: LanguageHostService;\n\n /**\n * Printer used to serialize cleaned AST nodes back to text\n * @since 2.0.0\n */\n\n private readonly printer: ts.Printer;\n\n /**\n * Cache of already analyzed files \u2192 their dependency and export graph nodes\n * @since 2.0.0\n */\n\n private readonly nodesCache: Map<string, FileNodeInterface> = new Map();\n\n /**\n * Injected singleton instance of the file snapshot cache.\n *\n * Provides fast access to file versions, resolved paths, and content snapshots\n * without repeated disk I/O.\n *\n * @see {@link FilesModel}\n * @since 2.0.0\n */\n\n private readonly filesCache = inject(FilesModel);\n\n /**\n * Initializes a new {@link GraphModel} instance.\n *\n * @remarks\n * Creates a TypeScript printer configured for consistent line ending formatting.\n * The printer is reused across all analysis operations for efficiency.\n *\n * @since 2.0.0\n */\n\n constructor() {\n this.printer = ts.createPrinter({\n newLine: ts.NewLineKind.LineFeed\n });\n }\n\n /**\n * Clears all cached file analysis results.\n * @since 2.0.0\n */\n\n clear(): void {\n this.nodesCache.clear();\n }\n\n /**\n * Retrieves a previously analyzed graph node for a file if it exists.\n *\n * @param path - file path (relative or absolute)\n * @returns cached node or `undefined` if not yet scanned or invalidated\n *\n * @since 2.0.0\n */\n\n get(path: string): FileNodeInterface | undefined {\n const resolvedPath = this.filesCache.resolve(path);\n\n return this.nodesCache.get(resolvedPath);\n }\n\n /**\n * Scans a source file, emits its declaration file, analyzes imports/exports,\n * and returns a dependency & export graph node.\n *\n * @param source - already parsed TypeScript source file\n * @param languageService - active TS language service (used for emitting)\n * @param languageHostService - host providing resolution and file system access\n * @returns graph node containing version, cleaned content, internal deps, and import/export maps\n *\n * @remarks\n * Re-uses a cached result if a file version hasn't changed.\n *\n * Temporarily attaches `languageService` and `languageHostService` to `this` for private method calls.\n *\n * @example\n * ```ts\n * const sourceFile = program.getSourceFile(fileName, ts.ScriptTarget.Latest)!;\n * const node = graphModel.scan(sourceFile, languageService, hostService);\n *\n * console.log(node.internalDeps.size, 'internal dependencies');\n * console.log(Object.keys(node.externalImports.named), 'external named imports');\n * ```\n *\n * @see {@link FilesModel}\n * @see {@link FileNodeInterface}\n *\n * @since 2.0.0\n */\n\n scan(source: SourceFile, languageService: LanguageService, languageHostService: LanguageHostService): FileNodeInterface {\n const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this, {\n languageService,\n languageHostService\n });\n\n const version = this.filesCache.getSnapshot(source.fileName)!.version.toString();\n const cached = this.nodesCache.get(source.fileName);\n if (cached?.version === version) return cached;\n\n const node = this.initDeclaration(source.fileName, version);\n const declarationSource = this.emitDeclaration.call(self, source);\n\n node.content = this.stripImportsExports.call(self, declarationSource, node);\n this.nodesCache.set(source.fileName, node);\n\n return node;\n }\n\n /**\n * Creates empty graph node skeleton with given file name and version.\n *\n * @param fileName - resolved absolute file path\n * @param version - snapshot version string\n * @returns initialized node structure\n *\n * @since 2.0.0\n */\n\n private initDeclaration(fileName: string, version: string): FileNodeInterface {\n return {\n version,\n fileName,\n content: '',\n internalDeps: new Set(),\n externalImports: {\n named: Object.create(null),\n default: Object.create(null),\n namespace: Object.create(null)\n },\n internalExports: {\n star: [],\n exports: [],\n namespace: Object.create(null)\n },\n externalExports: {\n star: [],\n exports: Object.create(null),\n namespace: Object.create(null)\n }\n };\n }\n\n /**\n * Resolves a module specifier to either an internal file path or external module name.\n *\n * @param moduleSpecifier - string literal from import/export declaration\n * @param currentFile - path of the file containing the import/export\n * @returns module info or `null` if resolution fails\n *\n * @since 2.0.0\n */\n\n private resolveModule(moduleSpecifier: ts.Expression, currentFile: string): ModuleInfoInterface | null {\n if (!ts.isStringLiteral(moduleSpecifier)) return null;\n\n const modulePath = moduleSpecifier.text;\n const resolvedFileName = this.languageHostService.resolveModuleName(modulePath, currentFile)\n .resolvedModule?.resolvedFileName;\n\n if (!resolvedFileName || resolvedFileName.includes('node_modules')) {\n return { fileName: modulePath, isExternal: true };\n }\n\n return { fileName: resolvedFileName, isExternal: false };\n }\n\n /**\n * Appends named import/export specifiers (with optional `as` aliases) to the target array.\n *\n * @param target - array to push names into\n * @param elements - import/export specifiers\n *\n * @since 2.0.0\n */\n\n private addNamedElements(target: Array<string>, elements: ts.NodeArray<ts.ImportSpecifier | ts.ExportSpecifier>): void {\n for (const element of elements) {\n const name = element.propertyName\n ? `${ element.propertyName.text } as ${ element.name.text }`\n : element.name.text;\n target.push(name);\n }\n }\n\n /**\n * Checks whether a statement has an `export` modifier.\n *\n * @param stmt - any statement node\n * @returns `true` if statement is exported\n *\n * @since 2.0.0\n */\n\n private hasExportModifier(stmt: ts.Statement): boolean {\n if (!ts.canHaveModifiers(stmt)) return false;\n const modifiers = ts.getModifiers(stmt);\n\n return modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;\n }\n\n /**\n * Emits a declaration file (.d.ts content) for a given source file using language service.\n *\n * @param source - source file to emit declarations from\n * @returns parsed declaration source file\n *\n * @throws Error when emit output is empty or missing\n *\n * @since 2.0.0\n */\n\n private emitDeclaration(source: SourceFile): SourceFile {\n const output = this.languageService.getEmitOutput(\n source.fileName,\n true,\n true\n );\n\n const declarationText = output.outputFiles[0]?.text;\n if (!declarationText) {\n throw new Error(`Failed to emit declaration: ${ source.fileName }`);\n }\n\n return ts.createSourceFile(\n source.fileName.replace(/\\.tsx?$/, '.d.ts'),\n declarationText,\n ts.ScriptTarget.Latest,\n true\n );\n }\n\n /**\n * Removes imports, exports, and export modifiers from a declaration file,\n * collects dependency/export information, and cleans alias references.\n *\n * @param sourceFile - emitted declaration source file\n * @param node - graph node being populated\n * @returns final cleaned declaration text (no imports/exports)\n *\n * @since 2.0.0\n */\n\n private stripImportsExports(sourceFile: SourceFile, node: FileNodeInterface): string {\n const aliasStatements: Array<string> = [];\n const keptStatements: Array<ts.Statement> = [];\n\n for (const stmt of sourceFile.statements) {\n if (ts.isImportDeclaration(stmt)) {\n this.handleImport(stmt, node, aliasStatements);\n continue;\n }\n\n if (ts.isExportDeclaration(stmt)) {\n this.handleExport(stmt, node);\n continue;\n }\n\n if (this.hasExportModifier(stmt)) {\n this.extractExportName(stmt, node);\n }\n\n keptStatements.push(stmt);\n }\n\n const nodeArray = ts.factory.createNodeArray(keptStatements);\n const printed = this.printer.printList(\n ts.ListFormat.MultiLine,\n nodeArray,\n sourceFile\n );\n\n let content = removeExportModifiers(cleanContent(printed));\n for (const alias of aliasStatements) {\n if(alias.includes(' as ')) {\n const [ aliasName, aliasType ] = alias.split(' as ');\n content = content.replace(new RegExp(`\\\\b${ aliasType }\\\\b`, 'g'), aliasName);\n } else {\n content = content.replace(new RegExp(`\\\\b${ alias }\\\\.`, 'g'), '');\n }\n }\n\n return content;\n }\n\n /**\n * Processes import declaration \u2192 tracks dependencies and collects imported names.\n *\n * @param stmt - import declaration AST node\n * @param node - graph node to update\n * @param aliasStatements - mutable list of local alias names to clean later\n *\n * @since 2.0.0\n */\n\n private handleImport(stmt: ts.ImportDeclaration, node: FileNodeInterface, aliasStatements: Array<string>): void {\n const { importClause, moduleSpecifier } = stmt;\n if (!importClause || !moduleSpecifier) return;\n\n const moduleInfo = this.resolveModule(moduleSpecifier, node.fileName);\n if (!moduleInfo) return;\n\n const { fileName, isExternal } = moduleInfo;\n\n if (!isExternal) {\n node.internalDeps.add(fileName);\n\n const { namedBindings } = importClause;\n if(!namedBindings) return;\n\n if (ts.isNamespaceImport(namedBindings)) {\n aliasStatements.push(namedBindings.name.text);\n } else if (ts.isNamedImports(namedBindings)) {\n this.addNamedElements(aliasStatements, namedBindings.elements);\n }\n\n return;\n }\n\n if (!importClause) {\n // Side-effect import: import 'module'\n node.externalImports.namespace[fileName] = '';\n\n return;\n }\n\n // Default import: import Foo from 'module'\n if (importClause.name) {\n node.externalImports.default[fileName] = importClause.name.text;\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) return;\n\n if (ts.isNamespaceImport(namedBindings)) {\n // import * as Foo from 'module'\n node.externalImports.namespace[namedBindings.name.text] = fileName;\n } else if (ts.isNamedImports(namedBindings)) {\n // import { a, b as c } from 'module'\n this.addNamedElements(\n node.externalImports.named[fileName] ??= [],\n namedBindings.elements\n );\n }\n }\n\n /**\n * Processes re-export declaration (`export \u2026 from \u2026`).\n *\n * @param stmt - export declaration AST node\n * @param node - graph node to update\n *\n * @since 2.0.0\n */\n\n private handleExport(stmt: ts.ExportDeclaration, node: FileNodeInterface): void {\n const { moduleSpecifier, exportClause } = stmt;\n if (!moduleSpecifier) return;\n\n const moduleInfo = this.resolveModule(moduleSpecifier, node.fileName);\n if (!moduleInfo) return;\n\n const { fileName, isExternal } = moduleInfo;\n\n // Track internal dependencies\n if (!isExternal) {\n node.internalDeps.add(fileName);\n }\n\n // export * from 'module'\n if (!exportClause) {\n if (isExternal) {\n node.externalExports.star.push(fileName);\n } else {\n node.internalExports.star.push(fileName);\n }\n\n return;\n }\n\n // export * as Foo from 'module'\n if (ts.isNamespaceExport(exportClause)) {\n if (isExternal) {\n node.externalExports.namespace[exportClause.name.text] = fileName;\n } else {\n node.internalExports.namespace[exportClause.name.text] = fileName;\n }\n\n return;\n }\n\n if (ts.isNamedExports(exportClause)) {\n // export { a, b as c } from 'module'\n if (isExternal) {\n this.addNamedElements(\n node.externalExports.exports[fileName] ??= [],\n exportClause.elements\n );\n } else {\n this.addNamedElements(\n node.internalExports.exports,\n exportClause.elements\n );\n }\n }\n }\n\n /**\n * Extracts locally declared export names from statements with the ` export ` modifier.\n *\n * @param stmt - statement with export modifier\n * @param node - graph node to update\n *\n * @since 2.0.0\n */\n\n private extractExportName(stmt: ts.Statement, node: FileNodeInterface): void {\n if (ts.isVariableStatement(stmt)) {\n for (const decl of stmt.declarationList.declarations) {\n if (ts.isIdentifier(decl.name)) {\n node.internalExports.exports.push(decl.name.text);\n }\n }\n\n return;\n }\n\n // Handle other named declarations\n if (ts.isEnumDeclaration(stmt) ||\n ts.isClassDeclaration(stmt) ||\n ts.isFunctionDeclaration(stmt) ||\n ts.isInterfaceDeclaration(stmt) ||\n ts.isTypeAliasDeclaration(stmt)) {\n if (stmt.name && ts.isIdentifier(stmt.name)) {\n node.internalExports.exports.push(stmt.name.text);\n }\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CompilerOptions } from 'typescript';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { dirname, relative, toPosix } from '@components/path.component';\n\n/**\n * Matches Unix shebang lines at the beginning of files for removal during compilation.\n *\n * @remarks\n * Matches shebang lines (e.g., `#!/usr/bin/env node`) at the start of files,\n * including optional carriage return and line feed characters for cross-platform compatibility.\n *\n * Pattern breakdown:\n * - `^#!` - Start of line with `#!`\n * - `.*` - Any characters until the end of line\n * - `(\\r?\\n)?` - Optional CR+LF or LF line ending\n *\n * @example\n * ```ts\n * const content = '#!/usr/bin/env node\\nconsole.log(\"hello\");';\n * SHEBANG_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeShebang}\n *\n * @since 2.0.0\n */\n\nexport const SHEBANG_REGEX = /^#!.*(\\r?\\n)?/;\n\n/**\n * Matches empty export statements that should be removed from declaration files.\n *\n * @remarks\n * Matches TypeScript empty export statements (`export {};`) which are often\n * generated during compilation but are invalid in final declaration files.\n *\n * Pattern breakdown:\n * - `export {};` - Literal empty export statement\n * - `\\n?` - Optional trailing newline\n *\n * The global flag ensures all occurrences are matched throughout the content.\n *\n * @example\n * ```ts\n * const content = 'export {};\\nexport const x = 1;';\n * EMPTY_EXPORT_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeEmptyExports}\n *\n * @since 2.0.0\n */\n\nexport const EMPTY_EXPORT_REGEX = /export {};\\n?/g;\n\n/**\n * Matches orphaned JSDoc comment blocks that are not associated with any declaration.\n *\n * @remarks\n * Matches consecutive JSDoc comment blocks that appear without associated declarations.\n * These orphaned comments commonly appear in bundled files where comments are preserved\n * during bundling but lose their associated declarations.\n *\n * Pattern breakdown:\n * - `(?:\\/\\*\\*[\\s\\S]*?\\*\\/\\s*)+` - One or more JSDoc blocks with the following whitespace (non-capturing)\n * - `(\\/\\*\\*[\\s\\S]*?\\*\\/)` - Final JSDoc block (captured for potential reuse)\n *\n * The captured group allows preserving the last comment if needed during replacement.\n *\n * @example\n * ```ts\n * const content = '/** Comment 1 *\\/\\n/** Comment 2 *\\/\\nexport const x = 1;';\n * ORPHAN_COMMENT_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeOrphanComments}\n *\n * @since 2.0.0\n */\n\nexport const ORPHAN_COMMENT_REGEX = /(?:\\/\\*\\*[\\s\\S]*?\\*\\/\\s*)+(\\/\\*\\*[\\s\\S]*?\\*\\/)/g;\n\n/**\n * Matches export modifiers on declarations for removal while preserving the declarations themselves.\n *\n * @remarks\n * Matches the `export` keyword (and optional `default`) at the start of lines\n * in declaration files. Used to strip export modifiers while preserving the\n * declaration itself when consolidating exports.\n *\n * Pattern breakdown:\n * - `^export` - Export keyword at line start (multiline mode)\n * - `\\s+` - Required whitespace after export\n * - `(?:default\\s+)?` - Optional default keyword with whitespace\n *\n * The multiline flag (`m`) ensures `^` matches line starts throughout the content.\n *\n * @example\n * ```ts\n * const content = 'export interface Config { x: number; }';\n * content.replace(EXPORT_MODIFIER_REGEX, ''); // 'interface Config { x: number; }'\n * ```\n *\n * @see {@link removeExportModifiers}\n *\n * @since 2.0.0\n */\n\nexport const EXPORT_MODIFIER_REGEX = /^export\\s+(?:default\\s+)?/gm;\n\n/**\n * Matches single-line trailing JSDoc comment blocks at the end of lines for removal.\n *\n * @remarks\n * Matches JSDoc comment blocks that appear at the end of lines, including\n * surrounding whitespace. Used to clean up documentation comments that are\n * misplaced or unnecessary in bundled output.\n *\n * Pattern breakdown:\n * - `\\s*` - Leading whitespace\n * - `\\/\\*\\*[^\\\\r\\\\n]*?\\*\\/` - Single-line JSDoc comment block (no line breaks)\n * - `\\s*$` - Trailing whitespace and end of line\n *\n * @example\n * ```ts\n * const content = 'const x = 1; /** Documentation *\\/';\n * TRAILING_COMMENT_REGEX.test(content); // true\n * ```\n *\n * @see {@link removeOrphanComments}\n *\n * @since 2.0.0\n */\n\nexport const TRAILING_COMMENT_REGEX = /(?<=[:;,{}\\[\\]()\\w\"'`])[ \\t]*\\/\\*\\*[^\\r\\n]*?\\*\\/[ \\t]*$/gm;\n\n/**\n * Removes shebang line from the beginning of file content.\n *\n * @param content - The file content to process\n *\n * @returns Content with shebang line removed, or unchanged if no shebang present\n *\n * @remarks\n * Removes Unix shebang lines (e.g., `#!/usr/bin/env node`) from the start of files.\n * Uses character code checks for performance (35 = '#', 33 = '!'), avoiding regex\n * execution for files that don't have shebangs.\n *\n * Shebang lines are typically only present in executable scripts and are not valid\n * in declaration files or bundled TypeScript code.\n *\n * @example\n * ```ts\n * const withShebang = '#!/usr/bin/env node\\nconsole.log(\"hello\");';\n * const cleaned = removeShebang(withShebang);\n * // 'console.log(\"hello\");'\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link SHEBANG_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeShebang(content: string): string {\n // 35 = '#', 33 = '!'\n return (content.charCodeAt(0) === 35 && content.charCodeAt(1) === 33)\n ? content.replace(SHEBANG_REGEX, '')\n : content;\n}\n\n/**\n * Removes empty export statements from file content.\n *\n * @param content - The file content to process\n *\n * @returns Content with all empty export statements removed\n *\n * @remarks\n * Removes `export {};` statements which TypeScript often generates to mark\n * a file as an ES module without exporting anything. These statements are invalid\n * in declaration files and should be removed during compilation.\n *\n * Performs a quick string check before applying the regex for performance optimization.\n *\n * @example\n * ```ts\n * const content = 'export {};\\nexport const x = 1;';\n * const cleaned = removeEmptyExports(content);\n * // 'export const x = 1;'\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link EMPTY_EXPORT_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeEmptyExports(content: string): string {\n return content.includes('export {}')\n ? content.replace(EMPTY_EXPORT_REGEX, '')\n : content;\n}\n\n/**\n * Removes orphaned and trailing JSDoc comment blocks from file content.\n *\n * @param content - The file content to process\n *\n * @returns Content with orphaned and trailing comments removed\n *\n * @remarks\n * Performs two sequential cleaning operations:\n * 1. Removes trailing JSDoc comments at the end of lines\n * 2. Removes orphaned JSDoc blocks (comments not associated with declarations)\n *\n * Orphaned comments commonly appear in bundled files where comments are preserved\n * during bundling but lose their associated declarations due to tree shaking or\n * module consolidation.\n *\n * The replacement pattern `'$1'` preserves the last comment in a sequence of orphaned\n * comments if it might still be associated with a declaration.\n *\n * @example\n * ```ts\n * const content = '/** Orphan *\\/\\n/** Doc *\\/\\nexport const x = 1;';\n * const cleaned = removeOrphanComments(content);\n * // Removes orphaned comments while preserving declaration-associated ones\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link ORPHAN_COMMENT_REGEX}\n * @see {@link TRAILING_COMMENT_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeOrphanComments(content: string): string {\n content = content.replace(TRAILING_COMMENT_REGEX, '');\n\n return content.replace(ORPHAN_COMMENT_REGEX, '$1');\n}\n\n/**\n * Removes export modifiers from all declarations while preserving the declarations themselves.\n *\n * @param content - The file content to process\n *\n * @returns Content with export modifiers removed from all declarations\n *\n * @remarks\n * Strips `export` and `export default` keywords from declarations, transforming:\n * - `export const x = 1;` \u2192 `const x = 1;`\n * - `export default interface Config {}` \u2192 `interface Config {}`\n * - `export function foo() {}` \u2192 `function foo() {}`\n *\n * This transformation is used when bundling declarations to remove export modifiers\n * from internal declarations that will be consolidated into a single export list or\n * re-exported through a barrel file.\n *\n * @example\n * ```ts\n * const content = 'export const x = 1;\\nexport function foo() {}';\n * const cleaned = removeExportModifiers(content);\n * // 'const x = 1;\\nfunction foo() {}'\n * ```\n *\n * @see {@link cleanContent}\n * @see {@link EXPORT_MODIFIER_REGEX}\n *\n * @since 2.0.0\n */\n\nexport function removeExportModifiers(content: string): string {\n return content.replace(EXPORT_MODIFIER_REGEX, '');\n}\n\n/**\n * Checks whether file content contains elements that require cleaning.\n *\n * @param content - The file content to check\n *\n * @returns `true` if content requires cleaning operations, `false` otherwise\n *\n * @remarks\n * Performs quick checks to determine if cleaning operations are necessary:\n * - Checks for shebang (character code 35 = '#')\n * - Checks for empty export statements\n * - Checks for JSDoc comments\n *\n * Used to short-circuit expensive cleaning operations when content doesn't need\n * processing, improving performance on already-clean files.\n *\n * @example\n * ```ts\n * needsCleaning('export const x = 1;'); // false\n * needsCleaning('#!/bin/bash\\nexport const x = 1;'); // true\n * needsCleaning('export {};\\nexport const x = 1;'); // true\n * needsCleaning('/** Doc *\\/\\nexport const x = 1;'); // true\n * ```\n *\n * @see {@link cleanContent}\n *\n * @since 2.0.0\n */\n\nexport function needsCleaning(content: string): boolean {\n return content.charCodeAt(0) === 35 || // '#' for shebang\n content.includes('export {}') ||\n content.includes('/**');\n}\n\n/**\n * Applies all cleaning transformations to file content in sequence.\n *\n * @param content - The file content to clean\n *\n * @returns Cleaned content with all transformations applied\n *\n * @remarks\n * Applies cleaning operations in the following order:\n * 1. Short-circuit check using {@link needsCleaning} for performance\n * 2. Removes shebang lines\n * 3. Removes empty export statements\n * 4. Removes orphaned JSDoc comments\n *\n * Typically applied to declaration files during emission or bundling to remove\n * artifacts that are not valid in `.d.ts` files or that clutter bundled output.\n * The sequential application ensures all unwanted elements are removed while\n * preserving valid TypeScript declarations.\n *\n * @example\n * ```ts\n * const raw = `#!/usr/bin/env node\n * /**\n * * Orphaned comment\n * *\\/\n * export {};\n * export const x = 1;`;\n *\n * const cleaned = cleanContent(raw);\n * // 'export const x = 1;'\n * ```\n *\n * @see {@link needsCleaning}\n * @see {@link removeShebang}\n * @see {@link removeEmptyExports}\n * @see {@link removeOrphanComments}\n *\n * @since 2.0.0\n */\n\nexport function cleanContent(content: string): string {\n if (!needsCleaning(content)) return content;\n\n content = removeShebang(content);\n content = removeEmptyExports(content);\n content = removeOrphanComments(content);\n\n return content;\n}\n\n\n/**\n * Calculates the output file path for a compiled TypeScript declaration file.\n *\n * @param sourcePath - The source TypeScript file path\n * @param options - TypeScript compiler options containing output directory settings\n *\n * @returns The normalized output path for the declaration file with forward slashes\n *\n * @remarks\n * Determines an output path using the following logic:\n * 1. Selects output base: `declarationDir` `>` `outDir` `>` source directory\n * 2. Selects root directory: `rootDir` `>` source directory\n * 3. Computes a relative path from root to a source file\n * 4. Changes file extension from `.ts`/`.tsx` to `.d.ts`\n * 5. Combines an output base path with the output file name\n * 6. Resolves a full path and normalizes to forward slashes\n *\n * Path resolution example:\n * - Source: `/project/src/components/Button.tsx`\n * - Root: `/project/src`\n * - Relative: `components/Button.tsx`\n * - Output file: `components/Button.d.ts`\n * - Final: `/project/dist/components/Button.d.ts`\n *\n * @example\n * ```ts\n * const sourcePath = '/project/src/index.ts';\n * const options: CompilerOptions = {\n * outDir: 'dist',\n * rootDir: 'src'\n * };\n *\n * const outputPath = calculateOutputPath(sourcePath, options);\n * // '/project/dist/index.d.ts'\n * ```\n *\n * @example\n * ```ts\n * // With declarationDir override\n * const options: CompilerOptions = {\n * outDir: 'dist',\n * declarationDir: 'types',\n * rootDir: 'src'\n * };\n *\n * const outputPath = calculateOutputPath(sourcePath, options);\n * // '/project/types/index.d.ts'\n * ```\n *\n * @see {@link EmitterService}\n * @see {@link BundlerService}\n *\n * @since 2.0.0\n */\n\nexport function calculateOutputPath(sourcePath: string, options: CompilerOptions): string {\n const { outDir, rootDir, declarationDir } = options;\n\n const outputBase = declarationDir || outDir || dirname(sourcePath);\n const root = rootDir || dirname(sourcePath);\n\n const relativePath = relative(root, sourcePath);\n const outputFileName = relativePath.replace(/\\.tsx?$/, '.d.ts');\n const fullPath = ts.sys.resolvePath(`${ outputBase }/${ outputFileName }`);\n\n return toPosix(fullPath);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ParsedCommandLine, LanguageService, Diagnostic } from 'typescript';\nimport type { CachedServiceInterface, DiagnosticInterface } from './interfaces/typescript-service.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { Injectable } from '@symlinks/symlinks.module';\nimport { BundlerService } from '@typescript/services/bundler.service';\nimport { EmitterService } from '@typescript/services/emitter.service';\nimport { LanguageHostService } from '@typescript/services/hosts.service';\n\n/**\n * Manages TypeScript language services with caching and reference counting for shared compiler instances.\n * Provides type checking, code emission, and bundling capabilities through a unified interface that coordinates\n * multiple internal services while maintaining efficient resource usage across multiple consumers.\n *\n * @remarks\n * This service implements a caching strategy to share language service instances across multiple consumers\n * that reference the same `tsconfig.json` file. The lifecycle is managed through reference counting:\n * - Each instantiation increments the reference count for the config path\n * - Calling {@link dispose} decrements the count\n * - When the count reaches zero, the language service is cleaned up automatically\n *\n * The service coordinates three key subsystems:\n * - Language service and host for type checking and analysis\n * - Emitter service for standard TypeScript compilation output\n * - Bundler service for creating bundled outputs from entry points\n *\n * @example\n * ```ts\n * const service = new TypescriptService('tsconfig.json');\n *\n * // Type check all files\n * const diagnostics = service.check();\n * if (diagnostics.length > 0) {\n * console.error('Type errors found:', diagnostics);\n * }\n *\n * // Emit compiled output\n * await service.emit('./dist');\n *\n * // Clean up when done\n * service.dispose('tsconfig.json');\n * ```\n *\n * @see {@link EmitterService}\n * @see {@link BundlerService}\n * @see {@link LanguageHostService}\n *\n * @since 2.0.0\n */\n\n@Injectable({\n providers: [{ useValue: 'tsconfig.json' }]\n})\nexport class TypescriptService {\n /**\n * Parsed TypeScript compiler configuration including options, file names, and project references.\n * @since 2.0.0\n */\n\n readonly config: ParsedCommandLine;\n\n /**\n * TypeScript language service instance providing type checking, intellisense, and compilation capabilities.\n * @since 2.0.0\n */\n\n readonly languageService: LanguageService;\n\n /**\n * Custom language service host managing file system interactions and compiler options.\n * @since 2.0.0\n */\n\n readonly languageHostService: LanguageHostService;\n\n /**\n * Shared cache mapping config paths to language service instances with reference counting.\n *\n * @remarks\n * This static cache enables multiple service instances to share the same underlying language service\n * when they reference the same `tsconfig.json` file, reducing memory usage and compilation overhead.\n * Entries are automatically cleaned up when reference counts reach zero.\n *\n * @since 2.0.0\n */\n\n private static readonly serviceCache = new Map<string, CachedServiceInterface>();\n\n /**\n * Service responsible for emitting compiled TypeScript output files.\n * @since 2.0.0\n */\n\n private readonly emitterService: EmitterService;\n\n /**\n * Service responsible for creating bundled outputs from entry points.\n * @since 2.0.0\n */\n\n private readonly bundlerService: BundlerService;\n\n /**\n * Creates a new TypeScript service instance or retrieves a cached one for the specified configuration.\n *\n * @param configPath - Path to the `tsconfig.json` file, defaults to `'tsconfig.json'` in the current directory\n *\n * @remarks\n * The constructor performs the following initialization steps:\n * - Acquires or creates a cached language service for the config path\n * - Increments the reference count for the shared service instance\n * - Touches all files listed in the parsed configuration to ensure they're loaded\n * - Initializes emitter and bundler services with the language service\n *\n * If a language service already exists for the given config path, it will be reused rather than\n * creating a new instance, improving performance and reducing memory usage.\n *\n * @example\n * ```ts\n * // Use default tsconfig.json\n * const service = new TypescriptService();\n *\n * // Use custom config path\n * const customService = new TypescriptService('./custom-tsconfig.json');\n * ```\n *\n * @see {@link acquireLanguageService}\n * @see {@link LanguageHostService.touchFiles}\n *\n * @since 2.0.0\n */\n\n constructor(private configPath: string = 'tsconfig.json') {\n const { config, host, service } = this.acquireLanguageService();\n\n this.config = config;\n this.languageService = service;\n this.languageHostService = host;\n this.languageHostService.touchFiles(this.config.fileNames);\n\n this.emitterService = new EmitterService(service, host);\n this.bundlerService = new BundlerService(service, host);\n }\n\n /**\n * Performs type checking on all source files in the project and returns collected diagnostics.\n *\n * @returns Array of formatted diagnostic information including errors, warnings, and suggestions\n *\n * @remarks\n * This method filters out files that should not be checked (such as `node_modules` and declaration files)\n * and collects three types of diagnostics for each remaining file:\n * - Semantic diagnostics (type errors, type mismatches)\n * - Syntactic diagnostics (parse errors, invalid syntax)\n * - Suggestion diagnostics (optional improvements can be slow)\n *\n * If the language service has no program available, an empty array is returned.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n * const diagnostics = service.check();\n *\n * for (const diagnostic of diagnostics) {\n * console.log(`${diagnostic.file}:${diagnostic.line}:${diagnostic.column}`);\n * console.log(`${diagnostic.message}`);\n * }\n * ```\n *\n * @see {@link shouldCheckFile}\n * @see {@link collectDiagnostics}\n *\n * @since 2.0.0\n */\n\n check(filesList?: Array<string>): Array<DiagnosticInterface> {\n const program = this.languageService.getProgram();\n if (!program) return [];\n\n const files = (filesList && filesList.length > 0) ?\n filesList.map(file => program.getSourceFile(file)!) :\n this.languageService.getProgram()?.getSourceFiles();\n\n if (!files) return [];\n\n return files\n .filter(file => this.shouldCheckFile(file))\n .flatMap(file => this.collectDiagnostics(file));\n }\n\n /**\n * Marks files as modified to trigger recompilation and updates configuration if the config file changed.\n *\n * @param files - Array of file paths that have been modified or created\n *\n * @remarks\n * This method performs two key operations:\n * - For files that exist in the script snapshot cache, marks them as touched to invalidate cached data\n * - If the modified files include the `tsconfig.json` file, reloads the configuration and updates the host options\n *\n * This is essential for watch mode scenarios where files change during development and the service\n * needs to stay synchronized with the file system state.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n *\n * // Notify service of file changes\n * service.touchFiles(['src/index.ts', 'src/utils.ts']);\n *\n * // Config change triggers reload\n * service.touchFiles(['tsconfig.json']);\n * ```\n *\n * @see {@link LanguageHostService.touchFile}\n * @see {@link LanguageHostService.hasScriptSnapshot}\n *\n * @since 2.0.0\n */\n\n touchFiles(files: Array<string>): void {\n for (const file of files) {\n if (this.languageHostService.hasScriptSnapshot(file)) {\n this.languageHostService.touchFile(file);\n }\n\n if (file.includes(this.configPath)) {\n const cached = TypescriptService.serviceCache.get(this.configPath)!;\n cached.config = this.parseConfig();\n cached.host.options = cached.config.options;\n }\n }\n }\n\n /**\n * Emits a bundled output by processing specified entry points through the bundler service.\n *\n * @param entryPoints - Record mapping bundle names to their entry point file paths\n * @param outdir - Optional output directory path, uses compiler options default if not specified\n *\n * @returns Promise that resolves when bundling and emission completes\n *\n * @remarks\n * This method delegates to the bundler service which handles dependency resolution, tree shaking,\n * and output generation. Unlike standard emission, bundling combines multiple modules into\n * optimized output files.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n *\n * await service.emitBundle(\n * { 'main': './src/index.ts', 'worker': './src/worker.ts' },\n * './dist/bundles'\n * );\n * ```\n *\n * @see {@link BundlerService.emit}\n *\n * @since 2.0.0\n */\n\n async emitBundle(entryPoints: Record<string, string>, outdir?: string): Promise<void> {\n await this.bundlerService.emit(entryPoints, outdir);\n }\n\n /**\n * Emits compiled TypeScript output files to the specified directory.\n *\n * @param outdir - Optional output directory path, uses compiler options default if not specified\n *\n * @returns Promise that resolves when emission completes\n *\n * @remarks\n * This method performs standard TypeScript compilation, emitting JavaScript files, declaration files,\n * and source maps according to the compiler options. The emission includes all files in the program\n * that are not excluded by configuration.\n *\n * @example\n * ```ts\n * const service = new TypescriptService();\n *\n * // Emit to default outDir from tsconfig\n * await service.emit();\n *\n * // Emit to custom directory\n * await service.emit('./build');\n * ```\n *\n * @see {@link EmitterService.emit}\n *\n * @since 2.0.0\n */\n\n async emit(outdir?: string): Promise<void> {\n await this.emitterService.emit(outdir);\n }\n\n /**\n * Decrements the reference count for a cached service and cleans up if no longer in use.\n *\n * @param tsconfigPath - Path to the TypeScript configuration file identifying which cached service to dispose\n *\n * @remarks\n * This method implements the cleanup phase of the reference counting lifecycle. When the reference count\n * reaches zero, the language service is disposed of and removed from the cache. This should be called\n * when a consumer no longer needs the TypeScript service to prevent resource leaks.\n *\n * If no cached service exists for the given path, this method does nothing.\n *\n * @example\n * ```ts\n * const service = new TypescriptService('tsconfig.json');\n *\n * // Use the service...\n * const diagnostics = service.check();\n *\n * // Clean up when done\n * service.dispose('tsconfig.json');\n * ```\n *\n * @see {@link cleanupUnusedServices}\n *\n * @since 2.0.0\n */\n\n dispose(tsconfigPath: string): void {\n const cached = TypescriptService.serviceCache.get(tsconfigPath);\n if (!cached) return;\n\n cached.refCount--;\n TypescriptService.cleanupUnusedServices();\n }\n\n /**\n * Removes cached language services with zero references and disposes of their resources.\n *\n * @remarks\n * This static method iterates through the service cache and removes entries where the reference\n * count has dropped below one. For each removed entry, the language service's `dispose()` method\n * is called to clean up internal resources before deletion from the cache.\n *\n * This method is called automatically by {@link dispose} and should not typically be invoked directly.\n *\n * @see {@link dispose}\n *\n * @since 2.0.0\n */\n\n private static cleanupUnusedServices(): void {\n for (const [ path, cached ] of this.serviceCache) {\n if (cached.refCount < 1) {\n cached.service.dispose();\n this.serviceCache.delete(path);\n }\n }\n }\n\n /**\n * Determines whether a source file should be included in type checking.\n *\n * @param file - TypeScript source file to evaluate\n *\n * @returns `true` if the file should be checked, `false` if it should be excluded\n *\n * @remarks\n * Files are excluded from checking if they meet either condition:\n * - Located in the ` node_modules ` directory (third-party dependencies)\n * - Are TypeScript declaration files (`.d.ts` files)\n *\n * @since 2.0.0\n */\n\n private shouldCheckFile(file: ts.SourceFile): boolean {\n return file && !file.fileName.includes('node_modules') && !file.isDeclarationFile;\n }\n\n /**\n * Collects all diagnostic information for a source file, including errors, warnings, and suggestions.\n *\n * @param file - TypeScript source file to collect diagnostics from\n *\n * @returns Array of formatted diagnostic objects with file location and message details\n *\n * @remarks\n * This method gathers three types of diagnostics:\n * - Semantic diagnostics: type errors, undefined variables, type mismatches\n * - Syntactic diagnostics: parse errors, invalid syntax, malformed code\n * - Suggestion diagnostics: optional code improvements (can impact performance)\n *\n * Each diagnostic is formatted using {@link formatDiagnostic} to provide consistent output.\n *\n * @see {@link formatDiagnostic}\n *\n * @since 2.0.0\n */\n\n private collectDiagnostics(file: ts.SourceFile): DiagnosticInterface[] {\n return [\n ...this.languageService.getSemanticDiagnostics(file.fileName),\n ...this.languageService.getSyntacticDiagnostics(file.fileName),\n ...this.languageService.getSuggestionDiagnostics(file.fileName) // optional: slow\n ].map(d => this.formatDiagnostic(d));\n }\n\n /**\n * Retrieves an existing cached language service or creates a new one if none exists.\n *\n * @returns Cached service interface containing config, host, service, and reference count\n *\n * @remarks\n * This method checks the static service cache for an existing language service matching the\n * current `configPath`. If found, it increments the reference count and returns the cached instance.\n * If not found, it delegates to {@link createLanguageService} to create and cache a new instance.\n *\n * @see {@link createLanguageService}\n *\n * @since 2.0.0\n */\n\n private acquireLanguageService(): CachedServiceInterface {\n const cached = TypescriptService.serviceCache.get(this.configPath);\n if (cached) {\n cached.refCount++;\n\n return cached;\n }\n\n return this.createLanguageService();\n }\n\n /**\n * Creates a new language service instance with host and caches it for future reuse.\n *\n * @returns Newly created cached service interface with reference count initialized to 1\n *\n * @remarks\n * This method performs the following steps:\n * - Parses the TypeScript configuration using {@link parseConfig}\n * - Creates a new language service host with the parsed options\n * - Initializes a TypeScript language service with the host and document registry\n * - Wraps everything in a cache entry with `refCount` set to 1\n * - Stores the entry in the static service cache\n *\n * @see {@link parseConfig}\n * @see {@link LanguageHostService}\n *\n * @since 2.0.0\n */\n\n private createLanguageService(): CachedServiceInterface {\n const config = this.parseConfig();\n const host = new LanguageHostService(config.options);\n const service = ts.createLanguageService(host, ts.createDocumentRegistry());\n\n const cached: CachedServiceInterface = { config, host, service, refCount: 1 };\n TypescriptService.serviceCache.set(this.configPath, cached);\n\n return cached;\n }\n\n /**\n * Creates a new language service instance with host and caches it for future reuse.\n *\n * @returns Newly created cached service interface with reference count initialized to 1\n *\n * @remarks\n * This method performs the following steps:\n * - Parses the TypeScript configuration using {@link parseConfig}\n * - Creates a new language service host with the parsed options\n * - Initializes a TypeScript language service with the host and document registry\n * - Wraps everything in a cache entry with `refCount` set to 1\n * - Stores the entry in the static service cache\n *\n * @see {@link parseConfig}\n * @see {@link LanguageHostService}\n *\n * @since 2.0.0\n */\n\n private parseConfig(): ParsedCommandLine {\n let config = ts.getParsedCommandLineOfConfigFile(\n this.configPath,\n {\n skipLibCheck: true,\n stripInternal: true,\n emitDeclarationOnly: true\n },\n {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {}\n }\n );\n\n if (!config) {\n config = {\n options: {\n strict: true,\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.NodeNext,\n declaration: true,\n skipLibCheck: true,\n moduleResolution: ts.ModuleResolutionKind.NodeNext\n },\n errors: [],\n fileNames: [],\n projectReferences: undefined\n };\n }\n\n config.options = {\n ...config.options,\n rootDir: config.options?.rootDir ?? process.cwd()\n };\n\n return config;\n }\n\n /**\n * Converts a TypeScript diagnostic into a standardized diagnostic interface with a formatted message and location.\n *\n * @param diagnostic - Raw TypeScript diagnostic from the compiler\n *\n * @returns Formatted diagnostic object with message, file path, line, column, and error code\n *\n * @remarks\n * This method flattens multi-line diagnostic messages into a single string using newline separators.\n * If the diagnostic includes file and position information, it calculates the human-readable line and\n * column numbers (1-indexed) and includes the diagnostic code.\n *\n * If no file or position information is available, only the message is included in the result.\n *\n * @since 2.0.0\n */\n\n private formatDiagnostic(diagnostic: Diagnostic): DiagnosticInterface {\n const result: DiagnosticInterface = {\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n category: diagnostic.category\n };\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n result.file = diagnostic.file.fileName;\n result.line = line + 1;\n result.column = character + 1;\n result.code = diagnostic.code;\n }\n\n return result;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LanguageService, Program, SourceFile } from 'typescript';\nimport type { LanguageHostService } from '@typescript/services/hosts.service';\nimport type { FileNodeInterface } from '@typescript/models/interfaces/graph-model.interface';\nimport type { BundleExportsInterface } from '@typescript/services/interfaces/bundler-serrvice.interface';\nimport type { ModuleImportsInterface } from '@typescript/services/interfaces/bundler-serrvice.interface';\nimport type { NamespaceExportsInterface } from '@typescript/services/interfaces/bundler-serrvice.interface';\n\n/**\n * Imports\n */\n\nimport { mkdir, writeFile } from 'fs/promises';\nimport { inject } from '@symlinks/symlinks.module';\nimport { join, dirname } from '@components/path.component';\nimport { GraphModel } from '@typescript/models/graph.model';\nimport { HeaderDeclarationBundle } from '@typescript/constants/typescript.constant';\n\n/**\n * Bundles multiple internal TypeScript files into consolidated, cleaned declaration files (.d.ts bundles).\n *\n * Starting from one or more entry points, traverses the internal dependency graph, collects all\n * relevant declarations, flattens namespaces, deduplicates exports, gathers external imports,\n * and writes a single portable declaration file per entry point.\n *\n * Primarily used for module federation, library publishing, public API bundling, or\n * creating type-only entry points that hide implementation details.\n *\n * @since 2.0.0\n */\n\nexport class BundlerService {\n /**\n * Injected singleton instance of the dependency graph builder.\n *\n * Provides scanned file nodes with cleaned content, internal dependencies,\n * and detailed import/export information.\n *\n * @remarks\n * Resolved via the framework's `inject()` helper \u2014 always returns the shared singleton.\n *\n * @see {@link GraphModel}\n * @since 2.0.0\n */\n\n private readonly graphModel = inject(GraphModel);\n\n /**\n * Creates bundler bound to a specific language service and host.\n *\n * @param languageService - active TS language service\n * @param languageHostService - host with compiler options and resolution\n *\n * @since 2.0.0\n */\n\n constructor(private languageService: LanguageService, private languageHostService: LanguageHostService) {\n }\n\n /**\n * Bundles declarations for each entry point and writes consolidated .d.ts files.\n *\n * @param entryPoints - map of output filename (without extension) \u2192 entry file path\n * @param outdir - optional override for output directory\n * @returns promise that resolves when all bundles are written\n *\n * @throws Error when language service program is unavailable\n *\n * @example\n * ```ts\n * await bundler.emit({\n * index: './src/index.ts',\n * components: './src/components/index.ts',\n * utils: './src/utils/index.ts'\n * }, './dist/types');\n *\n * // Results in:\n * // dist/types/index.d.ts\n * // dist/types/components.d.ts\n * // dist/types/utils.d.ts\n * ```\n *\n * @see {@link bundleCollectDeclarations}\n * @since 2.0.0\n */\n\n async emit(entryPoints: Record<string, string>, outdir?: string): Promise<void> {\n const program = this.languageService?.getProgram();\n if (!program) throw new Error('Language service program not available');\n\n let config = this.languageHostService.getCompilationSettings();\n if (outdir) config = { ...config, outDir: outdir };\n\n await Promise.all(\n Object.entries(entryPoints).map(async ([ outputPath, entryFile ]) => {\n const sourceFile = program.getSourceFile(entryFile);\n if (!sourceFile) return;\n\n const outputFile = join(config.outDir!, `${ outputPath }.d.ts`);\n await this.bundleCollectDeclarations(sourceFile, program, outputFile);\n })\n );\n }\n\n /**\n * Scans entry point, collects transitive declarations, and writes a bundled file.\n *\n * @param source - entry source file\n * @param program - current program (for source file lookup)\n * @param output - target output file path\n * @returns promise that resolves when write completes\n *\n * @since 2.0.0\n */\n\n private async bundleCollectDeclarations(source: SourceFile, program: Program, output: string): Promise<void> {\n const entryDeclaration = this.graphModel.scan(\n source, this.languageService, this.languageHostService\n );\n\n const content = await this.getBundleContent(entryDeclaration, program);\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, content, 'utf-8');\n }\n\n /**\n * Performs DFS traversal of internal dependencies, collects all relevant content,\n * and prepares it for final bundling.\n *\n * @param entryPoint - scanned entry file node\n * @param program - program for source file lookup\n * @returns concatenated and processed bundle content\n *\n * @remarks\n * Handles transitive star exports by propagating them during traversal.\n *\n * @since 2.0.0\n */\n\n private async getBundleContent(entryPoint: FileNodeInterface, program: Program): Promise<string> {\n const visited = new Set<string>();\n const exportList = new Set([ entryPoint ]);\n const dependencyList = new Set([ entryPoint ]);\n const dependencyQueue = [ ...entryPoint.internalDeps ];\n const starExportModules = new Set(entryPoint.internalExports.star);\n\n let content = '';\n while (dependencyQueue.length > 0) {\n const currentFile = dependencyQueue.pop()!;\n if (visited.has(currentFile)) continue;\n visited.add(currentFile);\n\n const sourceFile = program.getSourceFile(currentFile);\n if (!sourceFile) continue;\n\n const declaration = this.graphModel.scan(sourceFile, this.languageService, this.languageHostService);\n dependencyList.add(declaration);\n\n if (starExportModules.has(currentFile)) {\n exportList.add(declaration);\n for (const starModule of declaration.internalExports.star) starExportModules.add(starModule);\n }\n\n for (const dep of declaration.internalDeps) {\n if (!visited.has(dep)) dependencyQueue.push(dep);\n }\n\n content += declaration.content;\n }\n\n content += entryPoint.content;\n\n return this.parseContent(content, dependencyList, exportList);\n }\n\n /**\n * Aggregates all external imports across the bundle into a deduplicated map.\n *\n * @param declarations - set of scanned file nodes in the bundle\n * @returns map of module \u2192 consolidated imports (default, named, namespace)\n *\n * @since 2.0.0\n */\n\n private collectExternalImports(declarations: Set<FileNodeInterface>): Map<string, ModuleImportsInterface> {\n const imports = new Map<string, ModuleImportsInterface>();\n for (const declaration of declarations) {\n // Default imports: import Foo from 'module'\n for (const [ module, name ] of Object.entries(declaration.externalImports.default)) {\n if (!imports.has(module)) {\n imports.set(module, { named: new Set(), namespace: new Map() });\n }\n const moduleImports = imports.get(module)!;\n if (!moduleImports.default) {\n moduleImports.default = name;\n }\n }\n\n // Named imports: import { a, b } from 'module'\n for (const [ module, names ] of Object.entries(declaration.externalImports.named)) {\n if (!imports.has(module)) {\n imports.set(module, { named: new Set(), namespace: new Map() });\n }\n for (const name of names) {\n imports.get(module)!.named.add(name);\n }\n }\n\n // Namespace imports: import * as Foo from 'module'\n for (const [ name, module ] of Object.entries(declaration.externalImports.namespace)) {\n if (!imports.has(module)) {\n imports.set(module, { named: new Set(), namespace: new Map() });\n }\n imports.get(module)!.namespace.set(name, module);\n }\n }\n\n return imports;\n }\n\n /**\n * Converts collected external imports into sorted import statements.\n *\n * @param imports - deduplicated imports map\n * @returns array of `import \u2026 from \u2026` statements\n *\n * @remarks\n * Namespace imports are emitted separately to preserve `* as` semantics.\n *\n * @since 2.0.0\n */\n\n private generateImportStatements(imports: Map<string, ModuleImportsInterface>): Array<string> {\n const statements: Array<string> = [];\n for (const [ module, { default: defaultImport, named, namespace }] of imports) {\n const parts: Array<string> = [];\n\n if (defaultImport) {\n parts.push(defaultImport);\n }\n\n if (named.size > 0) {\n parts.push(`{ ${ Array.from(named).sort().join(', ') } }`);\n }\n\n if (namespace.size > 0) {\n for (const [ name ] of namespace) {\n statements.push(`import * as ${ name } from '${ module }';`);\n }\n }\n\n if (parts.length > 0) {\n statements.push(`import ${ parts.join(', ') } from '${ module }';`);\n }\n }\n\n return statements;\n }\n\n /**\n * Recursively collects exports from a namespace-exported module.\n *\n * @param fileName - file to start recursion from\n * @param visited - prevents cycles\n * @returns collected exports and supporting declarations\n *\n * @since 2.0.0\n */\n\n private collectNamespaceExports(fileName: string, visited = new Set<string>()): NamespaceExportsInterface {\n if (visited.has(fileName)) {\n return { exports: [], declarations: [] };\n }\n visited.add(fileName);\n\n const declaration = this.graphModel.get(fileName);\n if (!declaration) {\n return { exports: [], declarations: [] };\n }\n\n const exports: Array<string> = [ ...declaration.internalExports.exports ];\n const declarations: Array<string> = [];\n\n // Handle namespace exports: export * as Foo from './module'\n for (const [ namespaceName, targetModule ] of Object.entries(declaration.internalExports.namespace)) {\n const nested = this.collectNamespaceExports(targetModule, visited);\n\n if (nested.exports.length > 0) {\n declarations.push(...nested.declarations);\n declarations.push(`const ${ namespaceName } = { ${ nested.exports.join(', ') } };`);\n exports.push(namespaceName);\n }\n }\n\n // Handle star exports: export * from './module'\n for (const starModule of declaration.externalExports.star) {\n const nested = this.collectNamespaceExports(starModule, visited);\n exports.push(...nested.exports);\n declarations.push(...nested.declarations);\n }\n\n return { exports, declarations };\n }\n\n /**\n * Gathers all exports and supporting declarations for the bundle entry points.\n *\n * @param exportList - set of files that should be re-exported\n * @returns structured bundle exports\n *\n * @since 2.0.0\n */\n\n private collectBundleExports(exportList: Set<FileNodeInterface>): BundleExportsInterface {\n const exports: Array<string> = [];\n const declarations: Array<string> = [];\n const externalExports: Array<string> = [];\n\n for (const declaration of exportList) {\n exports.push(...declaration.internalExports.exports);\n\n // Namespace exports: export * as Foo from './module'\n for (const [ namespaceName, targetModule ] of Object.entries(declaration.internalExports.namespace)) {\n const nested = this.collectNamespaceExports(targetModule);\n\n if (nested.exports.length > 0) {\n declarations.push(...nested.declarations);\n declarations.push(`const ${ namespaceName } = { ${ nested.exports.join(', ') } };`);\n exports.push(namespaceName);\n }\n }\n\n // External star exports: export * from 'external-module'\n for (const module of declaration.externalExports.star) {\n declarations.push(`export * from '${ module }';`);\n }\n\n // External namespace exports: export * as Foo from 'external-module'\n for (const [ namespaceName, module ] of Object.entries(declaration.externalExports.namespace)) {\n externalExports.push(`export * as ${ namespaceName } from '${ module }';`);\n }\n\n // External named exports: export { a, b } from 'external-module'\n for (const [ module, names ] of Object.entries(declaration.externalExports.exports)) {\n externalExports.push(`export { ${ names.join(',\\n') } } from '${ module }';`);\n }\n }\n\n return { exports, declarations, externalExports };\n }\n\n /**\n * Combines all parts into final bundle content with header, imports, declarations, content, and exports.\n *\n * @param content - concatenated cleaned declaration text\n * @param dependencyList - all files in dependency closure\n * @param exportList - files whose exports should be re-exported\n * @returns final bundled declaration text\n *\n * @since 2.0.0\n */\n\n private parseContent(content: string, dependencyList: Set<FileNodeInterface>, exportList: Set<FileNodeInterface>): string {\n const parts: Array<string> = [ HeaderDeclarationBundle ];\n const imports = this.collectExternalImports(dependencyList);\n const importStatements = this.generateImportStatements(imports);\n parts.push(...importStatements);\n\n if (importStatements.length > 0) parts.push(''); // Empty line after imports\n const { exports, declarations, externalExports } = this.collectBundleExports(exportList);\n if (declarations.length > 0) {\n parts.push(...declarations);\n parts.push('');\n }\n\n parts.push(content);\n if (exports.length > 0) {\n const uniqueExports = Array.from(new Set(exports)).sort();\n parts.push(`export {\\n\\t${ uniqueExports.join(',\\n\\t') }\\n};`);\n }\n\n if (externalExports.length > 0) {\n parts.push(...externalExports);\n }\n\n return parts.join('\\n');\n }\n}\n", "/**\n * Header text included at the top of generated declaration bundle files.\n *\n * @remarks\n * This constant provides a standardized header comment prepended to all\n * declaration bundle files generated by the TypeScript module. The header clearly\n * indicates that the file was automatically generated and should not be edited manually.\n *\n * The header serves as:\n * - A warning to developers not to manually modify generated files\n * - Documentation indicating the source of the file\n * - A consistent marker for identifying generated declaration files\n *\n * @example\n * ```ts\n * import { HeaderDeclarationBundle } from './typescript.constant';\n * import { writeFileSync } from 'fs';\n *\n * const bundledContent = `${HeaderDeclarationBundle}\\n${actualDeclarations}`;\n * writeFileSync('dist/index.d.ts', bundledContent);\n * ```\n *\n * @since 1.5.9\n */\n\nexport const HeaderDeclarationBundle = `/**\n * This file was automatically generated by xBuild.\n * DO NOT EDIT MANUALLY.\n */\n`;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { LanguageHostService } from '@typescript/services/hosts.service';\nimport type { CompilerOptions, Program, SourceFile, LanguageService } from 'typescript';\n\n/**\n * Imports\n */\n\nimport { mkdir, writeFile } from 'fs/promises';\nimport { dirname } from '@components/path.component';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { calculateOutputPath, cleanContent } from '@typescript/components/transformer.component';\n\n/**\n * Incremental declaration emitter that writes cleaned `.d.ts` files to disk.\n *\n * Uses the TypeScript language service to emit declaration files only for changed\n * project files (skipping external libraries and unchanged versions), applies alias\n * path resolution, cleans unnecessary content, and writes files to the configured `outDir`.\n *\n * Designed for build tools, watch-mode compilers, module federation setups, or\n * public API packaging workflows that need fresh, minimal type declarations.\n *\n * @since 2.0.0\n */\n\nexport class EmitterService {\n /**\n * Maps output declaration path \u2192 last emitted version string.\n *\n * Used to skip redundant emits when file content/version has not changed.\n *\n * @remarks\n * Static, so the cache survives across service instances (useful in long-running processes).\n *\n * @since 2.0.0\n */\n\n private static emittedVersions: Map<string, string> = new Map();\n\n /**\n * Creates emitter bound to a specific language service and host.\n *\n * @param languageService - active TS language service instance\n * @param languageHostService - host with compiler options and resolution capabilities\n *\n * @since 2.0.0\n */\n\n constructor(private languageService: LanguageService, private languageHostService: LanguageHostService) {\n }\n\n /**\n * Clears the static version cache used for incremental emit decisions.\n * @since 2.0.0\n */\n\n static clearCache(): void {\n this.emittedVersions.clear();\n }\n\n /**\n * Emits cleaned declaration files for all changed project source files.\n *\n * @param outdir - optional override for output directory (overrides `outDir` in config)\n * @returns promise that resolves when all writes are complete\n *\n * @throws Error when language service program is unavailable\n *\n * @example\n * ```ts\n * // One-time full emit to custom directory\n * await emitter.emit('./dist/types');\n *\n * // Incremental emit on watch change\n * emitter.emit(); // uses original compilerOptions.outDir\n * ```\n *\n * @see {@link shouldEmitFile}\n * @see {@link emitSingleDeclaration}\n *\n * @since 2.0.0\n */\n\n async emit(outdir?: string): Promise<void> {\n const program = this.languageService.getProgram();\n if (!program) {\n throw new Error(`${ xterm.deepOrange('[TS]') } Language service program is not available`);\n }\n\n let config = this.languageHostService.getCompilationSettings();\n if (outdir) config = { ...config, outDir: outdir };\n\n const filesToEmit: Array<SourceFile> = [];\n const sourceFiles = program.getSourceFiles();\n for (let i = 0; i < sourceFiles.length; i++) {\n const file = sourceFiles[i];\n if (this.shouldEmitFile(file, program, config)) {\n filesToEmit.push(file);\n }\n }\n\n if (filesToEmit.length === 0) return;\n await Promise.all(filesToEmit.map(\n source => this.emitSingleDeclaration(source, config)\n ));\n }\n\n /**\n * Determines whether a source file should be (re-)emitted based on version and type.\n *\n * @param file - candidate source file\n * @param program - current program (for external library check)\n * @param config - effective compiler options (with possible outDir override)\n * @returns `true` if a file needs emission\n *\n * @remarks\n * Skips:\n * - `.d.ts` files\n * - files from external libraries (node_modules)\n * - files whose version matches the last emitted version\n *\n * Updates cache when emission is needed.\n *\n * @since 2.0.0\n */\n\n private shouldEmitFile(file: SourceFile, program: Program, config: CompilerOptions): boolean {\n if (file.isDeclarationFile || program.isSourceFileFromExternalLibrary(file))\n return false;\n\n const outputPath = calculateOutputPath(file.fileName, config);\n const version = EmitterService.emittedVersions.get(outputPath);\n const currentVersion = this.languageHostService.getScriptVersion(file.fileName);\n\n if (!version) {\n EmitterService.emittedVersions.set(\n outputPath, currentVersion\n );\n\n return true;\n }\n\n if (version !== currentVersion) {\n EmitterService.emittedVersions.set(outputPath, currentVersion);\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Emits and writes a single cleaned declaration file to disk.\n *\n * @param sourceFile - file to emit\n * @param options - compiler options (including outDir)\n * @returns promise that resolves when write completes\n *\n * @remarks\n * - Uses `emitOnlyDtsFiles: true`\n * - Applies `cleanContent` and alias resolution (if aliases are configured)\n * - Creates directories recursively if needed\n *\n * @example\n * ```ts\n * // Internal usage pattern\n * const output = languageService.getEmitOutput(file.fileName, true);\n * let text = output.outputFiles[0].text;\n * text = cleanContent(text);\n * if (aliasRegex) text = this.resolveAliases(aliasRegex, text, sourceFile);\n * await writeFile(calculatedPath, text, 'utf8');\n * ```\n *\n * @since 2.0.0\n */\n\n private async emitSingleDeclaration(sourceFile: SourceFile, options: CompilerOptions): Promise<void> {\n const output = this.languageService.getEmitOutput(sourceFile.fileName, true);\n if (output.emitSkipped) return;\n\n let content = output.outputFiles[0].text;\n const fileName = calculateOutputPath(sourceFile.fileName, options);\n\n content = cleanContent(content);\n content = this.languageHostService.resolveAliases(content, sourceFile.fileName, '.d.ts');\n\n await mkdir(dirname(fileName), { recursive: true });\n await writeFile(fileName, content, 'utf8');\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ResolvedModuleWithFailedLookupLocations } from 'typescript';\nimport type { CompilerOptions, IScriptSnapshot, ModuleResolutionCache } from 'typescript';\nimport type { FileSnapshotInterface } from '@typescript/models/interfaces/files-model.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { inject } from '@symlinks/symlinks.module';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { relative, dirname } from '@components/path.component';\n\n/**\n * Implements a TypeScript Language Service host with file snapshot caching and module resolution.\n *\n * @remarks\n * The `LanguageHostService` implements the {@link ts.LanguageServiceHost} interface to provide\n * TypeScript's language service with file system access, file snapshots, and compiler configuration.\n *\n * @example\n * ```ts\n * // Initialize with compiler options\n * const host = new LanguageHostService({\n * target: ts.ScriptTarget.ES2020,\n * module: ts.ModuleKind.ESNext,\n * paths: {\n * '@utils/*': ['src/utils/*'],\n * '@components/*': ['src/components/*']\n * }\n * });\n *\n * // Track files for analysis\n * host.touchFile('src/index.ts');\n * host.touchFiles(['src/utils.ts', 'src/types.ts']);\n *\n * // Get file snapshots for language service\n * const snapshot = host.getScriptSnapshot('src/index.ts');\n *\n * // Resolve module imports\n * const resolved = host.resolveModuleName('@utils/helpers', 'src/index.ts');\n *\n * // Check for path aliases\n * const hasAliases = host.aliasRegex !== undefined;\n *\n * // Update configuration\n * host.options = { target: ts.ScriptTarget.ES2022 };\n * ```\n *\n * @see {@link ts.LanguageServiceHost} for the implemented interface specification\n * @see {@link FilesModel} for file snapshot caching implementation\n *\n * @since 2.0.0\n */\n\nexport class LanguageHostService implements ts.LanguageServiceHost {\n /**\n * Reference to TypeScript's system interface for file operations.\n *\n * @remarks\n * Static reference to `ts.sys` that provides abstracted file system operations\n * (read, write, directory traversal) compatible with different environments (Node.js, browsers, etc.).\n * Used for all file I/O operations in this service to maintain platform independence.\n *\n * @see {@link ts.sys}\n *\n * @since 2.0.0\n */\n\n private static readonly sys = ts.sys;\n\n /**\n * Cached regular expression for matching import/export statements with path aliases.\n *\n * @remarks\n * Compiled from `compilerOptions.paths` to efficiently detect imports using path aliases.\n * Regenerated when compiler options change. Undefined if no path aliases are configured.\n *\n * Used by tools that need to identify which import statements use aliases for proper\n * handling during transformation or bundling.\n *\n * @see {@link generateAliasRegex} for pattern generation\n *\n * @since 2.0.0\n */\n\n private alias: RegExp | undefined;\n\n private aliasCache = new Map<string, string | undefined>();\n\n /**\n * Cache for TypeScript module resolution results.\n *\n * @remarks\n * TypeScript's internal module resolution cache that stores resolution results to avoid\n * redundant lookups. Improves performance significantly when resolving many imports,\n * especially in large projects with complex path mappings.\n *\n * Recreated when compiler options change (since different options may affect resolution).\n *\n * @see {@link ts.createModuleResolutionCache}\n *\n * @since 2.0.0\n */\n\n private moduleResolutionCache: ModuleResolutionCache;\n\n /**\n * A set containing the file paths of all actively tracked script files.\n *\n * @remarks\n * This set ensures that files are tracked for later operations, such as retrieving script versions\n * or snapshots. Files are added to this set when they are first processed or read by the service.\n *\n * @example\n * ```ts\n * trackFiles.add('/src/main.ts');\n * console.log(trackFiles.has('/src/main.ts')); // true\n * ```\n *\n * @see {@link getScriptFileNames} - Retrieves all tracked files.\n *\n * @since 2.0.0\n */\n\n private readonly trackFiles = new Set<string>();\n\n /**\n * Model for managing file snapshots and version tracking.\n *\n * @remarks\n * Delegates file snapshot management to {@link FilesModel} for centralized\n * caching and change detection. Snapshots are tracked by modification time\n * to detect file changes efficiently.\n *\n * @see {@link FilesModel}\n *\n * @since 2.0.0\n */\n\n private readonly filesCache = inject(FilesModel);\n\n /**\n * Initializes a new {@link LanguageHostService} instance.\n *\n * @param compilerOptions - Optional TypeScript compiler options (defaults to an empty object)\n *\n * @remarks\n * Performs initialization including:\n * 1. Stores compiler options for later use\n * 2. Generates path alias regex from options if configured\n * 3. Creates module resolution cache with appropriate settings\n *\n * The module resolution cache is necessary for efficient resolution of imports in large projects.\n * Path alias regex is generated up-front and cached for performance.\n *\n * @example\n * ```ts\n * // Create host with default options\n * const host = new LanguageHostService();\n *\n * // Create host with specific compiler options\n * const host = new LanguageHostService({\n * target: ts.ScriptTarget.ES2020,\n * module: ts.ModuleKind.ESNext,\n * paths: {\n * '@utils/*': ['src/utils/*']\n * }\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(private compilerOptions: CompilerOptions = {}) {\n this.alias = LanguageHostService.generateAliasRegex(compilerOptions);\n this.moduleResolutionCache = ts.createModuleResolutionCache(\n process.cwd(),\n s => s,\n this.compilerOptions\n );\n }\n\n /**\n * Regular expression that matches import/export statements using path aliases (if `paths` is configured).\n *\n * @remarks\n * Used mainly for advanced refactoring or rewrite tools that need to identify aliased imports.\n *\n * @since 2.0.0\n */\n\n get aliasRegex(): RegExp | undefined {\n return this.alias;\n }\n\n /**\n * Replaces current compiler options and regenerates derived state (alias regex, module cache).\n *\n * @param options - new compiler configuration\n *\n * @since 2.0.0\n */\n\n set options(options: CompilerOptions) {\n this.compilerOptions = options;\n this.alias = LanguageHostService.generateAliasRegex(options);\n this.moduleResolutionCache = ts.createModuleResolutionCache(\n process.cwd(),\n s => s,\n this.compilerOptions\n );\n }\n\n /**\n * Updates file snapshot in the cache and returns the current state.\n *\n * @param path - file path (relative or absolute)\n * @returns current snapshot data (version, mtime, content snapshot)\n *\n * @see {@link FilesModel#touchFile}\n * @since 2.0.0\n */\n\n touchFile(path: string): FileSnapshotInterface {\n this.trackFiles.add(this.filesCache.resolve(path));\n\n return this.filesCache.touchFile(path);\n }\n\n /**\n * Ensures multiple files are tracked and their snapshots are up to date.\n *\n * @param filesPath - list of file paths to touch\n *\n * @since 2.0.0\n */\n\n touchFiles(filesPath: Array<string>): void {\n for (const file of filesPath) {\n this.touchFile(file);\n }\n }\n\n /**\n * Returns current compiler options used by this host.\n *\n * @returns active TypeScript compiler configuration\n *\n * @since 2.0.0\n */\n\n getCompilationSettings(): CompilerOptions {\n return this.compilerOptions;\n }\n\n /**\n * Checks whether a file exists on disk.\n *\n * @param path - absolute path\n * @returns `true` if file exists\n *\n * @since 2.0.0\n */\n\n fileExists(path: string): boolean {\n return LanguageHostService.sys.fileExists(path);\n }\n\n /**\n * Reads file content from disk.\n *\n * @param path - absolute path\n * @param encoding - optional encoding (defaults to UTF-8)\n * @returns file content or `undefined` if read fails\n *\n * @since 2.0.0\n */\n\n readFile(path: string, encoding?: string): string | undefined {\n return LanguageHostService.sys.readFile(path, encoding);\n }\n\n /**\n * Lists files and/or directories matching criteria.\n *\n * @param path - starting directory\n * @param extensions - allowed file extensions\n * @param exclude - glob exclude patterns\n * @param include - glob include patterns\n * @param depth - max recursion depth\n * @returns matching file paths\n *\n * @since 2.0.0\n */\n\n readDirectory(path: string, extensions?: Array<string>, exclude?: Array<string>, include?: Array<string>, depth?: number): Array<string> {\n return LanguageHostService.sys.readDirectory(path, extensions, exclude, include, depth);\n }\n\n /**\n * Returns immediate subdirectories of a given path.\n *\n * @param path - directory to list\n * @returns subdirectory names\n *\n * @since 2.0.0\n */\n\n getDirectories(path: string): Array<string> {\n return LanguageHostService.sys.getDirectories(path);\n }\n\n /**\n * Checks whether a directory exists.\n *\n * @param path - absolute path\n * @returns `true` if directory exists\n *\n * @since 2.0.0\n */\n\n directoryExists(path: string): boolean {\n return LanguageHostService.sys.directoryExists(path);\n }\n\n /**\n * Returns the current working directory used as resolution base.\n *\n * @returns absolute path of cwd\n *\n * @since 2.0.0\n */\n\n getCurrentDirectory(): string {\n return LanguageHostService.sys.getCurrentDirectory();\n }\n\n /**\n * Returns names of all known script files tracked by this host.\n *\n * @returns array of resolved absolute paths\n *\n * @remarks\n * Only includes files previously requested via `getScriptSnapshot` or explicitly `touchFile`/`touchFiles`.\n *\n * @since 2.0.0\n */\n\n getScriptFileNames(): Array<string> {\n return [ ...this.trackFiles ];\n }\n\n /**\n * Returns a path to a default lib `.d.ts` file matching the given target.\n *\n * @param options - compiler options (mainly `target`)\n * @returns absolute path to lib.d.ts / lib.esxxxx.d.ts\n *\n * @since 2.0.0\n */\n\n getDefaultLibFileName(options: CompilerOptions): string {\n return ts.getDefaultLibFilePath(options);\n }\n\n /**\n * Returns string version identifier for the given file.\n *\n * @param path - file path\n * @returns version as string (usually `\"0\"`, `\"1\"`, `\"2\"`, \u2026)\n *\n * @remarks\n * Tracks file in `trackFiles` set as a side effect so it appears in `getScriptFileNames()`.\n *\n * @since 2.0.0\n */\n\n getScriptVersion(path: string): string {\n const state = this.filesCache.getSnapshot(path);\n this.trackFiles.add(this.filesCache.resolve(path));\n\n return state ? state.version.toString() : '0';\n }\n\n /**\n * Checks whether a file is actively tracked (has been requested before).\n *\n * @param path - file path\n * @returns `true` if the file is known to this host\n *\n * @since 2.0.0\n */\n\n hasScriptSnapshot(path: string): boolean {\n return this.trackFiles.has(this.filesCache.resolve(path));\n }\n\n /**\n * Returns an up-to-date script snapshot for the file.\n *\n * @param path - file path\n * @returns `IScriptSnapshot` or `undefined` if a file is missing/empty\n *\n * @remarks\n * Automatically touches the file (reads disk if needed) when no snapshot exists yet.\n *\n * @since 2.0.0\n */\n\n getScriptSnapshot(path: string): IScriptSnapshot | undefined {\n const state = this.filesCache.getSnapshot(path);\n this.trackFiles.add(this.filesCache.resolve(path));\n if (state) return state.contentSnapshot;\n\n return this.touchFile(path).contentSnapshot;\n }\n\n /**\n * Resolves module import using current compiler options and cache.\n *\n * @param moduleName - module specifier\n * @param containingFile - path of a file containing the import\n * @returns resolution result (success and failed lookups)\n *\n * @since 2.0.0\n */\n\n resolveModuleName(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations {\n return ts.resolveModuleName(\n moduleName, containingFile, this.compilerOptions, ts.sys, this.moduleResolutionCache\n );\n }\n\n /**\n * Resolves a module specifier to its absolute file path using the host.\n *\n * @param moduleName - import/export specifier (e.g. \"lodash\", \"./utils\")\n * @param containingFile - path of a file containing the import\n * @returns resolved absolute path or `undefined` if resolution fails\n *\n * @since 2.0.0\n */\n\n resolveModuleFileName(moduleName: string, containingFile: string): string | undefined {\n if (this.aliasCache.has(moduleName)) {\n return this.aliasCache.get(moduleName);\n }\n\n const resolved = this.resolveModuleName(moduleName, containingFile);\n const result = resolved.resolvedModule?.resolvedFileName;\n this.aliasCache.set(moduleName, result);\n\n return result;\n }\n\n /**\n * Rewrites path aliases in declaration content to relative paths.\n *\n * @param content - raw declaration text\n * @param fileName - source file name\n * @param type - file extension to append to resolved paths (e.g., `'.d.ts'`, `'.js'`), defaults to empty string\n * @returns content with aliases replaced by relative paths\n *\n * @remarks\n * Ensures emitted files use portable relative imports instead of aliases.\n * The `type` parameter allows flexible transformation of resolved TypeScript source file extensions\n * (`.ts`, `.tsx`) to any target extension.\n *\n * **Common use cases**:\n * - Pass `'.d.ts'` for declaration file generation\n * - Pass `'.js'` for JavaScript output paths\n * - Pass `''` (default) to preserve the resolved file extension\n *\n * @example\n * ```ts\n * // For regular source files (preserve extension)\n * const code = host.resolveAliases(content, 'src/index.ts');\n *\n * // For declaration files\n * const dts = host.resolveAliases(content, 'src/index.ts', '.d.ts');\n * // '@utils/helpers' -> './utils/helpers.d.ts'\n *\n * // For JavaScript output\n * const js = host.resolveAliases(content, 'src/index.ts', '.js');\n * // '@utils/helpers' -> './utils/helpers.js'\n * ```\n *\n * @since 2.0.0\n */\n\n resolveAliases(content: string, fileName: string, type: string = ''): string {\n if(!this.alias) return content;\n\n return content.replace(this.alias, (match, importPath) => {\n const resolve = this.resolveModuleFileName(importPath, fileName);\n if (!resolve) return match;\n\n const targetFile = resolve.replace(/\\.tsx?$/, type);\n const relativePath = relative(dirname(fileName), targetFile);\n\n return match.replace(importPath, relativePath.startsWith('.') ? relativePath : './' + relativePath);\n });\n }\n\n /**\n * Builds regex that matches import/export declarations using any configured path alias.\n *\n * @param config - compiler options containing `paths`\n * @returns regex or `undefined` if no `paths` configured\n *\n * @since 2.0.0\n */\n\n private static generateAliasRegex(config: CompilerOptions): RegExp | undefined {\n const paths = config.paths;\n if (!paths || Object.keys(paths).length < 1) return;\n\n const aliases = Object.keys(paths)\n .map(alias => alias.replace('/*', '').replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('|');\n\n return new RegExp(\n '(?:^|\\\\s)(?:import|export)\\\\s+' + // import or export keyword\n '(?:type\\\\s+)?' + // optional 'type' keyword\n '(?:[^\\'\"]*from\\\\s+)?' + // optional '... from' (non-greedy)\n `['\"]((${ aliases })[^'\"]*)['\"]` + // capture the quoted path with alias\n ';?', // optional semicolon\n 'gm'\n );\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions, BuildResult, Metafile } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { build } from 'esbuild';\nimport { isBuildResultError, processEsbuildMessages } from '@providers/esbuild-messages.provider';\n\n/**\n * Default ESBuild options used when building or transpiling files.\n *\n * @remarks\n * These defaults bundle, minify, preserve symlinks, and generate external sourcemaps\n * targeting modern browser environments.\n *\n * see BuildOptions\n * @since 2.0.0\n */\n\nexport const defaultBuildOptions: BuildOptions = {\n write: false,\n bundle: true,\n minify: true,\n outdir: `${ cwd() }`,\n format: 'esm',\n target: 'esnext',\n platform: 'browser',\n sourcemap: 'external',\n mangleQuoted: true,\n sourcesContent: true,\n preserveSymlinks: true\n};\n\n/**\n * Builds multiple files using ESBuild with specified options.\n *\n * @param entryPoints - Array of entry points to build\n * @param buildOptions - Optional override build options\n *\n * @returns A promise resolving to an ESBuild BuildResult including metafile information\n *\n * @throws AggregateError - Thrown if esBuild encounters errors during build\n *\n * @remarks\n * This function merges user-provided options with default options and ensures\n * that a metafile is generated. If any errors occur during the build, they are\n * wrapped in a {@link AggregateError} for consistent error reporting.\n *\n * @example\n * ```ts\n * const result = await buildFiles(['src/index.ts'], { minify: false });\n * console.log(result.outputFiles);\n * ```\n *\n * @see esBuildError\n * @see AggregateError\n *\n * @since 2.0.0\n */\n\nexport async function buildFiles(entryPoints: BuildOptions['entryPoints'], buildOptions: BuildOptions = {}): Promise<BuildResult<BuildOptions & Metafile>> {\n try {\n return await build({\n absWorkingDir: cwd(),\n ...defaultBuildOptions,\n ...buildOptions,\n metafile: true,\n entryPoints: entryPoints\n }) as BuildResult<BuildOptions & Metafile>;\n } catch (err) {\n if(isBuildResultError(err)) {\n const aggregateError = new AggregateError([], 'Failed to build entryPoints');\n processEsbuildMessages(err.errors, aggregateError.errors);\n\n throw aggregateError;\n }\n\n throw err;\n }\n}\n\n/**\n * Transpiles TypeScript source code from a string into bundled JavaScript output without writing to disk.\n *\n * @param source - TypeScript source code as a string to transpile\n * @param path - Source file path used for source map generation and error reporting\n * @param buildOptions - Optional esbuild configuration options to override defaults\n *\n * @returns Promise resolving to a {@link BuildResult} containing transpiled code, source maps, and metadata\n *\n * @remarks\n * This function performs in-memory transpilation of TypeScript code using esbuild's stdin feature.\n * It's particularly useful for:\n * - Runtime code evaluation and transformation\n * - Macro expansion and inline directives\n * - Dynamic code generation during builds\n * - Testing and validation without file system writes\n *\n * The function applies the following configuration:\n * - Uses {@link defaultBuildOptions} as the base configuration\n * - Overrides with provided `buildOptions` parameter\n * - Forces `write: false` to keep output in memory\n * - Enables `metafile: true` for dependency analysis\n * - Sets `logLevel: 'silent'` to suppress build output\n * - Generates external source maps for debugging\n *\n * The source code is treated as TypeScript (`loader: 'ts'`) and resolved relative to the current\n * working directory. The `path` parameter is used for source map generation and error messages\n * but does not need to reference an actual file on disk.\n *\n * @example\n * ```ts\n * // Basic transpilation\n * const result = await buildFromString(\n * 'const x: number = 42; export default x;',\n * 'virtual.ts'\n * );\n * console.log(result.outputFiles[0].text); // Transpiled JS\n * ```\n *\n * @example\n * ```ts\n * // With custom build options\n * const result = await buildFromString(\n * 'export const add = (a: number, b: number) => a + b;',\n * 'math.ts',\n * {\n * format: 'cjs',\n * target: 'node16',\n * minify: true\n * }\n * );\n * ```\n *\n * @example\n * ```ts\n * // Used in macro evaluation\n * const code = extractExecutableCode(node, state);\n * const transpiled = await buildFromString(\n * code.data,\n * state.sourceFile.fileName,\n * {\n * bundle: false,\n * format: 'cjs',\n * packages: 'external',\n * platform: 'node'\n * }\n * );\n * // Execute transpiled code in VM\n * ```\n *\n * @see {@link BuildResult} for output structure\n * @see {@link defaultBuildOptions} for base configuration\n * @see {@link BuildOptions} for available configuration options\n * @see {@link analyzeDependencies} for dependency analysis without transpilation\n *\n * @since 2.0.0\n */\n\nexport async function buildFromString(source: string, path: string, buildOptions: BuildOptions = {}): Promise<BuildResult> {\n return await build({\n absWorkingDir: cwd(),\n ...defaultBuildOptions,\n ...buildOptions,\n stdin: {\n loader: 'ts',\n contents: source,\n resolveDir: cwd(),\n sourcefile: path\n },\n write: false,\n metafile: true,\n logLevel: 'silent',\n sourcemap: 'external'\n });\n}\n\n/**\n * Analyzes dependencies of entry point files without writing output.\n *\n * @param entryPoint - Entry point file path(s) for dependency analysis.\n * @param buildOptions - Optional esbuild configuration options to customize the analysis.\n * @returns A promise that resolves to a {@link BuildResult} with metafile metadata containing dependency information.\n *\n * @remarks\n * This function performs a lightweight dependency analysis by:\n *\n * 1. Running esbuild in bundling mode to resolve all imports and dependencies\n * 2. Generating a metafile containing detailed dependency graph information\n * 3. Marking external packages to avoid bundling node_modules\n * 4. Disabling file output to keep the analysis fast and non-destructive\n * 5. Suppressing log output for cleaner execution\n *\n * The resulting metafile contains:\n * - All resolved imports and their relationships\n * - Module dependencies and their sizes\n * - Entry point analysis\n * - Import/export structure information\n *\n * This is useful for:\n * - Understanding project dependency graphs\n * - Identifying circular dependencies\n * - Analyzing import chains\n * - Profiling bundle composition\n * - Validating module resolution\n *\n * @example\n * ```ts\n * // Basic dependency analysis\n * const result = await analyzeDependencies('src/index.ts');\n * console.log('Dependencies:', Object.keys(result.metafile.inputs));\n *\n * // With custom build options\n * const result = await analyzeDependencies('src/main.ts', {\n * external: ['lodash', 'react'],\n * alias: { '@utils': './src/utils' }\n * });\n *\n * // Analyze multiple entry points\n * const result = await analyzeDependencies(\n * ['src/index.ts', 'src/cli.ts']\n * );\n *\n * for (const [input, data] of Object.entries(result.metafile.inputs)) {\n * console.log(`File: ${input}`);\n * console.log(`Imports: ${data.imports.map(i => i.path).join(', ')}`);\n * }\n * ```\n *\n * @see Metafile\n * @see BuildResult\n * @see BuildOptions\n *\n * @since 1.0.0\n */\n\nexport async function analyzeDependencies(entryPoint: BuildOptions['entryPoints'], buildOptions: BuildOptions = {}): Promise<\n BuildResult & { metafile: Metafile }\n> {\n try {\n return await build({\n ...buildOptions,\n outdir: 'tmp',\n write: false, // Prevent writing output files\n bundle: true, // Bundle to analyze imports\n metafile: true, // Generate a metafile to analyze dependencies\n packages: 'external',\n logLevel: 'silent',\n entryPoints: entryPoint\n });\n } catch(err) {\n if(isBuildResultError(err)) {\n const aggregateError = new AggregateError([], 'Failed to analyze entryPoint');\n processEsbuildMessages(err.errors, aggregateError.errors);\n\n throw aggregateError;\n }\n\n throw err;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { xBuildError } from '@errors/xbuild.error';\nimport { collectFilesFromGlob } from '@components/glob.component';\n\n/**\n * Extracts and normalizes entry points from various esbuild entry point formats.\n *\n * @param baseDir - Base directory to resolve glob patterns from\n * @param entryPoints - Entry points in any esbuild-supported format\n * @returns Normalized object mapping output names to input file paths\n *\n * @remarks\n * Supports three esbuild entry point formats:\n *\n * **Array of strings (glob patterns):**\n * - Treats entries as glob patterns to match files\n * - Keys are filenames without extensions\n *\n * **Array of objects with `in` and `out` properties:**\n * - `in`: Input file path\n * - `out`: Output file path\n * - Keys are the `out` values\n *\n * **Record object:**\n * - Keys are output names\n * - Values are input file paths\n * - Returned as-is without modification\n *\n * @throws {@link xBuildError}\n * Thrown when entry points format is unsupported or invalid\n *\n * @example\n * Array of glob patterns:\n * ```ts\n * const entries = extractEntryPoints('./src', ['**\\/*.ts', '!**\\/*.test.ts']);\n * // Returns: { 'index': 'index.ts', 'utils/helper': 'utils/helper.ts' }\n * ```\n *\n * @example\n * Array of in/out objects:\n * ```ts\n * const entries = extractEntryPoints('./src', [\n * { in: 'src/index.ts', out: 'bundle' },\n * { in: 'src/worker.ts', out: 'worker' }\n * ]);\n * // Returns: { 'bundle': 'src/index.ts', 'worker': 'src/worker.ts' }\n * ```\n *\n * @example\n * Record object:\n * ```ts\n * const entries = extractEntryPoints('./src', {\n * main: 'src/index.ts',\n * worker: 'src/worker.ts'\n * });\n * // Returns: { 'main': 'src/index.ts', 'worker': 'src/worker.ts' }\n * ```\n *\n * @see {@link https://esbuild.github.io/api/#entry-points|esbuild Entry Points}\n *\n * @since 2.0.0\n */\n\nexport function extractEntryPoints(baseDir: string, entryPoints: BuildOptions['entryPoints']): Record<string, string> {\n if (Array.isArray(entryPoints)) {\n let result: Record<string, string> = {};\n\n if (entryPoints.length > 0 && typeof entryPoints[0] === 'object') {\n (entryPoints as { in: string, out: string }[]).forEach(entry => {\n result[entry.out] = entry.in;\n });\n } else if (typeof entryPoints[0] === 'string') {\n result = collectFilesFromGlob(baseDir, <Array<string>> entryPoints);\n }\n\n return result;\n } else if (entryPoints && typeof entryPoints === 'object') {\n return entryPoints;\n }\n\n throw new xBuildError('Unsupported entry points format');\n}\n", "/**\n * Type imports (removed at compile time)\n */\n\nimport type { PluginBuild, Plugin, OnStartResult, PartialMessage, Message } from 'esbuild';\nimport type { OnEndType, OnLoadType, OnStartType } from './interfaces/lifecycle-provider.interface';\nimport type { BuildResult, OnResolveResult, OnResolveArgs, OnLoadResult, OnLoadArgs } from 'esbuild';\nimport type { OnResolveType, LifecycleContextInterface } from './interfaces/lifecycle-provider.interface';\n\n/**\n * Imports\n */\n\nimport { readFile } from 'fs/promises';\nimport { inject } from '@symlinks/symlinks.module';\nimport { resolve } from '@components/path.component';\nimport { FilesModel } from '@typescript/models/files.model';\n\n/**\n * Manages lifecycle hooks for esbuild plugins with support for build stages and hook execution coordination.\n * Provides a centralized system for registering and executing hooks during different phases of the build process,\n * including resolution, loading, start, end, and success stages.\n *\n * @remarks\n * This provider implements a hook-based architecture that allows multiple handlers to be registered\n * for each build lifecycle stage. Hooks are stored in maps keyed by name, allowing for organized\n * registration and execution of build-time logic.\n *\n * The lifecycle stages are executed in the following order:\n * 1. **onStart**: Executed when the build begins, before any file processing\n * 2. **onResolve**: Executed during module resolution for each import\n * 3. **onLoad**: Executed when loading file contents for each module\n * 4. **onEnd**: Executed when the build completes (success or failure)\n * 5. **onSuccess**: Executed only when the build completes without errors\n *\n * Hook execution strategy:\n * - Start and end hooks aggregate errors and warnings from all handlers\n * - Resolve hooks merge results from multiple handlers\n * - Load hooks apply transformations sequentially (pipeline pattern)\n * - All hooks receive a specialized context object appropriate for their lifecycle stage\n *\n * @example\n * ```ts\n * const provider = new LifecycleProvider('my-plugin', { debug: true });\n *\n * provider.onStart(async (context) => {\n * console.log('Build starting...');\n * return { warnings: [] };\n * });\n *\n * provider.onLoad(async (context) => {\n * // Transform TypeScript files\n * if (context.args.path.endsWith('.ts')) {\n * return { contents: transformCode(context.contents), loader: 'ts' };\n * }\n * });\n *\n * const plugin = provider.create();\n * ```\n *\n * @see {@link FilesModel}\n * @see {@link LoadContextInterface}\n * @see {@link BuildContextInterface}\n * @see {@link ResultContextInterface}\n * @see {@link ResolveContextInterface}\n * @see {@link LifecycleContextInterface}\n *\n * @since 2.0.0\n */\n\nexport class LifecycleProvider {\n /**\n * File model for accessing TypeScript language service snapshots and file content.\n * @since 2.0.0\n */\n\n private filesModel: FilesModel = inject(FilesModel);\n\n /**\n * Registered handlers to execute when the build completes, regardless of success or failure.\n * @since 2.0.0\n */\n\n private readonly endHooks = new Map<string, OnEndType>();\n\n /**\n * Registered handlers to execute when loading file contents during module processing.\n * @since 2.0.0\n */\n\n private readonly loadHooks = new Map<string, OnLoadType>();\n\n /**\n * Registered handlers to execute when the build process begins.\n * @since 2.0.0\n */\n\n private readonly startHooks = new Map<string, OnStartType>();\n\n /**\n * Registered handlers to execute when the build completes successfully without errors.\n * @since 2.0.0\n */\n\n private readonly successHooks = new Map<string, OnEndType>();\n\n /**\n * Registered handlers to execute during module path resolution.\n * @since 2.0.0\n */\n\n private readonly resolveHooks = new Map<string, OnResolveType>();\n\n /**\n * Creates a new lifecycle provider instance with the specified variant name and configuration.\n *\n * @param variantName - The variant name used for identification and included in hook contexts\n * @param argv - Command-line arguments and configuration options passed to hook handlers\n *\n * @remarks\n * The constructor initializes empty hook maps for each lifecycle stage. The `variantName` parameter\n * is used as the default identifier when registering hooks without explicit names and is\n * included in the context passed to all handlers as `variantName`.\n *\n * The `argv` configuration is stored and made available to all hooks through their context objects,\n * allowing build-time behavior to be customized based on command-line flags or configuration.\n *\n * @example\n * ```ts\n * const provider = new LifecycleProvider('production', {\n * watch: false,\n * sourcemap: true,\n * minify: true\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n constructor(protected variantName: string, protected argv: Record<string, unknown>) {\n }\n\n /**\n * Registers a handler to execute when the build process begins.\n *\n * @param handler - Optional callback function to execute at build start\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Start hooks are executed before any file processing occurs and receive a build context\n * containing the esbuild `PluginBuild` object, variant name, arguments, and stage state.\n * They can return errors and warnings that will be aggregated with results from other start hooks.\n *\n * If no handler is provided, this method does nothing (allowing conditional registration).\n * Multiple start hooks can be registered with different names and will all execute in\n * registration order.\n *\n * Common use cases:\n * - Initialization and setup tasks\n * - Validation of build configuration\n * - Cleaning output directories\n * - Logging build start time\n *\n * @example\n * ```ts\n * provider.onStart(async (context) => {\n * console.log(`${context.variantName} build started at ${context.stage.startTime}`);\n * return { warnings: [], errors: [] };\n * });\n * ```\n *\n * @see {@link executeStartHooks}\n * @see {@link BuildContextInterface}\n *\n * @since 2.0.0\n */\n\n onStart(handler?: OnStartType, name: string = this.variantName): void {\n if (handler) this.startHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute when the build completes, regardless of success or failure.\n *\n * @param handler - Optional callback function to execute at build end\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * End hooks are executed after all build operations are complete and receive a result context\n * containing the final build result, calculated duration, variant name, arguments, and stage state.\n * They can return additional errors and warnings to append to the build output.\n *\n * If no handler is provided, this method does nothing. Multiple end hooks execute in registration\n * order, and all results are aggregated.\n *\n * Common use cases:\n * - Cleanup and resource disposal\n * - Logging build completion and duration\n * - Generating build reports or statistics\n * - Post-processing output files\n *\n * @example\n * ```ts\n * provider.onEnd(async (context) => {\n * console.log(`${context.variantName} build completed in ${context.duration}ms`);\n * return { warnings: [], errors: [] };\n * });\n * ```\n *\n * @see {@link onSuccess}\n * @see {@link executeEndHooks}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\n onEnd(handler?: OnEndType, name: string = this.variantName): void {\n if (handler) this.endHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute when the build completes successfully without errors.\n *\n * @param handler - Optional callback function to execute on successful build\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Success hooks are a specialized subset of end hooks that only execute when the build\n * completes with zero errors. They receive a result context containing the build result,\n * duration, and stage state, and are guaranteed to run only after successful builds.\n *\n * If no handler is provided, this method does nothing. Success hooks execute after all\n * regular end hooks have completed. Any errors thrown by success hooks are captured and\n * appended to the aggregated end-hook error list.\n *\n * Common use cases:\n * - Deploying build artifacts\n * - Running post-build validation\n * - Updating deployment status\n * - Sending success notifications\n *\n * @example\n * ```ts\n * provider.onSuccess(async (context) => {\n * console.log('Build succeeded! Deploying...');\n * await deploy(context.buildResult.metafile);\n * });\n * ```\n *\n * @see {@link onEnd}\n * @see {@link executeEndHooks}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\n onSuccess(handler?: OnEndType, name: string = this.variantName): void {\n if (handler) this.successHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute during module path resolution.\n *\n * @param handler - Optional callback function to execute during resolution\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Resolve hooks are executed when esbuild needs to resolve import paths to file system locations.\n * They receive a resolve context containing the resolution arguments, variant name, and stage state.\n * Hooks can return modified resolution results or redirect imports.\n *\n * If no handler is provided, this method does nothing. Multiple resolve hooks can execute, and\n * their results are merged, with later hooks potentially overriding earlier ones.\n *\n * Common use cases:\n * - Implementing custom module resolution algorithms\n * - Redirecting imports to alternative locations\n * - Handling path aliases and mappings\n * - Resolving virtual modules\n *\n * @example\n * ```ts\n * provider.onResolve(async (context) => {\n * if (context.args.path.startsWith('@/')) {\n * return { path: resolve('src', context.args.path.slice(2)) };\n * }\n * });\n * ```\n *\n * @see {@link executeResolveHooks}\n * @see {@link ResolveContextInterface}\n *\n * @since 2.0.0\n */\n\n onResolve(handler?: OnResolveType, name: string = this.variantName): void {\n if (handler) this.resolveHooks.set(name, handler);\n }\n\n /**\n * Registers a handler to execute when loading file contents during module processing.\n *\n * @param handler - Optional callback function to execute during file loading\n * @param name - Optional identifier for this hook, defaults to the variant name\n *\n * @remarks\n * Load hooks are executed when esbuild loads file contents and receive a load context containing\n * the current contents (potentially transformed by previous hooks), loader type, load arguments,\n * variant name, and stage state. Hooks can transform the contents and change the loader,\n * with transformations applied sequentially in a pipeline pattern.\n *\n * If no handler is provided, this method does nothing. Multiple load hooks execute in\n * registration order, with each hook receiving the transformed output of previous hooks\n * through the context.\n *\n * Common use cases:\n * - Transforming file contents (transpilation, minification)\n * - Injecting code or imports\n * - Applying preprocessors\n * - Changing file loader types\n *\n * @example\n * ```ts\n * provider.onLoad(async (context) => {\n * if (context.args.path.endsWith('.custom')) {\n * return {\n * contents: transformCustomSyntax(context.contents),\n * loader: 'ts'\n * };\n * }\n * });\n * ```\n *\n * @see {@link executeLoadHooks}\n * @see {@link LoadContextInterface}\n *\n * @since 2.0.0\n */\n\n onLoad(handler?: OnLoadType, name: string = this.variantName): void {\n if (handler) this.loadHooks.set(name, handler);\n }\n\n /**\n * Clears all registered hooks from all lifecycle stages.\n *\n * @remarks\n * This method removes all registered handlers for start, end, success, resolve, and load hooks.\n * It's typically used when resetting the provider state or preparing for a new build configuration.\n *\n * After calling this method, the provider has no registered hooks and will not execute any\n * handlers until new ones are registered.\n *\n * @example\n * ```ts\n * provider.onStart(startHandler);\n * provider.onEnd(endHandler);\n *\n * // Remove all hooks\n * provider.clearAll();\n *\n * // Provider now has no registered hooks\n * ```\n *\n * @since 2.0.0\n */\n\n clearAll(): void {\n this.endHooks.clear();\n this.loadHooks.clear();\n this.startHooks.clear();\n this.successHooks.clear();\n this.resolveHooks.clear();\n }\n\n /**\n * Creates an esbuild plugin instance with all registered hooks configured.\n *\n * @returns Configured esbuild plugin object ready for use in build configuration\n *\n * @remarks\n * This method generates an esbuild plugin that wires up all registered hooks to the\n * appropriate esbuild lifecycle events. The plugin setup function:\n * - Initializes a base lifecycle context with variant name, arguments, and start time\n * - Enables metafile generation for build metadata\n * - Registers onStart handler if any start hooks exist\n * - Registers onEnd handler if any end or success hooks exist\n * - Registers onResolve handler with catch-all filter if any resolve hooks exist\n * - Registers onLoad handler with catch-all filter if any load hooks exist\n *\n * Each hook receives a specialized context appropriate for its lifecycle stage:\n * - Start hooks receive `BuildContextInterface` with the build object\n * - End/Success hooks receive `ResultContextInterface` with build result and duration\n * - Resolve hooks receive `ResolveContextInterface` with resolution arguments\n * - Load hooks receive `LoadContextInterface` with contents, loader, and load arguments\n *\n * Handlers are bound at setup time using `Function.prototype.bind` with the shared\n * lifecycle context, avoiding repeated closure allocations on each invocation.\n *\n * @example\n * ```ts\n * const provider = new LifecycleProvider('production', {});\n * provider.onStart(startHandler);\n * provider.onLoad(loadHandler);\n *\n * const plugin = provider.create();\n *\n * await esbuild.build({\n * entryPoints: ['src/index.ts'],\n * plugins: [plugin]\n * });\n * ```\n *\n * @see {@link executeEndHooks}\n * @see {@link executeLoadHooks}\n * @see {@link executeStartHooks}\n * @see {@link executeResolveHooks}\n *\n * @since 2.0.0\n */\n\n create(): Plugin {\n return {\n name: this.variantName,\n setup: (build: PluginBuild): void => {\n const context: LifecycleContextInterface = {\n argv: this.argv,\n options: build.initialOptions,\n variantName: this.variantName,\n stage: { startTime: new Date() }\n };\n\n build.initialOptions.metafile = true;\n\n if (this.startHooks.size > 0)\n build.onStart(this.executeStartHooks.bind(this, context, build));\n\n if (this.endHooks.size > 0 || this.successHooks.size > 0)\n build.onEnd(this.executeEndHooks.bind(this, context));\n\n if (this.resolveHooks.size > 0)\n build.onResolve({ filter: /.*/ }, this.executeResolveHooks.bind(this, context));\n\n if (this.loadHooks.size > 0)\n build.onLoad({ filter: /.*/ }, this.executeLoadHooks.bind(this, context));\n }\n };\n }\n\n /**\n * Appends a caught error to the provided error list as a normalized `PartialMessage`.\n *\n * @param errors - The error array to append to\n * @param id - Logical source identifier for the failing hook phase (e.g. `startHook`, `endHook`)\n * @param err - The thrown value to wrap\n * @param names - The hook name to set as `pluginName`, defaults to the variant name\n *\n * @remarks\n * Captured errors are normalized with:\n * - `id` to identify which lifecycle phase produced the message\n * - `pluginName` to attribute the failure to the registered hook name\n * - `location: null` because these errors are runtime hook failures, not source-mapped diagnostics\n *\n * @since 2.0.0\n */\n\n private pushError(errors: Array<PartialMessage>, id: string, err: unknown, names: string = this.variantName): void {\n errors.push({\n id,\n detail: err,\n location: null,\n pluginName: names\n });\n }\n\n /**\n * Executes all registered start hooks and aggregates their results.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param build - The esbuild plugin build object\n * @returns Aggregated result containing all errors and warnings from start hooks\n *\n * @remarks\n * This method resets the start time in the stage object, then executes all registered\n * start hooks in order. Each hook receives a build context that includes the esbuild\n * build object along with the base lifecycle context.\n *\n * Results from all hooks are aggregated:\n * - Errors from all hooks are combined into a single array\n * - Warnings from all hooks are combined into a single array\n *\n * Errors thrown by a hook are caught and appended to the error array rather than\n * propagating, so all hooks always execute regardless of individual failures.\n * Each captured error is attributed to its hook's registered name via `pluginName`\n * on the `PartialMessage`, making the source of the failure identifiable in esbuild output.\n *\n * The context object is passed through to later lifecycle stages for consistent\n * state management across the build.\n *\n * @see {@link onStart}\n * @see {@link BuildContextInterface}\n *\n * @since 2.0.0\n */\n\n private async executeStartHooks(context: LifecycleContextInterface, build: PluginBuild): Promise<OnStartResult> {\n context.stage.startTime = new Date();\n const errors: Array<PartialMessage> = [];\n const warnings: Array<PartialMessage> = [];\n const hookContext = { build, ...context };\n\n for (const [ name, hook ] of this.startHooks.entries()) {\n try {\n const result = await hook(hookContext);\n if (result?.errors) errors.push(...result.errors);\n if (result?.warnings) warnings.push(...result.warnings);\n } catch (err) {\n this.pushError(errors, 'startHook', err, name);\n }\n }\n\n return { errors, warnings };\n }\n\n /**\n * Executes all registered end hooks and success hooks, mutating the provided `buildResult`.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param buildResult - The final build result from esbuild (mutated in place)\n *\n * @remarks\n * This method computes build duration and executes hooks in two phases:\n * 1. **End hooks**: Always run. Returned `errors`/`warnings` are appended to `buildResult`.\n * Thrown errors are captured and normalized through {@link pushError} using `id: \"endHook\"`.\n * 2. **Success hooks**: Run only when `buildResult.errors.length === 0` after end hooks.\n * Return values are ignored; thrown errors are captured as `endHook`-scoped messages.\n *\n * Hook handlers share a single result context object that includes `duration`, `buildResult`,\n * and the base lifecycle metadata.\n *\n * @see {@link onEnd}\n * @see {@link onSuccess}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\n private async executeEndHooks(context: LifecycleContextInterface, buildResult: BuildResult): Promise<void> {\n const { errors, warnings } = buildResult;\n const duration = Date.now() - context.stage.startTime.getTime();\n const hookContext = { buildResult, duration, ...context };\n\n for (const [ name, hook ] of this.endHooks.entries()) {\n try {\n const result = await hook(hookContext);\n if (result?.errors) errors.push(...result.errors as Array<Message>);\n if (result?.warnings) warnings.push(...result.warnings as Array<Message>);\n } catch (err) {\n this.pushError(errors, 'endHook', err, name);\n }\n }\n\n if (buildResult.errors.length === 0) {\n for (const [ name, hook ] of this.successHooks.entries()) {\n try {\n await hook(hookContext);\n } catch (err) {\n this.pushError(errors, 'endHook', err, name);\n }\n }\n }\n }\n\n /**\n * Executes all registered resolve hooks and merges their results.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param args - The resolution arguments from esbuild\n * @returns Merged resolution result from all hooks, always including an `errors` array\n *\n * @remarks\n * This method executes all resolve hooks in registration order, passing each hook a resolve\n * context that includes the resolution arguments along with the base lifecycle context.\n * Results are merged using object spreading, meaning later hooks can override properties\n * set by earlier hooks.\n *\n * The result is initialized as `{ errors: [] }` and used as the merge base. If all hooks\n * return `undefined`/`null`, the method still returns this base result.\n *\n * Unlike start/end/load hooks, resolve hook errors are not caught \u2014 esbuild will surface\n * them directly as build errors.\n *\n * @see {@link onResolve}\n * @see {@link ResolveContextInterface}\n *\n * @since 2.0.0\n */\n\n private async executeResolveHooks(context: LifecycleContextInterface, args: OnResolveArgs): Promise<OnResolveResult> {\n let result: OnResolveResult = { errors: [] };\n const hookContext = { args, ...context };\n\n for (const [ name, hook ] of this.resolveHooks.entries()) {\n try {\n const hookResult = await hook(hookContext);\n if (!hookResult) continue;\n result = { ...result, ...hookResult };\n } catch (err) {\n this.pushError(result.errors!, 'endResolve', err, name);\n }\n }\n\n return result;\n }\n\n /**\n * Executes all registered load hooks in sequence, applying content transformations as a pipeline.\n *\n * @param context - Base lifecycle context containing variant name, arguments, and stage state\n * @param args - The load arguments from esbuild containing file path and namespace\n * @returns Load result with final transformed contents and loader type\n *\n * @remarks\n * This method implements a transformation pipeline where:\n * 1. Initial contents are loaded from a TypeScript snapshot or file system\n * 2. Each load hook receives a load context with current contents, loader, and arguments\n * 3. Hooks can transform contents and change the loader\n * 4. Each hook's output becomes the input for the next hook's context\n *\n * Content loading priority:\n * - First attempts to load from TypeScript language service snapshot (if available),\n * accessed via optional chaining on `contentSnapshot`\n * - Falls back to reading the file from disk using `fs/promises`\n *\n * The loader starts as `'default'` and can be changed by any hook in the pipeline.\n * Errors thrown by individual hooks are caught and appended to the error list, attributed to\n * the hook's registered name via `pluginName` on the `PartialMessage`, so the pipeline continues\n * running for subsequent hooks and the failing hook is clearly identifiable in esbuild output.\n * The final contents, loader, errors, and warnings are returned to esbuild for processing.\n *\n * @see {@link onLoad}\n * @see {@link LoadContextInterface}\n * @see {@link FilesModel.getSnapshot}\n *\n * @since 2.0.0\n */\n\n private async executeLoadHooks(context: LifecycleContextInterface, args: OnLoadArgs): Promise<OnLoadResult | null> {\n const errors: Array<PartialMessage> = [];\n const warnings: Array<PartialMessage> = [];\n let loader: OnLoadResult['loader'] = 'default';\n\n const filePath = resolve(args.path);\n const snapshot = this.filesModel.getSnapshot(filePath);\n let contents: string | Uint8Array = snapshot?.contentSnapshot\n ? snapshot.contentSnapshot.text\n : await readFile(filePath, 'utf8');\n\n for (const [ name, hook ] of this.loadHooks.entries()) {\n try {\n const result = await hook({ contents, loader, args, ...context });\n if (!result) continue;\n if (result.contents !== undefined) contents = result.contents;\n if (result.loader) loader = result.loader;\n if (result.errors) errors.push(...result.errors);\n if (result.warnings) warnings.push(...result.warnings);\n } catch (err) {\n this.pushError(errors, 'loadHook', err, name);\n }\n }\n\n return { contents, loader, errors, warnings };\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OnLoadResult } from 'esbuild';\nimport type { VariantService } from '@services/variant.service';\nimport type { CallExpression, VariableStatement, ExpressionStatement } from 'typescript';\nimport type { MacrosStateInterface } from '@directives/interfaces/analyze-directive.interface';\nimport type { LoadContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { SubstInterface, StateInterface } from '@directives/interfaces/macros-directive.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { esBuildError } from '@errors/esbuild.error';\nimport { highlightCode } from '@remotex-labs/xmap/highlighter.component';\nimport { astDefineVariable, astDefineCallExpression } from '@directives/define.directive';\nimport { astInlineCallExpression, astInlineVariable } from '@directives/inline.directive';\n\n/**\n * Regular expression matching TypeScript and JavaScript file extensions.\n *\n * @remarks\n * Used to filter files that should undergo macro transformation. Only files\n * with `.ts` or `.js` extensions are processed by the transformer directive.\n *\n * @since 2.0.0\n */\n\nconst TS_JS_REGEX = /\\.(ts|js)$/;\n\n/**\n * Array of recognized macro function names for conditional compilation and inline evaluation.\n *\n * @remarks\n * Defines the complete set of macro directives supported by xBuild:\n * - `$$ifdef`: Conditional inclusion when definition is truthy\n * - `$$ifndef`: Conditional inclusion when definition is falsy or undefined\n * - `$$inline`: Runtime code evaluation during build time\n *\n * Used for:\n * - Validating macro calls during AST traversal\n * - Determining argument count requirements\n * - Filtering disabled macro references\n *\n * @since 2.0.0\n */\n\nconst MACRO_FUNCTIONS = [ '$$ifdef', '$$ifndef', '$$inline' ];\n\n/**\n * Checks whether a given AST node\u2019s source text contains any supported macro function name.\n *\n * @param node - AST node to inspect\n * @param sourceFile - Optional source file used by TypeScript to compute node text\n *\n * @returns `true` if the node text contains at least one macro identifier; otherwise `false`.\n *\n * @remarks\n * This is a fast, text-based pre-check used to avoid deeper macro parsing work when a node\n * clearly cannot contain macro calls.\n *\n * @since 2.0.0\n */\n\nexport function nodeContainsMacro(node: ts.Node, sourceFile?: ts.SourceFile): boolean {\n return (MACRO_FUNCTIONS as ReadonlyArray<string>).some(m => node.getText(sourceFile).includes(m));\n}\n\n/**\n * Returns the expected argument count for a supported macro function.\n *\n * @param fnName - Macro function name (e.g. `$$ifdef`, `$$ifndef`, `$$inline`)\n *\n * @returns The required number of arguments for the macro.\n *\n * @remarks\n * - `$$inline` expects 1 argument (a thunk/callback)\n * - `$$ifdef` / `$$ifndef` expect 2 arguments (name + callback/value)\n *\n * @since 2.0.0\n */\n\nfunction expectedArgCount(fnName: string): number {\n return fnName === MACRO_FUNCTIONS[2] ? 1 : 2;\n}\n\n/**\n * Processes variable statements containing macro calls and adds replacements to the replacement set.\n *\n * @param node - The variable statement node to process\n * @param replacements - Set of code replacements to populate\n * @param state - The macro transformation state containing definitions and source file\n *\n * @returns A promise that resolves when all variable declarations have been processed\n *\n * @remarks\n * This function handles macro variable declarations of the form:\n * ```ts\n * const $$myFunc = $$ifdef('DEFINITION', callback);\n * export const $$inline = $$inline(() => computeValue());\n * let $$feature = $$ifndef('PRODUCTION', devFeature);\n * ```\n *\n * The processing flow:\n * 1. Iterates through all variable declarations in the statement\n * 2. Validates that the initializer is a macro call expression\n * 3. Checks that the macro function name is recognized\n * 4. Validates argument count (2 for ifdef/ifndef, 1 for inline)\n * 5. Detects export modifiers to preserve in the output\n * 6. Delegates to the appropriate transformer based on macro type\n * 7. Adds successful transformations to the replacement set\n *\n * **Macro type routing**:\n * - `$$inline`: Delegates to {@link astInlineVariable} (async evaluation)\n * - `$$ifdef`/`$$ifndef`: Delegates to {@link astDefineVariable} (conditional inclusion)\n *\n * Replacements track the start and end positions of the original statement\n * for accurate text substitution during the final transformation pass.\n *\n * @example Processing conditional macro\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * // With: { DEBUG: true }\n * await isVariableStatement(node, replacements, state);\n * // replacements contains: {\n * // start: 0,\n * // end: 52,\n * // replacement: 'function $$debug() { return console.log; }'\n * // }\n * ```\n *\n * @example Processing inline macro\n * ```ts\n * // Source: export const API_URL = $$inline(() => process.env.API);\n * await isVariableStatement(node, replacements, state);\n * // replacements contains: {\n * // start: 0,\n * // end: 59,\n * // replacement: 'export const API_URL = undefined;'\n * // }\n * ```\n *\n * @example Invalid macro (skipped)\n * ```ts\n * // Source: const $$bad = $$ifdef('DEV'); // Missing callback argument\n * await isVariableStatement(node, replacements, state);\n * // No replacement added (insufficient arguments)\n * ```\n *\n * @see {@link astProcess} for the calling context\n * @see {@link astInlineVariable} for inline macro transformation\n * @see {@link astDefineVariable} for conditional macro transformation\n *\n * @since 2.0.0\n */\n\nexport async function isVariableStatement(node: VariableStatement, replacements: Set<SubstInterface>, state: StateInterface): Promise<boolean> {\n let replacement: string | false = false;\n\n for (const decl of node.declarationList.declarations) {\n let suffix = '';\n let call: ts.CallExpression | undefined;\n const init = decl.initializer;\n if (!init) continue;\n\n if (ts.isCallExpression(init) && ts.isIdentifier(init.expression)) {\n // Plain: $$macro(...)\n call = init;\n } else if (\n ts.isCallExpression(init) &&\n ts.isCallExpression(init.expression) &&\n ts.isIdentifier(init.expression.expression)\n ) {\n // IIFE: $$macro(...)(...outerArgs)\n call = init.expression;\n const args = init.arguments.map(a => a.getText(state.sourceFile)).join(', ');\n suffix = `(${ args })`;\n } else if (\n ts.isAsExpression(init) &&\n ts.isCallExpression(init.expression) &&\n ts.isIdentifier(init.expression.expression)\n ) {\n call = init.expression;\n }\n\n if (!call) continue;\n\n const fnName = (call.expression as ts.Identifier).text;\n if (!MACRO_FUNCTIONS.includes(fnName)) continue;\n if (call.arguments.length !== expectedArgCount(fnName)) {\n const { line, character } = state.sourceFile.getLineAndCharacterOfPosition(call.getStart(state.sourceFile));\n throw new esBuildError({\n text: `Invalid macro call: ${ fnName } with ${ call.arguments.length } arguments`,\n location: {\n file: state.sourceFile.fileName,\n line: line + 1,\n column: character\n }\n });\n }\n\n const hasExport =\n node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;\n\n if (fnName === MACRO_FUNCTIONS[2]) replacement = await astInlineVariable(decl, node, call, hasExport, state);\n else if (suffix) replacement = astDefineCallExpression(call, state, decl, hasExport, suffix);\n else replacement = astDefineVariable(decl, call, hasExport, state);\n\n if (replacement !== false) {\n replacements.add({\n replacement,\n end: node.getEnd(),\n start: node.getStart(state.sourceFile)\n });\n }\n }\n\n return replacement !== false;\n}\n\n/**\n * Processes standalone macro call expressions and adds replacements to the replacement set.\n *\n * @param node - The expression statement containing the macro call\n * @param replacements - Set of code replacements to populate\n * @param state - The macro transformation state containing definitions and source file\n *\n * @returns A promise that resolves when the expression has been processed\n *\n * @remarks\n * This function handles standalone macro calls that appear as expression statements:\n * ```ts\n * $$ifdef('DEBUG', () => console.log('debug'));\n * $$inline(() => initialize());\n * ```\n *\n * The processing flow:\n * 1. Validates that the expression is a macro call with identifier\n * 2. Checks that the macro function name is recognized\n * 3. Validates argument count (2 for ifdef/ifndef, 1 for inline)\n * 4. Delegates to the appropriate transformer based on macro type\n * 5. Adds successful transformations to the replacement set\n *\n * **Macro type routing**:\n * - `$$inline`: Delegates to {@link astInlineCallExpression} (async evaluation)\n * - `$$ifdef`/`$$ifndef`: Delegates to {@link astDefineCallExpression} (conditional inclusion)\n *\n * **Note**: The define call expression handler currently doesn't return a replacement\n * (returns `false` implicitly), so only inline macros result in replacements at this level.\n *\n * @example Processing inline call\n * ```ts\n * // Source: $$inline(() => configureApp());\n * await isCallExpression(node, replacements, state);\n * // replacements contains: {\n * // start: 0,\n * // end: 35,\n * // replacement: 'undefined'\n * // }\n * ```\n *\n * @example Processing conditional call\n * ```ts\n * // Source: $$ifdef('DEBUG', () => enableDebugMode());\n * await isCallExpression(node, replacements, state);\n * // No replacement added (define expressions handle differently)\n * ```\n *\n * @see {@link astProcess} for the calling context\n * @see {@link astInlineCallExpression} for inline macro transformation\n * @see {@link astDefineCallExpression} for conditional macro transformation\n *\n * @since 2.0.0\n */\n\nexport async function isCallExpression(\n node: ExpressionStatement, replacements: Set<SubstInterface>, state: StateInterface\n): Promise<boolean> {\n const callExpr = <CallExpression> node.expression;\n if (!callExpr.expression || !ts.isIdentifier(callExpr.expression)) return false;\n\n const fnName = callExpr.expression.text;\n if (!MACRO_FUNCTIONS.includes(fnName)) return false;\n if (callExpr.arguments.length !== expectedArgCount(fnName)) {\n const { line, character } = state.sourceFile.getLineAndCharacterOfPosition(node.getStart(state.sourceFile));\n throw new esBuildError({\n text: `Invalid macro call: ${ fnName } with ${ callExpr.arguments.length } arguments`,\n location: {\n file: state.sourceFile.fileName,\n line: line + 1,\n column: character\n }\n });\n }\n\n let replacement: string | false = false;\n if (fnName == MACRO_FUNCTIONS[2]) {\n await astInlineCallExpression(callExpr.arguments, state);\n replacement = 'undefined';\n } else replacement = astDefineCallExpression(callExpr, state);\n\n if (replacement !== false) {\n replacements.add({\n replacement,\n end: callExpr.getEnd(),\n start: callExpr.getStart(state.sourceFile)\n });\n }\n\n return replacement !== false;\n}\n\n/**\n * Processes a `CallExpression` AST node that targets one of the supported macro functions and,\n * if possible, registers a text replacement.\n *\n * @param node - The AST node to process (must be a `CallExpression` to be meaningful)\n * @param replacements - Collection of replacements to apply later (sorted and spliced into the source)\n * @param state - Current macro processing state (includes `sourceFile`, `contents`, metadata, etc.)\n *\n * @returns `true` when a macro replacement was added; otherwise `false`.\n *\n * @remarks\n * This handler is used for *nested* macro call sites (i.e. `CallExpression` nodes that are not\n * expression statements or variable statements), for example:\n *\n * ```ts\n * const value = someFn($$inline(() => 123));\n * ```\n *\n * Routing:\n * - `$$inline(...)` \u2192 {@link astInlineCallExpression} (async)\n * - `$$ifdef(...)` / `$$ifndef(...)` \u2192 {@link astDefineCallExpression}\n *\n * The replacement range is based on the node\u2019s `[start, end]` positions in {@link StateInterface.sourceFile}.\n *\n * @see {@link astInlineCallExpression}\n * @see {@link astDefineCallExpression}\n *\n * @since 2.0.0\n */\n\nasync function macroCallExpression(node: ts.Node, replacements: Set<SubstInterface>, state: StateInterface): Promise<boolean> {\n if (!ts.isCallExpression(node)) return false;\n if (!nodeContainsMacro(node, state.sourceFile)) return false;\n\n const callNode = node as ts.CallExpression;\n if (!ts.isIdentifier(callNode.expression)) return false;\n\n const fnName = callNode.expression.text;\n\n if (fnName === MACRO_FUNCTIONS[2]) {\n // $$inline macro\n const replacement = await astInlineCallExpression(callNode.arguments, state);\n if (replacement === false) return false;\n\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement\n });\n\n return true;\n }\n\n // $$ifdef / $$ifndef macro\n const replacement = astDefineCallExpression(callNode, state);\n if (replacement === false) return false;\n\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement\n });\n\n return true;\n}\n\n/**\n * Recursively traverses the AST to find and transform all macro occurrences in the source file.\n *\n * @param state - The macro transformation state containing source file, definitions, and content\n * @param variant - The build variant name for tracking replacements (defaults to 'unknow')\n *\n * @returns A promise resolving to the transformed source code with all macro replacements applied\n *\n * @remarks\n * This is the main transformation function that orchestrates macro processing across the entire\n * source file. It performs a recursive AST traversal to locate and transform different macro patterns:\n *\n * **Macro patterns handled**:\n * 1. **Variable statements**: `const $$x = $$ifdef(...)` or `const x = $$inline(...)`\n * 2. **Expression statements**: Standalone `$$ifdef(...)` or `$$inline(...)` calls\n * 3. **Nested inline calls**: `$$inline(...)` within other expressions (not variable/expression statements)\n * 4. **Disabled macro calls**: Calls to macros marked as disabled in metadata\n * 5. **Disabled macro identifiers**: References to disabled macro names (replaced with `undefined`)\n *\n * @example Complete transformation\n * ```ts\n * // Original source:\n * const $$debug = $$ifdef('DEBUG', () => console.log);\n * const value = $$inline(() => 42);\n * $$debug();\n *\n * // With definitions: { DEBUG: false }\n * const result = await astProcess(state, 'production');\n *\n * // Transformed result:\n * const value = undefined;\n * undefined();\n *\n * // Tracked in state.stage.replacementInfo['production']\n * ```\n *\n * @example Handling disabled macros\n * ```ts\n * // Original source (with DEBUG=false):\n * const $$debug = $$ifdef('DEBUG', log);\n * if ($$debug) $$debug();\n *\n * // After processing:\n * if (undefined) undefined();\n * ```\n *\n * @example No macros (short circuit)\n * ```ts\n * const state = {\n * contents: 'const x = 1;',\n * sourceFile,\n * stage: { defineMetadata: { filesWithMacros: new Set(), disabledMacroNames: new Set() } }\n * };\n * const result = await astProcess(state);\n * // Returns original content unchanged immediately\n * ```\n *\n * @see {@link macroCallExpression} for nested inline calls\n * @see {@link isCallExpression} for expression statement handling\n * @see {@link isVariableStatement} for variable declaration handling\n * @see {@link MacrosStateInterface.replacementInfo} for replacement tracking\n *\n * @since 2.0.0\n */\n\nexport async function astProcess(state: StateInterface, variant: string = 'unknow'): Promise<string> {\n const fnToRemove = state.stage.defineMetadata.disabledMacroNames;\n const hasMacro = state.stage.defineMetadata.filesWithMacros.has(state.sourceFile.fileName);\n if (!hasMacro && fnToRemove.size === 0) return state.contents;\n\n const stack: Array<ts.Node> = [ state.sourceFile ];\n const replacements: Set<SubstInterface> = new Set();\n\n while (stack.length > 0) {\n const node = stack.pop();\n const kind = node?.kind;\n if (!node || !kind) continue;\n if (hasMacro) {\n if (kind === ts.SyntaxKind.VariableStatement) {\n if (await isVariableStatement(node as VariableStatement, replacements, state)) continue;\n }\n\n if (kind === ts.SyntaxKind.ExpressionStatement && nodeContainsMacro(node, state.sourceFile)) {\n if (await isCallExpression(node as ExpressionStatement, replacements, state)) continue;\n }\n\n if (kind === ts.SyntaxKind.CallExpression && nodeContainsMacro(node, state.sourceFile)) {\n if (await macroCallExpression(node as ExpressionStatement, replacements, state)) continue;\n }\n }\n\n if (fnToRemove.size > 0) {\n if (kind === ts.SyntaxKind.CallExpression) {\n const callNode = node as ts.CallExpression;\n if (ts.isIdentifier(callNode.expression) && fnToRemove.has(callNode.expression.text)) {\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement: 'undefined'\n });\n }\n } else if (kind === ts.SyntaxKind.Identifier) {\n const identifier = node as ts.Identifier;\n if (fnToRemove.has(identifier.text)) {\n const parent = node.parent ?? node;\n\n if (parent && !ts.isImportSpecifier(parent) && !ts.isExportSpecifier(parent)) {\n const parentText = parent?.getText(state.sourceFile);\n\n if (!ts.isCallExpression(parent) || parent.expression !== node) {\n if (!parentText || MACRO_FUNCTIONS.every(key => !parentText.includes(key))) {\n replacements.add({\n start: node.getStart(state.sourceFile),\n end: node.getEnd(),\n replacement: 'undefined'\n });\n }\n }\n }\n }\n }\n }\n\n const children = node.getChildren(state.sourceFile);\n for (let i = children.length - 1; i >= 0; i--) {\n stack.push(children[i]);\n }\n }\n\n if (replacements.size === 0) return state.contents;\n const replacementsArray = Array.from(replacements);\n replacementsArray.sort((a, b) => b.start - a.start);\n\n state.stage.replacementInfo ??= {};\n state.stage.replacementInfo[variant] ??= [];\n const replacementInfo = state.stage.replacementInfo[variant];\n\n for (const { start, end, replacement } of replacementsArray) {\n replacementInfo.push({\n source: highlightCode(state.contents.slice(start, end)),\n replacement: highlightCode(replacement)\n });\n\n state.contents = state.contents.slice(0, start) + replacement + state.contents.slice(end);\n }\n\n return state.contents;\n}\n\n/**\n * Main transformer directive that processes macro transformations for a build variant.\n *\n * @param variant - The build variant service containing configuration and TypeScript services\n * @param context - The load context containing file information, loader type, and build stage\n *\n * @returns A promise resolving to the transformed file result with processed macros, warnings, and errors\n *\n * @remarks\n * This is the entry point for macro transformation during the build process, integrated as\n * an esbuild plugin loader. It orchestrates the complete transformation pipeline:\n *\n * **Transformation pipeline**:\n * 1. **File filtering**: Validates file extension and content length\n * 2. **Source file acquisition**: Retrieves or creates TypeScript source file\n * 3. **State initialization**: Prepares transformation state with definitions and metadata\n * 4. **Macro processing**: Applies AST transformations via {@link astProcess}\n * 5. **Alias resolution**: Resolves TypeScript path aliases for non-bundled builds\n * 6. **Result assembly**: Returns transformed content with diagnostics\n *\n * **Early exits**:\n * - Non-TypeScript/JavaScript files: Returns content unchanged\n * - Empty files: Returns content unchanged\n * - Files without macros: Processes but no transformations occur\n *\n * **Alias resolution**:\n * When not bundling (`variant.config.esbuild.bundle === false`), path aliases are\n * resolved to relative paths with `.js` extensions for proper module resolution.\n *\n * **Source file handling**:\n * If the source file isn't in the language service program, it's touched (loaded)\n * to ensure the TypeScript compiler has current file information.\n *\n * @example Basic transformation flow\n * ```ts\n * const context = {\n * args: { path: 'src/index.ts' },\n * loader: 'ts',\n * stage: { defineMetadata: { ... } },\n * contents: 'const $$debug = $$ifdef(\"DEBUG\", log);'\n * };\n *\n * const result = await transformerDirective(variant, context);\n * // result.contents: transformed code\n * // result.warnings: macro warnings\n * // result.errors: transformation errors\n * ```\n *\n * @example Non-TypeScript file (skipped)\n * ```ts\n * const context = {\n * args: { path: 'styles.css' },\n * loader: 'css',\n * contents: '.class { color: red; }'\n * };\n *\n * const result = await transformerDirective(variant, context);\n * // result.contents === original content (unchanged)\n * ```\n *\n * @example With alias resolution\n * ```ts\n * // Source contains: import { utils } from '@utils/helpers';\n * // Non-bundled build\n * const result = await transformerDirective(variant, context);\n * // Import resolved: import { utils } from './utils/helpers.js';\n * ```\n *\n * @see {@link astProcess} for macro transformation logic\n * @see {@link LanguageHostService.resolveAliases} for alias resolution\n * @see {@link LoadContextInterface} for context structure\n *\n * @since 2.0.0\n */\n\nexport async function transformerDirective(variant: VariantService, context: LoadContextInterface): Promise<OnLoadResult | undefined> {\n const { args, loader, stage, contents, variantName, options, argv } = context;\n if (args.path.includes('node_modules')) return;\n\n if (contents.length < 1) return;\n if (!TS_JS_REGEX.test(args.path)) return;\n\n const languageService = variant.typescript.languageService;\n const sourceFile = languageService.getProgram()?.getSourceFile(args.path);\n if (!sourceFile) return;\n\n const state: StateInterface = {\n stage: stage as MacrosStateInterface,\n errors: [],\n contents: contents.toString(),\n warnings: [],\n defines: variant.config.define ?? {},\n sourceFile: sourceFile!,\n context: {\n argv,\n options,\n variantName\n }\n };\n\n let content = await astProcess(state, variant.name);\n if (!variant.config.esbuild.bundle) {\n const alias = variant.typescript.languageHostService.aliasRegex;\n if (alias) {\n content = variant.typescript.languageHostService.resolveAliases(content, args.path, '.js');\n }\n }\n\n return { loader, contents: content, warnings: state.warnings, errors: state.errors };\n}\n", "/**\n * Type imports (removed at compile time)\n */\n\nimport type { VariableDeclaration, CallExpression } from 'typescript';\nimport type { SourceFile, Node, ArrowFunction, FunctionExpression } from 'typescript';\nimport type { DefinesType, StateInterface } from './interfaces/macros-directive.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\n\n/**\n * The name of the conditional inclusion directive for checking if a definition is truthy.\n *\n * @remarks\n * Used to identify `$$ifdef` macro calls in the AST. Paired with `$$ifndef` (not-defined check),\n * this directive enables conditional compilation based on build-time definitions.\n *\n * @see {@link isDefinitionMet} for condition evaluation logic\n *\n * @since 2.0.0\n */\n\nconst IFDEF_DIRECTIVE = '$$ifdef';\n\n/**\n * Transforms an AST node into a function declaration or constant assignment.\n *\n * @param fnName - The name for the generated function or constant\n * @param node - The AST node to transform (typically a function or expression)\n * @param sourceFile - The source file containing the node (for text extraction)\n * @param hasExport - Whether to prepend `export` keyword; defaults to `false`\n *\n * @returns A string containing the transformed function declaration or constant assignment\n *\n * @remarks\n * This function handles transformation for conditional macro definitions by converting\n * the macro's callback argument into a named function or constant. The transformation\n * strategy depends on the node type:\n *\n * **For function-like nodes** (arrow functions and function expressions):\n * - Extracts parameters, return type, and body\n * - Generates a proper function declaration\n * - Preserves type annotations if present\n *\n * **For other node types** (expressions, literals, etc.):\n * - Generates a constant assignment\n * - Uses the node's text representation as the value\n *\n * The `hasExport` parameter controls whether the generated declaration is exported,\n * preserving the original export status of the macro variable.\n *\n * @example Arrow function transformation\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * const node = arrowFunctionNode; // () => console.log\n * const result = transformToFunction('$$debug', node, sourceFile, false);\n * // 'function $$debug() { return console.log; }'\n * ```\n *\n * @example Function expression with types\n * ```ts\n * // Source: export const $$getConfig = $$ifdef('DEV', function(): Config { return devConfig; });\n * const result = transformToFunction('$$getConfig', node, sourceFile, true);\n * // 'export function $$getConfig(): Config { return devConfig; }'\n * ```\n *\n * @example Non-function transformation\n * ```ts\n * // Source: const $$apiUrl = $$ifdef('PROD', 'https://api.example.com');\n * const node = stringLiteralNode;\n * const result = transformToFunction('$$apiUrl', node, sourceFile, false);\n * // 'const $$apiUrl = \"https://api.example.com\";'\n * ```\n *\n * @see {@link astDefineVariable} for the calling context\n * @see {@link transformFunctionLikeNode} for function-specific transformation\n *\n * @since 2.0.0\n */\n\nexport function transformToFunction(fnName: string, node: Node, sourceFile: SourceFile, hasExport = false): string {\n const prefix = hasExport ? 'export function ' : 'function ';\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node))\n return transformFunctionLikeNode(fnName, node, sourceFile, prefix);\n\n // Fallback for other node types\n const constPrefix = hasExport ? 'export const ' : 'const ';\n\n return `${ constPrefix }${ fnName } = ${ node.getText(sourceFile) };`;\n}\n\n/**\n * Transforms arrow functions and function expressions into proper function declarations.\n *\n * @param fnName - The name for the generated function\n * @param node - The arrow function or function expression to transform\n * @param sourceFile - The source file containing the node\n * @param prefix - The declaration prefix (e.g., `'function '` or `'export function '`)\n *\n * @returns A string containing the function declaration, prefixed with `async` if the\n * original node carried the `async` modifier\n *\n * @remarks\n * This function extracts the components of a function-like node and reconstructs them\n * as a proper function declaration:\n * - **Async**: Detected from the node's `modifiers` array via `ts.SyntaxKind.AsyncKeyword`\n * and prepended before the declaration prefix, yielding `async function name()` form\n * - **Parameters**: Extracted with full type annotations\n * - **Return type**: Preserved if present in the original\n * - **Body**: Transformed using {@link getFunctionBody} to handle arrow function syntax\n *\n * The transformation preserves all type information, making it suitable for TypeScript\n * projects that rely on type safety in conditional compilation scenarios.\n *\n * @example Async arrow function\n * ```ts\n * const node = parseExpression('async (x: number): Promise<number> => x * 2');\n * const result = transformFunctionLikeNode('double', node, sourceFile, 'export function ');\n * // 'async export function double(x: number): Promise<number> { return x * 2; }'\n * ```\n *\n * @example Arrow function with return type\n * ```ts\n * const node = parseExpression('(x: number): number => x * 2');\n * const result = transformFunctionLikeNode('double', node, sourceFile, 'export function ');\n * // 'export function double(x: number): number { return x * 2; }'\n * ```\n *\n * @example Function expression without types\n * ```ts\n * const node = parseExpression('function(a, b) { return a + b; }');\n * const result = transformFunctionLikeNode('add', node, sourceFile, 'function ');\n * // 'function add(a, b) { return a + b; }'\n * ```\n *\n * @see {@link getFunctionBody} for body extraction\n * @see {@link transformToFunction} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction transformFunctionLikeNode(\n fnName: string, node: ArrowFunction | FunctionExpression, sourceFile: SourceFile, prefix: string\n): string {\n const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;\n const asyncPrefix = isAsync ? 'async ' : '';\n const params = node.parameters.map(p => p.getText(sourceFile)).join(', ');\n const returnType = node.type ? `: ${ node.type.getText(sourceFile) }` : '';\n const body = getFunctionBody(node, sourceFile);\n\n return `${ asyncPrefix }${ prefix }${ fnName }(${ params })${ returnType } ${ body }`;\n}\n\n/**\n * Extracts and formats the function body, handling arrow function shorthand syntax.\n *\n * @param node - The arrow function or function expression to extract from\n * @param sourceFile - The source file containing the node\n *\n * @returns The formatted function body as a string\n *\n * @remarks\n * This function handles two body formats:\n * - **Block body**: Returns as-is (already wrapped in `{}`)\n * - **Expression body**: Wraps in block with `return` statement\n *\n * This ensures that all transformed functions have proper block bodies,\n * which is necessary for function declarations (they cannot have expression bodies).\n *\n * @example Arrow function with expression body\n * ```ts\n * const node = parseExpression('() => 42');\n * const body = getFunctionBody(node, sourceFile);\n * // '{ return 42; }'\n * ```\n *\n * @example Arrow function with block body\n * ```ts\n * const node = parseExpression('() => { console.log(\"test\"); return 42; }');\n * const body = getFunctionBody(node, sourceFile);\n * // '{ console.log(\"test\"); return 42; }'\n * ```\n *\n * @example Function expression (always has block body)\n * ```ts\n * const node = parseExpression('function() { return true; }');\n * const body = getFunctionBody(node, sourceFile);\n * // '{ return true; }'\n * ```\n *\n * @see {@link transformFunctionLikeNode} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction getFunctionBody(node: ArrowFunction | FunctionExpression, sourceFile: SourceFile): string {\n const bodyText = node.body.getText(sourceFile);\n if (ts.isArrowFunction(node) && !ts.isBlock(node.body)) {\n return `{ return ${ bodyText }; }`;\n }\n\n return bodyText;\n}\n\n/**\n * Transforms an AST node into an Immediately Invoked Function Expression (IIFE).\n *\n * @param node - The AST node to transform\n * @param sourceFile - The source file containing the node\n * @param prefix - The prefix to prepend before the IIFE; defaults to `''`\n * @param suffix - The suffix to append after the IIFE; defaults to `'();'`\n *\n * @returns A string containing the IIFE expression, prefixed with `async` when the\n * original function-like node carried the `async` modifier\n *\n * @remarks\n * This function wraps code in IIFE syntax for immediate execution in expression contexts.\n * The transformation strategy depends on the node type:\n *\n * **For function-like nodes** (arrow functions and function expressions):\n * - Detects the `async` modifier via `ts.SyntaxKind.AsyncKeyword` and prepends `async`\n * before `prefix` when present\n * - Wraps directly: `(function)()` or `(() => value)()`\n * - Preserves the function body as-is\n *\n * **For other node types** (expressions, statements):\n * - Wraps in a synchronous arrow function IIFE with explicit return\n * - Ensures the value is returned for use in expressions\n * - Applies `prefix` before and `suffix` after the IIFE\n *\n * The `prefix` and `suffix` parameters allow customization of the IIFE syntax, useful when\n * the IIFE needs additional context, chaining, or specific wrapping.\n *\n * Used when conditional macros appear in expression contexts where a function\n * declaration is not valid syntax.\n *\n * @example Async arrow function to IIFE\n * ```ts\n * const node = parseExpression('async () => await fetchData()');\n * const result = transformToIIFE(node, sourceFile);\n * // 'async (() => await fetchData())()'\n * ```\n *\n * @example Arrow function to IIFE\n * ```ts\n * const node = parseExpression('() => 42');\n * const result = transformToIIFE(node, sourceFile);\n * // '(() => 42)()'\n * ```\n *\n * @example Function expression to IIFE\n * ```ts\n * const node = parseExpression('function() { return \"hello\"; }');\n * const result = transformToIIFE(node, sourceFile);\n * // '(function() { return \"hello\"; })()'\n * ```\n *\n * @example Expression to IIFE\n * ```ts\n * const node = parseExpression('1 + 1');\n * const result = transformToIIFE(node, sourceFile);\n * // '(() => { return 1 + 1; })()'\n * ```\n *\n * @example Custom prefix and suffix\n * ```ts\n * const node = parseExpression('getValue()');\n * const result = transformToIIFE(node, sourceFile, 'await ', '.catch(handleError)');\n * // 'await (() => { return getValue(); })().catch(handleError)'\n * ```\n *\n * @see {@link astDefineCallExpression} for the calling context\n *\n * @since 2.0.0\n */\n\nexport function transformToIIFE(node: Node, sourceFile: SourceFile, prefix: string = '', suffix: string = '();'): string {\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;\n const asyncPrefix = isAsync ? 'async ' : '';\n\n return `${ asyncPrefix }${ prefix }(${ node.getText(sourceFile) })${ suffix }`;\n }\n\n if (prefix) return `${ prefix }${ node.getText(sourceFile) }`;\n\n return `(() => { return ${ node.getText(sourceFile) }; })${ suffix }`;\n}\n\n/**\n * Determines whether a conditional macro definition should be included based on build definitions.\n *\n * @param defineName - The definition name to check (e.g., `'DEBUG'`, `'PRODUCTION'`)\n * @param directiveName - The directive name (`'$$ifdef'` or `'$$ifndef'`)\n * @param defines - The build definitions object mapping names to boolean values\n *\n * @returns `true` if the definition condition is met, `false` otherwise\n *\n * @remarks\n * This function implements the core conditional logic for `$$ifdef` and `$$ifndef` macros:\n *\n * **For `$$ifdef`** (if defined):\n * - Returns `true` when the definition exists and is truthy\n * - Returns `false` when the definition is missing, `false`, `0`, `''`, etc.\n *\n * **For `$$ifndef`** (if not defined):\n * - Returns `true` when the definition is missing or falsy\n * - Returns `false` when the definition exists and is truthy\n *\n * The check uses JavaScript's truthiness rules via `!!defines[defineName]`.\n *\n * @example `$$ifdef` with true definition\n * ```ts\n * const defines = { DEBUG: true, PRODUCTION: false };\n * isDefinitionMet('DEBUG', '$$ifdef', defines); // true\n * isDefinitionMet('PRODUCTION', '$$ifdef', defines); // false\n * ```\n *\n * @example `$$ifndef` with false definition\n * ```ts\n * const defines = { DEBUG: true, PRODUCTION: false };\n * isDefinitionMet('DEBUG', '$$ifndef', defines); // false\n * isDefinitionMet('PRODUCTION', '$$ifndef', defines); // true\n * ```\n *\n * @example Missing definition\n * ```ts\n * const defines = { DEBUG: true };\n * isDefinitionMet('MISSING', '$$ifdef', defines); // false\n * isDefinitionMet('MISSING', '$$ifndef', defines); // true\n * ```\n *\n * @see {@link astDefineVariable} for usage context\n * @see {@link astDefineCallExpression} for usage context\n *\n * @since 2.0.0\n */\n\nfunction isDefinitionMet(defineName: string, directiveName: string, defines: DefinesType): boolean {\n const isDefined = defineName in defines && !!defines[defineName];\n\n return (directiveName === IFDEF_DIRECTIVE) === isDefined;\n}\n\n/**\n * Transforms a conditional macro variable declaration into a function or returns an empty string if excluded.\n *\n * @param decl - The variable declaration node containing the macro\n * @param init - The call expression node representing the macro call\n * @param hasExport - Whether the variable declaration has an `export` modifier\n * @param state - The macro transformation state containing definitions and source file\n *\n * @returns The transformed function/constant string, empty string if excluded, or `false` if invalid\n *\n * @remarks\n * This function processes conditional macro variable declarations of the form:\n * ```ts\n * const $$myFunc = $$ifdef('DEFINITION', callback);\n * const $$myFunc = $$ifndef('DEFINITION', callback);\n * ```\n *\n * The transformation process:\n * 1. Validates that the first argument is a string literal (the definition name)\n * 2. Checks if the definition condition is met using {@link isDefinitionMet}\n * 3. If included: transforms the callback into a function using {@link transformToFunction}\n * 4. If excluded: returns an empty string (macro is stripped from output)\n * 5. If invalid: returns `false` (non-string definition argument)\n *\n * The variable name from the declaration becomes the function name in the output.\n *\n * @example Included macro (DEBUG=true)\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * // With: { DEBUG: true }\n * const result = astDefineVariable(decl, init, false, state);\n * // 'function $$debug() { return console.log; }'\n * ```\n *\n * @example Excluded macro (DEBUG=false)\n * ```ts\n * // Source: const $$debug = $$ifdef('DEBUG', () => console.log);\n * // With: { DEBUG: false }\n * const result = astDefineVariable(decl, init, false, state);\n * // ''\n * ```\n *\n * @example Exported macro\n * ```ts\n * // Source: export const $$feature = $$ifdef('FEATURE_X', () => true);\n * // With: { FEATURE_X: true }\n * const result = astDefineVariable(decl, init, true, state);\n * // 'export function $$feature() { return true; }'\n * ```\n *\n * @example Invalid macro (non-string definition)\n * ```ts\n * // Source: const $$bad = $$ifdef(DEBUG, () => {});\n * const result = astDefineVariable(decl, init, false, state);\n * // false\n * ```\n *\n * @see {@link isDefinitionMet} for condition evaluation\n * @see {@link transformToFunction} for transformation logic\n *\n * @since 2.0.0\n */\n\nexport function astDefineVariable(\n decl: VariableDeclaration, init: CallExpression, hasExport: boolean, state: StateInterface\n): string | false {\n const [ defineArg, callbackArg ] = init.arguments;\n\n if (!ts.isStringLiteral(defineArg)) return false;\n\n const fnName = (init.expression as ts.Identifier).text;\n const defineName = defineArg.text;\n\n if (!isDefinitionMet(defineName, fnName, state.defines)) {\n return 'undefined';\n }\n\n const varName = decl.name.getText(state.sourceFile);\n\n return transformToFunction(varName, callbackArg, state.sourceFile, hasExport);\n}\n\n/**\n * Transforms a conditional macro call expression into a constant assignment with an IIFE or returns empty string if excluded.\n *\n * @param decl - The variable declaration node containing the macro\n * @param init - The call expression node representing the macro call\n * @param hasExport - Whether the variable declaration has an `export` modifier\n * @param state - The macro transformation state containing definitions and source file\n * @param outerSuffix - Optional suffix to append after the IIFE invocation\n *\n * @returns The transformed constant assignment string, empty string if excluded, or `false` if invalid\n *\n * @remarks\n * This function processes conditional macro call expressions that are assigned to constants:\n * ```ts\n * const $$value = $$ifdef('DEBUG', () => \"debug mode\");\n * export const $$config = $$ifndef('PRODUCTION', () => devConfig);\n * ```\n *\n * Unlike {@link astDefineVariable}, which transforms macros into function declarations,\n * this handles macros that should remain as constant assignments with IIFE values.\n *\n * The transformation process:\n * 1. Validates that the first argument is a string literal (the definition name)\n * 2. Extracts the macro function name (`$$ifdef` or `$$ifndef`)\n * 3. Checks if the definition condition is met using {@link isDefinitionMet}\n * 4. If included: transforms the callback into a constant assignment with IIFE using {@link transformToIIFE}\n * 5. If excluded: returns an empty string (macro is stripped from output)\n * 6. If invalid: returns `false` (non-string definition argument)\n *\n * The variable name from the declaration becomes the constant name in the output,\n * and the `hasExport` parameter controls whether the constant is exported.\n *\n * @example Included expression (DEBUG=true)\n * ```ts\n * // Source: const $$debugMsg = $$ifdef('DEBUG', () => \"debugging\");\n * // With: { DEBUG: true }\n * const result = astDefineCallExpression(decl, init, false, state);\n * // 'const $$debugMsg = (() => { return \"debugging\"; })();'\n * ```\n *\n * @example Excluded expression (DEBUG=false)\n * ```ts\n * // Source: const $$debugMsg = $$ifdef('DEBUG', () => \"debugging\");\n * // With: { DEBUG: false }\n * const result = astDefineCallExpression(decl, init, false, state);\n * // ''\n * ```\n *\n * @example Exported constant\n * ```ts\n * // Source: export const $$apiUrl = $$ifndef('PRODUCTION', () => 'http://localhost');\n * // With: { PRODUCTION: false }\n * const result = astDefineCallExpression(decl, init, true, state);\n * // 'export const $$apiUrl = (() => { return \"http://localhost\"; })();'\n * ```\n *\n * @example With custom suffix\n * ```ts\n * // Source: const $$data = $$ifdef('FEATURE', () => fetchData());\n * // With: { FEATURE: true }\n * const result = astDefineCallExpression(decl, init, false, state, '.then(process)');\n * // 'const $$data = (() => { return fetchData(); })().then(process)'\n * ```\n *\n * @see {@link isDefinitionMet} for condition evaluation\n * @see {@link transformToIIFE} for transformation logic\n * @see {@link astDefineVariable} for function declaration handling\n *\n * @since 2.0.0\n */\n\nexport function astDefineCallExpression(\n init: CallExpression, state: StateInterface, decl?: VariableDeclaration, hasExport: boolean = false, outerSuffix?: string\n): string | false {\n const [ defineArg, callbackArg ] = init.arguments;\n\n if (!ts.isStringLiteral(defineArg)) return false;\n\n const defineName = defineArg.text;\n const fnName = (init.expression as ts.Identifier).text;\n if (!isDefinitionMet(defineName, fnName, state.defines)) return '';\n\n let constPrefix = '';\n const varName = decl?.name.getText(state.sourceFile);\n if(varName) {\n constPrefix = hasExport ? `export const ${ varName } = ` : `const ${ varName } = `;\n }\n\n return transformToIIFE(callbackArg, state.sourceFile, constPrefix, outerSuffix);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { CallExpression, VariableDeclaration, Node } from 'typescript';\nimport type { SourceFile, NodeArray, Expression, VariableStatement } from 'typescript';\nimport type { StateInterface } from '@directives/interfaces/macros-directive.interface';\nimport type { FunctionNodeType, ModuleInterface } from '@directives/interfaces/inline-directive.interface';\nimport type { ExecutableInterface, VariableKeywordType } from '@directives/interfaces/inline-directive.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { createRequire } from 'module';\nimport { InlineError } from '@errors/inline.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { sandboxExecute } from '@services/vm.service';\nimport { dirname, relative } from '@components/path.component';\nimport { FrameworkService } from '@services/framework.service';\nimport { buildFromString } from '@services/transpiler.service';\n\n/**\n * Evaluates inline macro code in a sandboxed environment and returns the result as a string.\n *\n * @param code - The JavaScript code to execute (typically an IIFE wrapping a function or expression)\n * @param state - The current macro transformation state containing source file and error tracking\n * @param node - The AST node representing the inline macro call (used for error location tracking)\n *\n * @returns A promise resolving to the stringified result of the code execution, or `'undefined'` on error\n *\n * @remarks\n * This function performs the following steps:\n * 1. Transpiles and bundles the code using {@link buildFromString} in CommonJS format\n * 2. Creates a sandboxed execution context with access to Node.js globals and the file system\n * 3. Executes the code using {@link sandboxExecute} in an isolated VM context\n * 4. Captures and formats any errors using {@link InlineError} with source mapping\n * 5. Returns `'undefined'` on failure (errors are tracked in `state.errors`)\n *\n * The sandbox has access to:\n * - Global Node.js APIs (`Buffer`, `process`, `console`)\n * - Module system (`require`, `module`, `__dirname`, `__filename`)\n * - Timers (`setTimeout`, `setInterval`, and their clear counterparts)\n * - Standard JavaScript globals from `globalThis`\n *\n * Errors that occur during execution are enhanced with source maps to point back to the\n * original source code location, accounting for line offsets where the inline macro appears.\n *\n * @example Basic inline evaluation\n * ```ts\n * const code = '(() => { return 42; })()';\n * const result = await evaluateCode(code, state, node);\n * // result === 'undefined' (function executed but returns undefined as string)\n * ```\n *\n * @example Inline computation with imports\n * ```ts\n * const code = `(() => {\n * const fs = require('fs');\n * return fs.existsSync('./package.json') ? 'found' : 'missing';\n * })()`;\n *\n * const result = await evaluateCode(code, state, node);\n * // Executes in sandbox with require() support\n * ```\n *\n * @example Error handling with source mapping\n * ```ts\n * const code = '(() => { throw new Error(\"Test error\"); })()';\n * const result = await evaluateCode(code, state, node);\n * // Returns 'undefined'\n * // state.errors contains InlineError with mapped stack trace\n * ```\n *\n * @see {@link sandboxExecute} for VM execution\n * @see {@link InlineError} for error formatting\n * @see {@link createSandboxContext} for context creation\n * @see {@link handleExecutionError} for error processing\n * @see {@link buildFromString} for transpilation and bundling\n *\n * @since 2.0.0\n */\n\nexport async function evaluateCode(code: string, state: StateInterface, node: Node): Promise<string> {\n const [ map, data ] = (await buildFromString(code, state.sourceFile.fileName, {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n packages: 'external'\n })).outputFiles!;\n\n try {\n const module = { exports: {} };\n const require = createRequire(state.sourceFile.fileName);\n const context = createSandboxContext(state.sourceFile.fileName, module, require);\n context.context = state.context;\n\n const result = await sandboxExecute(data.text, context, {\n filename: state.sourceFile.fileName\n });\n\n if (result === null) return 'undefined';\n if (typeof result === 'number' || typeof result === 'boolean') return String(result);\n\n return JSON.stringify(result);\n } catch (err) {\n handleExecutionError(err, state, map.text, node);\n }\n\n return 'undefined';\n}\n\n/**\n * Creates a sandboxed execution context with Node.js globals and module system access.\n *\n * @param fileName - The absolute path to the source file (used for `__filename` and module resolution)\n * @param module - The CommonJS module object with `exports` property\n * @param require - The require function scoped to the source file's location\n *\n * @returns A context object containing all globals available during inline macro execution\n *\n * @remarks\n * The sandbox context provides a controlled environment for executing inline macros with:\n * - **Standard globals**: All properties from `globalThis` (including `RegExp` explicitly)\n * - **Node.js APIs**: `Buffer`, `process`, `console`\n * - **Module system**: `module`, `require`, `__dirname`, `__filename`\n * - **Timers**: `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`\n *\n * The context is designed to mimic a normal Node.js execution environment while maintaining\n * isolation from the build process. The `require` function is scoped to the source file's\n * directory, allowing relative imports to resolve correctly.\n *\n * @example Context structure\n * ```ts\n * const module = { exports: {} };\n * const require = createRequire('/project/src/config.ts');\n *\n * const context = createSandboxContext('/project/src/config.ts', module, require);\n *\n * // context contains:\n * // - process, Buffer, console\n * // - require (scoped to /project/src/)\n * // - __dirname === '/project/src'\n * // - __filename === '/project/src/config.ts'\n * // - setTimeout, setInterval, etc.\n * ```\n *\n * @example Usage in inline evaluation\n * ```ts\n * const context = createSandboxContext(state.sourceFile.fileName, module, require);\n *\n * await sandboxExecute(compiledCode, context, {\n * filename: state.sourceFile.fileName\n * });\n * ```\n *\n * @see {@link sandboxExecute} for execution\n * @see {@link evaluateCode} for usage context\n *\n * @since 2.0.0\n */\n\nexport function createSandboxContext(fileName: string, module: ModuleInterface, require: NodeJS.Require): Record<string, unknown> {\n return {\n ...globalThis,\n Error,\n RegExp,\n process,\n Buffer,\n module,\n require,\n console,\n setTimeout,\n setInterval,\n clearTimeout,\n clearInterval,\n ReferenceError,\n __dirname: dirname(fileName),\n __filename: fileName\n };\n}\n\n/**\n * Handles execution errors during inline macro evaluation and adds them to the transformation state.\n *\n * @param err - The error that occurred during execution\n * @param state - The macro transformation state to store the error in\n * @param mapText - The source map text for mapping error locations back to original source\n * @param node - The AST node representing the inline macro (used for calculating line offset)\n *\n * @remarks\n * This function processes errors that occur during {@link evaluateCode} by:\n * 1. Filtering out non-Error objects (ignores thrown primitives or undefined)\n * 2. Calculating the line offset where the inline macro appears in the source file\n * 3. Creating an {@link InlineError} with source map support and line offset adjustment\n * 4. Adding the formatted error to `state.errors` for build reporting\n *\n * The line offset is crucial for accurate error reporting because inline macros are extracted\n * from their original location, compiled separately, and executed in isolation. The offset\n * ensures that error locations point to the correct line in the original source file.\n *\n * @example Error handling flow\n * ```ts\n * try {\n * await sandboxExecute(code, context);\n * } catch (err) {\n * // err is a runtime error from the executed code\n * handleExecutionError(err, state, sourceMapText, node);\n * // state.errors now contains formatted error with correct source location\n * }\n * ```\n *\n * @example Error output\n * ```ts\n * // Original source at line 42: const x = $$inline(() => undefined.toString());\n * // After handling:\n * // state.errors === [{\n * // text: \"Cannot read property 'toString' of undefined\",\n * // detail: InlineError (with formatted stack pointing to line 42)\n * // }]\n * ```\n *\n * @see {@link evaluateCode} for execution context\n * @see {@link InlineError} for error formatting and source mapping\n *\n * @since 2.0.0\n */\n\nfunction handleExecutionError(err: unknown, state: StateInterface, mapText: string, node: Node): void {\n if (!err || (typeof err !== 'object') || !('stack' in err)) {\n err = new Error(String(err));\n }\n\n const start = node.getStart(state.sourceFile);\n const { line } = state.sourceFile.getLineAndCharacterOfPosition(start);\n\n inject(FrameworkService).setSource(mapText, state.sourceFile.fileName);\n const error = new InlineError(<Error> err, line);\n\n state.errors.push({\n text: error.message,\n detail: error\n });\n}\n\n/**\n * Searches for a function declaration or function variable by name in the source file.\n *\n * @param functionName - The name of the function to find\n * @param sourceFile - The TypeScript source file to search\n *\n * @returns The found function node (declaration, arrow function, or function expression), or `null` if not found\n *\n * @remarks\n * This function recursively traverses the AST to locate functions that match the given name.\n * It handles three types of function definitions:\n * - `function myFunction() {}` (function declarations)\n * - `const myFunction = () => {}` (arrow functions in variable declarations)\n * - `const myFunction = function() {}` (function expressions in variable declarations)\n *\n * The search stops at the first match found. This is used when an inline macro references\n * a function by name rather than providing an inline function expression.\n *\n * @example Finding a function declaration\n * ```ts\n * const sourceFile = ts.createSourceFile(\n * 'test.ts',\n * 'function myFunc() { return 42; }',\n * ts.ScriptTarget.Latest\n * );\n *\n * const func = findFunctionByName('myFunc', sourceFile);\n * // func is a FunctionDeclaration node\n * ```\n *\n * @example Finding an arrow function variable\n * ```ts\n * const sourceFile = ts.createSourceFile(\n * 'test.ts',\n * 'const myFunc = () => 42;',\n * ts.ScriptTarget.Latest\n * );\n *\n * const func = findFunctionByName('myFunc', sourceFile);\n * // func is an ArrowFunction node\n * ```\n *\n * @example Function not found\n * ```ts\n * const func = findFunctionByName('nonExistent', sourceFile);\n * // func === null\n * ```\n *\n * @see {@link extractFromIdentifier} for usage context\n * @see {@link findFunctionInVariableStatement} for variable extraction logic\n *\n * @since 2.0.0\n */\n\nfunction findFunctionByName(functionName: string, sourceFile: SourceFile): FunctionNodeType | null {\n let foundFunction: FunctionNodeType | null = null;\n\n const visit = (node: Node): void => {\n if (foundFunction) return;\n if (ts.isFunctionDeclaration(node) && node.name?.text === functionName) {\n foundFunction = node;\n\n return;\n }\n\n if (ts.isVariableStatement(node)) {\n foundFunction = findFunctionInVariableStatement(node, functionName);\n if (foundFunction) return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n\n return foundFunction;\n}\n\n/**\n * Extracts a function initializer from a variable statement if it matches the given name.\n *\n * @param node - The variable statement to search\n * @param functionName - The variable name to match\n *\n * @returns The arrow function or function expression initializer, or `null` if not found\n *\n * @remarks\n * This helper function is used by {@link findFunctionByName} to extract functions defined\n * as variables with arrow functions or function expressions as initializers.\n *\n * Only matches variables declared with simple identifiers (not destructured patterns)\n * that have arrow functions or function expressions as their initializer.\n *\n * @example Matching arrow function\n * ```ts\n * const statement = parseStatement('const myFunc = () => 42;');\n * const func = findFunctionInVariableStatement(statement, 'myFunc');\n * // func is the ArrowFunction node\n * ```\n *\n * @example Matching function expression\n * ```ts\n * const statement = parseStatement('const myFunc = function() { return 42; };');\n * const func = findFunctionInVariableStatement(statement, 'myFunc');\n * // func is the FunctionExpression node\n * ```\n *\n * @example No match\n * ```ts\n * const statement = parseStatement('const myFunc = 42;');\n * const func = findFunctionInVariableStatement(statement, 'myFunc');\n * // func === null (initializer is not a function)\n * ```\n *\n * @see {@link findFunctionByName} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction findFunctionInVariableStatement(node: VariableStatement, functionName: string): FunctionNodeType | null {\n for (const decl of node.declarationList.declarations) {\n if (\n ts.isIdentifier(decl.name) &&\n decl.name.text === functionName &&\n decl.initializer &&\n (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))\n ) {\n return decl.initializer;\n }\n }\n\n return null;\n}\n\n/**\n * Wraps JavaScript code in an Immediately Invoked Function Expression (IIFE).\n *\n * @param code - The code to wrap\n *\n * @returns The code wrapped in IIFE syntax: `module.exports = (code)();`\n *\n * @remarks\n * Converts function definitions or expressions into immediately executed forms for\n * inline evaluation. This is necessary when the inline macro contains a function\n * that should be executed and its return value used, rather than the function itself.\n *\n * The wrapping ensures that:\n * - Function declarations become function expressions (valid in expression context)\n * - Arrow functions and function expressions are immediately invoked\n * - The result of execution is captured rather than the function object\n *\n * @example Wrapping an arrow function\n * ```ts\n * const code = '() => 42';\n * const wrapped = wrapInIIFE(code);\n * // 'module.exports = (() => 42)();'\n * ```\n *\n * @example Wrapping a function expression\n * ```ts\n * const code = 'function() { return \"hello\"; }';\n * const wrapped = wrapInIIFE(code);\n * // 'module.exports = (function() { return \"hello\"; })();'\n * ```\n *\n * @example Wrapping a function declaration\n * ```ts\n * const code = 'function myFunc() { return 123; }';\n * const wrapped = wrapInIIFE(code);\n * // 'module.exports = (function myFunc() { return 123; })();'\n * ```\n *\n * @see {@link evaluateCode} for execution\n * @see {@link extractExecutableCode} for usage context\n *\n * @since 2.0.0\n */\n\nexport function wrapInIIFE(code: string): string {\n return `module.exports = (${ code })();`;\n}\n\n/**\n * Determines the variable keyword (`const`, `let`, or `var`) from TypeScript node flags.\n *\n * @param flags - TypeScript node flags from a variable declaration list\n *\n * @returns The appropriate variable keyword\n *\n * @remarks\n * Extracts the variable declaration keyword by checking TypeScript's node flags:\n * - Returns `'const'` if `NodeFlags.Const` is set\n * - Returns `'let'` if `NodeFlags.Let` is set\n * - Returns `'var'` as the default fallback\n *\n * This is used when transforming inline macro variable declarations to preserve\n * the original variable declaration style in the output.\n *\n * @example\n * ```ts\n * const flags = ts.NodeFlags.Const;\n * const keyword = getVariableKeyword(flags);\n * // 'const'\n * ```\n *\n * @example\n * ```ts\n * const flags = ts.NodeFlags.Let;\n * const keyword = getVariableKeyword(flags);\n * // 'let'\n * ```\n *\n * @example\n * ```ts\n * const flags = ts.NodeFlags.None;\n * const keyword = getVariableKeyword(flags);\n * // 'var'\n * ```\n *\n * @see {@link astInlineVariable} for usage context\n *\n * @since 2.0.0\n */\n\nfunction getVariableKeyword(flags: ts.NodeFlags): VariableKeywordType {\n if (flags & ts.NodeFlags.Const) return 'const';\n if (flags & ts.NodeFlags.Let) return 'let';\n\n return 'var';\n}\n\n/**\n * Extracts executable code from various AST node types for inline macro evaluation.\n *\n * @param node - The AST node to extract code from\n * @param state - The macro transformation state for error reporting and source file access\n *\n * @returns An object containing the extracted code and the source node, or `null` if extraction fails\n *\n * @remarks\n * This function handles multiple node types:\n * - **Identifiers**: Looks up function declarations by name and wraps them in IIFEs\n * - **Arrow functions**: Wraps them in IIFEs for immediate execution\n * - **Function expressions**: Wraps them in IIFEs for immediate execution\n * - **Other expressions**: Returns the code as-is for direct evaluation\n *\n * When a function is referenced by name (identifier), the function must be defined\n * in the same source file. If not found, a warning is added to the transformation state.\n *\n * The returned `ExecutableInterface` contains both the formatted executable code and\n * the original AST node for error location tracking during execution.\n *\n * @example Extracting from an identifier reference\n * ```ts\n * // Source contains: function myFunc() { return 42; }\n * const node = ts.factory.createIdentifier('myFunc');\n * const result = extractExecutableCode(node, state);\n * // result.data === '(function myFunc() { return 42; })()'\n * ```\n *\n * @example Extracting from an arrow function\n * ```ts\n * const node = parseExpression('() => 42');\n * const result = extractExecutableCode(node, state);\n * // result.data === '(() => 42)()'\n * ```\n *\n * @example Extracting from an expression\n * ```ts\n * const node = parseExpression('1 + 2');\n * const result = extractExecutableCode(node, state);\n * // result.data === '1 + 2'\n * ```\n *\n * @example Function not found (generates warning)\n * ```ts\n * const node = ts.factory.createIdentifier('nonExistent');\n * const result = extractExecutableCode(node, state);\n * // result.data === ''\n * // state.warnings contains: \"Function $$inline(nonExistent); not found in ...\"\n * ```\n *\n * @see {@link evaluateCode} for execution\n * @see {@link wrapInIIFE} for IIFE wrapping\n * @see {@link extractFromIdentifier} for identifier handling\n *\n * @since 2.0.0\n */\n\nexport function extractExecutableCode(node: Node, state: StateInterface): ExecutableInterface | null {\n if (!node) return null;\n\n // Handle identifier (function name reference)\n if (ts.isIdentifier(node)) {\n return extractFromIdentifier(node, state);\n }\n\n // Handle arrow functions and function expressions\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n return {\n node,\n data: wrapInIIFE(node.getText(state.sourceFile))\n };\n }\n\n // Handle other expressions\n return {\n node,\n data: node.getText(state.sourceFile)\n };\n}\n\n/**\n * Extracts executable code from a function identifier reference.\n *\n * @param node - The identifier node referencing a function name\n * @param state - The macro transformation state for function lookup and warnings\n *\n * @returns An object containing the wrapped function code and source node, or empty code with warning if not found\n *\n * @remarks\n * This function handles inline macros that reference functions by name rather than\n * defining them inline. It:\n * 1. Searches for the function declaration in the source file using {@link findFunctionByName}\n * 2. If found, wraps the function in an IIFE for immediate execution\n * 3. If not found, adds a warning to the transformation state and returns empty code\n *\n * The warning includes the relative path to help developers locate the issue quickly.\n *\n * @example Successful extraction\n * ```ts\n * // Source contains: function myFunc() { return 42; }\n * const identifier = ts.factory.createIdentifier('myFunc');\n * const result = extractFromIdentifier(identifier, state);\n * // result.data === '(function myFunc() { return 42; })()'\n * // result.node === FunctionDeclaration node\n * ```\n *\n * @example Function not found\n * ```ts\n * const identifier = ts.factory.createIdentifier('missing');\n * const result = extractFromIdentifier(identifier, state);\n * // result.data === ''\n * // result.node === identifier\n * // state.warnings contains a warning message\n * ```\n *\n * @see {@link findFunctionByName} for function lookup\n * @see {@link extractExecutableCode} for the calling context\n * @see {@link addFunctionNotFoundWarning} for warning generation\n *\n * @since 2.0.0\n */\n\nfunction extractFromIdentifier(node: ts.Identifier, state: StateInterface): ExecutableInterface {\n const functionDeclaration = findFunctionByName(node.text, state.sourceFile);\n\n if (!functionDeclaration) {\n addFunctionNotFoundWarning(node.text, state, node);\n\n return { data: '', node };\n }\n\n return {\n node: functionDeclaration,\n data: wrapInIIFE(functionDeclaration.getText(state.sourceFile))\n };\n}\n\n/**\n * Adds a warning to the transformation state when a referenced function is not found.\n *\n * @param functionName - The name of the function that was not found\n * @param state - The macro transformation state to add the warning to\n * @param node - The AST node representing the function reference (used for location tracking)\n *\n * @remarks\n * Generates a user-friendly warning message with the relative file path and precise location\n * information to help developers quickly identify and fix missing function references in inline macros.\n *\n * The warning includes:\n * - A descriptive message with the function name and file path\n * - Precise location information (line, column, file path)\n * - The source line text containing the reference\n *\n * The warning message format is:\n * ```\n * Function $$inline(functionName); not found in path/to/file.ts\n * ```\n *\n * @example\n * ```ts\n * // In file: /project/src/config.ts at line 42, column 15\n * // Code contains: const x = $$inline(missingFunc);\n *\n * const identifier = ts.factory.createIdentifier('missingFunc');\n * addFunctionNotFoundWarning('missingFunc', state, identifier);\n * // state.warnings === [{\n * // text: \"Function $$inline(missingFunc); not found in src/config.ts\",\n * // location: {\n * // line: 43, // 1-indexed\n * // column: 15,\n * // file: '/project/src/config.ts',\n * // lineText: 'asd'\n * // }\n * // }]\n * ```\n *\n * @see {@link extractFromIdentifier} for the calling context\n *\n * @since 2.0.0\n */\n\nfunction addFunctionNotFoundWarning(functionName: string, state: StateInterface, node: Node): void {\n const start = node.getStart(state.sourceFile);\n const { line, character } = state.sourceFile.getLineAndCharacterOfPosition(start);\n const relativePath = relative('.', state.sourceFile.fileName);\n\n state.warnings.push({\n text: `Function $$inline(${ functionName }); not found in ${ relativePath }`,\n location: {\n line: line + 1,\n column: character,\n file: state.sourceFile.fileName,\n lineText: 'asd'\n }\n });\n}\n\n/**\n * Transforms an inline macro variable declaration into executable code with the evaluated result.\n *\n * @param decl - The variable declaration node containing the inline macro\n * @param node - The complete variable statement (needed for flags and export status)\n * @param init - The call expression node representing the `$$inline()` macro call\n * @param hasExport - Whether the variable declaration has an `export` modifier\n * @param state - The macro transformation state for code extraction and evaluation\n *\n * @returns A promise resolving to the transformed variable declaration string, or `false` if transformation fails\n *\n * @remarks\n * This function processes inline macro variable declarations of the form:\n * ```ts\n * const myVar = $$inline(...);\n * export const myVar = $$inline(...);\n * ```\n *\n * The transformation process:\n * 1. Extracts the executable code from the macro argument using {@link extractExecutableCode}\n * 2. Evaluates the code in a sandboxed environment using {@link evaluateCode}\n * 3. Replaces the macro call with the evaluated result\n * 4. Preserves the variable keyword (`const`, `let`, or `var`) and export status\n *\n * @example Basic inline variable\n * ```ts\n * // Input AST for: a const result = $$inline(() => 1 + 1);\n * const transformed = await astInlineVariable(decl, node, init, false, state);\n * // transformed === 'const result = undefined;'\n * // (actual evaluation would return the computed value)\n * ```\n *\n * @example Exported inline variable\n * ```ts\n * // Input AST for: export const API_URL = $$inline(() => process.env.API_URL);\n * const transformed = await astInlineVariable(decl, node, init, true, state);\n * // transformed === 'export const API_URL = undefined;'\n * ```\n *\n * @example With function reference\n * ```ts\n * // Input AST for: let config = $$inline(getConfig);\n * const transformed = await astInlineVariable(decl, node, init, false, state);\n * // transformed === 'let config = undefined;'\n * ```\n *\n * @see {@link evaluateCode} for code evaluation\n * @see {@link extractExecutableCode} for code extraction\n * @see {@link getVariableKeyword} for variable keyword detection\n *\n * @since 2.0.0\n */\n\nexport async function astInlineVariable(\n decl: VariableDeclaration, node: VariableStatement, init: CallExpression, hasExport: boolean, state: StateInterface\n): Promise<string | false> {\n const arg = init.arguments[0];\n const code = extractExecutableCode(arg, state);\n if (!code) return false;\n\n const result = await evaluateCode(code.data, state, code.node);\n const varKeyword = getVariableKeyword(node.declarationList.flags);\n const exportPrefix = hasExport ? 'export ' : '';\n const varName = decl.name.getText(state.sourceFile);\n\n return `${ exportPrefix }${ varKeyword } ${ varName } = ${ result };`;\n}\n\n/**\n * Transforms an inline macro call expression into its evaluated result.\n *\n * @param args - The arguments passed to the `$$inline()` call\n * @param state - The macro transformation state for code extraction and evaluation\n *\n * @returns A promise resolving to the evaluated result string, or `false` if transformation fails\n *\n * @remarks\n * This function processes standalone inline macro calls that appear in expression contexts:\n * ```ts\n * console.log($$inline(() => \"hello\"));\n * const x = someFunction($$inline(getValue));\n * ```\n *\n * Unlike {@link astInlineVariable}, this handles inline macros that are not part of\n * variable declarations but are used directly as expressions.\n *\n * The transformation process:\n * 1. Extracts the executable code from the first argument using {@link extractExecutableCode}\n * 2. Evaluates the code using {@link evaluateCode}\n * 3. Returns the stringified result to replace the macro call\n *\n * @example Inline function call\n * ```ts\n * // Input AST for: console.log($$inline(() => 42));\n * const transformed = await astInlineCallExpression(args, state);\n * // transformed === 'undefined'\n * // Original: console.log($$inline(() => 42));\n * // Result: console.log(undefined);\n * ```\n *\n * @example Inline with function reference\n * ```ts\n * // Input AST for: const result = compute($$inline(getValue));\n * const transformed = await astInlineCallExpression(args, state);\n * // transformed === 'undefined'\n * ```\n *\n * @example Extraction failure\n * ```ts\n * const transformed = await astInlineCallExpression([], state);\n * // transformed === false\n * ```\n *\n * @see {@link evaluateCode} for code evaluation\n * @see {@link extractExecutableCode} for code extraction\n * @see {@link astInlineVariable} for variable declaration handling\n *\n * @since 2.0.0\n */\n\nexport async function astInlineCallExpression(args: NodeArray<Expression>, state: StateInterface): Promise<string | false> {\n const arg = args[0];\n const code = extractExecutableCode(arg, state);\n\n if (!code) return false;\n\n return evaluateCode(code.data, state, code.node);\n}\n", "/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\nimport { getErrorMetadata, formatStack } from '@providers/stack.provider';\n\n/**\n * Custom error class for inline errors with enhanced formatting and source code context.\n *\n * @remarks\n * The `InlineError` class extends {@link xBuildBaseError} to provide specialized handling for\n * JavaScript/TypeScript errors with optional line offset adjustment. It automatically:\n * - Extracts and formats error metadata using {@link getErrorMetadata}\n * - Applies syntax highlighting to code context\n * - Generates enhanced stack traces with file locations\n * - Supports line offset adjustment for accurate error positioning\n * - Stores structured metadata in {@link StackInterface} format\n *\n * This class is designed to transform standard Error objects into human-readable, visually enhanced\n * output suitable for terminal display, making it easier to identify and fix errors in source code.\n *\n * **Key features:**\n * - Automatic error metadata extraction and formatting\n * - Contextual code display with configurable line offset\n * - Syntax highlighting with color-coded error indicators\n * - Enhanced stack trace generation\n * - Structured error metadata for programmatic access\n *\n * @example\n * ```ts\n * import { InlineError } from './inline.error';\n *\n * try {\n * // Some code that might throw an error\n * throw new Error('Unexpected token');\n * } catch (err) {\n * throw new InlineError(err as Error);\n * }\n * ```\n *\n * @example\n * ```ts\n * // Error with line offset adjustment\n * try {\n * // Code execution\n * } catch (err) {\n * // Adjust error line number by 2 lines\n * const error = new InlineError(err as Error, 2);\n * console.error(error); // Displays formatted error with adjusted line context\n * }\n * ```\n *\n * @see {@link StackInterface} for metadata structure\n * @see {@link xBuildBaseError} for base error functionality\n * @see {@link getErrorMetadata} for metadata extraction logic\n * @see {@link formatStack} for stack formatting logic\n *\n * @since 2.0.0\n */\n\nexport class InlineError extends xBuildBaseError {\n /**\n * Creates a new inline error with formatted output and metadata.\n *\n * @param error - The base Error object containing error details\n * @param lineOffset - Optional line number offset for adjusting error position (default: 0)\n *\n * @remarks\n * The constructor processes the error to:\n * 1. Extract the error message for the base Error\n * 2. Generate error metadata using {@link getErrorMetadata} with optional line offset\n * 3. Format the stack trace using {@link formatStack}\n * 4. Store structured metadata in {@link errorMetadata}\n *\n * The `lineOffset` parameter allows you to adjust the reported line number in the error output.\n * This is useful when the actual error location differs from the reported location due to\n * transpilation, code generation, or other transformations:\n * - Positive values shift the line number down\n * - Negative values shift the line number up\n * - Zero (default) uses the original line number\n *\n * The error name is always set to `'InlineError'` and the stack is replaced\n * with a custom formatted version that includes:\n * - Error name and message with color coding\n * - Highlighted code snippet showing the error location\n * - Enhanced stack trace with file path and position\n *\n * @example\n * ```ts\n * const error = new Error('Syntax error in file');\n * const inlineError = new InlineError(error);\n * // inlineError.stack contains formatted output with code context\n * // inlineError.metadata contains structured location data\n * ```\n *\n * @example\n * ```ts\n * // Adjust error line by -3 to account for wrapper code\n * const error = new Error('Type mismatch');\n * const inlineError = new InlineError(error, -3);\n * // Error will be displayed 3 lines higher than originally reported\n * ```\n *\n * @see {@link getErrorMetadata} for metadata extraction and formatting\n * @see {@link formatStack} for stack trace formatting\n *\n * @since 2.0.0\n */\n\n constructor(error: Error, lineOffset: number = 0) {\n super(error.message, 'InlineError');\n\n this.errorMetadata = getErrorMetadata(error, {}, lineOffset);\n this.stack = formatStack(this.errorMetadata, this.name, this.message);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Context, ScriptOptions } from 'vm';\n\n/**\n * Imports\n */\n\nimport { Script, createContext } from 'vm';\n\n/**\n * Executes arbitrary code inside a Node.js VM sandbox.\n *\n * @param code - The JavaScript source code to execute\n * @param sandbox - Optional {@link Context} object to inject into the VM environment\n * @param options - Optional {@link ScriptOptions} used when compiling the script\n *\n * @returns A promise resolving to the result of the executed code\n *\n * @throws Error - If the provided code fails to compile or runtime execution throws\n *\n * @remarks\n * This function uses Node.js's {@link Script} and {@link createContext} APIs to safely run code in\n * an isolated environment. Execution is configured with `breakOnSigint` enabled and `displayErrors` disabled.\n *\n * @example\n * ```ts\n * const result = await sandboxExecute(\"2 + 2\");\n * console.log(result); // 4\n * ```\n *\n * @example\n * ```ts\n * const result = await sandboxExecute(\"user.name\", { user: { name: \"Alice\" } });\n * console.log(result); // \"Alice\"\n * ```\n *\n * @see Context\n * @see ScriptOptions\n *\n * @since 1.0.0\n */\n\nexport async function sandboxExecute(code: string, sandbox: Context = {}, options: ScriptOptions = {}): Promise<unknown> {\n const script = new Script(code, options);\n const context = createContext(sandbox);\n\n return await script.runInContext(context, { breakOnSigint: true, displayErrors: false });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { VariantService } from '@services/variant.service';\nimport type { PartialMessage, Location, OnLoadResult } from 'esbuild';\nimport type { BuildContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { MacrosMetadataInterface } from '@directives/interfaces/analyze-directive.interface';\n\n/**\n * Imports\n */\n\nimport { inject } from '@symlinks/symlinks.module';\nimport { FilesModel } from '@typescript/models/files.model';\n\n/**\n * Constants\n */\n\nconst MACRO_PREFIX = '$$';\nconst IFDEF_REGEX = /(?:(?:export\\s+)?(?:const|let|var)\\s+([\\w$]+)\\s*=\\s*)?\\$\\$(ifdef|ifndef|inline)\\s*\\(\\s*(?:['\"]([^'\"]+)['\"])?/g;\n\n/**\n * Calculates the line and column position of a macro name within source text.\n *\n * @param text - The complete source file content\n * @param name - The macro name to locate\n * @param file - The file path for location reporting\n * @param index - The starting index in the text where the match was found\n * @returns A partial {@link Location} object containing file, line, and column information\n *\n * @since 2.0.0\n */\n\nexport function getLineAndColumn(text: string, name: string, file: string, index: number): Partial<Location> {\n let line = 1;\n for (let i = 0; i < index; i++) if (text[i] === '\\n') line++;\n const startLinePosition = text.lastIndexOf('\\n', index - 1) + 1;\n\n return {\n file,\n line,\n column: text.indexOf(name, startLinePosition) - startLinePosition\n };\n}\n\n/**\n * Determines whether a given position in source code is within a comment.\n *\n * @param content - The complete source file content\n * @param index - The position to check\n * @returns `true` if the position is within a single-line (`//`), multi-line (`\\/* *\\/`), or JSDoc comment, otherwise `false`\n *\n * @remarks\n * Scans backward from the given index to the start of the line, skipping whitespace.\n * Checks if the first non-whitespace characters form a comment start sequence.\n * This is used to avoid processing macros that appear in comments.\n *\n * @example Single-line comment detection\n * ```ts\n * const code = '// const $$debug = $$ifdef(\"DEBUG\");\\nconst $$prod = $$ifdef(\"PROD\");';\n *\n * const debugIndex = code.indexOf('$$debug');\n * console.log(isCommentLine(code, debugIndex)); // true\n *\n * const prodIndex = code.indexOf('$$prod');\n * console.log(isCommentLine(code, prodIndex)); // false\n * ```\n *\n * @example Multi-line comment detection\n * ```ts\n * const code = `/*\n * * const $$feature = $$ifdef(\"FEATURE\");\n * *\\/\n * const $$active = $$ifdef(\"ACTIVE\");`;\n *\n * const featureIndex = code.indexOf('$$feature');\n * console.log(isCommentLine(code, featureIndex)); // true\n *\n * const activeIndex = code.indexOf('$$active');\n * console.log(isCommentLine(code, activeIndex)); // false\n * ```\n *\n * @example Indented code\n * ```ts\n * const code = ' // Commented macro\\n const $$real = $$ifdef(\"REAL\");';\n * const index = code.indexOf('// Commented');\n * console.log(isCommentLine(code, index)); // true\n * ```\n *\n * @since 2.0.0\n */\n\nexport function isCommentLine(content: string, index: number): boolean {\n let lineStart = content.lastIndexOf('\\n', index - 1) + 1;\n\n while (lineStart < index && (content[lineStart] === ' ' || content[lineStart] === '\\t')) {\n lineStart++;\n }\n\n if (lineStart >= index) return false;\n\n const char1 = content[lineStart];\n const char2 = content[lineStart + 1];\n\n return (char1 === '/' && (char2 === '/' || char2 === '*')) || char1 === '*';\n}\n\n/**\n * Analyzes all project files for macro usage and generates metadata about disabled macros.\n *\n * @param variant - The current build variant containing define configurations\n * @param context - The build context to store metadata and configuration\n * @returns A promise resolving to an {@link AnalyzerMessageInterface} containing any warnings\n *\n * @remarks\n * Scans all entry point dependencies for `$$ifdef` and `$$ifndef` macro declarations.\n * Determines which macros should be disabled based on the variant's definition configuration.\n * Generates warnings for macros that don't follow the `$$` naming convention.\n * Stores results in `context.stage.defineMetadata` for use during the build process.\n *\n * @example Basic macro analysis with definitions\n * ```ts\n * const variant = {\n * config: {\n * define: {\n * DEBUG: true,\n * PRODUCTION: false\n * }\n * }\n * };\n *\n * const context = {\n * build: {\n * initialOptions: {\n * entryPoints: ['src/index.ts']\n * }\n * },\n * stage: {}\n * };\n *\n * const result = await analyzeMacroMetadata(variant, context);\n *\n * // context.stage.defineMetadata now contains:\n * // {\n * // disabledMacroNames: Set(['$$noProd']), // from $$ifndef('PRODUCTION')\n * // filesWithMacros: Set(['src/index.ts', 'src/config.ts'])\n * // }\n *\n * console.log(result.warnings); // Array of warnings for improperly named macros\n * ```\n *\n * @example Handling ifdef vs. ifndef\n * ```ts\n * // the Source file contains:\n * // const $$hasDebug = $$ifdef('DEBUG'); // enabled when DEBUG=true\n * // const $$noDebug = $$ifndef('DEBUG'); // enabled when DEBUG=false\n *\n * const variant = {\n * config: {\n * define: { DEBUG: true }\n * }\n * };\n *\n * await analyzeMacroMetadata(variant, context);\n * // disabledMacroNames will contain: Set(['$$noDebug'])\n * ```\n *\n * @example Warning generation for invalid macro names\n * ```ts\n * // Source contains: const myMacro = $$ifdef('FEATURE');\n * // (missing $$ prefix)\n *\n * const result = await analyzeMacroMetadata(variant, context);\n *\n * console.log(result.warnings);\n * // [{\n * // text: \"Macro function 'myMacro' not start with '$$' prefix to avoid conflicts\",\n * // location: { file: 'src/feature.ts', line: 10, column: 6 }\n * // }]\n * ```\n *\n * @see {@link MacrosMetadataInterface}\n *\n * @since 2.0.0\n */\n\nexport async function analyzeMacroMetadata(variant: VariantService, context: BuildContextInterface): Promise<OnLoadResult> {\n const metadata: MacrosMetadataInterface = {\n disabledMacroNames: new Set(),\n filesWithMacros: new Set()\n };\n\n context.stage.defineMetadata = metadata;\n\n const warnings: Array<PartialMessage> = [];\n const filesModel = inject(FilesModel);\n const defines = variant.config.define ?? {};\n const files = Object.values(variant.dependencies ?? {});\n\n for (const file of files) {\n const content = filesModel.getOrTouchFile(file)?.contentSnapshot?.text;\n if (!content) continue;\n\n const resolvedFile = filesModel.resolve(file);\n\n IFDEF_REGEX.lastIndex = 0;\n for (const match of content.matchAll(IFDEF_REGEX)) {\n const matchIndex = match.index!;\n if (isCommentLine(content, matchIndex)) continue;\n\n const [ , fn, directive, define ] = match;\n metadata.filesWithMacros.add(resolvedFile); // always register the file\n if (!fn) continue;\n\n if (!fn.startsWith(MACRO_PREFIX)) {\n warnings.push({\n text: `Macro function '${ fn }' not start with '${ MACRO_PREFIX }' prefix to avoid conflicts`,\n location: getLineAndColumn(content, fn, file, matchIndex)\n });\n }\n\n if(directive === 'inline') continue;\n const isDefined = !!defines[define];\n if ((directive === 'ifndef') === isDefined) {\n metadata.disabledMacroNames.add(fn);\n }\n }\n }\n\n return { warnings };\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { OnLoadResult, Message, PartialMessage } from 'esbuild';\nimport type { BuildContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { OnEndType, OnStartType } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { ResultContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\nimport type { BuildResultInterface } from '@providers/interfaces/esbuild-messages-provider.interface';\nimport type { BuildConfigInterface, PartialBuildConfigType } from '@interfaces/configuration.interface';\nimport type { DiagnosticInterface } from '@typescript/services/interfaces/typescript-service.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildError } from '@errors/xbuild.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { VariantService } from '@services/variant.service';\nimport { LifecycleProvider } from '@providers/lifecycle.provider';\nimport { transformerDirective } from '@directives/macros.directive';\nimport { analyzeMacroMetadata } from '@directives/analyze.directive';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { enhancedBuildResult, isBuildResultError } from '@providers/esbuild-messages.provider';\n\n/**\n * Orchestrates the build process across multiple variants with lifecycle management and configuration.\n *\n * @remarks\n * The `BuildService` is the primary service for managing multi-variant builds in xBuild.\n * It handles configuration changes, variant lifecycle, type checking, and build execution\n * with support for hot reloading and file watching.\n *\n * **Key responsibilities**:\n * - Manages multiple build variants (e.g., production, development, testing)\n * - Provides reactive configuration updates through subscription system\n * - Coordinates lifecycle hooks (onStart, onEnd) across all variants\n * - Handles macro transformation and directive processing\n * - Supports incremental builds and file touch notifications\n * - Aggregates build results and type checking diagnostics\n *\n * **Architecture**:\n * Each variant is managed by a {@link VariantService} instance with its own:\n * - esbuild configuration and context\n * - TypeScript language service\n * - Lifecycle provider for hooks and plugins\n * - Build state and watch mode support\n *\n * The service uses a subscription pattern to react to configuration changes,\n * automatically creating new variants or disposing removed ones.\n *\n * @example Basic usage\n * ```ts\n * const buildService = new BuildService({\n * variants: {\n * production: {\n * esbuild: { minify: true, sourcemap: false }\n * },\n * development: {\n * esbuild: { minify: false, sourcemap: true }\n * }\n * }\n * });\n *\n * // Build all variants\n * const results = await buildService.build();\n * console.log(results.production.errors);\n * ```\n *\n * @example With lifecycle hooks\n * ```ts\n * const buildService = new BuildService(config);\n *\n * buildService.onStart = (context) => {\n * console.log(`Building variant: ${context.variantName}`);\n * };\n *\n * buildService.onEnd = (context) => {\n * console.log(`Completed ${context.variantName}: ${context.result.errors.length} errors`);\n * };\n *\n * await buildService.build();\n * ```\n *\n * @example Configuration reload\n * ```ts\n * const buildService = new BuildService(initialConfig);\n *\n * // Reload with new configuration\n * buildService.reload({\n * variants: {\n * production: { esbuild: { target: 'es2020' } },\n * staging: { esbuild: { minify: true } }\n * }\n * });\n * // Old variants disposed, new ones created\n * ```\n *\n * @example Type checking\n * ```ts\n * const buildService = new BuildService(config);\n * const diagnostics = await buildService.typeChack();\n *\n * for (const [variant, errors] of Object.entries(diagnostics)) {\n * console.log(`${variant}: ${errors.length} type errors`);\n * }\n * ```\n *\n * @see {@link VariantService} for individual variant management\n * @see {@link ConfigurationService} for configuration handling\n * @see {@link LifecycleProvider} for hook management\n *\n * @since 2.0.0\n */\n\nexport class BuildService {\n /**\n * Callback invoked when a build completes for any variant.\n *\n * @remarks\n * Set via the `onEnd` setter. Called after each variant's build finishes,\n * providing access to build results, errors, warnings, and metadata.\n *\n * @since 2.0.0\n */\n\n private onEndCallback?: OnEndType;\n\n /**\n * Callback invoked when a build starts for any variant.\n *\n * @remarks\n * Set via the `onStart` setter. Called before each variant's build begins,\n * after macro metadata analysis completes.\n *\n * @since 2.0.0\n */\n\n private onStartCallback?: OnStartType;\n\n /**\n * Map of variant names to their service instances.\n *\n * @remarks\n * Contains all active build variants. Variants are created during construction\n * and updated when configuration changes via {@link reload} or {@link setConfiguration}.\n *\n * @since 2.0.0\n */\n\n private variants: { [variant: string]: VariantService } = {};\n\n /**\n * Configuration service managing build settings and variant definitions.\n *\n * @remarks\n * Injected singleton that provides reactive configuration updates through\n * its subscription system. Changes trigger automatic variant recreation.\n *\n * @since 2.0.0\n */\n\n private readonly configuration: ConfigurationService<BuildConfigInterface> = inject(ConfigurationService);\n\n /**\n * Creates a new BuildService instance with optional configuration and command-line arguments.\n *\n * @param argv - Command-line arguments passed to variant services (default: empty object)\n *\n * @remarks\n * The constructor:\n * 1. Accepts optional initial configuration\n * 2. Stores command-line arguments for variant initialization\n * 3. Subscribes to configuration changes via {@link parseVariants}\n * 4. Automatically creates variants defined in the configuration\n *\n * Configuration can be provided later via {@link reload} or {@link setConfiguration}\n * if not supplied during construction.\n *\n * @since 2.0.0\n */\n\n constructor(private argv: Record<string, unknown> = {}) {\n this.configuration.subscribe(this.parseVariants.bind(this));\n }\n\n /**\n * Gets the current complete build configuration.\n *\n * @returns The active build configuration including all variants and common settings\n *\n * @remarks\n * Retrieves the immutable snapshot of the current configuration from the\n * configuration service. Changes to the returned object do not affect\n * the actual configuration - use {@link setConfiguration} or {@link reload} instead.\n *\n * @since 2.0.0\n */\n\n get config(): BuildConfigInterface {\n return this.configuration.getValue();\n }\n\n /**\n * Sets the callback to invoke when any variant build completes.\n *\n * @param callback - Function receiving the result context with build output and metadata\n *\n * @remarks\n * The callback receives a {@link ResultContextInterface} containing:\n * - Variant name\n * - Build result (errors, warnings, outputs)\n * - Metadata files and outputs\n * - Timestamp and duration\n *\n * Called after the build finishes but before promises resolve.\n *\n * @example\n * ```ts\n * buildService.onEnd = (context) => {\n * const { variantName, result } = context;\n * console.log(`\u2713 ${variantName}: ${result.errors.length} errors`);\n * };\n * ```\n *\n * @since 2.0.0\n */\n\n set onEnd(callback: OnEndType) {\n this.onEndCallback = callback;\n }\n\n /**\n * Sets the callback to invoke when any variant build starts.\n *\n * @param callback - Function receiving the build context with file and variant information\n *\n * @remarks\n * The callback receives a {@link BuildContextInterface} containing:\n * - Variant name\n * - File path being processed\n * - Build stage and metadata\n * - Loader type\n *\n * Called after macro analysis but before transformation begins.\n *\n * @example\n * ```ts\n * buildService.onStart = (context) => {\n * console.log(`Building ${context.args.path} for ${context.variantName}`);\n * };\n * ```\n *\n * @since 2.0.0\n */\n\n set onStart(callback: OnStartType) {\n this.onStartCallback = callback;\n }\n\n /**\n * Reloads the build configuration and updates variants accordingly.\n *\n * @param config - Optional new configuration to replace the current one\n *\n * @remarks\n * The reload process:\n * 1. Replaces configuration if provided\n * 2. Compares new variant names with existing ones\n * 3. Disposes variants no longer in configuration\n * 4. Creates new variants from the updated configuration\n * 5. Existing variants with matching names continue unchanged\n *\n * This is useful for hot-reloading configuration files without restarting the build process.\n *\n * @example\n * ```ts\n * // Add a new staging variant\n * buildService.reload({\n * variants: {\n * ...buildService.config.variants,\n * staging: { esbuild: { minify: true } }\n * }\n * });\n * ```\n *\n * @since 2.0.0\n */\n\n reload(config?: PartialBuildConfigType): void {\n if (config) this.configuration.reload(config);\n this.disposeVariants(this.compareKeys(this.config.variants, this.variants));\n this.parseVariants();\n }\n\n /**\n * Notifies all variants that specific files have been modified.\n *\n * @param files - Array of file paths that have changed\n *\n * @remarks\n * Propagates file change notifications to all variant services, triggering\n * incremental rebuilds in watch mode. Each variant's watch service handles\n * the actual rebuild logic.\n *\n * Typically used by file watchers or development servers to trigger hot reloads.\n *\n * @example\n * ```ts\n * // File watcher integration\n * watcher.on('change', (changedFiles) => {\n * buildService.touchFiles(changedFiles);\n * });\n * ```\n *\n * @see {@link VariantService.touchFiles}\n *\n * @since 2.0.0\n */\n\n touchFiles(files: Array<string>): void {\n for (const instance of Object.values(this.variants)) {\n instance.touchFiles(files);\n }\n }\n\n /**\n * Partially updates the build configuration without replacing it entirely.\n *\n * @param config - Partial configuration to merge with the current configuration\n *\n * @remarks\n * Performs a shallow merge of the provided configuration with the current one.\n * Use {@link reload} for deep configuration replacement or variant restructuring.\n *\n * Common use cases:\n * - Toggling minification\n * - Updating define constants\n * - Modifying common build options\n *\n * @example\n * ```ts\n * // Enable minification for all variants\n * buildService.setConfiguration({\n * common: { esbuild: { minify: true } }\n * });\n * ```\n *\n * @see {@link reload} for full configuration replacement\n *\n * @since 2.0.0\n */\n\n setConfiguration(config: Partial<BuildConfigInterface>): void {\n this.configuration.patch(config);\n }\n\n /**\n * Performs TypeScript type checking across all variants.\n *\n * @returns Promise resolving to a map of variant names to their diagnostic results\n *\n * @remarks\n * Runs the TypeScript compiler's diagnostic checker for each variant in parallel.\n * Returns all type errors, warnings, and suggestions without failing the build.\n *\n * **Note**: Method name has a typo - should be `typeCheck` but kept for backward compatibility.\n *\n * Useful for:\n * - Pre-build validation\n * - CI/CD type checking pipelines\n * - IDE integration and diagnostics display\n *\n * @example\n * ```ts\n * const diagnostics = await buildService.typeChack();\n *\n * for (const [variant, errors] of Object.entries(diagnostics)) {\n * if (errors.length > 0) {\n * console.error(`${variant} has ${errors.length} type errors`);\n * errors.forEach(err => console.error(err.messageText));\n * }\n * }\n * ```\n *\n * @see {@link DiagnosticInterface}\n * @see {@link VariantService.check}\n *\n * @since 2.0.0\n */\n\n async typeChack(): Promise<Record<string, DiagnosticInterface[]>> {\n const result: Record<string, Array<DiagnosticInterface>> = {};\n\n for(const variant of Object.values(this.variants)) {\n result[variant.name] = await variant.check();\n }\n\n return result;\n }\n\n /**\n * Executes the build process for all or specific variants.\n *\n * @param names - Optional array of variant names to build (builds all if omitted)\n *\n * @returns Promise resolving to a map of variant names to their enhanced build results\n *\n * @throws AggregateError - When any variant build fails, containing all error details\n *\n * @remarks\n * The build process:\n * 1. Filters variants if specific names are provided\n * 2. Builds all variants in parallel\n * 3. Collects results and errors from each variant\n * 4. Enhances build results with additional metadata\n * 5. Aggregates errors if any builds failed\n * 6. Throws AggregateError if errors occurred\n *\n * **Error handling**:\n * - Build failures don't stop other variants from building\n * - All errors are collected and thrown together after all builds are complete\n * - Supports both esbuild errors and generic JavaScript errors\n *\n * **Result enhancement**:\n * Build results are processed by {@link enhancedBuildResult} to provide\n * structured error and warning information.\n *\n * @example Build all variants\n * ```ts\n * try {\n * const results = await buildService.build();\n * console.log(`Built ${Object.keys(results).length} variants`);\n * } catch (error) {\n * if (error instanceof AggregateError) {\n * error.errors.forEach(err => console.error(err.message));\n * }\n * }\n * ```\n *\n * @example Build specific variants\n * ```ts\n * const results = await buildService.build(['production', 'staging']);\n * // Only production and staging variants are built\n * ```\n *\n * @example Handle individual variant errors\n * ```ts\n * try {\n * await buildService.build();\n * } catch (error) {\n * if (error instanceof AggregateError) {\n * console.error(`${error.errors.length} variants failed`);\n * }\n * }\n * ```\n *\n * @see {@link enhancedBuildResult}\n * @see {@link BuildResultInterface}\n * @see {@link VariantService.build}\n *\n * @since 2.0.0\n */\n\n async build(names?: Array<string>): Promise<Record<string, BuildResultInterface>> {\n const errorList: Array<Error> = [];\n const results: Record<string, BuildResultInterface> = {};\n const buildPromises = Object.entries(this.variants).map(async ([ variantName, variantInstance ]) => {\n if(names && !names.includes(variantName)) return;\n\n try {\n const result = await variantInstance.build();\n if(result) results[variantName] = enhancedBuildResult(result);\n } catch(error) {\n if (isBuildResultError(error) || error instanceof AggregateError) {\n const result = enhancedBuildResult({\n errors: error.errors as Array<Message>\n });\n\n errorList.push(...result.errors);\n } else if(error instanceof Error) {\n errorList.push(error);\n } else {\n errorList.push(new Error(String(error)));\n }\n }\n });\n\n await Promise.allSettled(buildPromises);\n if(errorList.length) throw new AggregateError(errorList, 'Build failed');\n\n return results;\n }\n\n /**\n * Triggers the onEnd callback when a variant build completes.\n *\n * @param context - The result context containing build output and metadata\n *\n * @remarks\n * Internal handler that safely invokes the user-provided onEnd callback if set.\n * Called by variant lifecycle providers after each build finishes.\n *\n * @since 2.0.0\n */\n\n private onEndTrigger(context: ResultContextInterface): void {\n if(this.onEndCallback) this.onEndCallback(context);\n }\n\n /**\n * Triggers the onStart callback and performs macro analysis before a variant build starts.\n *\n * @param context - The build context containing file and variant information\n *\n * @returns Promise resolving to the load result after macro metadata analysis\n *\n * @throws Error - Propagates errors from macro analysis that aren't AggregateErrors\n *\n * @remarks\n * Internal handler that:\n * 1. Analyzes macro metadata for the file being built\n * 2. Invokes the user-provided onStart callback if set\n * 3. Returns the analysis result to the build pipeline\n * 4. Converts AggregateErrors to esbuild-compatible error format\n *\n * The macro analysis prepares directive information ($$ifdef, $$inline, etc.)\n * that will be used during the transformation phase.\n *\n * @see {@link analyzeMacroMetadata}\n *\n * @since 2.0.0\n */\n\n private async onStartTrigger(context: BuildContextInterface): Promise<OnLoadResult> {\n try {\n const result = await analyzeMacroMetadata(this.variants[context.variantName], context);\n if(this.onStartCallback) this.onStartCallback(context);\n\n return result;\n } catch(error) {\n const errors: Array<PartialMessage> = [];\n if(error instanceof AggregateError) {\n for (const err of error.errors) {\n errors.push({\n detail: err,\n text: err.message\n });\n }\n\n return { errors };\n }\n\n throw error;\n }\n }\n\n /**\n * Disposes and removes variants by name.\n *\n * @param dispose - Array of variant names to dispose\n *\n * @remarks\n * Cleanly shuts down variant services and removes them from the internal map.\n * Called during configuration reload to remove variants no longer in config.\n *\n * Each variant's dispose method:\n * - Stops watch mode if active\n * - Cleans up esbuild contexts\n * - Releases TypeScript language service resources\n *\n * @since 2.0.0\n */\n\n private disposeVariants(dispose: Array<string>): void {\n if (dispose.length) {\n for (const variant of dispose) {\n this.variants[variant].dispose();\n delete this.variants[variant];\n }\n }\n }\n\n /**\n * Compares two objects and returns keys present in the second but not the first.\n *\n * @param obj1 - Reference object (usually new configuration)\n * @param obj2 - Comparison object (usually existing variants)\n *\n * @returns Array of keys present in obj2 but missing in obj1\n *\n * @remarks\n * Used to identify variants that should be disposed during configuration reload.\n * If a variant exists in the service but not in the new configuration, it's removed.\n *\n * @since 2.0.0\n */\n\n private compareKeys(obj1: object, obj2: object): Array<string> {\n const keys2 = Object.keys(obj2);\n const onlyInObj2 = keys2.filter(key => !(key in obj1));\n\n return [ ...onlyInObj2 ];\n }\n\n /**\n * Creates variant service instances from the current configuration.\n *\n * @throws xBuildError - When no variants are defined in the configuration\n *\n * @remarks\n * Invoked by the configuration subscription whenever configuration changes.\n * For each variant in the configuration:\n * 1. Skips if the variant already exists (prevents recreation)\n * 2. Creates a new LifecycleProvider with hooks\n * 3. Attaches onStart and onEnd listeners\n * 4. Creates VariantService with configuration\n * 5. Registers macro transformer directive\n *\n * The lifecycle hooks enable:\n * - Build start/end notifications\n * - Macro analysis and transformation\n * - Custom plugin integration\n *\n * @see {@link VariantService}\n * @see {@link LifecycleProvider}\n * @see {@link transformerDirective}\n *\n * @since 2.0.0\n */\n\n private parseVariants(): void {\n if(!this.config.variants)\n throw new xBuildError('Variants are not defined in the configuration');\n\n for (const name of Object.keys(this.config.variants)) {\n if (this.variants[name]) continue;\n const lifecycle = new LifecycleProvider(name, this.argv);\n lifecycle.onEnd(this.onEndTrigger.bind(this), 'build-service');\n lifecycle.onStart(this.onStartTrigger.bind(this), 'build-service');\n this.variants[name] = new VariantService(name, lifecycle, this.config.variants[name], this.argv);\n lifecycle.onLoad(transformerDirective.bind({}, this.variants[name]), 'build-service');\n }\n }\n}\n", "\n/**\n * Main entry point and public API for the xBuild build system.\n *\n * @remarks\n * This module serves as the primary interface for xBuild, providing:\n * - Type definitions for configuration and diagnostics\n * - Core services for building, watching, and serving\n * - Utility functions for configuration management\n * - Global macro function declarations for build-time transforms\n *\n * **Usage patterns**:\n * - **CLI usage**: Imported by {@link bash.ts} for command-line operations\n * - **Programmatic usage**: Imported by custom build scripts and tools\n * - **Configuration files**: Type exports used in `xbuild.config.ts`\n *\n * **Key exports**:\n * - `BuildService`: Main build orchestration service\n * - `WatchService`: File system monitoring for rebuilds\n * - `ServerModule`: Development HTTP server\n * - Configuration helper functions\n * - Global macro type declarations\n *\n * @example Programmatic build\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * production: {\n * esbuild: { minify: true, outdir: 'dist' }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n * await service.build('production');\n * ```\n *\n * @example Configuration file typing\n * ```ts\n * import type { xBuildConfig } from '@remotex-labs/xbuild';\n *\n * export default {\n * variants: {\n * dev: { esbuild: { minify: false } }\n * }\n * } satisfies xBuildConfig;\n * ```\n *\n * @packageDocumentation\n * @since 1.0.0\n */\n\n/**\n * Import will remove at compile time\n */\n\nimport type { PartialBuildConfigType } from '@interfaces/configuration.interface';\nimport type { xBuildConfigInterface } from '@providers/interfaces/config-file-provider.interface';\n\n/**\n * Imports\n */\n\nimport { inject } from '@symlinks/symlinks.module';\nimport { ConfigurationService } from '@services/configuration.service';\n\n/**\n * Export types\n */\n\nexport type * from '@providers/interfaces/lifecycle-provider.interface';\nexport type { ArgumentsInterface } from '@argv/interfaces/argv-module.interface';\nexport type { ServerConfigurationInterface } from '@server/interfaces/server.interface';\nexport type { MacroContextInterface } from '@directives/interfaces/macros-directive.interface';\nexport type { DiagnosticInterface } from '@typescript/services/interfaces/typescript-service.interface';\n\n/**\n * Export\n */\n\nexport * from '@components/glob.component';\nexport * from '@providers/esbuild-messages.provider';\nexport { ServerModule } from '@server/server.module';\nexport { WatchService } from '@services/watch.service';\n\n/**\n * Type alias for xBuild configuration objects.\n *\n * @remarks\n * Provides a shorter, more conventional name for the configuration interface.\n * Used primarily in configuration files to declare configuration object types\n * with TypeScript's `satisfies` operator or type annotations.\n *\n * **Properties include**:\n * - `variants`: Build variant configurations (dev, prod, etc.)\n * - `common`: Shared settings across all variants\n * - `serve`: Development server configuration\n * - `userArgv`: Custom CLI argument definitions\n * - `verbose`: Detailed logging flag\n *\n * @example Type annotation\n * ```ts\n * const config: xBuildConfig = {\n * variants: {\n * production: {\n * esbuild: { minify: true, outdir: 'dist' }\n * }\n * }\n * };\n * ```\n *\n * @example With satisfies operator (recommended)\n * ```ts\n * export default {\n * common: { esbuild: { platform: 'node' } },\n * variants: {\n * dev: { esbuild: { minify: false } },\n * prod: { esbuild: { minify: true } }\n * }\n * } satisfies xBuildConfig;\n * ```\n *\n * @see {@link xBuildConfigInterface} for detailed property documentation\n *\n * @since 2.0.0\n */\n\nexport type xBuildConfig = xBuildConfigInterface;\n\n/**\n * Global type declarations for xBuild's build-time macro system.\n *\n * @remarks\n * Declares globally available macro functions that are transformed at build time.\n * These functions provide conditional compilation and inline evaluation capabilities\n * without requiring explicit imports.\n *\n * **Macro functions**:\n * - `$$ifdef`: Include code when definition is truthy\n * - `$$ifndef`: Include code when definition is falsy/undefined\n * - `$$inline`: Evaluate expressions at build time\n *\n * All macro functions are:\n * - Prefixed with `$$` to avoid naming conflicts\n * - Transformed during the build process (not runtime functions)\n * - Available globally without imports\n * - Type-safe with TypeScript\n *\n * **DefineType**: String literal union representing common definition names,\n * extensible with custom strings via `| string`.\n *\n * @example Conditional compilation\n * ```ts\n * const logger = $$ifdef('DEBUG', () => console.log);\n * // In production (DEBUG=false), becomes: const logger = undefined;\n * // In development (DEBUG=true), becomes: function logger() { return console.log; }\n * ```\n *\n * @example Negated conditional\n * ```ts\n * const optimized = $$ifndef('DEBUG', () => fastImplementation());\n * // Included only when DEBUG is not defined or false\n * ```\n *\n * @example Inline evaluation\n * ```ts\n * const version = $$inline(() => process.env.VERSION);\n * // Evaluates at build time, replaces with actual value\n * ```\n *\n * @see {@link transformerDirective} for macro transformation implementation\n *\n * @since 2.0.0\n */\n\ndeclare global {\n /**\n * Type representing valid definition names for conditional macros.\n *\n * @remarks\n * Provides autocomplete for common definition names while allowing\n * custom strings. Definitions are typically set via:\n * - `config.variants[name].define` in configuration\n * - `--define` CLI flag\n * - Environment variables\n *\n * **Common definitions**:\n * - `DEBUG`: Development/debugging features\n * - `PRODUCTION`: Production-only optimizations\n * - `TEST`: Test environment features\n * - `DEV`: Development mode\n * - `CI`: Continuous integration environment\n * - `LOCAL`: Local development\n *\n * @example\n * ```ts\n * // With type checking\n * const fn = $$ifdef('DEBUG', log); // 'DEBUG' autocompletes\n * const custom = $$ifdef('MY_FEATURE', impl); // Custom string also allowed\n * ```\n *\n * @since 2.0.0\n */\n\n type DefineType = 'DEBUG' | 'PRODUCTION' | 'TEST' | 'DEV' | 'CI' | 'LOCAL' | string;\n\n /**\n * Conditional inclusion macro that includes code when a definition is truthy.\n *\n * @template T - The type of the callback return value\n * @param define - The definition name to check\n * @param callback - The code to include when definition is truthy\n *\n * @returns The callback value when condition is true, `undefined` when false\n *\n * @remarks\n * Transformed at build time based on the variant's `define` configuration.\n * When the specified definition is truthy, the callback is included in the\n * output; otherwise, the entire expression is replaced with `undefined`.\n *\n * **Transformation behavior**:\n * - Definition is truthy \u2192 Callback is included as-is\n * - Definition is falsy/undefined \u2192 Replaced with `undefined`\n * - Works with functions, objects, primitives, or any expression\n *\n * **Variable declarations**:\n * ```ts\n * const $$debug = $$ifdef('DEBUG', () => console.log);\n * // DEBUG=true \u2192 function $$debug() { return console.log; }\n * // DEBUG=false \u2192 undefined (entire declaration removed)\n * ```\n *\n * **Expression statements**:\n * ```ts\n * $$ifdef('DEBUG', () => initDebugTools());\n * // DEBUG=true \u2192 (() => initDebugTools())()\n * // DEBUG=false \u2192 (removed)\n * ```\n *\n * @example Function inclusion\n * ```ts\n * const logger = $$ifdef('DEBUG', () => console.log);\n *\n * // With DEBUG=true\n * logger('test'); // Works: logs 'test'\n *\n * // With DEBUG=false\n * logger('test'); // TypeError: logger is undefined\n * ```\n *\n * @example Object inclusion\n * ```ts\n * const config = {\n * apiUrl: 'https://api.example.com',\n * debug: $$ifdef('DEBUG', { verbose: true, logLevel: 'trace' })\n * };\n *\n * // With DEBUG=true\n * // config.debug = { verbose: true, logLevel: 'trace' }\n *\n * // With DEBUG=false\n * // config.debug = undefined\n * ```\n *\n * @example Guards in code\n * ```ts\n * if ($$ifdef('DEBUG', true)) {\n * console.log('Debug mode active');\n * }\n * // DEBUG=false \u2192 if (undefined) { ... } (block never executes)\n * ```\n *\n * @see {@link DefineType} for valid definition names\n * @since 2.0.0\n */\n\n function $$ifdef<T>(define: DefineType, callback: T):\n T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;\n\n /**\n * Conditional inclusion macro that includes code when a definition is falsy or undefined.\n *\n * @template T - The type of the callback return value\n * @param define - The definition name to check\n * @param callback - The code to include when definition is falsy/undefined\n *\n * @returns The callback value when condition is false, `undefined` when true\n *\n * @remarks\n * The inverse of `$$ifdef`. Transformed at build time based on the\n * variant's `define` configuration. When the specified definition is falsy\n * or undefined, the callback is included; otherwise, replaced with `undefined`.\n *\n * **Transformation behavior**:\n * - Definition is falsy/undefined \u2192 Callback is included as-is\n * - Definition is truthy \u2192 Replaced with `undefined`\n * - Works with functions, objects, primitives, or any expression\n *\n * **Use cases**:\n * - Development-only features (disabled in production)\n * - Fallback implementations (when optimized version unavailable)\n * - Debugging tools (removed in release builds)\n *\n * @example Development-only features\n * ```ts\n * const devTools = $$ifndef('PRODUCTION', () => initDevTools());\n *\n * // With PRODUCTION=false (dev mode)\n * devTools(); // Works: initializes dev tools\n *\n * // With PRODUCTION=true (production)\n * devTools(); // TypeError: devTools is undefined\n * ```\n *\n * @example Fallback implementation\n * ```ts\n * const optimizer = $$ifndef('NATIVE_OPTIMIZER', () => jsOptimizer());\n *\n * // With NATIVE_OPTIMIZER undefined\n * // Uses JavaScript fallback implementation\n *\n * // With NATIVE_OPTIMIZER=true\n * // optimizer is undefined, use native implementation elsewhere\n * ```\n *\n * @example Conditional exports\n * ```ts\n * export const debug = $$ifndef('PRODUCTION', {\n * log: console.log,\n * trace: console.trace\n * });\n *\n * // In development: exports debug object\n * // In production: export const debug = undefined;\n * ```\n *\n * @see {@link DefineType} for valid definition names\n * @since 2.0.0\n */\n\n function $$ifndef<T>(define: DefineType, callback: T):\n T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;\n\n /**\n * Inline evaluation macro that executes code at build time and replaces it with the result.\n *\n * @template T - The return type of the callback function\n * @param callback - Expression to evaluate at build time\n *\n * @returns The evaluated result with its original type, or `undefined` on evaluation failure\n *\n * @remarks\n * Executes the provided callback during the build process (not at runtime) and\n * replaces the macro call with the evaluated result. This enables:\n * - Injecting build-time environment variables\n * - Computing values during compilation\n * - Generating code from external sources\n * - Eliminating runtime overhead for static values\n *\n * **Execution context**:\n * - Runs in the Node.js build environment\n * - Has access to process.env and Node.js APIs\n * - Executes once per build, not per file or variant\n * - Errors during evaluation cause build failure\n *\n * **Return value handling**:\n * - The result preserves the original return type from the callback\n * - Primitives (string, number, boolean) are properly typed\n * - Objects and arrays maintain their structure and types\n * - Functions are toString()'d (use carefully)\n * - Returns `undefined` if evaluation fails or callback returns undefined\n *\n * **Common use cases**:\n * - Environment variable injection\n * - Build timestamp generation\n * - Package version embedding\n * - Configuration value computation\n *\n * @example Environment variable injection\n * ```ts\n * const apiUrl = $$inline(() => process.env.API_URL);\n * // Type: string | undefined\n * // Becomes: const apiUrl = \"https://api.example.com\";\n * ```\n *\n * @example Build metadata\n * ```ts\n * const buildInfo = {\n * version: $$inline(() => require('./package.json').version),\n * timestamp: $$inline(() => new Date().toISOString()),\n * commit: $$inline(() => process.env.GIT_COMMIT)\n * };\n * // Each value retains its type (string | undefined)\n * ```\n *\n * @example Computed configuration\n * ```ts\n * const maxWorkers = $$inline(() => {\n * const cpus = require('os').cpus().length;\n * return Math.max(1, cpus - 1);\n * });\n * // Type: number | undefined\n * // Computes optimal worker count during build\n * ```\n *\n * @example Feature flags from environment\n * ```ts\n * const features = {\n * betaFeatures: $$inline(() => process.env.ENABLE_BETA === 'true'),\n * debugMode: $$inline(() => process.env.NODE_ENV !== 'production')\n * };\n * // Boolean values computed at build time, typed as boolean | undefined\n * ```\n *\n * @see {@link astInlineCallExpression} for evaluation implementation\n *\n * @since 2.0.0\n */\n\n function $$inline<T>(callback: () => T): T | undefined;\n\n /**\n * Pre-configuration CLI arguments snapshot (bootstrap argv).\n *\n * @remarks\n * A globally accessible object used during early CLI bootstrap to store the result of\n * the *minimal* argument parse (typically just enough to locate the config file).\n *\n * This is useful when later stages need access to the initial argv values before the\n * full, enhanced parse (with user extensions) is performed.\n *\n * **Intended usage:**\n * - Set once at startup (e.g., right after parsing `--config`)\n * - Read later by services/modules that need bootstrap context\n *\n * **Shape:**\n * Uses `Record<string, unknown>` because the exact keys depend on the CLI parser and\n * configuration-defined options.\n *\n * @example\n * ```ts\n * // After minimal parsing\n * globalThis.$argv = { config: 'xbuild.config.ts', _: [], $0: 'xbuild' };\n *\n * // Later\n * const configPath = String($argv.config);\n * ```\n *\n * @since 2.0.0\n */\n\n var $argv: Record<string, unknown>;\n}\n\n/**\n * Core build orchestration service for managing multi-variant builds with lifecycle hooks.\n *\n * @remarks\n * The `BuildService` is the primary entry point for programmatic xBuild usage,\n * providing comprehensive build orchestration across multiple variants (e.g.,\n * production, development, staging) with reactive configuration management.\n *\n * **Key capabilities**:\n * - Multi-variant build execution with parallel processing\n * - Reactive configuration updates via subscription pattern\n * - TypeScript type checking across all variants\n * - Incremental builds with file touch notifications\n * - Lifecycle hooks (onStart, onEnd) for custom build logic\n * - Macro transformation and conditional compilation\n * - Hot-reloading configuration in watch mode\n *\n * **Variant management**:\n * Each variant is an isolated build configuration with its own:\n * - esbuild settings (minification, sourcemaps, platform, etc.)\n * - TypeScript compiler options and language service\n * - Output directory and entry points\n * - Define constants for conditional compilation\n * - Custom lifecycle hooks and plugins\n *\n * **Usage patterns**:\n * - **CLI mode**: Instantiated by {@link bash.ts} with command-line arguments\n * - **Programmatic mode**: Created in custom build scripts for automation\n * - **Watch mode**: Responds to file changes with incremental rebuilds\n * - **Testing**: Type-check only mode for CI/CD pipelines\n *\n * @example Programmatic build with single variant\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * // Configure build\n * overwriteConfig({\n * variants: {\n * production: {\n * esbuild: {\n * minify: true,\n * sourcemap: false,\n * outdir: 'dist',\n * platform: 'node'\n * }\n * }\n * }\n * });\n *\n * // Execute build\n * const service = new BuildService();\n * await service.build('production');\n * console.log('Build complete!');\n * ```\n *\n * @example Multi-variant build with lifecycle hooks\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * cjs: {\n * esbuild: { format: 'cjs', outdir: 'dist/cjs' }\n * },\n * esm: {\n * esbuild: { format: 'esm', outdir: 'dist/esm' }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n *\n * // Track build progress\n * service.onStart = (context) => {\n * console.log(`Building ${context.variantName}...`);\n * };\n *\n * service.onEnd = (context) => {\n * const { variantName, buildResult, duration } = context;\n * if (buildResult.errors.length === 0) {\n * console.log(`\u2713 ${variantName} completed in ${duration}ms`);\n * } else {\n * console.error(`\u2717 ${variantName} failed with ${buildResult.errors.length} errors`);\n * }\n * };\n *\n * // Build all variants in parallel\n * await service.build();\n * ```\n *\n * @example Type checking without building\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * main: {\n * esbuild: { entryPoints: ['src/**\\/*.ts'] },\n * types: { failOnError: true }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n * const diagnostics = await service.typeChack();\n *\n * for (const [variant, errors] of Object.entries(diagnostics)) {\n * if (errors.length > 0) {\n * console.error(`${variant}: ${errors.length} type errors`);\n * process.exit(1);\n * }\n * }\n * ```\n *\n * @example Configuration hot-reloading in watch mode\n * ```ts\n * import { BuildService } from '@remotex-labs/xbuild';\n * import { watch } from 'chokidar';\n *\n * const service = new BuildService();\n *\n * // Watch for configuration changes\n * watch('xbuild.config.ts').on('change', async () => {\n * const newConfig = await import('./xbuild.config.ts');\n * service.reload(newConfig.default);\n * console.log('Configuration reloaded, rebuilding...');\n * });\n *\n * // Watch for source file changes\n * watch('src/**\\/*.ts').on('change', (paths) => {\n * service.touchFiles([paths]);\n * });\n * ```\n *\n * @example Conditional compilation with defines\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * development: {\n * esbuild: { outdir: 'dev' },\n * define: {\n * DEBUG: true,\n * PRODUCTION: false\n * }\n * },\n * production: {\n * esbuild: { minify: true, outdir: 'dist' },\n * define: {\n * DEBUG: false,\n * PRODUCTION: true\n * }\n * }\n * }\n * });\n *\n * // Source code can use conditional macros:\n * // const logger = $$ifdef('DEBUG', () => console.log);\n * // logger?.('Debug message'); // Only included in development\n *\n * const service = new BuildService();\n * await service.build();\n * ```\n *\n * @example Custom arguments and metadata\n * ```ts\n * import { BuildService, overwriteConfig } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * userArgv: {\n * deploy: { type: 'boolean', description: 'Deploy after build' },\n * environment: { type: 'string', default: 'staging' }\n * },\n * variants: {\n * main: { esbuild: { outdir: 'dist' } }\n * }\n * });\n *\n * const service = new BuildService({\n * deploy: true,\n * environment: 'production'\n * });\n *\n * service.onEnd = async (context) => {\n * if (context.argv.deploy && context.buildResult.errors.length === 0) {\n * await deployToCDN(context.argv.environment);\n * }\n * };\n *\n * await service.build();\n * ```\n *\n * @see {@link OnEndType} for end hook signature\n * @see {@link OnStartType} for start hook signature\n * @see {@link WatchService} for file watching capabilities\n * @see {@link VariantService} for individual variant management\n * @see {@link patchConfig} for incremental configuration updates\n * @see {@link overwriteConfig} for full configuration replacement\n *\n * @since 2.0.0\n */\n\nexport { BuildService } from '@services/build.service';\n\n/**\n * Replaces the entire xBuild configuration with a new configuration.\n *\n * @param config - New configuration to apply\n *\n * @remarks\n * Completely overwrites the current configuration with the provided configuration.\n * This is a destructive operation that discards all existing settings, including:\n * - All variant configurations\n * - Common settings\n * - Server configuration\n * - User-defined CLI arguments\n *\n * **Use cases**:\n * - Programmatic build scripts that fully control configuration\n * - Testing scenarios requiring isolated configuration\n * - Dynamic configuration generation\n * - Configuration hot-reloading in watch mode\n *\n * **Timing considerations**:\n * - Must be called before creating `BuildService` instances\n * - In watch mode, triggers rebuild with new configuration\n * - Settings take effect immediately for subsequent builds\n *\n * **Difference from {@link patchConfig}**:\n * - `overwriteConfig`: Replaces entire configuration (destructive)\n * - `patchConfig`: Merges with existing configuration (additive)\n *\n * @example Programmatic configuration\n * ```ts\n * import { overwriteConfig, BuildService } from '@remotex-labs/xbuild';\n *\n * overwriteConfig({\n * variants: {\n * production: {\n * esbuild: {\n * minify: true,\n * outdir: 'dist',\n * platform: 'node'\n * }\n * }\n * }\n * });\n *\n * const service = new BuildService();\n * await service.build('production');\n * ```\n *\n * @example Dynamic configuration\n * ```ts\n * const isProd = process.env.NODE_ENV === 'production';\n *\n * overwriteConfig({\n * variants: {\n * main: {\n * esbuild: {\n * minify: isProd,\n * sourcemap: !isProd,\n * outdir: isProd ? 'dist' : 'dev'\n * }\n * }\n * }\n * });\n * ```\n *\n * @example Configuration reload in watch mode\n * ```ts\n * // In file change handler\n * if (changedFile === 'xbuild.config.ts') {\n * const newConfig = await loadConfig();\n * overwriteConfig(newConfig);\n * // Next build uses new configuration\n * }\n * ```\n *\n * @see {@link PartialBuildConfigType} for configuration structure\n * @see {@link patchConfig} for non-destructive configuration updates\n * @see {@link ConfigurationService.reload} for implementation details\n *\n * @since 2.0.0\n */\n\nexport function overwriteConfig(config: PartialBuildConfigType): void {\n inject(ConfigurationService).reload(config);\n}\n\n/**\n * Merges the provided configuration with the existing xBuild configuration.\n *\n * @param config - Partial configuration to merge\n *\n * @remarks\n * Performs a deep merge of the provided configuration with the current configuration,\n * preserving existing settings not specified in the patch. This is a non-destructive\n * operation that allows incremental configuration updates.\n *\n * **Merge behavior**:\n * - Object properties are deeply merged (not replaced)\n * - Array properties are replaced (not concatenated)\n * - Undefined values in patch are ignored (don't remove existing values)\n * - Null values in patch replace existing values\n *\n * **Use cases**:\n * - Adding new variants without affecting existing ones\n * - Updating specific settings while preserving others\n * - Applying conditional configuration overlays\n * - Plugin-based configuration extension\n *\n * **Timing considerations**:\n * - Can be called before or after creating `BuildService` instances\n * - Settings take effect immediately for subsequent builds\n * - Useful for progressive configuration in build scripts\n *\n * **Difference from {@link overwriteConfig}**:\n * - `patchConfig`: Merges with existing configuration (additive)\n * - `overwriteConfig`: Replaces entire configuration (destructive)\n *\n * @example Adding a new variant\n * ```ts\n * import { patchConfig } from '@remotex-labs/xbuild';\n *\n * // Existing config has 'dev' and 'prod' variants\n * patchConfig({\n * variants: {\n * staging: {\n * esbuild: {\n * minify: true,\n * outdir: 'staging'\n * }\n * }\n * }\n * });\n * // Now has 'dev', 'prod', and 'staging' variants\n * ```\n *\n * @example Updating specific settings\n * ```ts\n * // Update only output directory, preserve other settings\n * patchConfig({\n * variants: {\n * production: {\n * esbuild: {\n * outdir: 'build'\n * }\n * }\n * }\n * });\n * // Other production settings (minify, platform, etc.) unchanged\n * ```\n *\n * @example Conditional configuration\n * ```ts\n * if (process.env.ENABLE_SOURCE_MAPS === 'true') {\n * patchConfig({\n * common: {\n * esbuild: {\n * sourcemap: 'linked'\n * }\n * }\n * });\n * }\n * ```\n *\n * @example Plugin pattern\n * ```ts\n * function addTypeScriptPaths(paths: Record<string, string[]>) {\n * patchConfig({\n * common: {\n * esbuild: {\n * tsconfig: './tsconfig.json'\n * }\n * }\n * });\n * }\n *\n * addTypeScriptPaths({ '@/*': ['src/*'] });\n * ```\n *\n * @see {@link overwriteConfig} for full configuration replacement\n * @see {@link PartialBuildConfigType} for configuration structure\n * @see {@link ConfigurationService.patch} for implementation details\n *\n * @since 2.0.0\n */\n\nexport function patchConfig(config: PartialBuildConfigType): void {\n inject(ConfigurationService).patch(config);\n}\n", "/**\n * Maps terminal control codes to exit signal identifiers.\n *\n * @remarks\n * This constant object defines the ANSI escape sequences for common\n * terminal interrupt signals. These are used to detect when users\n * attempt to terminate the application via keyboard shortcuts.\n *\n * The signals are:\n * - `\\x03` (Ctrl+C) - SIGINT signal for interrupting the process\n * - `\\x04` (Ctrl+D) - SIGQUIT signal for quitting the process\n *\n * @example\n * ```ts\n * if (code === EXIT_SIGNALS.SIGINT) {\n * console.log('Caught Ctrl+C, exiting...');\n * process.exit(1);\n * }\n * ```\n *\n * @see WatchModule\n * @since 2.0.0\n */\n\n\nexport const EXIT_SIGNALS = {\n SIGINT: '\\x03', // Ctrl+C\n SIGQUIT: '\\x04' // Ctrl+D\n} as const;\n\n/**\n * Maps keyboard shortcuts to their corresponding action identifiers.\n *\n * @remarks\n * This constant object defines the single-character keys used for interactive terminal commands.\n * Each key triggers a specific development action such as restarting the server or clearing the console.\n *\n * The mappings are:\n * - `h` - Display help/shortcuts\n * - `q` - Quit the application\n * - `c` - Clear console\n * - `r` - Restart the server\n * - `u` - Show server URL\n * - `o` - Open in browser\n *\n * @example\n * ```ts\n * if (key.name === KEY_MAPPINGS.RELOAD) {\n * console.log('Restarting server...');\n * }\n * ```\n *\n * @see WatchModule\n * @since 2.0.0\n */\n\nexport const KEY_MAPPINGS = {\n HELP: 'h',\n QUIT: 'q',\n CLEAR: 'c',\n RELOAD: 'r',\n VERBOSE: 'v',\n SHOW_URL: 'u',\n OPEN_BROWSER: 'o'\n} as const;\n\n/**\n * Maps operating system platform identifiers to their browser-opening commands.\n *\n * @remarks\n * This constant object provides the appropriate shell command for opening\n * URLs in the default browser on different operating systems. It is used\n * by {@link openInBrowser} to ensure cross-platform compatibility.\n *\n * The platform commands are:\n * - `win32` - Windows: `start`\n * - `darwin` - macOS: `open`\n * - `linux` - Linux: `xdg-open`\n *\n * For unsupported platforms, `xdg-open` is used as a fallback.\n *\n * @example\n * ```ts\n * const platform = process.platform as keyof typeof COMMAND_MAP;\n * const command = COMMAND_MAP[platform] ?? 'xdg-open';\n * exec(`${command} http://localhost:3000`);\n * ```\n *\n * @see WatchModule\n * @since 2.0.0\n */\n\nexport const COMMAND_MAP = {\n win32: 'start',\n darwin: 'open',\n linux: 'xdg-open'\n} as const;\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions } from 'esbuild';\nimport type { xBuildConfigInterface } from '@providers/interfaces/config-file-provider.interface';\n\n/**\n * Imports\n */\n\nimport { existsSync } from 'fs';\nimport { runInThisContext } from 'vm';\nimport { createRequire } from 'module';\nimport { inject } from '@symlinks/symlinks.module';\nimport { resolve } from '@components/path.component';\nimport { buildFiles } from '@services/transpiler.service';\nimport { FilesModel } from '@typescript/models/files.model';\nimport { FrameworkService } from '@services/framework.service';\n\n/**\n * Transpilation options for configuration file compilation.\n *\n * @remarks\n * These esbuild options are used exclusively for transpiling TypeScript configuration\n * files (e.g., `config.xbuild.ts`) into executable JavaScript. The configuration\n * prioritizes correctness and simplicity over output size or performance.\n *\n * **Key settings:**\n * - **No bundling**: Dependencies are external to avoid conflicts\n * - **CommonJS output**: Enables `require()` and `module.exports` execution\n * - **Node.js platform**: Uses Node.js module resolution\n * - **Minimal minification**: Only syntax and whitespace for readability\n * - **Symbol preservation**: Maintains symlinks for monorepo support\n *\n * These options ensure configuration files can safely import types and utilities\n * without bundling their dependencies into the transpiled output.\n *\n * @since 2.0.0\n */\n\nconst transpileOptions: BuildOptions = {\n minify: false,\n format: 'cjs',\n platform: 'node',\n logLevel: 'silent',\n packages: 'external',\n minifySyntax: true,\n preserveSymlinks: true,\n minifyWhitespace: true,\n minifyIdentifiers: false\n};\n\n/**\n * Loads and executes a TypeScript configuration file, returning its exported configuration.\n *\n * @param path - Absolute or relative path to the configuration file\n * @returns Parsed configuration object, or empty object if file doesn't exist\n *\n * @template T - Configuration interface type (extends {@link xBuildConfigInterface})\n *\n * @remarks\n * This provider enables xBuild to load TypeScript configuration files with full type\n * safety and IDE support. It performs the following steps:\n *\n * 1. **Validation**: Checks if the file exists (returns an empty object if not)\n * 2. **Transpilation**: Compiles TypeScript to JavaScript using esbuild\n * 3. **Source map registration**: Registers the source map for error reporting\n * 4. **Environment setup**: Creates Node.js module context with `require()` support\n * 5. **Execution**: Runs the compiled code in an isolated VM context\n * 6. **Export extraction**: Retrieves the configuration from `module.exports`\n *\n * **Export resolution:**\n * - Prefers named export: `export const config = { ... }`\n * - Falls back to default export: `export default { ... }`\n * - Returns empty object if no valid export found\n *\n * **Module context:**\n * The function creates a temporary module context to execute the configuration file,\n * providing access to Node.js built-ins and the ability to import dependencies. This\n * allows configuration files to use dynamic imports, helper functions, and shared utilities.\n *\n * **Source map support:**\n * Source maps are registered with the framework service to ensure TypeScript error\n * locations are correctly mapped when errors occur in configuration files.\n *\n * @example\n * ```ts\n * // Load default configuration\n * const config = await configFileProvider<BuildConfigInterface>(\n * 'config.xbuild.ts'\n * );\n * ```\n *\n * @example\n * ```ts\n * // Load custom configuration with type safety\n * interface CustomConfig extends xBuildConfigInterface {\n * customField: string;\n * }\n *\n * const config = await configFileProvider<CustomConfig>(\n * 'custom.config.ts'\n * );\n *\n * console.log(config.customField); // Type-safe access\n * ```\n *\n * @example\n * ```ts\n * // Configuration file structure\n * // config.xbuild.ts\n * import { BuildConfigInterface } from '@xbuild/types';\n *\n * export const config: BuildConfigInterface = {\n * variants: {\n * esm: {\n * esbuild: {\n * entryPoints: ['src/index.ts'],\n * format: 'esm'\n * }\n * }\n * }\n * };\n * ```\n *\n * @example\n * ```ts\n * // Configuration with default export\n * // config.xbuild.ts\n * export default {\n * common: {\n * types: true\n * },\n * variants: { ... }\n * };\n * ```\n *\n * @see {@link buildFiles}\n * @see {@link xBuildConfigInterface}\n * @see {@link FrameworkService.setSource}\n *\n * @since 2.0.0\n */\n\nexport async function configFileProvider<T extends xBuildConfigInterface>(path: string): Promise<T> {\n if (!path || !existsSync(path)) return <T>{};\n inject(FilesModel).touchFile(path);\n\n const [ map, code ] = (await buildFiles([ path ], { ...transpileOptions, outdir: 'tmp' })).outputFiles!;\n inject(FrameworkService).setSource(map.text, path);\n\n globalThis.module = { exports: {} };\n globalThis.require = createRequire(resolve(path));\n\n await runInThisContext(code.text, { filename: path });\n const config = module.exports.config ?? module.exports.default;\n if (!config) return <T> {};\n\n return <T> config;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { StackTraceInterface } from '@providers/interfaces/stack-provider.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildBaseError } from '@errors/base.error';\n\n/**\n * Represents an error that occurs during VM runtime execution.\n *\n * Extends {@link xBuildBaseError} and adds support for wrapping native errors,\n * handling `AggregateError` instances, and preserving nested errors.\n *\n * @remarks\n * This class is designed to encapsulate runtime errors in a virtual machine context.\n * If the original error is already a `xJetBaseError`, it is returned as-is.\n * AggregateErrors are flattened into an array of `VMRuntimeError` instances.\n *\n * The formatted stack trace is automatically generated for both single and nested errors.\n *\n * @example\n * ```ts\n * try {\n * // Some VM execution code that throws\n * } catch (err) {\n * const vmError = new VMRuntimeError(err, { withFrameworkFrames: true });\n * console.error(vmError.formattedStack);\n * }\n * ```\n *\n * @since 2.0.0\n */\n\nexport class VMRuntimeError extends xBuildBaseError {\n /**\n * If the original error is an AggregateError, contains nested VMRuntimeError instances.\n *\n * @since 2.0.0\n */\n\n errors?: Array<VMRuntimeError> = [];\n\n /**\n * Creates a new `VMRuntimeError` instance from a native or xJetBaseError.\n *\n * @param originalError - The original error object thrown during execution.\n * @param options - Optional stack trace formatting options.\n *\n * @remarks\n * - If `originalError` is already an instance of `xJetBaseError`, it is returned as-is.\n * - If `originalError` is an `AggregateError`, each nested error is converted into a `VMRuntimeError`.\n * - The message and stack of the original error are preserved.\n * - The formatted stack trace is generated via {@link xBuildBaseError.reformatStack}.\n *\n * @since 2.0.0\n */\n\n constructor(private originalError: Error, options?: StackTraceInterface) {\n if (originalError instanceof xBuildBaseError) {\n return <VMRuntimeError> originalError;\n }\n\n // Pass the message to the base class Error\n super(originalError.message, 'VMRuntimeError');\n\n // Handle AggregateError\n if (this.originalError instanceof AggregateError && Array.isArray(this.originalError.errors)) {\n // Process nested errors\n this.errors = this.originalError.errors.map(error =>\n new VMRuntimeError(error, options)\n );\n }\n\n this.stack = this.originalError.stack;\n this.message = this.originalError.message;\n this.reformatStack(this.originalError, options);\n }\n\n /**\n * Custom Node.js inspect method for displaying the error in the console.\n *\n * @returns A string representation of the formatted stack trace, or\n * a concatenated list of nested errors if present.\n *\n * @remarks\n * Overrides the Node.js default inspection behavior.\n * If this instance contains nested errors, they are listed with their formatted stacks.\n *\n * @since 2.0.0\n */\n\n [Symbol.for('nodejs.util.inspect.custom')](): string | undefined {\n if (this.errors && this.errors.length > 0) {\n const errorList = this.errors.map(\n (error) => `${ error.formattedStack ?? error.stack }`\n ).join('');\n\n return `VMRuntimeError Contains ${ this.errors.length } nested errors:\\n${ errorList }\\n`;\n }\n\n return this.formattedStack || this.stack;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Metafile } from 'esbuild';\nimport type { IssueType } from '@components/interfaces/printer-component.interface';\nimport type { MacrosStateInterface } from '@directives/interfaces/analyze-directive.interface';\nimport type { DiagnosticInterface } from '@typescript/services/interfaces/typescript-service.interface';\nimport type { BuildContextInterface, ResultContextInterface } from '@providers/interfaces/lifecycle-provider.interface';\n\n/**\n * Imports\n */\n\nimport { TypesError } from '@errors/types.error';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { inject } from '@symlinks/symlinks.module';\nimport { xBuildBaseError } from '@errors/base.error';\nimport { prefix } from '@components/banner.component';\nimport { relative } from '@components/path.component';\nimport { VMRuntimeError } from '@errors/vm-runtime.error';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { ConfigurationService } from '@services/configuration.service';\nimport { mutedColor, pathColor, textColor, warnColor } from '@components/color.component';\nimport { errorColor, infoColor, keywordColor, okColor } from '@components/color.component';\nimport { enhancedBuildResult, isBuildResultError } from '@providers/esbuild-messages.provider';\n\n/**\n * Constants\n */\n\nexport const INDENT = ' ';\nexport const KILOBYTE = 1024;\nexport const MEGABYTE = KILOBYTE * 1024;\nexport const DASH_SYMBOL = '\u2014';\nexport const ARROW_SYMBOL = '\u2192';\nexport const ERROR_SYMBOL = '\u00D7';\nexport const WARNING_SYMBOL = '\u2022';\n\n/**\n * Creates a formatted prefix for action log messages.\n *\n * @remarks\n * Generates a standardized prefix combining the build banner prefix,\n * a symbol (typically an arrow), and a colored action name. This ensures\n * consistent formatting across all build action logs.\n *\n * @param action - The action name to display (e.g., 'build', 'completed')\n * @param symbol - The symbol to display, defaults to a dimmed arrow\n *\n * @returns A formatted string with prefix, symbol, and colored action name\n *\n * @example\n * ```ts\n * const buildPrefix = createActionPrefix('build');\n * // Output: \"[xBuild] \u2192 build\"\n *\n * const errorPrefix = createActionPrefix('completed', errorColor(ERROR_SYMBOL));\n * // Output: \"[xBuild] \u00D7 completed\"\n * ```\n *\n * @see {@link prefix}\n * @see {@link infoColor}\n *\n * @since 2.0.0\n */\n\nexport function createActionPrefix(action: string, symbol: string = infoColor.dim(ARROW_SYMBOL)): string {\n return `${ prefix() } ${ symbol } ${ infoColor(action) }`;\n}\n\n/**\n * Formats a byte size into a human-readable string with appropriate units.\n *\n * @remarks\n * Converts raw byte counts into formatted strings using B, KB, or MB units\n * depending on the size. Values are rounded to 2 decimal places for KB and MB.\n * This function is used primarily for displaying file sizes in build output.\n *\n * @param bytes - The number of bytes to format\n *\n * @returns A formatted string with the size and the appropriate unit (B, KB, or MB)\n *\n * @example\n * ```ts\n * formatByteSize(512); // \"512 B\"\n * formatByteSize(2048); // \"2.00 KB\"\n * formatByteSize(1572864); // \"1.50 MB\"\n * ```\n *\n * @since 2.0.0\n */\n\nexport function formatByteSize(bytes: number): string {\n if (bytes < KILOBYTE) return `${ bytes } B`;\n if (bytes < MEGABYTE) return `${ (bytes / KILOBYTE).toFixed(2) } KB`;\n\n return `${ (bytes / MEGABYTE).toFixed(2) } MB`;\n}\n\n/**\n * Formats a TypeScript diagnostic's file location into a readable string.\n *\n * @remarks\n * Creates a standardized location string in the format `file:line:column`,\n * similar to standard compiler output. Line and column numbers are 1-based\n * (incremented from TypeScript's 0-based values). The file path is made\n * relative to the current working directory for brevity.\n *\n * @param diagnostic - The TypeScript diagnostic containing location information\n *\n * @returns A formatted location string with colored path and position\n *\n * @example\n * ```ts\n * const diagnostic: DiagnosticInterface = {\n * file: '/project/src/index.ts',\n * line: 10,\n * column: 5,\n * code: 2304,\n * message: 'Cannot find name'\n * };\n *\n * formatDiagnosticLocation(diagnostic);\n * // Output: \"src/index.ts:11:6\"\n * ```\n *\n * @see {@link pathColor}\n * @see {@link warnColor}\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\nexport function formatDiagnosticLocation(diagnostic: DiagnosticInterface): string {\n const filePath = diagnostic.file ? relative(process.cwd(), diagnostic.file) : '(unknown)';\n const lineNumber = warnColor(String((diagnostic.line ?? 0) + 1));\n const columnNumber = warnColor(String((diagnostic.column ?? 0) + 1));\n\n return `${ pathColor(filePath) }:${ lineNumber }:${ columnNumber }`;\n}\n\n/**\n * Appends formatted error metadata to a buffer array.\n *\n * @remarks\n * Internal helper that adds formatted code snippets and enhanced stack traces\n * to the provided buffer. Only processes errors that have metadata with formatted\n * code. Used by {@link appendIssue} to include additional error context.\n *\n * @param buffer - Array to append formatted lines to\n * @param error - The xBuild error containing metadata to format\n *\n * @since 2.0.0\n */\n\nexport function appendErrorMetadata(buffer: Array<string>, error: xBuildBaseError): void {\n if (!error.metadata?.formatCode) return;\n\n const codeLines = error.metadata.formatCode.split('\\n');\n const stackTrace = error.metadata.stacks.join('\\n ');\n\n buffer.push('');\n for (const line of codeLines) {\n buffer.push(`${ INDENT }${ line }`);\n }\n buffer.push('');\n buffer.push(`${ INDENT }Enhanced Stack Trace:`);\n buffer.push(` ${ stackTrace }`);\n}\n\n/**\n * Logs formatted error metadata to the console.\n *\n * @remarks\n * Outputs formatted code snippets and enhanced stack traces for xBuild errors\n * that contain metadata. Used by {@link logError} to provide detailed error\n * context in the console output.\n *\n * @param error - The xBuild error containing metadata to log\n *\n * @example\n * ```ts\n * const error = new xBuildBaseError('Build failed', {\n * formatCode: 'const x = undefined;\\nx.toString();',\n * stacks: ['at build.ts:45:12', 'at main.ts:10:5']\n * });\n *\n * logErrorMetadata(error);\n * // Outputs formatted code and stack trace to console\n * ```\n *\n * @see {@link logError}\n * @see {@link xBuildBaseError}\n *\n * @since 2.0.0\n */\n\nexport function logErrorMetadata(error: xBuildBaseError): void {\n if (!error.metadata?.formatCode) return;\n\n const formattedCode = error.metadata.formatCode\n .split('\\n')\n .map(line => `${ INDENT }${ line }`)\n .join('\\n');\n\n const stackTrace = error.metadata.stacks.join('\\n ');\n\n console.log(`\\n${ formattedCode }\\n\\n${ INDENT }Enhanced Stack Trace:\\n ${ stackTrace }`);\n}\n\n/**\n * Formats a TypeScript diagnostic into a single-line string.\n *\n * @remarks\n * Internal helper that creates a formatted diagnostic string with location,\n * error code, and message. Used by {@link appendTypesError} to prepare\n * diagnostics for buffer output.\n *\n * @param diagnostic - The TypeScript diagnostic to format\n * @param symbol - The symbol to prefix the diagnostic with\n * @param codeColor - Color function for the error code\n *\n * @returns A formatted diagnostic string\n *\n * @since 2.0.0\n */\n\nexport function formatTypescriptDiagnostic(diagnostic: DiagnosticInterface, symbol: string, codeColor: typeof errorColor): string {\n const location = formatDiagnosticLocation(diagnostic);\n const diagnosticCode = codeColor(`TS${ diagnostic.code }`);\n const message = mutedColor(diagnostic.message);\n\n return `${ INDENT }${ symbol } ${ location } ${ textColor(ARROW_SYMBOL) } ${ diagnosticCode } ${ textColor(DASH_SYMBOL) } ${ message }`;\n}\n\n/**\n * Logs a formatted TypeScript diagnostic to the console.\n *\n * @remarks\n * Outputs a single TypeScript diagnostic with location, error code, and message\n * in a standardized format. Used internally for immediate console output of\n * diagnostics during type checking.\n *\n * @param diagnostic - The TypeScript diagnostic to log\n * @param symbol - The symbol to prefix the diagnostic with\n * @param codeColor - Color function for the error code, defaults to error color\n *\n * @since 2.0.0\n */\n\nexport function logTypescriptDiagnostic(diagnostic: DiagnosticInterface, symbol: string, codeColor: typeof errorColor = errorColor): void {\n const location = formatDiagnosticLocation(diagnostic);\n const diagnosticCode = codeColor(`TS${ diagnostic.code }`);\n const message = mutedColor(diagnostic.message);\n\n console.log(\n `${ INDENT }${ symbol } ${ location }`,\n textColor(ARROW_SYMBOL),\n `${ diagnosticCode } ${ textColor(DASH_SYMBOL) } ${ message }`\n );\n}\n\n/**\n * Appends formatted TypeScript type errors to a buffer array.\n *\n * @remarks\n * Internal helper that processes {@link TypesError} instances and adds their\n * diagnostics to the buffer. If no diagnostics exist, adds a generic warning\n * message. Returns the count of diagnostics processed.\n *\n * @param buffer - Array to append formatted lines to\n * @param error - The TypesError containing diagnostics to format\n * @param symbol - The symbol to prefix each diagnostic with\n *\n * @returns The number of diagnostics added to the buffer\n *\n * @since 2.0.0\n */\n\nexport function appendTypesError(buffer: Array<string>, error: TypesError, symbol: string): number {\n const diagnosticCount = error.diagnostics.length;\n\n if (diagnosticCount === 0) {\n buffer.push(`${ INDENT }${ warnColor(symbol) } ${ warnColor('TypesError') }: ${ mutedColor(error.message || 'Type checking warning') }`);\n\n return 1;\n }\n\n buffer.push('');\n for (const diagnostic of error.diagnostics) {\n buffer.push(formatTypescriptDiagnostic(diagnostic, warnColor(symbol), xterm.deepOrange));\n }\n\n return diagnosticCount;\n}\n\n/**\n * Appends a formatted generic issue to a buffer array.\n *\n * @remarks\n * Internal helper that processes non-TypesError issues and adds them to the buffer.\n * If the issue is an xBuildBaseError with metadata, also appends the error metadata.\n *\n * @param buffer - Array to append formatted lines to\n * @param issue - The issue to format and append\n * @param symbol - The symbol to prefix the issue with\n * @param color - Color function for the symbol and formatting\n *\n * @since 2.0.0\n */\n\nexport function appendGenericIssue(buffer: Array<string>, issue: IssueType, symbol: string, color: typeof errorColor): void {\n const title = `${ color(issue.name) }: ${ issue.message }`;\n buffer.push(`\\n${ INDENT }${ color(symbol) } ${ title }`);\n\n if (issue instanceof xBuildBaseError) {\n appendErrorMetadata(buffer, issue);\n }\n}\n\n/**\n * Appends a formatted build issue to a buffer array.\n *\n * @remarks\n * Processes different types of build issues (TypesError, xBuildBaseError, or\n * generic Error) and appends them to the provided buffer with appropriate\n * formatting. Returns the count of individual issues added, which may be\n * greater than 1 for TypesError containing multiple diagnostics.\n *\n * This function is used by {@link logBuildIssues} to prepare formatted issues\n * for batch console output.\n *\n * @param buffer - Array to append formatted issue lines to\n * @param issue - The build issue to format and append\n * @param symbol - The symbol to prefix the issue with (typically error or warning symbol)\n * @param color - Color function to apply to the symbol and formatting\n *\n * @returns The number of individual issues added to the buffer\n *\n * @example\n * ```ts\n * const buffer: string[] = [];\n * const error = new TypesError([diagnostic1, diagnostic2]);\n *\n * const count = appendIssue(buffer, error, ERROR_SYMBOL, errorColor);\n * // count = 2 (two diagnostics)\n * // buffer contains formatted diagnostic lines\n * ```\n *\n * @see {@link IssueType}\n * @see {@link TypesError}\n * @see {@link logBuildIssues}\n * @see {@link xBuildBaseError}\n *\n * @since 2.0.0\n */\n\nexport function appendIssue(buffer: Array<string>, issue: IssueType, symbol: string, color: typeof errorColor): number {\n if (issue instanceof TypesError) {\n return appendTypesError(buffer, issue, symbol);\n }\n\n appendGenericIssue(buffer, issue, symbol, color);\n\n return 1;\n}\n\n/**\n * Logs all build issues (errors or warnings) to the console in a formatted batch.\n *\n * @remarks\n * Processes an array of build issues and outputs them as a single formatted\n * block with a header showing the issue count. Uses buffering to prepare all\n * output before logging, ensuring clean and consistent console output.\n *\n * If no issues exist, this function returns early without logging anything.\n * The function handles different issue types (TypesError with multiple diagnostics,\n * xBuildBaseError with metadata, and generic errors) and formats them appropriately.\n *\n * @param issues - Array of build issues to log\n * @param issueType - Type label for the issues ('Errors' or 'Warnings')\n *\n * @example\n * ```ts\n * const errors = [\n * new xBuildBaseError('Build failed'),\n * new TypesError([diagnostic1, diagnostic2])\n * ];\n *\n * logBuildIssues(errors, 'Errors');\n * // Output:\n * // Errors (3)\n * // \u00D7 Build failed\n * // \u00D7 src/index.ts:10:5 \u2192 TS2304 \u2014 Cannot find name 'x'\n * // \u00D7 src/index.ts:15:3 \u2192 TS2322 \u2014 Type mismatch\n * ```\n *\n * @see {@link IssueType}\n * @see {@link appendIssue}\n *\n * @since 2.0.0\n */\n\nexport function logBuildIssues(issues: Array<IssueType>, issueType: 'Errors' | 'Warnings'): void {\n if (issues.length === 0) return;\n\n const isError = issueType === 'Errors';\n const symbol = isError ? ERROR_SYMBOL : WARNING_SYMBOL;\n const color = isError ? errorColor : warnColor;\n\n let totalIssueCount = 0;\n const buffer: Array<string> = [ '' ];\n\n for (const issue of issues) {\n totalIssueCount += appendIssue(buffer, issue, symbol, color);\n }\n\n buffer[0] = `\\n ${ color(issueType) } (${ totalIssueCount })`;\n console.log(buffer.join('\\n'));\n}\n\n/**\n * Logs build output files with their sizes to the console.\n *\n * @remarks\n * Processes the esbuild metafile to extract output file information and\n * displays each output file with its size in a formatted list. The output\n * includes a header with the total count of output files.\n *\n * File sizes are automatically formatted using appropriate units (B, KB, MB)\n * for readability.\n *\n * @param metafile - The esbuild metafile containing output information\n *\n * @example\n * ```ts\n * const metafile: Metafile = {\n * outputs: {\n * 'dist/index.js': { bytes: 1024, inputs: {} },\n * 'dist/utils.js': { bytes: 512, inputs: {} }\n * }\n * };\n *\n * logBuildOutputs(metafile);\n * // Output:\n * // Outputs (2)\n * // \u2192 dist/index.js: 1.00 KB\n * // \u2192 dist/utils.js: 512 B\n * ```\n *\n * @see {@link Metafile}\n * @see {@link formatByteSize}\n *\n * @since 2.0.0\n */\n\nexport function logBuildOutputs(metafile: Metafile): void {\n const outputEntries = Object.entries(metafile.outputs);\n const outputCount = outputEntries.length;\n\n const buffer: Array<string> = [];\n buffer.push(`\\n ${ okColor('Outputs') } (${ outputCount })`);\n\n for (const [ outputPath, info ] of outputEntries) {\n const size = warnColor.dim(formatByteSize(info.bytes));\n buffer.push(`${ INDENT }${ infoColor(ARROW_SYMBOL) } ${ pathColor(outputPath) }: ${ size }`);\n }\n\n buffer.push('');\n console.log(buffer.join('\\n'));\n}\n\n/**\n * Logs an error or issue to the console with appropriate formatting.\n *\n * @remarks\n * Provides unified error logging with special handling for different error types:\n * - {@link AggregateError}: Recursively logs all contained errors\n * - {@link TypesError}: Logs TypeScript diagnostics with file locations\n * - {@link xBuildBaseError}: Logs error with enhanced metadata and stack traces\n * - Generic {@link Error}: Wraps in {@link VMRuntimeError} before logging\n * - Other types: Converts to string, wraps in VMRuntimeError, and logs\n *\n * This is the primary function for error output throughout the build system,\n * ensuring consistent error formatting and the appropriate detail level.\n *\n * @param issue - The error or issue to log\n *\n * @example\n * ```ts\n * try {\n * await build();\n * } catch (error) {\n * logError(error);\n * }\n * ```\n *\n * @example\n * ```ts\n * // Logs multiple TypeScript errors\n * const typesError = new TypesError([diagnostic1, diagnostic2]);\n * logError(typesError);\n * // Output:\n * // \u00D7 src/index.ts:10:5 \u2192 TS2304 \u2014 Cannot find name 'x'\n * // \u00D7 src/main.ts:20:3 \u2192 TS2322 \u2014 Type mismatch\n * ```\n *\n * @see {@link TypesError}\n * @see {@link VMRuntimeError}\n * @see {@link xBuildBaseError}\n * @see {@link logErrorMetadata}\n *\n * @since 2.0.0\n */\n\nexport function logError(issue: unknown): void {\n if (issue instanceof xBuildBaseError) {\n const title = `${ errorColor(issue.name) }: ${ issue.message }`;\n console.log(`\\n${ INDENT }${ errorColor(ERROR_SYMBOL) } ${ title }`);\n logErrorMetadata(issue);\n } else if (isBuildResultError(issue)) {\n for (const error of issue.errors) {\n logError(error);\n }\n } else if (issue instanceof TypesError) {\n for (const diagnostic of issue.diagnostics) {\n logTypescriptDiagnostic(diagnostic, errorColor(ERROR_SYMBOL));\n }\n } else if (issue instanceof Error) {\n logError(new VMRuntimeError(issue));\n } else {\n logError(new xBuildError(String(issue)));\n }\n}\n\n/**\n * Logs TypeScript diagnostics for a single variant to the console.\n *\n * @remarks\n * Internal helper that outputs diagnostics for a named variant with a\n * completion status. Shows an error symbol if diagnostics exist, or\n * an arrow symbol for successful completion.\n *\n * @param name - The variant name\n * @param diagnostics - Array of TypeScript diagnostics for this variant\n *\n * @since 2.0.0\n */\n\nexport function logTypeDiagnostic(name: string, diagnostics: Array<DiagnosticInterface>): void {\n const hasErrors = diagnostics.length > 0;\n const nameColor = hasErrors ? warnColor(name) : keywordColor(name);\n const statusSymbol = hasErrors ? errorColor(ERROR_SYMBOL) : infoColor.dim(ARROW_SYMBOL);\n const status = createActionPrefix('completed', statusSymbol);\n\n console.log(`${ status } ${ nameColor }`);\n\n if (hasErrors) {\n console.log('');\n for (const diagnostic of diagnostics) {\n logTypescriptDiagnostic(diagnostic, errorColor(ERROR_SYMBOL));\n }\n console.log('');\n }\n}\n\n/**\n * Logs TypeScript type diagnostics for all variants to the console.\n *\n * @remarks\n * Processes a record of variant names to diagnostic arrays and outputs\n * each variant's type checking results. Used to provide feedback after\n * TypeScript type checking operations across multiple build variants.\n *\n * Each variant is logged with its completion status and any diagnostics\n * found during type checking.\n *\n * @param diagnostics - Record mapping variant names to their diagnostic arrays\n *\n * @example\n * ```ts\n * const diagnostics = {\n * 'production': [diagnostic1, diagnostic2],\n * 'development': []\n * };\n *\n * logTypeDiagnostics(diagnostics);\n * // Output:\n * // [xBuild] \u2192 completed production\n * // \u00D7 src/index.ts:10:5 \u2192 TS2304 \u2014 Cannot find name 'x'\n * // \u00D7 src/main.ts:15:3 \u2192 TS2322 \u2014 Type mismatch\n * //\n * // [xBuild] \u2192 completed development\n * ```\n *\n * @see {@link DiagnosticInterface}\n *\n * @since 2.0.0\n */\n\nexport function logTypeDiagnostics(diagnostics: Record<string, Array<DiagnosticInterface>>): void {\n for (const [ name, errors ] of Object.entries(diagnostics)) {\n logTypeDiagnostic(name, errors);\n }\n}\n\n/**\n * Logs the start of a build operation for a variant.\n *\n * @remarks\n * Outputs a formatted message indicating that a build has started for the\n * specified variant. Used by the build lifecycle to provide feedback at\n * the beginning of build operations.\n *\n * @param context - Build context containing the variant name\n *\n * @example\n * ```ts\n * const context: BuildContextInterface = {\n * variantName: 'production',\n * // ... other properties\n * };\n *\n * logBuildStart(context);\n * // Output: [xBuild] \u2192 build production\n * ```\n *\n * @see {@link createActionPrefix}\n * @see {@link BuildContextInterface}\n *\n * @since 2.0.0\n */\n\nexport function logBuildStart({ variantName }: BuildContextInterface): void {\n console.log(`${ createActionPrefix('build') } ${ keywordColor(variantName) }`);\n}\n\n/**\n * Logs macro replacement information for a specific build variant.\n *\n * @remarks\n * Displays all macro transformations that occurred during the build process\n * for the specified variant. This function only outputs when verbose mode is enabled\n * in the configuration.\n *\n * Each replacement shows:\n * - The replacement value (if not 'undefined')\n * - The original source code as a comment\n *\n * Output is indented and color-coded for better readability.\n *\n * @param variant - The build variant name to retrieve replacements for\n * @param stage - The macro state interface containing replacement information\n *\n * @example\n * ```ts\n * const stage: MacrosStateInterface = {\n * defineMetadata: { ... },\n * replacementInfo: {\n * 'production': [\n * { source: \"$$ifdef('DEBUG', () => log())\", replacement: \"undefined\" },\n * { source: \"$$inline(() => 1 + 1)\", replacement: \"2\" }\n * ]\n * }\n * };\n *\n * logMacroReplacements('production', stage);\n * // Output (when verbose):\n * // [xBuild] macro replacement\n * // \u2192 2 // $$inline(() => 1 + 1)\n * // \u2192 // $$ifdef('DEBUG', () => log())\n * ```\n *\n * @see {@link MacrosStateInterface}\n * @see {@link MacroReplacementInterface}\n *\n * @since 2.1.5\n */\n\nexport function logMacroReplacements(variant: string, stage: MacrosStateInterface): void {\n if (!inject(ConfigurationService).getValue().verbose) return;\n const replaceInfo = stage?.replacementInfo?.[variant];\n if (!replaceInfo || !Array.isArray(replaceInfo) || replaceInfo.length === 0) return;\n\n const prefix = INDENT + pathColor(ARROW_SYMBOL);\n const buffer: Array<string> = [ createActionPrefix(`macro ${ warnColor('replacement') }`) ];\n\n for (const { source, replacement } of replaceInfo) {\n const code = xterm.dim('// ' + source).replaceAll('\\n', `\\n${ INDENT }`);\n\n if (replacement && replacement !== 'undefined') {\n const resultCode = replacement.replaceAll('\\n', `\\n${ INDENT }`);\n buffer.push(`\\n${ prefix } ${ resultCode } ${ code }`);\n } else {\n buffer.push(`\\n${ prefix } ${ code }`);\n }\n }\n\n console.log(buffer.join('\\n'));\n}\n\n/**\n * Logs the completion of a build operation with results summary.\n *\n * @remarks\n * Outputs a comprehensive build summary including\n * - Completion status with build duration\n * - All errors encountered during the build\n * - All warnings encountered during the build\n * - Macro replacements (if verbose mode is enabled)\n * - Output files with their sizes (if build succeeded)\n *\n * The completion status shows an error symbol if the build failed (no metafile),\n * or an arrow symbol for successful builds. Build duration is displayed in\n * milliseconds.\n *\n * This is the primary function for providing build feedback to users and is\n * called by the build lifecycle at the end of each build operation.\n *\n * @param context - Result context containing variant name, duration, build result, and stage\n *\n * @example\n * ```ts\n * const context: ResultContextInterface = {\n * variantName: 'production',\n * duration: 1523,\n * buildResult: {\n * errors: [],\n * warnings: [warning1],\n * metafile: { outputs: { ... } }\n * },\n * stage: macroStage\n * };\n *\n * logBuildEnd(context);\n * // Output:\n * // [xBuild] \u2192 completed production in 1523 ms\n * //\n * // Warnings (1)\n * // \u2022 Unused variable warning\n * //\n * // [xBuild] macro replacement\n * // \u2192 2 // $$inline(() => 1 + 1)\n * //\n * // Outputs (2)\n * // \u2192 dist/index.js: 45.23 KB\n * // \u2192 dist/utils.js: 12.45 KB\n * ```\n *\n * @see {@link logBuildIssues}\n * @see {@link logBuildOutputs}\n * @see {@link logMacroReplacements}\n * @see {@link ResultContextInterface}\n *\n * @since 2.0.0\n */\n\nexport function logBuildEnd({ variantName, duration, buildResult, stage }: ResultContextInterface): void {\n const { errors, warnings, metafile } = enhancedBuildResult(buildResult);\n const isSuccess = !!metafile;\n\n const nameColor = isSuccess ? keywordColor(variantName) : warnColor(variantName);\n const statusSymbol = isSuccess ? infoColor.dim(ARROW_SYMBOL) : errorColor(ERROR_SYMBOL);\n const status = createActionPrefix('completed', statusSymbol);\n\n console.log(`${ status } ${ nameColor } ${ xterm.dim(`in ${ duration } ms`) }`);\n\n logBuildIssues(errors, 'Errors');\n logBuildIssues(warnings, 'Warnings');\n\n if(errors.length || warnings.length) console.log(''); // add space line\n logMacroReplacements(variantName, <MacrosStateInterface> stage);\n\n if (isSuccess) {\n logBuildOutputs(metafile);\n } else {\n console.log(''); // add space line\n }\n}\n", "/**\n * Imports\n */\n\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\n\n/**\n * Style token for successful/OK messages (green).\n *\n * @since 2.0.0\n */\n\nexport const okColor = xterm.hex('#80a36b');\n\n/**\n * Base text color token (neutral light).\n *\n * @since 2.0.0\n */\n\nexport const textColor = xterm.hex('#dcdfe4');\n\n/**\n * Style token for informational messages (blue).\n *\n * @since 2.0.0\n */\n\nexport const infoColor = xterm.hex('#5798cd');\n\n/**\n * Style token for warnings (yellow).\n *\n * @since 2.0.0\n */\n\nexport const warnColor = xterm.hex('#e5c07b');\n\n/**\n * Style token for file paths, URLs, and locations (cyan).\n *\n * @since 2.0.0\n */\n\nexport const pathColor = xterm.hex('#56b6c2');\n\n/**\n * Style token for errors and failures (red).\n *\n * @since 2.0.0\n */\n\nexport const errorColor = xterm.hex('#e06c75');\n\n/**\n * Style token for highlighted keywords and identifiers (purple).\n *\n * @since 2.0.0\n */\n\nexport const keywordColor = xterm.hex('#c678dd');\n\n/**\n * Style token for de-emphasized / secondary text (muted gray).\n *\n * @since 2.0.0\n */\n\nexport const mutedColor = xterm.hex('#a5a7ab');\n"],
|
|
6
|
+
"mappings": ";u4DAcA,OAAS,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a,OAAOrB,CAAM,CAC9B,CAEA,QAAQ,IAAI;AAAA,EAAMyC,EAAO,CAAE,IAAKC,GAAW,YAAY,CAAE,YAAaH,EAAa,MAAO;AAAA,CAAK,EAC/F,MAAMnB,GAAaC,EAAcpB,CAAI,CACzC,CAAC,CAGL,CAsFA,eAAe0C,IAAsB,CAEjC,QAAQ,IAAIC,GAAgB,CAAC,EAG7B,IAAMC,EAAcC,EAAOC,EAAU,EAC/BC,EAAYH,EAAY,gBAAgB,QAAQ,IAAI,EAE1D,WAAW,MAAQG,EACnB,IAAMhD,EAAS,MAAMwC,GAAmBQ,EAAU,MAAM,EAClD/C,EAAO4C,EAAY,cAAc,QAAQ,KAAM7C,EAAO,QAAQ,EAC9DiD,EAAWJ,EAAY,cAAc,QAAQ,KAAM7C,EAAO,QAAQ,EAGxED,GAAqBC,EAAQC,CAAI,EACjCI,GAA0BL,EAAQC,CAAI,EACtCiD,GAAgBlD,CAAM,EAGtB,IAAMqB,EAAe,IAAI8B,GAAaF,CAAQ,EAC9C5B,EAAa,MAAQ+B,GACrB/B,EAAa,QAAUgC,GAGvB,IAAMtC,EAAM,MAAMN,GAAYT,EAAQC,CAAI,EAC1C,MAAMkC,GAAed,EAAcrB,EAAQC,EAAMc,CAAG,EACpD,MAAMK,GAAaC,EAAcpB,CAAI,CACzC,CAEA0C,GAAK",
|
|
7
7
|
"names": ["rmSync", "cwd", "process", "SINGLETONS", "INJECTABLES", "isProviderUseClass", "provider", "isProviderUseFactory", "isProviderUseValue", "Injectable", "options", "target", "providersIntoArgs", "providers", "args", "scopeAgs", "inject", "token", "metadata", "instance", "xterm", "ts", "path", "pathPosix", "BACKSLASH_RE", "DUPLICATE_SLASH_RE", "toPosix", "input", "p", "normalize", "join", "paths", "resolve", "dirname", "relative", "from", "to", "closeSync", "fstatSync", "openSync", "readFileSync", "_FilesModel_decorators", "_init", "Injectable", "FilesModel", "path", "resolvedPath", "entry", "cached", "resolved", "resolve", "fd", "openSync", "mtimeMs", "fstatSync", "content", "readFileSync", "ts", "closeSync", "__decoratorStart", "__decorateElement", "__runInitializers", "readFileSync", "SourceService", "_FrameworkService_decorators", "_init", "Injectable", "FrameworkService", "position", "source", "sourceRoot", "lowerCaseSource", "path", "resolve", "key", "error", "map", "sourceMapData", "readFileSync", "toPosix", "sourceMap", "SourceService", "__decoratorStart", "__decorateElement", "__runInitializers", "parseErrorStack", "map", "project", "source", "ObservableService", "observer", "value", "result", "err", "distinctUntilChanged", "compareFn", "a", "b", "hasPrevious", "previous", "ObservableService", "handler", "observerOrNext", "error", "complete", "observer", "cleanup", "err", "operators", "prev", "op", "SubjectService", "ObservableService", "observer", "value", "errors", "o", "err", "e", "BehaviorSubjectService", "SubjectService", "initialValue", "observerOrNext", "error", "complete", "observer", "unsub", "value", "isObject", "item", "deepMerge", "target", "sources", "source", "key", "sourceValue", "targetValue", "equals", "a", "b", "strictCheck", "deepEquals", "hasKey", "obj", "val", "i", "aKeys", "bKeys", "DEFAULTS_COMMON_CONFIG", "_ConfigurationService_decorators", "_init", "Injectable", "ConfigurationService", "initialConfig", "DEFAULTS_COMMON_CONFIG", "BehaviorSubjectService", "deepMerge", "selector", "observer", "map", "distinctUntilChanged", "prev", "curr", "equals", "partial", "mergedConfig", "config", "__decoratorStart", "__decorateElement", "__runInitializers", "highlightCode", "Bias", "formatErrorCode", "MULTIPLE_SPACES", "URL_PATTERN", "FILE_PROTOCOL", "getErrorStack", "raw", "parseErrorStack", "getSource", "frame", "fileName", "mapped", "snapshot", "code", "lines", "line", "column", "_bias", "options", "before", "after", "startLine", "endLine", "highlightPositionCode", "position", "xterm", "formatStackFrame", "relative", "getSourceLocation", "source", "sourceRoot", "httpIndex", "path", "dirname", "join", "formatFrameWithPosition", "stackEntry", "getErrorMetadata", "lineOffset", "verbose", "inject", "ConfigurationService", "c", "context", "FilesModel", "FrameworkService", "formatStack", "metadata", "name", "message", "notes", "parts", "note", "xBuildBaseError", "message", "name", "error", "options", "getErrorMetadata", "formatStack", "formatErrors", "reason", "err", "xBuildBaseError", "metadata", "getErrorMetadata", "formatStack", "process", "yargs", "hideBin", "CLI_CONFIG_PATH", "CLI_DEFAULT_OPTIONS", "CLI_USAGE_EXAMPLES", "_ArgvModule_decorators", "_init", "Injectable", "ArgvModule", "argv", "yargs", "CLI_DEFAULT_OPTIONS", "argvOptions", "userExtensions", "parser", "hideBin", "originalShowHelp", "consoleFunction", "CLI_USAGE_EXAMPLES", "command", "description", "__decoratorStart", "__decorateElement", "__runInitializers", "readline", "exec", "cwd", "readdirSync", "matchesGlob", "parseGlobs", "globs", "include", "exclude", "g", "matchesAny", "p", "patterns", "pattern", "matchesGlob", "isDirectoryExcluded", "relativePath", "dirWithGlob", "collectFilesFromGlob", "baseDir", "globs", "include", "exclude", "parseGlobs", "collected", "rootDirLength", "cwd", "baseDirLength", "hasExcludes", "walk", "dir", "entries", "readdirSync", "len", "i", "entry", "fullPath", "join", "relativeFromBase", "isDirectoryExcluded", "matchesAny", "relativeFromRoot", "lastDotIndex", "keyPath", "TypesError", "_TypesError", "message", "diagnostics", "xBuildError", "xBuildBaseError", "message", "options", "esBuildError", "xBuildBaseError", "message", "options", "getErrorMetadata", "formatStack", "normalizeMessageToError", "msg", "xBuildBaseError", "TypesError", "esBuildError", "xBuildError", "processEsbuildMessages", "messages", "target", "error", "enhancedBuildResult", "source", "isBuildResultError", "http", "https", "extname", "readFileSync", "server_default", "xterm", "asciiLogo", "bannerComponent", "prefix", "readdir", "stat", "readFile", "xterm", "ServerModule", "config", "dir", "resolve", "inject", "FrameworkService", "prefix", "xterm", "reject", "err", "address", "req", "res", "options", "readFileSync", "join", "defaultHandler", "error", "ext", "requestPath", "fullPath", "stats", "stat", "msg", "fileList", "readdir", "file", "extname", "activePath", "segments", "path", "htmlResult", "server_default", "contentType", "data", "readFile", "matchesGlob", "stat", "watch", "WatchService", "inject", "FrameworkService", "excludes", "include", "callback", "changedFilesSet", "watcher", "watch", "filename", "fullPath", "normalize", "pattern", "matchesGlob", "absolutePath", "join", "stat", "fn", "delay", "ts", "build", "writeFile", "mkdir", "ts", "ts", "SHEBANG_REGEX", "EMPTY_EXPORT_REGEX", "ORPHAN_COMMENT_REGEX", "EXPORT_MODIFIER_REGEX", "TRAILING_COMMENT_REGEX", "removeShebang", "content", "removeEmptyExports", "removeOrphanComments", "removeExportModifiers", "needsCleaning", "cleanContent", "calculateOutputPath", "sourcePath", "options", "outDir", "rootDir", "declarationDir", "outputBase", "dirname", "root", "outputFileName", "relative", "fullPath", "ts", "toPosix", "_GraphModel_decorators", "_init", "Injectable", "GraphModel", "inject", "FilesModel", "ts", "path", "resolvedPath", "source", "languageService", "languageHostService", "self", "version", "cached", "node", "declarationSource", "fileName", "moduleSpecifier", "currentFile", "modulePath", "resolvedFileName", "target", "elements", "element", "name", "stmt", "m", "declarationText", "sourceFile", "aliasStatements", "keptStatements", "nodeArray", "printed", "content", "removeExportModifiers", "cleanContent", "alias", "aliasName", "aliasType", "importClause", "moduleInfo", "isExternal", "namedBindings", "exportClause", "decl", "__decoratorStart", "__decorateElement", "__runInitializers", "ts", "mkdir", "writeFile", "HeaderDeclarationBundle", "BundlerService", "languageService", "languageHostService", "inject", "GraphModel", "entryPoints", "outdir", "program", "config", "outputPath", "entryFile", "sourceFile", "outputFile", "join", "source", "output", "entryDeclaration", "content", "mkdir", "dirname", "writeFile", "entryPoint", "visited", "exportList", "dependencyList", "dependencyQueue", "starExportModules", "currentFile", "declaration", "starModule", "dep", "declarations", "imports", "module", "name", "moduleImports", "names", "statements", "defaultImport", "named", "namespace", "parts", "fileName", "exports", "namespaceName", "targetModule", "nested", "externalExports", "HeaderDeclarationBundle", "importStatements", "uniqueExports", "mkdir", "writeFile", "xterm", "EmitterService", "_EmitterService", "languageService", "languageHostService", "outdir", "program", "xterm", "config", "filesToEmit", "sourceFiles", "i", "file", "source", "outputPath", "calculateOutputPath", "version", "currentVersion", "sourceFile", "options", "output", "content", "fileName", "cleanContent", "mkdir", "dirname", "writeFile", "ts", "LanguageHostService", "_LanguageHostService", "compilerOptions", "ts", "s", "inject", "FilesModel", "options", "path", "filesPath", "file", "encoding", "extensions", "exclude", "include", "depth", "state", "moduleName", "containingFile", "result", "content", "fileName", "type", "match", "importPath", "resolve", "targetFile", "relativePath", "relative", "dirname", "config", "paths", "aliases", "alias", "_TypescriptService_decorators", "_init", "Injectable", "_TypescriptService", "configPath", "config", "host", "service", "EmitterService", "BundlerService", "filesList", "program", "files", "file", "cached", "entryPoints", "outdir", "tsconfigPath", "path", "d", "LanguageHostService", "ts", "diagnostic", "result", "line", "character", "__decoratorStart", "__decorateElement", "__runInitializers", "TypescriptService", "cwd", "build", "defaultBuildOptions", "cwd", "buildFiles", "entryPoints", "buildOptions", "build", "err", "isBuildResultError", "aggregateError", "processEsbuildMessages", "buildFromString", "source", "path", "analyzeDependencies", "entryPoint", "extractEntryPoints", "baseDir", "entryPoints", "result", "entry", "collectFilesFromGlob", "xBuildError", "VariantService", "name", "lifecycle", "buildConfig", "argv", "xBuildError", "TypescriptService", "config", "error", "inject", "ConfigurationService", "files", "result", "build", "isBuildResultError", "common", "deepMerge", "diagnostics", "TypesError", "errors", "warnings", "warning", "d", "ts", "context", "decl", "shouldBundle", "outDir", "err", "hooks", "onStart", "onResolve", "onLoad", "onEnd", "onSuccess", "type", "mkdir", "writeFile", "join", "defineFromConfig", "define", "key", "value", "extractEntryPoints", "variantConfig", "commonConfig", "filePath", "lastDotIndex", "esbuild", "metafile", "analyzeDependencies", "file", "relativePath", "relative", "resolve", "path", "content", "target", "readFile", "LifecycleProvider", "variantName", "argv", "inject", "FilesModel", "handler", "name", "build", "context", "errors", "id", "err", "names", "warnings", "hookContext", "hook", "result", "buildResult", "duration", "args", "hookResult", "loader", "filePath", "resolve", "snapshot", "contents", "readFile", "ts", "highlightCode", "ts", "IFDEF_DIRECTIVE", "transformToFunction", "fnName", "node", "sourceFile", "hasExport", "prefix", "transformFunctionLikeNode", "asyncPrefix", "m", "params", "p", "returnType", "body", "getFunctionBody", "bodyText", "transformToIIFE", "suffix", "isDefinitionMet", "defineName", "directiveName", "defines", "isDefined", "astDefineVariable", "decl", "init", "state", "defineArg", "callbackArg", "varName", "astDefineCallExpression", "outerSuffix", "constPrefix", "ts", "createRequire", "InlineError", "xBuildBaseError", "error", "lineOffset", "getErrorMetadata", "formatStack", "Script", "createContext", "sandboxExecute", "code", "sandbox", "options", "script", "context", "evaluateCode", "code", "state", "node", "map", "data", "buildFromString", "module", "require", "createRequire", "context", "createSandboxContext", "result", "sandboxExecute", "err", "handleExecutionError", "fileName", "dirname", "mapText", "start", "line", "inject", "FrameworkService", "error", "InlineError", "findFunctionByName", "functionName", "sourceFile", "foundFunction", "visit", "ts", "findFunctionInVariableStatement", "decl", "wrapInIIFE", "getVariableKeyword", "flags", "extractExecutableCode", "extractFromIdentifier", "functionDeclaration", "addFunctionNotFoundWarning", "character", "relativePath", "relative", "astInlineVariable", "init", "hasExport", "arg", "varKeyword", "exportPrefix", "varName", "astInlineCallExpression", "args", "TS_JS_REGEX", "MACRO_FUNCTIONS", "nodeContainsMacro", "node", "sourceFile", "m", "expectedArgCount", "fnName", "isVariableStatement", "replacements", "state", "replacement", "decl", "suffix", "call", "init", "ts", "a", "line", "character", "esBuildError", "hasExport", "astInlineVariable", "astDefineCallExpression", "astDefineVariable", "isCallExpression", "callExpr", "astInlineCallExpression", "macroCallExpression", "callNode", "astProcess", "variant", "fnToRemove", "hasMacro", "stack", "kind", "identifier", "parent", "parentText", "key", "children", "i", "replacementsArray", "b", "replacementInfo", "start", "end", "highlightCode", "transformerDirective", "context", "args", "loader", "stage", "contents", "variantName", "options", "argv", "content", "MACRO_PREFIX", "IFDEF_REGEX", "getLineAndColumn", "text", "name", "file", "index", "line", "i", "startLinePosition", "isCommentLine", "content", "lineStart", "char1", "char2", "analyzeMacroMetadata", "variant", "context", "metadata", "warnings", "filesModel", "inject", "FilesModel", "defines", "files", "resolvedFile", "match", "matchIndex", "fn", "directive", "define", "isDefined", "BuildService", "argv", "inject", "ConfigurationService", "callback", "config", "files", "instance", "result", "variant", "names", "errorList", "results", "buildPromises", "variantName", "variantInstance", "enhancedBuildResult", "error", "isBuildResultError", "context", "analyzeMacroMetadata", "errors", "err", "dispose", "obj1", "obj2", "key", "xBuildError", "name", "lifecycle", "LifecycleProvider", "VariantService", "transformerDirective", "overwriteConfig", "config", "inject", "ConfigurationService", "patchConfig", "platform", "exit", "stdin", "stdout", "xterm", "EXIT_SIGNALS", "KEY_MAPPINGS", "COMMAND_MAP", "generateHelp", "activeUrl", "shortcuts", "prefix", "xterm", "addShortcut", "key", "description", "KEY_MAPPINGS", "clearScreen", "repeatCount", "stdout", "readline", "openInBrowser", "url", "command", "COMMAND_MAP", "platform", "exec", "handleKeypress", "code", "reload", "help", "EXIT_SIGNALS", "exit", "verbose", "inject", "ConfigurationService", "cfg", "patchConfig", "init", "stdin", "helpString", "existsSync", "runInThisContext", "createRequire", "transpileOptions", "configFileProvider", "path", "existsSync", "inject", "FilesModel", "map", "code", "buildFiles", "FrameworkService", "createRequire", "resolve", "runInThisContext", "config", "VMRuntimeError", "_VMRuntimeError", "xBuildBaseError", "originalError", "options", "error", "errorList", "xterm", "xterm", "okColor", "textColor", "infoColor", "warnColor", "pathColor", "errorColor", "keywordColor", "mutedColor", "INDENT", "KILOBYTE", "MEGABYTE", "DASH_SYMBOL", "ARROW_SYMBOL", "ERROR_SYMBOL", "WARNING_SYMBOL", "createActionPrefix", "action", "symbol", "infoColor", "prefix", "formatByteSize", "bytes", "formatDiagnosticLocation", "diagnostic", "filePath", "relative", "lineNumber", "warnColor", "columnNumber", "pathColor", "appendErrorMetadata", "buffer", "error", "codeLines", "stackTrace", "line", "logErrorMetadata", "formattedCode", "formatTypescriptDiagnostic", "codeColor", "location", "diagnosticCode", "message", "mutedColor", "textColor", "logTypescriptDiagnostic", "errorColor", "appendTypesError", "diagnosticCount", "xterm", "appendGenericIssue", "issue", "color", "title", "xBuildBaseError", "appendIssue", "TypesError", "logBuildIssues", "issues", "issueType", "isError", "totalIssueCount", "logBuildOutputs", "metafile", "outputEntries", "outputCount", "okColor", "outputPath", "info", "size", "logError", "isBuildResultError", "VMRuntimeError", "xBuildError", "logTypeDiagnostic", "name", "diagnostics", "hasErrors", "nameColor", "keywordColor", "statusSymbol", "status", "logTypeDiagnostics", "errors", "logBuildStart", "variantName", "logMacroReplacements", "variant", "stage", "inject", "ConfigurationService", "replaceInfo", "source", "replacement", "code", "resultCode", "logBuildEnd", "duration", "buildResult", "warnings", "enhancedBuildResult", "isSuccess", "DEFAULT_IGNORE_PATTERNS", "WATCH_IGNORE_PATTERNS", "configureEntryPoints", "config", "args", "ignorePatterns", "collectFilesFromGlob", "cwd", "applyCommandLineOverrides", "variants", "variant", "collectWatchIgnorePatterns", "startServer", "urlString", "serveDir", "serverConfig", "host", "port", "url", "createActionPrefix", "keywordColor", "pathColor", "ServerModule", "executeBuild", "buildService", "distPath", "join", "rmSync", "diagnostics", "logTypeDiagnostics", "result", "name", "errors", "error", "status", "errorColor", "ERROR_SYMBOL", "logError", "startWatchMode", "watchService", "WatchService", "init", "changedFiles", "configFileProvider", "prefix", "mutedColor", "main", "bannerComponent", "argvService", "inject", "ArgvModule", "preConfig", "userArgs", "overwriteConfig", "BuildService", "logBuildEnd", "logBuildStart"]
|
|
8
8
|
}
|