@rzl-zone/build-tools 0.0.8 → 0.0.10
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/.references/index.d.cts +1 -1
- package/dist/.references/index.d.ts +1 -1
- package/dist/bundler/rolldown.cjs +2 -2
- package/dist/bundler/rolldown.d.cts +2 -2
- package/dist/bundler/rolldown.d.ts +2 -2
- package/dist/bundler/rolldown.js +1 -1
- package/dist/bundler/tsdown.cjs +3 -3
- package/dist/bundler/tsdown.d.cts +2 -2
- package/dist/bundler/tsdown.d.ts +2 -2
- package/dist/bundler/tsdown.js +3 -3
- package/dist/bundler/utils.cjs +2 -2
- package/dist/bundler/utils.d.cts +2 -2
- package/dist/bundler/utils.d.ts +2 -2
- package/dist/bundler/utils.js +2 -2
- package/dist/{client-C0ZDdv36.js → client-BmfdVI22.js} +3 -3
- package/dist/client-BmfdVI22.js.map +1 -0
- package/dist/{client-BczBMDS6.cjs → client-DnTjQyyo.cjs} +3 -3
- package/dist/client-DnTjQyyo.cjs.map +1 -0
- package/dist/commander-kit/index.cjs +5 -5
- package/dist/commander-kit/index.cjs.map +1 -1
- package/dist/commander-kit/index.d.cts +3 -3
- package/dist/commander-kit/index.d.ts +3 -3
- package/dist/commander-kit/index.js +5 -5
- package/dist/commander-kit/index.js.map +1 -1
- package/dist/{extra-CDUxrgcT.d.ts → extra-CYpD3D9p.d.ts} +2 -2
- package/dist/{extra-CnJhk-pp.d.cts → extra-Dc_eIyiW.d.cts} +2 -2
- package/dist/{fast-globe-options-B4edSsWz.d.cts → fast-globe-options-BtIrCNb6.d.cts} +3 -3
- package/dist/{fast-globe-options-CMxk8gD9.d.ts → fast-globe-options-CZ-9wIKV.d.ts} +3 -3
- package/dist/{helper-2m5t07Qe.js → helper-CWU8QYq3.js} +2 -2
- package/dist/{helper-2m5t07Qe.js.map → helper-CWU8QYq3.js.map} +1 -1
- package/dist/{helper-BRO-s2fI.cjs → helper-DvCvgDxy.cjs} +2 -2
- package/dist/{helper-BRO-s2fI.cjs.map → helper-DvCvgDxy.cjs.map} +1 -1
- package/dist/{identity-1Zk_fLSI.cjs → identity-D192lL-_.cjs} +6 -6
- package/dist/{identity-1Zk_fLSI.cjs.map → identity-D192lL-_.cjs.map} +1 -1
- package/dist/{identity-CCGqrTRL.js → identity-xuDCNgfm.js} +6 -6
- package/dist/{identity-CCGqrTRL.js.map → identity-xuDCNgfm.js.map} +1 -1
- package/dist/{index-De-ymoL3.d.cts → index-1FKLQ7ah.d.cts} +2 -2
- package/dist/{index-B3ChWfIR.d.cts → index-CEsO_rxz.d.ts} +2 -2
- package/dist/{index-DPGJBhEK.d.ts → index-DW1JFluR.d.cts} +2 -2
- package/dist/{index-C-jXEIZS.d.ts → index-qft-a5kh.d.ts} +2 -2
- package/dist/index.cjs +6 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/{package-banner-BAbZghTB.cjs → package-banner-BHyF8RdG.cjs} +5 -5
- package/dist/{package-banner-BAbZghTB.cjs.map → package-banner-BHyF8RdG.cjs.map} +1 -1
- package/dist/{package-banner-BM84W-TO.js → package-banner-BmLNyezO.js} +5 -5
- package/dist/{package-banner-BM84W-TO.js.map → package-banner-BmLNyezO.js.map} +1 -1
- package/dist/{server-DH801yY1.js → server-BA7ruG1h.js} +3 -3
- package/dist/{server-DH801yY1.js.map → server-BA7ruG1h.js.map} +1 -1
- package/dist/{server-DL-uLx4N.cjs → server-DZvrqlyy.cjs} +3 -3
- package/dist/{server-DL-uLx4N.cjs.map → server-DZvrqlyy.cjs.map} +1 -1
- package/dist/utils/client.cjs +2 -2
- package/dist/utils/client.d.cts +25 -7
- package/dist/utils/client.d.ts +25 -7
- package/dist/utils/client.js +2 -2
- package/dist/utils/server.cjs +2 -2
- package/dist/utils/server.d.cts +2 -2
- package/dist/utils/server.d.ts +2 -2
- package/dist/utils/server.js +2 -2
- package/package.json +3 -3
- package/dist/client-BczBMDS6.cjs.map +0 -1
- package/dist/client-C0ZDdv36.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isString","isArray","resolvePatternOptions","defaultPatternOptions","isNonEmptyString","traverseImport","t","picocolors","normalizeSpaces","formatOptionValue","ICONS","isNonEmptyString","isError","joinLines","isNumber","isPlainObject","joinLinesLoose","toStringSet","resolvePatternOptions","fastGlob","sourceOfPatternOptions","fsExtra","EOL","CommandIdentity","isNonEmptyString","CommandIdentity","isNonEmptyString","isNumber","isPlainObject","isNonEmptyString","isUndefined","isBoolean","picocolors","joinLinesLoose","joinInline","plural","isArray","CommandIdentity","isSet","toObjectSet","path","fsExtra","resolvePatternOptions","defaultPatternOptions","EOL","flattenStrings","isArray","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","EOL","picocolors","resolvePatternOptions","defaultPatternOptions","path","generatePackageBanner","EOL","isNonEmptyString","CommandIdentity","joinLinesLoose","toStringSet","sourceOfPatternOptions","fastGlob","pcr","fsExtra","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","isRegExp","EOL","picocolors","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","EOL","picocolors","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","EOL","safeStableStringify","picocolors","joinLinesLoose","EOL","formatOptionValue","isNonEmptyString","resolvePatternOptions","defaultPatternOptions","EOL","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra"],"sources":["../src/_internal/utils/log-level.ts","../src/core/clean/_internal/clean-build-artifacts-constant.ts","../src/_internal/utils/source.ts","../src/_internal/utils/logger-builder.ts","../src/core/clean/_internal/clean-build-artifacts-utils.ts","../src/core/clean/_internal/clean-build-artifacts-core.ts","../src/core/clean/_internal/clean-build-artifacts-runner.ts","../src/core/clean/clean-js-build-artifacts.ts","../src/core/clean/clean-types-build-artifacts.ts","../src/core/copy/file-to-dest/index.ts","../src/core/ensure/css-import/index.ts","../src/core/ensure/final-newline/index.ts","../src/core/generate/reference-index/index.ts","../src/core/inject/banner/index.ts","../src/core/inject/directive/index.ts","../src/core/normalize/js-build-newlines/index.ts","../src/core/run/command/runCommand.ts","../src/core/run/command/runCommandCapture.ts","../src/core/run/command/utils.ts","../src/core/strip/js-comments/index.ts"],"sourcesContent":["import type { LoggingOptions, LogLevel } from \"@/types\";\n\nimport { isArray, isString } from \"./helper\";\n\n/** ----------------------------------------------------------------\n * * ***Type guard to check if a value is a valid LogLevel.***\n * ----------------------------------------------------------------\n *\n * Checks if the given `value` is a string and corresponds to one\n * of the valid log levels defined in `LOG_LEVEL_PRIORITY`.\n *\n * - **Valid log levels:**\n * - `\"silent\"`.\n * - `\"error\"`.\n * - `\"info\"`.\n * - `\"debug\"`.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is a valid `LogLevel`, `false` otherwise.\n *\n * @example\n * ```ts\n * isLogLevel(\"info\"); // ➔ true\n * isLogLevel(\"verbose\"); // ➔ false\n * isLogLevel(123); // ➔ false\n * ```\n *\n * @internal\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && value in LOG_LEVEL_PRIORITY;\n}\n\n/** ----------------------------------------------------------------\n * * ***Default log level constant.***\n * ----------------------------------------------------------------\n *\n * Defines the default log level to be used when no explicit log level\n * is provided or fallback values are invalid.\n *\n * - Value: `\"info\"`.\n * - Guaranteed to be a valid `LogLevel`.\n *\n * @internal\n */\nexport const DEFAULT_LOG_LEVEL = \"info\" satisfies LogLevel;\n\n/** ----------------------------------------------------------------\n * * ***Verbose log levels array.***\n * ----------------------------------------------------------------\n *\n * Defines log levels considered verbose for more detailed logging.\n *\n * - Includes: `\"info\"` and `\"debug\"`.\n * - Used for enabling detailed log output in verbose modes.\n * - Readonly tuple of type `readonly LogLevel[]`.\n *\n * @internal\n */\nexport const VERBOSE_LOG = [\"info\", \"debug\"] as const;\n\n/** ----------------------------------------------------------------\n * * ***Log level priority mapping.***\n * ----------------------------------------------------------------\n *\n * @internal\n */\nexport const LOG_LEVEL_PRIORITY = Object.freeze({\n silent: 0,\n error: 1,\n info: 2,\n debug: 3\n});\n\n/** ----------------------------------------------------------------\n * * ***Resolves the effective log verbosity level.***\n * ----------------------------------------------------------------\n *\n * Resolves the final log level used by the logger in a **fully defensive**\n * manner.\n *\n * - **Behavior:**\n * - Uses the user-provided `logLevel` **only if it is a valid `LogLevel`**.\n * - Falls back when:\n * - `logLevel` is `undefined`.\n * - `logLevel` is invalid or unsupported.\n *\n * - **Fallback guarantees:**\n * - If the provided `fallback` is **also invalid**, the resolver\n * **forcibly falls back to the built-in default** (`\"info\"`).\n * - This ensures the logger **never operates with an invalid log level**.\n *\n * - **Resolution order (highest priority ➔ lowest):**\n * 1. Valid public option (`options.logLevel`).\n * 2. Valid fallback parameter (`fallback`).\n * 3. Built-in default (`\"info\"`).\n *\n * @remarks\n * This function is intentionally strict to prevent misconfiguration\n * from silencing logs or breaking log-level comparisons at runtime.\n *\n * @internal\n */\nexport function resolveLogVerbosity(\n options?: LoggingOptions,\n fallback: LogLevel = DEFAULT_LOG_LEVEL\n): LogLevel {\n const input = options?.logLevel;\n\n if (isLogLevel(input)) return input;\n\n return isLogLevel(fallback) ? fallback : DEFAULT_LOG_LEVEL;\n}\n\n/** ----------------------------------------------------------------\n * * ***Checks whether a log at a given level should be emitted.***\n * ----------------------------------------------------------------\n *\n * Determines whether a log message should be emitted based on\n * the **resolved current log verbosity level**.\n *\n * - **Behavior:**\n * - Supports a single target level or multiple target levels.\n * - The `current` level is used **only if it is a valid `LogLevel`**.\n * - When `current` is invalid:\n * - Falls back to `fallbackIfInvalid`.\n * - If `fallbackIfInvalid` is also invalid, it is **forcibly**\n * resolved to the built-in default (`\"info\"`).\n *\n * - **Emission rule:**\n * - A log is emitted when the resolved current level's priority\n * is **greater than or equal to** any of the target level priorities.\n *\n * - **Guarantees:**\n * - This function **never compares invalid log levels**.\n * - Priority lookup is always safe and deterministic.\n *\n * @remarks\n * This strict resolution prevents misconfiguration from silently\n * disabling logs or causing invalid priority comparisons.\n *\n * @internal\n */\nexport function canLog(\n current: LogLevel,\n target: LogLevel | readonly LogLevel[],\n fallbackIfInvalid: LogLevel = DEFAULT_LOG_LEVEL\n): boolean {\n const fallbackLog = isLogLevel(fallbackIfInvalid)\n ? fallbackIfInvalid\n : DEFAULT_LOG_LEVEL;\n const resolvedCurrent: LogLevel = isLogLevel(current) ? current : fallbackLog;\n\n const targets = isString(target)\n ? [target]\n : isArray(target)\n ? target\n : [fallbackLog];\n\n return targets.some(\n (level) => LOG_LEVEL_PRIORITY[resolvedCurrent] >= LOG_LEVEL_PRIORITY[level]\n );\n}\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n defaultPatternOptions,\n type PatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport { DEFAULT_LOG_LEVEL } from \"@/_internal/utils/log-level\";\n\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **clean build artifact** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`}.\n * - {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_CLEAN_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **clean build artifact** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`}.\n * - {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}.\n */\nexport const resolvedCleanPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_CLEAN_PATTERN_POLICY);\n\n/** @internal Default Options for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport const DEFAULT_CLEAN_OPTION = {\n removeSourceMap: false,\n removeRegion: true,\n removeAdjacentEmptyLines: false,\n patternOptions: resolvedCleanPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies CleanCoreOptions;\n","import type { NodePath } from \"@babel/traverse\";\n\nimport * as t from \"@babel/types\";\nimport { parse } from \"@babel/parser\";\nimport traverseImport from \"@babel/traverse\";\n\nimport { isNonEmptyString } from \"@/_internal/utils/helper\";\n\n/** @internal */\nexport const USE_STRICT_RE = /^['\"]use strict['\"];?\\s*$/gm;\n/** @internal */\nexport const SHEBANG_RE = /^#![^\\r\\n]*\\r?\\n/;\n/** @internal */\nexport const BANNER_RE = /^(?:\\/\\*![\\s\\S]*?\\*\\/\\s*)+/;\n\n/** ----------------------------------------------------------------\n * * ***Matches JavaScript build output files.***\n * ----------------------------------------------------------------\n *\n * Includes common formats such as:\n * `.js`, `.mjs`, `.cjs`, `.esm.js`, and `.module.js`.\n *\n * @internal\n */\nexport const JS_OUTPUT_FILE_RE = /\\.(?:js|mjs|cjs|esm\\.js|module\\.js)$/i;\n\n/** ----------------------------------------------------------------\n * * ***Matches canonical JavaScript module output extensions.***\n * ----------------------------------------------------------------\n *\n * Matches Node.js standard module formats:\n * - `.js`.\n * - `.mjs`.\n * - `.cjs`.\n *\n * ⚠️ This regex also technically matches `.cmjs`,\n * though such files are extremely rare in practice.\n *\n * - ***Intended for:***\n * - strict Node.js module outputs.\n * - internal tooling where minimal matching is desired.\n *\n * @internal\n */\nexport const JS_MODULE_OUTPUT_FILE_RE = /\\.(?:c?m?js)$/i;\n\n/** ----------------------------------------------------------------\n * * ***Matches TypeScript declaration output files.***\n * ----------------------------------------------------------------\n *\n * Includes standard declaration formats:\n * `.d.ts`, `.d.mts`, and `.d.cts`.\n *\n * @internal\n */\nexport const TS_DECLARATION_FILE_RE = /\\.d\\.(?:ts|mts|cts)$/i;\n\n/** ----------------------------------------------------------------\n * * ***Matches region marker comments in source files.***\n * ----------------------------------------------------------------\n *\n * Regular expression that detects single-line region marker comments\n * commonly used for code folding and logical section grouping.\n *\n * - ***Supported markers:***\n * - `// #region`.\n * - `// #endregion`.\n *\n * - ***Matching behavior:***\n * - Allows any number of leading spaces or tabs.\n * - Requires a single-line comment prefix (`//`).\n * - Allows zero or more spaces between `//` and `#`\n * (e.g. `//#region` and `// #region` are both valid).\n * - Matches both opening (`#region`) and closing (`#endregion`) markers.\n * - Uses a word boundary (`\\b`) after `region` to prevent\n * false positives such as `#regionX`.\n * - Does **not** require the marker to be at the end of the line;\n * trailing text is allowed.\n *\n * - ***Typical use cases:***\n * - Parsing generated source files.\n * - Preserving or removing code folding regions.\n * - Detecting logical boundaries during code cleanup.\n *\n * @example\n * ```ts\n * REGION_RE.test(\"//#region\");\n * // ➔ true\n *\n * REGION_RE.test(\"// #region utils\");\n * // ➔ true\n *\n * REGION_RE.test(\" //#endregion helpers\");\n * // ➔ true\n *\n * REGION_RE.test(\"// #regionX\");\n * // ➔ false\n * ```\n *\n * @internal\n */\nexport const REGION_RE = /^[ \\t]*\\/\\/\\s*#(?:end)?region\\b.*$/i;\n// export const REGION_RE = /^[ \\t]*\\/\\/\\s*#(?:end)?region\\b/;\n\n/** ----------------------------------------------------------------\n * * ***Matches source path comments emitted by bundlers or transpilers.***\n * ----------------------------------------------------------------\n *\n * Example:\n * ```js\n * // src/index.ts\n * // node_modules/react/index.js\n * ```\n *\n * @internal\n */\nexport const SOURCE_PATH_RE =\n /^[ \\t]*\\/\\/\\s*(?:\\.\\.\\/|\\.\\/)*[^ \\n]*?(?:src|node_modules)\\//;\n\n/** ----------------------------------------------------------------\n * * ***Matches ESLint directive comments.***\n * ----------------------------------------------------------------\n *\n * Example:\n * ```js\n * // eslint-disable-next-line\n * ```\n *\n * @internal\n */\nexport const ESLINT_RE = /^[ \\t]*\\/\\/\\s*eslint/;\n\n/** ----------------------------------------------------------------\n * * ***Matches source map reference comments.***\n * ----------------------------------------------------------------\n *\n * Example:\n * ```js\n * //# sourceMappingURL=index.js.map\n * //@ sourceMappingURL=index.js.map\n * //@ sourceMappingURL=index.d.ts.map\n * //# sourceMappingURL=index.d.cts.map\n * //# sourceMappingURL=index.d.mts.map\n * ```\n *\n * @internal\n */\nexport const SOURCE_MAP_RE = /^[ \\t]*\\/\\/[#@]\\s*sourceMappingURL=\\S+\\s*$/;\n\n/** ----------------------------------------------------------------\n * * ***Matches important comments that must be preserved.***\n * ----------------------------------------------------------------\n *\n * Regular expression that detects comments which **must not be removed**\n * during comment stripping or source cleanup.\n *\n * These comments are typically required for **legal compliance** or\n * **bundler/minifier optimizations** and therefore should be preserved\n * when generating distributable JavaScript.\n *\n * - ***Supported comment annotations:***\n * - `/*! ... *\\/`\n * Important \"bang\" comments typically used for license banners.\n *\n * - `@license`\n * - `@preserve`\n * - `@copyright`\n * - Legal or attribution metadata that must remain in distributed code.\n *\n * - `@cc_on`\n * Legacy Internet Explorer conditional compilation directive.\n *\n * - `@__PURE__`\n * - `@__INLINE__`\n * - `@__NOINLINE__`\n * - `@__NO_SIDE_EFFECTS__`\n * Optimization hints used by bundlers and minifiers for\n * tree-shaking and inlining decisions.\n *\n * - ***Matching behavior:***\n * - Detects \"bang comments\" beginning with `!` inside block comments.\n * - Matches important license or preservation annotations.\n * - Detects bundler optimization directives.\n * - Intended for use in comment-stripping utilities.\n *\n * - ***Typical use cases:***\n * - Stripping non-essential comments during build.\n * - Preserving license banners in distributed packages.\n * - Keeping optimization hints for bundlers and minifiers.\n * - Maintaining compatibility with tooling such as Rollup,\n * Webpack, Terser, and esbuild.\n *\n * @example\n * ```ts\n * IMPORTANT_COMMENT.test(\"! my-lib v1.0\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"@license MIT\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"@__PURE__\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"@__NO_SIDE_EFFECTS__\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"random comment\");\n * // ➔ false\n * ```\n *\n * @internal\n * @removeDocRuntime\n */\nexport const IMPORTANT_COMMENT =\n /^!|@license|@preserve|@copyright|@cc_on|@__(PURE|INLINE|NOINLINE|NO_SIDE_EFFECTS)__/;\n\n/** ----------------------------------------------------------------\n * * ***Matches empty or whitespace-only lines.***\n * ----------------------------------------------------------------\n *\n * Regular expression used to detect lines that contain **no visible\n * characters**, only whitespace or nothing at all.\n *\n * - ***Matching rules:***\n * - Matches an empty string.\n * - Matches lines containing only whitespace characters.\n * - Accepts spaces, tabs, and other standard whitespace.\n * - Rejects any line containing visible characters.\n *\n * This regex is typically used for **filtering or skipping blank lines**\n * during text or source code processing.\n *\n * @internal\n */\nexport const EMPTY_LINE_RE = /^\\s*$/;\n\n/** ----------------------------------------------------------------\n * * ***Matches documentation comments marked as removable.***\n * ----------------------------------------------------------------\n *\n * Regular expression that detects **documentation comments explicitly\n * marked for removal** during build output cleanup.\n *\n * This is intended for stripping development-only documentation from\n * compiled JavaScript while keeping important comments intact.\n *\n * ----------------------------------------------------------------\n *\n * - ***Supported directive tags***\n *\n * - `@removeDoc`\n * Marks a documentation block as **safe to remove** during\n * build cleanup.\n *\n * - `@keepDoc`\n * Explicitly marks a documentation block that **must be preserved**.\n *\n * ----------------------------------------------------------------\n *\n * - ***Matching behavior***\n *\n * - Matches block documentation comments containing `@removeDoc`.\n * - Ignores documentation blocks containing `@keepDoc`.\n * - Intended for use in **comment stripping utilities**.\n *\n * ----------------------------------------------------------------\n *\n * - ***Typical use cases***\n *\n * - Removing internal documentation from distributed builds.\n * - Keeping only public-facing documentation comments.\n * - Reducing bundle size while preserving intentional comments.\n *\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * REMOVABLE_DOC_COMMENT.test(\"/** \\\\@removeDoc internal helper *\\/\");\n * // ➔ true\n *\n * REMOVABLE_DOC_COMMENT.test(\"/** \\\\@keepDoc public API *\\/\");\n * // ➔ false\n *\n * REMOVABLE_DOC_COMMENT.test(\"/** normal doc comment *\\/\");\n * // ➔ false\n * ```\n *\n * @internal\n * @removeDocRuntime\n */\nexport const REMOVABLE_DOC_COMMENT =\n /^\\/\\*\\*(?![\\s\\S]*@keepDoc)[\\s\\S]*@removeDoc[\\s\\S]*?\\*\\//;\n\n/** ----------------------------------------------------------------\n * * ***Determine if a comment should be removed based on directives runtime.***\n * ----------------------------------------------------------------\n *\n * This helper ensures that the directive detection only runs **inside\n * comment text**, not raw source. It applies the following logic:\n *\n * 1. `@keepDocRuntime` ➔ always force keep.\n * 2. `@removeDocRuntime` ➔ always force remove.\n * 3. No tag ➔ leave as default (undefined).\n *\n * ----------------------------------------------------------------\n *\n * @param commentText - inner text of the comment (from parser like Acorn)\n * @returns `true` if forced to remove, `false` if forced to keep, `undefined` if default\n *\n * @example\n * ```ts\n * const commentText = \"* \\\\@removeDocRuntime Internal helper\";\n * const result = shouldRemoveDocRuntime(commentText);\n * console.log(result); // true\n *\n * const keepText = \"* \\\\@keepDoc public API\";\n * console.log(shouldRemoveDocRuntime(keepText)); // false\n *\n * const normalText = \"* normal comment\";\n * console.log(shouldRemoveDocRuntime(normalText)); // undefined\n * ```\n *\n * @internal\n * @removeDocRuntime\n */\nexport function shouldRemoveDocRuntime(\n commentText: string\n): boolean | undefined {\n const text = commentText.trim();\n\n const hasRemoveDocRuntime = /[@]removeDocRuntime\\b/.test(text);\n const hasKeepDocRuntime = /[@]keepDocRuntime\\b/.test(text);\n\n if (hasRemoveDocRuntime && hasKeepDocRuntime) {\n return true; // force remove\n }\n\n if (hasKeepDocRuntime) {\n return false; // force keep\n }\n\n if (hasRemoveDocRuntime) {\n return true; // force remove\n }\n\n return undefined; // default behavior\n}\n/** ----------------------------------------------------------------\n * * ***Matches files containing only top-level `\"use *\"` directives.***\n * ----------------------------------------------------------------\n *\n * Regular expression used to verify whether a source file consists\n * exclusively of one or more `\"use <directive>\"` statements.\n *\n * - ***Matching rules:***\n * - Matches one or more `\"use *\"` directives.\n * - Supports single or double quoted directives.\n * - Allows optional semicolons and trailing whitespace.\n * - Rejects any executable code or non-directive content.\n *\n * This regex is intended for **heuristic internal validation**\n * and does not perform full JavaScript parsing.\n *\n * @internal\n */\nexport const DIRECTIVE_RE = /^((?:(?:\"use\\s+\\w+\"|'use\\s+\\w+');\\s*)+)/;\n\n/** ----------------------------------------------------------------\n * * ***Matches executable code following top-level `\"use *\"` directives.***\n * ----------------------------------------------------------------\n *\n * Regular expression used to detect whether a source file contains\n * any content **after** one or more leading `\"use <directive>\"`\n * statements.\n *\n * - ***Matching rules:***\n * - Requires at least one `\"use <word>\"` directive at the start.\n * - Supports single or double quoted directives.\n * - Allows optional semicolons and trailing whitespace.\n * - Matches any remaining content after the directives.\n *\n * This regex is intended for **heuristic internal checks** and does\n * not perform full JavaScript syntax validation.\n *\n * @internal\n */\nexport const CODE_AFTER_DIRECTIVE_RE = /^(['\"]use\\s+\\w+['\"];?\\s*)+[\\s\\S]+$/;\n\n/** ----------------------------------------------------------------\n * * ***Matches files that MUST NOT contain comments.***\n * ----------------------------------------------------------------\n *\n * Identifies structured, machine-generated, or strict-spec files\n * that do NOT support JavaScript-style comments and should never\n * be mutated by comment injectors or build transformers.\n *\n * ----------------------------------------------------------------\n * Included Categories\n *\n * 1) Strict JSON Specification (RFC 8259 compliant):\n * - `.json`.\n * - `.map` (Source maps).\n * - `.webmanifest`.\n * - `.har`.\n * - `.geojson`.\n * - `.topojson`.\n *\n * 2) Lock-files & Dependency Metadata (machine-generated):\n * - `package-lock.json`.\n * - `composer.lock`.\n * - `bun.lockb`.\n *\n * 3) Tooling / Compiler Artifacts:\n * - `.tsbuildinfo`.\n *\n * ----------------------------------------------------------------\n * Important Notes\n *\n * - JSON strictly disallows comments.\n * - Source maps are JSON and must remain spec-compliant.\n * - Lock-files must never be altered by formatters or comment injectors.\n * - This regex is intentionally defensive for build tooling contexts.\n *\n * ----------------------------------------------------------------\n * Explicitly NOT Included:\n *\n * - `.jsonc` (supports comments).\n * - `.yaml` / `.yml` (supports comments).\n * - `.toml` (supports comments).\n * - `.xml` (supports comments).\n *\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * if (NON_COMMENTABLE_FILE_RE.test(filePath)) {\n * // skip comment injection / stripping\n * }\n * ```\n *\n * @internal\n */\nexport const NON_COMMENTABLE_FILE_RE =\n /(?:^|[\\\\/])(?:package-lock\\.json|composer\\.lock|bun\\.lockb)$|\\.(?:json|map|webmanifest|har|geojson|topojson|tsbuildinfo)$/i;\n// export const NON_COMMENTABLE_FILE_RE =\n// /(?:^|[\\\\/])(?:package-lock\\.json|composer\\.lock|bun\\.lockb)$|(?:\\.(?:json|map|webmanifest|har|geojson|topojson|tsbuildinfo))$/i;\n\n/** ----------------------------------------------------------------\n * * ***Checks whether a file contains only directive statements.***\n * ----------------------------------------------------------------\n *\n * Determines if the provided source content is composed solely of\n * top-level `\"use *\"` directives, or is effectively empty.\n *\n * - ***Evaluation rules:***\n * - Empty or whitespace-only content is considered valid.\n * - Content containing only `\"use *\"` directives returns `true`.\n * - Any additional code or statements cause a `false` result.\n *\n * This utility is primarily used to decide whether a file is\n * **directive-only** and safe for directive injection or hoisting.\n *\n * @param {string} content - JavaScript source content.\n *\n * @returns {boolean}\n * `true` if the file contains only directives or is empty,\n * otherwise `false`.\n *\n * @example\n * ```ts\n * isDirectiveOnlyFile('\"use strict\";\\n\"use client\";');\n * // ➔ true\n * ```\n *\n * @example\n * ```ts\n * isDirectiveOnlyFile('\"use client\";\\nconst a = 1;');\n * // ➔ false\n * ```\n *\n * @internal\n */\nexport function isDirectiveOnlyFile(content: string): boolean {\n const trimmed = content.trim();\n if (!trimmed) return true;\n\n const { body } = extractAndHoistBanner(trimmed);\n const { directives, rest } = extractDirectives(body);\n\n return isNonEmptyString(directives) && !isNonEmptyString(rest);\n}\n\n/** ----------------------------------------------------------------\n * * ***Determines whether executable code exists beyond directives.***\n * ----------------------------------------------------------------\n *\n * Checks if a source file contains **executable JavaScript code**\n * after removing non-executable preamble content.\n *\n * - ***The following elements are ignored during evaluation:***\n * - Leading shebang (if present).\n * - Banner comments (`/*! ... *\\/`).\n * - Top-level `\"use *\"` directive statements.\n *\n * - ***Evaluation rules:***\n * - Empty or whitespace-only files are treated as **executable**.\n * - Files containing only directives and/or banners return `false`.\n * - Any remaining non-empty content is considered executable code.\n *\n * This utility performs **structural heuristics** and does not\n * rely on full JavaScript parsing.\n *\n * @param {string} content - JavaScript source content.\n *\n * @returns {boolean}\n * `true` if executable code exists after directives,\n * otherwise `false`.\n *\n * @example\n * ```ts\n * hasExecutableCode('#!/usr/bin/env node\\n\"use strict\";\\nconst a = 1;');\n * // ➔ true\n * ```\n *\n * @example\n * ```ts\n * hasExecutableCode('\"use client\";\\n/*! banner *\\/');\n * // ➔ false\n * ```\n *\n * @internal\n */\nexport function hasExecutableCode(content: string): boolean {\n const trimmed = content.trim();\n\n const { body } = extractAndHoistBanner(trimmed);\n const { rest } = extractDirectives(body);\n\n return isNonEmptyString(rest);\n}\n\n/** @internal */\nexport type RemoveCommentsOptions = {\n /** Whether source map comments should be considered removable.\n *\n * @default false\n */\n removeSourceMap?: boolean;\n\n /** Whether source region comments should be considered removable.\n *\n * @default true\n */\n removeRegion?: boolean;\n};\n\nexport const defaultCommentOptions: RemoveCommentsOptions = {\n removeRegion: true,\n removeSourceMap: false\n};\n\n/** ----------------------------------------------------------------\n * * ***Determines whether a line is a removable build artifact comment.***\n * ----------------------------------------------------------------\n *\n * - ***This includes:***\n * - source path comments (`// src/...`, `// node_modules/...`).\n * - source region comments,\n * see {@link REGION_RE | `REGION_RE`}.\n * - ESLint directive comments.\n * - source map comments (optional).\n *\n * @param {string|null|undefined} line - A single line of file content.\n * @param {RemoveCommentsOptions} options - Options to check target comment.\n * @returns `true` if the line matches a removable comment pattern.\n *\n * @internal\n */\nexport const isTargetComment = (\n line: string | null | undefined,\n options: RemoveCommentsOptions = defaultCommentOptions\n) => {\n if (!isNonEmptyString(line)) return false;\n if (SOURCE_PATH_RE.test(line)) return true;\n if (ESLINT_RE.test(line)) return true;\n if (options.removeRegion && REGION_RE.test(line)) return true;\n if (options.removeSourceMap && SOURCE_MAP_RE.test(line)) return true;\n return false;\n};\n\n/** ----------------------------------------------------------------\n * * ***Checks whether a line is directly adjacent to a removable comment line.***\n * ----------------------------------------------------------------\n *\n * Used to optionally remove empty lines surrounding build artifact comments\n * to avoid leaving unnecessary visual gaps.\n *\n * @param {string[]} arr - Array of file lines.\n * @param {number} index - Current line index.\n * @param {RemoveCommentsOptions} options - Options to check target comment.\n * @returns `true` if an adjacent line matches a removable comment.\n *\n * @internal\n */\nexport const isAdjacentToTarget = (\n arr: string[],\n index: number,\n options: RemoveCommentsOptions = defaultCommentOptions\n) => {\n return (\n isTargetComment(arr[index - 1], options) ||\n isTargetComment(arr[index + 1], options)\n );\n};\n\n/** ----------------------------------------------------------------\n * * ***Represents supported JavaScript module kinds.***\n * ----------------------------------------------------------------\n *\n * Describes the detected module system of a JavaScript file.\n * Used internally to distinguish runtime module boundaries.\n *\n * @remarks\n * The classification is heuristic-based and intended primarily for\n * compiled or bundled output, not strict spec validation.\n *\n * @example\n * \"esm\" // ECMAScript module using `import` / `export`\n * \"cjs\" // CommonJS module using `require` / `module.exports`\n * \"umd\" // Universal Module Definition wrapper\n * \"iife\" // Immediately Invoked Function Expression bundle\n *\n * @internal\n */\nexport type ModuleKind = \"esm\" | \"cjs\" | \"umd\" | \"iife\";\n\n/** ----------------------------------------------------------------\n * * ***Detects module kind from JavaScript source content.***\n * ----------------------------------------------------------------\n *\n * Heuristic-based module format detection optimized for **compiled,\n * transpiled, or bundled JavaScript output**.\n *\n * This function analyzes the AST and attempts to infer the effective\n * runtime module boundary rather than relying purely on syntax shape.\n *\n * ----------------------------------------------------------------\n * #### 🔎 Priority Rules (highest ➔ lowest).\n * ----------------------------------------------------------------\n * 1. UMD environment wrapper detection\n * (`typeof exports` / `typeof module` + optional `define`) ➔ `\"umd\"`.\n *\n * 2. Runtime mutation of `module.exports` or `exports.*` ➔ `\"cjs\"`.\n *\n * 3. Real ESM `export` declarations ➔ `\"esm\"`.\n *\n * 4. ESM `import` declarations ➔ `\"esm\"`.\n *\n * 5. Top-level IIFE bundle without module system markers ➔ `\"iife\"`.\n *\n * 6. `require()` usage without explicit ESM ➔ `\"cjs\"`.\n *\n * 7. Fallback ➔ `\"esm\"`.\n *\n * ----------------------------------------------------------------\n * #### ⚠️ Limitations & Heuristic Caveats.\n * ----------------------------------------------------------------\n *\n * - Detection is heuristic-based and **not spec-guaranteed**.\n * - Designed primarily for bundled or transpiled build outputs.\n *\n * - UMD detection may fail when:\n * - The environment wrapper is heavily minified or obfuscated.\n * - `typeof exports` / `typeof module` checks are removed or transformed.\n * - The wrapper does not follow conventional UMD patterns.\n *\n * In such cases, UMD may be treated as `\"cjs\"`.\n *\n * - IIFE detection is intentionally conservative:\n * - Only top-level immediately-invoked function expressions are considered.\n * - If CommonJS mutations are present inside the IIFE,\n * the module will be classified as `\"cjs\"`.\n *\n * Therefore, certain bundled IIFE outputs may be classified as `\"cjs\"`\n * rather than `\"iife\"`.\n *\n * - Hybrid bundles (e.g. CJS wrapped in IIFE) are classified based on\n * detected runtime export behavior.\n *\n * ----------------------------------------------------------------\n * #### 🎯 Design Philosophy.\n * ----------------------------------------------------------------\n * This function favors **runtime export boundary detection**\n * over superficial syntax appearance.\n *\n * The goal is to determine how the file behaves when executed,\n * not how it was originally authored.\n *\n * @param code - JavaScript source code to analyze.\n * @returns Detected module kind:\n * `\"esm\"` | `\"cjs\"` | `\"umd\"` | `\"iife\"`.\n *\n * @internal\n */\nexport function detectModuleKindFromContent(code: string): ModuleKind {\n let hasImport = false;\n let hasExport = false;\n\n let hasModuleExports = false;\n let hasExportsMutation = false;\n let hasRequire = false;\n\n let hasDefine = false;\n let hasUMDEnvCheck = false;\n\n let hasTopLevelIIFE = false;\n\n const ast = parse(code, {\n sourceType: \"unambiguous\",\n plugins: [\"typescript\", \"jsx\"]\n });\n\n const traverse: typeof traverseImport =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (traverseImport as any).default ?? traverseImport;\n\n traverse(ast, {\n Program(path) {\n for (const node of path.node.body) {\n if (\n t.isExpressionStatement(node) &&\n t.isCallExpression(node.expression) &&\n (t.isFunctionExpression(node.expression.callee) ||\n t.isArrowFunctionExpression(node.expression.callee))\n ) {\n hasTopLevelIIFE = true;\n }\n\n if (t.isVariableDeclaration(node)) {\n for (const decl of node.declarations) {\n if (\n decl.init &&\n t.isCallExpression(decl.init) &&\n (t.isFunctionExpression(decl.init.callee) ||\n t.isArrowFunctionExpression(decl.init.callee))\n ) {\n hasTopLevelIIFE = true;\n }\n }\n }\n }\n },\n\n ImportDeclaration() {\n hasImport = true;\n },\n\n ExportNamedDeclaration() {\n hasExport = true;\n },\n\n ExportDefaultDeclaration() {\n hasExport = true;\n },\n\n AssignmentExpression(path: NodePath<t.AssignmentExpression>) {\n const left = path.node.left;\n\n if (t.isMemberExpression(left)) {\n if (t.isIdentifier(left.object) && t.isIdentifier(left.property)) {\n if (\n left.object.name === \"module\" &&\n left.property.name === \"exports\"\n ) {\n hasModuleExports = true;\n }\n\n if (left.object.name === \"exports\") {\n hasExportsMutation = true;\n }\n }\n }\n },\n\n CallExpression(path) {\n const { callee, arguments: args } = path.node;\n\n // Detect CJS-style export mutation\n if (\n args.length > 0 &&\n t.isIdentifier(args[0]) &&\n args[0].name === \"exports\"\n ) {\n hasExportsMutation = true;\n }\n\n if (t.isIdentifier(callee)) {\n // require()\n if (callee.name === \"require\") {\n hasRequire = true;\n }\n\n // define() for AMD/UMD\n if (callee.name === \"define\") {\n hasDefine = true;\n }\n }\n },\n\n UnaryExpression(path) {\n if (\n path.node.operator === \"typeof\" &&\n t.isIdentifier(path.node.argument) &&\n (path.node.argument.name === \"exports\" ||\n path.node.argument.name === \"module\")\n ) {\n hasUMDEnvCheck = true;\n }\n }\n });\n\n // -------------------------\n // FINAL CLASSIFICATION\n // -------------------------\n\n const isCJS = hasModuleExports || hasExportsMutation;\n const isUMD = hasUMDEnvCheck && (hasDefine || isCJS);\n\n // 1. UMD\n if (isUMD) return \"umd\";\n\n // 2. CJS\n if (isCJS) return \"cjs\";\n\n // 3. ESM\n if (hasExport || hasImport) return \"esm\";\n\n // 4. Pure IIFE (NO module system inside)\n if (hasTopLevelIIFE && !isCJS && !hasImport && !hasExport) {\n return \"iife\";\n }\n\n // 5. require-only fallback\n if (hasRequire) return \"cjs\";\n\n return \"esm\";\n}\n\n/** @deprecated use `detectModuleKind` instead.\n *\n * @internal\n */\nexport function detectModuleKindFromContent_(code: string): ModuleKind {\n // /* -------------------------------------------------------------\n // * Detect UMD wrapper (environment branching)\n // * ------------------------------------------------------------- */\n\n // if (/\\bmodule\\.exports\\s*=\\s*factory/.test(code) && /\\bdefine\\.amd\\b/.test(code)) {\n // return \"umd\";\n // }\n\n // const HAS_TYPEOF_EXPORTS = /\\btypeof\\s+exports\\b/;\n // const HAS_TYPEOF_MODULE = /\\btypeof\\s+module\\b/;\n // const HAS_DEFINE_AMD = /\\bdefine\\s*\\(\\s*\\[\\s*\\]|\\bdefine\\.amd\\b/;\n\n // if (\n // (HAS_TYPEOF_EXPORTS.test(code) && HAS_TYPEOF_MODULE.test(code)) ||\n // HAS_DEFINE_AMD.test(code)\n // ) {\n // return \"umd\";\n // }\n\n // /* -------------------------------------------------------------\n // * Detect top-level assigned IIFE bundle\n // * ------------------------------------------------------------- */\n\n // const IIFE_RE =\n // /\\(\\s*(?:async\\s*)?(?:function\\b|\\([\\w\\s,]*\\)\\s*=>)[\\s\\S]*?\\)\\s*\\(\\s*[\\s\\S]*?\\s*\\)\\s*;?/;\n\n // if (IIFE_RE.test(code)) {\n // return \"iife\";\n // }\n\n /* -------------------------------------------------------------\n * STRONGEST: CommonJS runtime export mutation\n * ------------------------------------------------------------- */\n\n const CJS_EXPORT_MUTATION_RE =\n /\\bmodule\\.exports\\s*=|\\bexports\\s*(?:\\.|\\[|\\?\\.)\\s*[\\w\"'`]+\\s*=|\\bObject\\.(?:definePropert(?:y|ies)|assign)\\s*\\(\\s*exports\\b|\\bReflect\\.defineProperty\\s*\\(\\s*exports\\b|\\b__export(?:Star)?\\s*\\(\\s*(?:\\w+\\s*,\\s*)?exports\\b/;\n\n if (CJS_EXPORT_MUTATION_RE.test(code)) {\n return \"cjs\";\n }\n\n /* -------------------------------------------------------------\n * TRUE ESM boundary (syntax-level)\n * ------------------------------------------------------------- */\n\n const ESM_EXPORT_RE =\n /^\\s*export\\s+(?:default|const|let|var|function|class|type|interface|enum|{)/m;\n\n if (ESM_EXPORT_RE.test(code)) {\n return \"esm\";\n }\n\n /* -------------------------------------------------------------\n * import syntax (weak signal, but valid if no mutation)\n * ------------------------------------------------------------- */\n\n const ESM_IMPORT_RE = /^\\s*import\\s+(?:[\\w*\\s{},]+?\\s+from\\s+)?['\"]/m;\n\n if (ESM_IMPORT_RE.test(code)) {\n return \"esm\";\n }\n\n /* -------------------------------------------------------------\n * require() fallback\n * ------------------------------------------------------------- */\n\n if (/\\brequire\\s*\\(/.test(code)) {\n return \"cjs\";\n }\n\n /* -------------------------------------------------------------\n * Default assumption\n * ------------------------------------------------------------- */\n\n return \"esm\";\n}\n\n/** ----------------------------------------------------------------\n * * ***Extracts and hoists leading shebang and banner comments.***\n * ----------------------------------------------------------------\n *\n * Extracts a Unix shebang (`#!...`) and the first `/*! ... *\\/`\n * style banner comment from the beginning of a source file,\n * separating them from the remaining body content.\n *\n * - ***Extraction rules:***\n * - Shebang is extracted first if present.\n * - Only the first banner comment is extracted.\n * - Order is preserved: shebang ➔ banner ➔ body.\n * - Remaining content is trimmed of leading whitespace.\n *\n * If neither shebang nor banner is found, the original content\n * is returned unchanged as the body.\n *\n * @param {string} content - Full file content.\n *\n * @returns {{\n * shebang: string;\n * banner: string;\n * body: string;\n * }}\n * An object containing the extracted shebang, banner, and remaining body.\n *\n * @example\n * ```ts\n * extractAndHoistBanner('#!/usr/bin/env node\\n/*! banner *\\/\\nconst a = 1;');\n * // ➔ {\n * // shebang: '#!/usr/bin/env node\\n',\n * // banner: '/*! banner *\\/',\n * // body: 'const a = 1;'\n * // }\n * ```\n *\n * @internal\n */\nexport function extractAndHoistBanner(content: string): {\n shebang: string;\n banner: string;\n body: string;\n} {\n let rest = content;\n let shebang = \"\";\n let banner = \"\";\n\n const shebangMatch = rest.match(SHEBANG_RE);\n if (shebangMatch && shebangMatch.index === 0) {\n shebang = shebangMatch[0];\n rest = rest.slice(shebang.length);\n }\n\n const bannerMatch = rest.match(BANNER_RE);\n if (bannerMatch && bannerMatch.index === 0) {\n banner = bannerMatch[0];\n rest = rest.slice(banner.length);\n }\n\n return {\n shebang,\n banner,\n body: rest.replace(/^\\s+/, \"\")\n };\n}\n\n/** ----------------------------------------------------------------\n * * ***Extracts top-level `\"use *\"` directives from source code.***\n * ----------------------------------------------------------------\n *\n * Collects consecutive `\"use <directive>\"` statements located\n * at the very beginning of the file.\n *\n * - ***Extraction rules:***\n * - Matches both single and double quoted directives.\n * - Stops at the first non-directive statement.\n * - Preserves original directive formatting.\n *\n * - ***The returned object splits the code into:***\n * - `directives` ➔ raw directive string.\n * - `rest` ➔ remaining source code.\n *\n * @param {string} code - JavaScript source code.\n *\n * @returns {{ directives: string; rest: string }}\n * Extracted directives and remaining code.\n *\n * @example\n * ```ts\n * extractDirectives('\"use strict\"; \"use client\"; const a = 1;');\n * // ➔ { directives: '\"use strict\"; \"use client\";', rest: 'const a = 1;' }\n * ```\n *\n * @internal\n */\nexport function extractDirectives(code: string): {\n directives: string;\n rest: string;\n} {\n const match = code.match(/^((?:(?:\"use\\s+\\w+\"|'use\\s+\\w+');\\s*)+)/);\n\n return {\n directives: match?.[1] ?? \"\",\n rest: code.slice(match?.[1]?.length ?? 0)\n };\n}\n\n/** ----------------------------------------------------------------\n * * ***Removes `\"use strict\"` directives from source content.***\n * ----------------------------------------------------------------\n *\n * Strips all standalone `\"use strict\"` directive statements from\n * the provided content while preserving other directives such as\n * `\"use client\"`.\n *\n * - ***Removal rules:***\n * - Matches both single and double quoted `\"use strict\"`.\n * - Only removes full directive lines (line-anchored).\n * - Supports optional trailing semicolon.\n *\n * By default, leading whitespace is trimmed after removal to keep\n * the resulting content properly aligned for further processing.\n *\n * @param {string} content - Source content containing directive statements.\n *\n * @param {object} [options] - Behavior configuration.\n * @param {boolean} [options.trimStart=true]\n * Whether to trim leading whitespace after stripping directives.\n *\n * @returns {string} Content with `\"use strict\"` directives removed.\n *\n * @example\n * ```ts\n * stripUseStrict('\"use strict\";\\n\"use client\";');\n * // ➔ '\"use client\";'\n * ```\n *\n * @example\n * ```ts\n * stripUseStrict('\"use strict\";\\n\\nconst a = 1;', { trimStart: false });\n * // ➔ '\\n\\nconst a = 1;'\n * ```\n *\n * @internal\n */\nexport function stripUseStrict(\n content: string,\n {\n trimStart = true,\n trimEnd = false\n }: {\n /** @default true */\n trimStart?: boolean;\n /** @default false */\n trimEnd?: boolean;\n } = {}\n): string {\n const result = content.replace(USE_STRICT_RE, \"\");\n if (trimStart) result.trimStart();\n if (trimEnd) result.trimEnd();\n\n return result;\n}\n\n/** ----------------------------------------------------------------\n * * ***Determines the correct insertion index for injected code.***\n * ----------------------------------------------------------------\n *\n * Calculates the byte index in source code where new content\n * (such as directives or imports) should be safely inserted.\n *\n * - ***Insertion rules:***\n * - Skips over a leading shebang (`#!...`) if present.\n * - Skips over a leading banner comment (`/*! ... *\\/`) if present.\n * - Preserves original file ordering and semantics.\n *\n * The returned index points to the position **after** any detected\n * shebang or banner, making it safe for code injection.\n *\n * @param {string} code - JavaScript source code.\n *\n * @returns {number}\n * Index position suitable for inserting additional code.\n *\n * @example\n * ```ts\n * findInsertIndex('#!/usr/bin/env node\\n/*! banner *\\/\\nconst a = 1;');\n * // ➔ index after shebang and banner.\n * ```\n *\n * @internal\n */\nexport function findInsertIndex(code: string): number {\n let index = 0;\n\n const shebang = code.match(SHEBANG_RE);\n if (shebang) index += shebang[0].length;\n\n const banner = code.slice(index).match(BANNER_RE);\n if (banner) index += banner[0].length;\n\n return index;\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { AnyString } from \"@/_internal/types/extra\";\n\nimport { isDeepStrictEqual } from \"node:util\";\n\nimport {\n isError,\n isNonEmptyString,\n isNumber,\n normalizeSpaces\n} from \"@/_internal/utils/helper\";\n\nimport {\n formatOptionValue,\n joinLines,\n picocolors\n} from \"@/utils/helper/formatter\";\nimport { ICONS } from \"@/utils/helper/icons\";\n\n/** -------------------------------------------------------------------\n * * ***Determines whether an option value comes from the default configuration\n * or has been explicitly overridden by the user.***\n * -------------------------------------------------------------------\n *\n * This utility is primarily intended for logging and debugging purposes,\n * especially in CLI tools or build pipelines where distinguishing between\n * default and user-provided values is important.\n *\n * The comparison is performed using `Object.is` to ensure accurate detection,\n * including edge cases such as:\n * - `NaN` vs `NaN`.\n * - `-0` vs `+0`.\n *\n * @template T - The type of the option value being compared.\n *\n * @param {unknown} value - The actual value used at runtime.\n * @param {unknown} defaultValue - The default value defined by the tool.\n *\n * @returns\n * A string indicating the source of the value:\n *\n * - `\"default\"` when `value` is strictly equal to `defaultValue`.\n * - `\"overridden\"` when the value differs from the default.\n *\n * @example\n * ```ts\n * sourceOf(\"dist\", \"dist\"); // ➔ \"default\"\n * sourceOf(\"dist/types\", \"dist\"); // ➔ \"overridden\"\n * ```\n *\n * @example\n * ***CLI-style option logging:***\n * ```ts\n * BUILD_LOGGER.OPTIONS(\n * \"outDir\",\n * outDir,\n * sourceOf(outDir, DEFAULTS.outDir)\n * );\n * ```\n */\nexport const sourceOf = <T>(\n value: T,\n defaultValue: T\n): \"default\" | \"overridden\" => {\n return Object.is(value, defaultValue) ? \"default\" : \"overridden\";\n};\n\n/** ----------------------------------------------------------------\n * * ***Deep default source detector.***\n * ----------------------------------------------------------------\n *\n * Determines whether a given value is structurally identical\n * to its default value using deep comparison.\n *\n * Unlike `Object.is`, this utility compares object contents\n * recursively rather than checking reference identity.\n *\n * Intended for configuration systems where option objects\n * may be cloned or reconstructed but still represent the\n * default state.\n *\n * @template T - Value type being compared.\n *\n * @param value - Current runtime value.\n * @param defaultValue - Default reference value.\n *\n * @returns\n * - `\"default\"` ➔ If values are deeply equal.\n * - `\"overridden\"` ➔ If values differ.\n *\n * @example\n * ```ts\n * sourceOfIsDeepStrictEqual(\n * { onlyFiles: true },\n * { onlyFiles: true }\n * );\n * // \"default\"\n * ```\n */\nexport const sourceOfIsDeepStrictEqual = <T>(\n value: T,\n defaultValue: T\n): \"default\" | \"overridden\" => {\n return isDeepStrictEqual(value, defaultValue) ? \"default\" : \"overridden\";\n};\n\n/** -------------------------------------------------------------------\n * * ***Structured build-time console logger with consistent formatting,\n * icons, and colorized output.***\n * --------------------------------------------------------------------\n *\n * `BUILD_LOGGER` provides a collection of standardized logging helpers\n * intended for **CLI tools, build scripts, and Node.js-based workflows**.\n *\n * - **It ensures:**\n * - Consistent log structure across different build phases.\n * - Clear visual distinction between states (start, success, skip, error).\n * - Emoji or ASCII icon support depending on environment configuration.\n * - Readable, colorized output via `picocolors`.\n *\n * Emoji usage is controlled via the environment variable:\n *\n * ```\n * FORCE_EMOJI=1\n * ```\n *\n * When disabled, all icons gracefully fall back to ASCII-safe symbols.\n *\n * ---\n *\n * - **Behavior:**\n * - Uses emoji icons when `FORCE_EMOJI === \"1\"`.\n * - Falls back to ASCII symbols otherwise.\n * - Applies consistent spacing, bulleting, and indentation.\n * - Formats messages using `picocolors` for visibility.\n * - Safely extracts error messages from unknown error values.\n *\n * ---\n *\n * - **Available log actions:**\n * - `SOURCE_OF`:\n * - See {@link sourceOf | **`sourceOf`**} helpers.\n *\n * - `OPTIONS({ label, value, source, isRequired })`:\n * - Logs the options argument function using\n * {@link sourceOf | **`sourceOf`**} helper.\n *\n * - `NEW_LINE()`:\n * - *Inserts an empty line in the console output.*\n *\n * - `ON_STARTING({ actionName })`:\n * - *Logs the start of a build or processing action.*\n *\n * - `ON_FINISH({ actionName, count })`:\n * - *Logs successful completion with item count.*\n *\n * - `ON_SKIPPING({ actionName, reasonEndText })`:\n * - *Logs skipped actions with human-readable reasons.*\n *\n * - `ON_ERROR({ actionName, error })`:\n * - *Logs formatted error output with extracted message.*\n *\n * - `ON_PROCESS_COPY({ actionName, copyFrom, copyTo })`:\n * - *Logs file copy operations.*\n *\n * - `ON_PROCESS({ actionName, nameDirect })`:\n * - *Logs generic processing steps.*\n *\n * - `ON_PROCESS_REFERENCING({ actionName, referenceFrom, referenceTo })`:\n * - *Logs reference or linking operations.*\n *\n * ---\n *\n * This logger is intentionally **side-effectful** and writes directly\n * to `console.log` / `console.error`.\n *\n * It is designed for **human-readable output**, not structured logging\n * or machine parsing.\n */\nexport const BUILD_LOGGER = {\n /** -------------------------------------------------------------------\n * * ***Determines whether an option value comes from the default configuration\n * or has been explicitly overridden by the user.***\n * -------------------------------------------------------------------\n *\n * This utility is primarily intended for logging and debugging purposes,\n * especially in CLI tools or build pipelines where distinguishing between\n * default and user-provided values is important.\n *\n * The comparison is performed using `Object.is` to ensure accurate detection,\n * including edge cases such as:\n * - `NaN` vs `NaN`.\n * - `-0` vs `+0`.\n *\n * @template T - The type of the option value being compared.\n *\n * @param value - The actual value used at runtime.\n * @param defaultValue - The default value defined by the tool.\n *\n * @returns\n * A colorized string indicating the source of the value:\n *\n * - `\"default\"` when `value` is strictly equal to `defaultValue`.\n * - `\"overridden\"` when the value differs from the default.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.SOURCE_OF(\"dist\", \"dist\"); // ➔ \"default\"\n * BUILD_LOGGER.SOURCE_OF(\"dist/types\", \"dist\"); // ➔ \"overridden\"\n * ```\n *\n * @example\n * ***CLI-style option logging:***\n * ```ts\n * BUILD_LOGGER.OPTIONS(\n * \"outDir\",\n * outDir,\n * BUILD_LOGGER.SOURCE_OF(outDir, DEFAULTS.outDir)\n * );\n * ```\n */\n SOURCE_OF: sourceOf,\n /** -------------------------------------------------------------------\n * * ***Logs a single option entry in a formatted, human-readable CLI style.***\n * -------------------------------------------------------------------\n *\n * This helper is used to display resolved configuration values along with\n * their origin (default or overridden), making it easier to debug and\n * understand how final options are derived.\n *\n * - **Output format example:**\n * ```bash\n * - outDir: dist/types (overridden)\n * - withExportTypes: false (default)\n * - inputDirReference: dist\n * ```\n *\n * - **Formatting rules:**\n * - Indented with a leading dash (`-`).\n * - Label is rendered in **bold**.\n * - Value is rendered in **cyan**.\n * - Source indicator (`default` / `overridden`) is **dimmed**.\n * - Arrays are stringified using a stable JSON formatter.\n * - When an option is marked as required, the source indicator is omitted.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @param {string} label - Human-readable option name\n * (e.g. `\"outDir\"`, `\"withExportTypes\"`, `\"inputDirReference\"`).\n *\n * @param {unknown} value - The resolved option value to display.\n * Can be of any type; arrays are stringified automatically.\n *\n * @param {\"default\" | \"overridden\" | ({} & string)} source - A value indicating whether the option comes from\n * the default configuration or was overridden by user input, typically\n * produced by {@link sourceOf | **`sourceOf`**}.\n *\n * @param {boolean | undefined} isRequired - When set to `true`, marks\n * the option as required and suppresses the source indicator in the output,\n * defaults to `false`.\n *\n * @example\n * ```ts\n * OPTIONS(\n * \"outDir\",\n * outDir,\n * sourceOf(outDir, DEFAULTS.outDir)\n * );\n * ```\n *\n * @example\n * Logging multiple options.\n * ```ts\n * OPTIONS(\n * \"outFileName\",\n * outFileName,\n * sourceOf(outFileName, DEFAULTS.outFileName)\n * );\n * OPTIONS(\n * \"inputDirReference\",\n * inputDirReference,\n * sourceOf(inputDirReference, DEFAULTS.inputDirReference)\n * );\n * OPTIONS(\n * \"withExportTypes\",\n * withExportTypes,\n * sourceOf(withExportTypes, DEFAULTS.withExportTypes)\n * );\n * ```\n *\n * @example\n * Logging a required option.\n * ```ts\n * OPTIONS(\n * \"input\",\n * inputPath,\n * sourceOf(inputPath, undefined),\n * true\n * );\n * ```\n */\n OPTIONS(\n label: string,\n value: unknown,\n source: ReturnType<typeof sourceOf> | AnyString,\n isRequired?: boolean\n ) {\n const sourceLabel =\n !isRequired && source\n ? source === \"default\"\n ? picocolors.blueBright(` (${source})`)\n : picocolors.yellowBright(` (${source})`)\n : \"\";\n\n console.log(\n picocolors.dim(\" - \") +\n normalizeSpaces(\n picocolors.bold(label || \"`⚠️ Label Unset!!!`\") +\n picocolors.dim(\": \") +\n formatOptionValue(value) +\n picocolors.italic(sourceLabel)\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a subsection title for grouped log output.***\n * -------------------------------------------------------------------\n *\n * Used to visually separate logical blocks such as:\n * - Arguments.\n * - Options.\n * - Configuration.\n * - Resolved Values.\n *\n * This improves readability when logging many related entries.\n *\n * @param {string} title - Section title text (e.g. \"Options\", \"Arguments\").\n * @param {{ icon?: string; indent?: string; }} options - Optional icon override.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.SECTION(\"Options\");\n * BUILD_LOGGER.SECTION(\"Arguments\", { icon: ICONS.folder });\n * ```\n */\n SECTION(title: string, options: LoggerBuilderSection = {}) {\n const { icon = ICONS.config, indent = \"\" } = options;\n\n console.log(\n picocolors.bold(\n `${indent}${picocolors.whiteBright(icon)} ${picocolors.underline(picocolors.cyanBright(title || \"`⚠️ Unset Title!!!`\"))}:`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Prints a single empty line to the console.***\n * -------------------------------------------------------------------\n *\n * Writes a newline to standard output, typically used as a visual\n * separator between log sections to improve CLI readability.\n *\n * If a string value is provided, it will be printed instead of an\n * empty line.\n *\n * @param {string} [value=\"\"] - Optional text to print. Defaults to an\n * empty string, resulting in a blank line.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.NEW_LINE();\n * ```\n *\n * @example\n * ```ts\n * BUILD_LOGGER.NEW_LINE(\" \");\n * ```\n */\n NEW_LINE(value: string = \"\") {\n return console.log(value);\n },\n /** -------------------------------------------------------------------\n * * ***Logs a starting action message.***\n * -------------------------------------------------------------------\n *\n * Used to indicate that a process or action has just started.\n * Typically printed once before any processing begins.\n *\n * - **Output format example:**\n * ```bash\n * ▶ Starting to generate-types.\n * ```\n *\n * - **Formatting rules:**\n * - Start icon is displayed.\n * - \"Starting\" keyword is highlighted.\n * - Action name is underlined and colored.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_STARTING({ actionName: \"build references\" });\n * ```\n */\n ON_STARTING: (options: LoggerBuilderOnStarting) => {\n const { actionName, textDirectAction = \"to\" } = options;\n\n console.log(\n picocolors.bold(\n `${picocolors.whiteBright(ICONS.start)} ${picocolors.cyanBright(\n \"Starting\"\n )} ${normalizeSpaces(`${textDirectAction} ${picocolors.underline(picocolors.blueBright(actionName))}`)}.`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a successful completion message.***\n * -------------------------------------------------------------------\n *\n * Used to indicate that an action has finished successfully,\n * including a summary count of processed items.\n *\n * - **Output format example:**\n * ```bash\n * ✔ Success generate-types (12 files).\n * ```\n *\n * - **Formatting rules:**\n * - Success icon and green highlight.\n * - Action name is underlined.\n * - Count is highlighted in yellow.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_FINISH({\n * actionName: \"generate references\",\n * count: 5\n * });\n * ```\n */\n ON_FINISH: (options: LoggerBuilderOnFinish) => {\n const {\n actionName,\n count,\n typeCount = \"file\",\n progress,\n textSuccess = \"Success\"\n } = options;\n\n console.log(\n picocolors.bold(\n `${picocolors.greenBright(ICONS.success)} ${picocolors.greenBright(textSuccess)} ${normalizeSpaces(\n `${picocolors.underline(\n picocolors.blueBright(actionName)\n )} (${picocolors.yellowBright(`${isNonEmptyString(progress) ? progress : count} ${typeCount}${count > 1 ? \"(s)\" : \"\"}`)}`\n )}).`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a skipped action with a detailed reason.***\n * -------------------------------------------------------------------\n *\n * Used when an action is intentionally skipped due to\n * unmet conditions or no remaining work.\n *\n * - **Output format example:**\n * ```bash\n * ⚠ Skipping generate-types because nothing left files to process.\n * ```\n *\n * - **Formatting rules:**\n * - Warning icon with yellow highlight.\n * - Action name is underlined.\n * - Skip reason is emphasized in red.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_SKIPPING({\n * actionName: \"generate references\",\n * reasonEndText: \"process\"\n * });\n * ```\n */\n ON_SKIPPING: (options: LoggerBuilderOnSkipping) => {\n const {\n actionName,\n reasonEndText,\n reasonSkipAction = \"nothing left\",\n reasonTitle = \"because\",\n reasonType = \"files\",\n textDirectAction = \"to\"\n } = options;\n\n console.log(\n picocolors.bold(\n `${picocolors.yellowBright(ICONS.warn)} ${picocolors.yellowBright(\"Skipping\")} ${normalizeSpaces(\n `${picocolors.underline(\n picocolors.blueBright(actionName)\n )} ${picocolors.white(reasonTitle)} ${picocolors.redBright(\n reasonSkipAction\n )} ${reasonType} ${textDirectAction} ${picocolors.redBright(reasonEndText)}`\n )}.`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs an error occurring during an action.***\n * -------------------------------------------------------------------\n *\n * Used to report fatal or recoverable errors during execution.\n * Automatically extracts the message from an `Error` instance.\n *\n * - **Output format example:**\n * ```bash\n * ✖ Error to generate-types,\n * ➜ Something went wrong\n * ```\n *\n * - **Formatting rules:**\n * - Error icon and red highlight.\n * - Action name is underlined.\n * - Error message is inverted for emphasis.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stderr`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_ERROR({\n * actionName: \"copy files\",\n * error: err\n * });\n * ```\n */\n ON_ERROR: (options: LoggerBuilderOnError) => {\n const { actionName, textDirectAction = \"to\", error } = options;\n\n const errorMsg = isError(error) ? error.message : \"Something went wrong\";\n\n console.error(\n picocolors.bold(\n `${picocolors.redBright(ICONS.error)} ${picocolors.redBright(\"Error\")} ${normalizeSpaces(\n `${textDirectAction} ${picocolors.underline(picocolors.blueBright(actionName))},`\n )} ${joinLines(\"because: \", \"\", ` ${picocolors.bold(picocolors.red(ICONS.arrowRight))} ${picocolors.inverse(picocolors.red(normalizeSpaces(errorMsg)))}`)}`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a generic processing step.***\n * -------------------------------------------------------------------\n *\n * Used for logging step-by-step progress inside a process,\n * typically for folders or grouped actions.\n *\n * - **Output format example:**\n * ```bash\n * • 2. Generating in dist/types.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS: (options: LoggerBuilderOnProcess) => {\n const { actionName, count, nameDirect, textDirectFolder = \"in\" } = options;\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.white(actionName)} ${picocolors.magentaBright(\n textDirectFolder\n )} ${picocolors.bold(picocolors.underline(picocolors.blue(nameDirect)))}.`\n )}`\n )}`\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a copy process entry.***\n * -------------------------------------------------------------------\n *\n * Used to log a file or directory copy operation as part\n * of a larger process.\n *\n * - **Output format example:**\n * ```bash\n * • 1. Copy from 'src/types' ➔ 'dist/types'.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS_COPY: (options: LoggerBuilderOnProcessCopy) => {\n const {\n actionName,\n count,\n copyTo,\n copyFrom,\n textFrom = \"from\",\n textArrow = \"➔\"\n } = options;\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.white(actionName)} ${picocolors.yellow(\n textFrom\n )} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyFrom)))}' ${picocolors.bold(\n picocolors.gray(textArrow)\n )} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyTo)))}'.`\n )}`\n )}`\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a copy process entry.***\n * -------------------------------------------------------------------\n *\n * Used to log a file or directory copy operation as part\n * of a larger process.\n *\n * - **Output format example:**\n * ```bash\n * • 1. Failed Copying from 'src/types' because source file not found.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS_COPY_ERROR: (options: LoggerBuilderOnProcessCopyError) => {\n const {\n actionName,\n count,\n errorReason,\n copyFrom,\n index,\n indexKey,\n textFrom = \"from\",\n textReason = \"because\"\n } = options;\n\n const errorReasonText = isError(errorReason)\n ? errorReason.message\n : String(errorReason);\n\n const atIndexText = isNumber(index)\n ? picocolors.blueBright(\n ` (at${isNonEmptyString(indexKey) ? ` '${indexKey}' ` : \" \"}index: ${picocolors.magentaBright(index)}) `\n )\n : \" \";\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.redBright(actionName)} ${picocolors.yellow(\n textFrom\n )} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyFrom)))}'${atIndexText}${picocolors.bold(\n picocolors.gray(textReason)\n )} ${picocolors.redBright(errorReasonText)}.`\n )}`\n )}`\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a reference linking process.***\n * -------------------------------------------------------------------\n *\n * Used to indicate that a reference is being created\n * from one location to another.\n *\n * - **Output format example:**\n * ```bash\n * • 3. Referencing from src/index.ts ➔ dist/index.d.ts.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS_REFERENCING: (options: LoggerBuilderOnProcessReferencing) => {\n const {\n actionName,\n count,\n referenceTo,\n referenceFrom,\n textFrom = \"from\",\n textArrow = \"➔\"\n } = options;\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.white(actionName)} ${picocolors.magentaBright(\n textFrom\n )} ${picocolors.bold(picocolors.underline(picocolors.cyanBright(referenceFrom)))} ${picocolors.bold(\n picocolors.gray(textArrow)\n )} ${picocolors.bold(picocolors.underline(picocolors.blueBright(referenceTo)))}.`\n )}`\n )}`\n );\n }\n};\n\ntype LoggerBuilderSection = {\n /** @default `ICON.config` */\n icon?: string;\n /** @default \"\" */\n indent?: string;\n};\ntype LoggerBuilderOnStarting = {\n /** The name of the action being started.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Connector word used before the action name.\n *\n * @default\n * \"to\"\n */\n textDirectAction?: string;\n};\ntype LoggerBuilderOnFinish = {\n /** The name of the completed action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** The success text.\n *\n * @default\n * @default \"Success\"\n */\n textSuccess?: string;\n /** Label for the count unit.\n *\n * @default\n * \"file\"\n */\n typeCount?: string;\n /** Number of processed items.\n *\n * @default\n * undefined\n */\n count: number;\n /** Progress of processed items (e.g. `2/7`).\n *\n * Represents how many items have been processed relative to the total.\n *\n * @example\n * \"2/7\"\n */\n progress?: string;\n};\ntype LoggerBuilderOnSkipping = {\n /** The name of the skipped action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Connector word explaining the reason.\n *\n * @default\n * \"because\"\n */\n reasonTitle?: string;\n /** Short reason phrase.\n *\n * @default\n * \"nothing left\"\n */\n reasonSkipAction?: string;\n /** Contextual explanation for the skip.\n *\n * @default\n * undefined\n */\n reasonEndText: string;\n /** Type of resource involved.\n *\n * @default\n * \"files\"\n */\n reasonType?: string;\n /** Connector word before the target.\n *\n * @default\n * \"to\"\n */\n textDirectAction?: string;\n};\ntype LoggerBuilderOnError = {\n /** The name of the action that failed.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Connector word before the action name.\n *\n * @default\n * \"to\"\n */\n textDirectAction?: string;\n /** Unknown error object or `Error` instance.\n *\n */\n error: unknown;\n};\ntype LoggerBuilderOnProcess = {\n /** Description of the process.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number.\n *\n * @default\n * undefined\n */\n count: number;\n /** Connector word before the target.\n *\n * @default\n * \"in\"\n */\n textDirectFolder?: string;\n /** Target name or location.\n *\n * @default\n * undefined\n */\n nameDirect: string;\n};\ntype LoggerBuilderOnProcessCopy = {\n /** The name of the action being the copy action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number of the process.\n *\n * @default\n * undefined\n */\n count: number;\n /** Connector text before source path.\n *\n * @default\n * \"from\"\n */\n textFrom?: string;\n /** Source path.\n *\n * @default\n * undefined\n */\n copyFrom: string;\n /** Destination path.\n *\n * @default\n * undefined\n */\n copyTo: string;\n /** Arrow symbol between paths.\n *\n * @default\n * \"➔\"\n */\n textArrow?: string;\n};\ntype LoggerBuilderOnProcessCopyError = {\n /** The name of the action being the error copy action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number of the process.\n *\n * @default\n * undefined\n */\n count: number;\n /** Index number parameter.\n *\n * @default\n * undefined\n */\n index?: number;\n /** Index key name for parameter.\n *\n * @default\n * undefined\n */\n indexKey?: string;\n /** Connector text before source path.\n *\n * @default\n * \"from\"\n */\n textFrom?: string;\n /** Source path.\n *\n * @default\n * undefined\n */\n copyFrom: string;\n /** The reason error on copying.\n *\n * @default\n * undefined\n */\n errorReason: string | Error;\n /** Connector word explaining the reason.\n *\n * @default\n * \"because\"\n */\n textReason?: string;\n};\ntype LoggerBuilderOnProcessReferencing = {\n /** The name of the action being the referencing action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number.\n *\n * @default\n * undefined\n */\n count: number;\n /** Connector text before source.\n *\n * @default\n * \"from\"\n */\n textFrom?: string;\n /** Source reference path.\n *\n * @default\n * undefined\n */\n referenceFrom: string;\n /** Target reference path.\n *\n * @default\n * undefined\n */\n referenceTo: string;\n /** Arrow symbol between references.\n *\n * @default\n * \"➔\"\n */\n textArrow?: string;\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n EMPTY_LINE_RE,\n isAdjacentToTarget,\n isTargetComment\n} from \"@/_internal/utils/source\";\n\n/** @internal Util for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function stripLineArtifacts(line: string, options: CleanCoreOptions) {\n let out = line\n // remove source path comments\n .replace(\n /^[ \\t]*\\/\\/\\s*(?:\\.\\.\\/|\\.\\/)*[^ \\n]*?(?:src|node_modules)\\/[^\\n]*\\n?/gm,\n \"\"\n )\n // remove eslint comments\n .replace(/\\/\\/\\s*eslint[^\\n]*/g, \"\");\n\n if (options.removeSourceMap) {\n // Remove all `sourceMappingURL` comments.\n out = out.replace(\n /^[ \\t]*\\/\\/[#@]\\s*sourceMappingURL\\s*=\\s*\\S+/gm,\n // /\\/\\/[#@]\\s*sourceMappingURL=[^\\n]*/g,\n \"\"\n );\n }\n\n // Collapse duplicate `sourceMappingURL` comments into a single one.\n out = out.replace(\n /(^[ \\t]*\\/\\/[#@]\\s*sourceMappingURL\\s*=\\s*\\S+)(?:\\r?\\n\\1)+/gm,\n // /(\\/\\/[#@]\\s*sourceMappingURL=[^\\r\\n]*)(?:\\r?\\n\\1)+/g,\n \"$1\"\n );\n\n return out;\n}\n\n/** @internal Util for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function splitLines(content: string) {\n return content.split(/\\r\\n|\\n/);\n}\n\n/** @internal Util for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function fileHasTarget(lines: string[], options: CleanCoreOptions) {\n return lines.some((line, i, arr) => {\n if (isTargetComment(line, options)) return true;\n\n if (\n options.removeAdjacentEmptyLines &&\n EMPTY_LINE_RE.test(line) &&\n isAdjacentToTarget(arr, i, options)\n ) {\n return true;\n }\n\n return false;\n });\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n EMPTY_LINE_RE,\n isAdjacentToTarget,\n isTargetComment,\n REGION_RE,\n SOURCE_MAP_RE\n} from \"@/_internal/utils/source\";\n\nimport { stripLineArtifacts } from \"./clean-build-artifacts-utils\";\n\n/** @internal Core for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function cleanBuildArtifactsCore(\n lines: string[],\n options: CleanCoreOptions\n) {\n const seenSourceMap = new Set<string>();\n\n return lines\n .filter((line, i, arr) => {\n if (SOURCE_MAP_RE.test(line)) {\n const key = line.trim();\n if (seenSourceMap.has(key)) return false;\n seenSourceMap.add(key);\n if (options.removeSourceMap) return false;\n\n return true;\n }\n\n if (options.removeRegion && REGION_RE.test(line)) return false;\n\n if (isTargetComment(line, options)) return false;\n\n if (\n options.removeAdjacentEmptyLines &&\n EMPTY_LINE_RE.test(line) &&\n isAdjacentToTarget(arr, i, options)\n ) {\n return false;\n }\n\n return true;\n })\n .map((line) => stripLineArtifacts(line, options));\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { RequiredOnly } from \"@/_internal/types/extra\";\nimport type { StringCollection } from \"@/types\";\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport { canLog, VERBOSE_LOG } from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isPlainObject, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/client\";\n\nimport { cleanBuildArtifactsCore } from \"./clean-build-artifacts-core\";\nimport { fileHasTarget, splitLines } from \"./clean-build-artifacts-utils\";\nimport {\n DEFAULT_CLEAN_OPTION,\n DEFAULT_CLEAN_PATTERN_POLICY\n} from \"./clean-build-artifacts-constant\";\n\ntype OmitLogActionName<T> = Omit<T, \"actionName\">;\ntype RunCleanBuildArtifactsParams = {\n patterns: StringCollection;\n options: RequiredOnly<CleanCoreOptions, \"logLevel\">;\n\n fileTest: RegExp;\n\n logAction: {\n title: string;\n actionName: string;\n onStart?: OmitLogActionName<\n Parameters<(typeof BUILD_LOGGER)[\"ON_STARTING\"]>[0]\n >;\n onProcess?: OmitLogActionName<\n Omit<\n Parameters<(typeof BUILD_LOGGER)[\"ON_PROCESS\"]>[0],\n \"count\" | \"nameDirect\"\n >\n >;\n onError?: OmitLogActionName<\n Omit<\n Parameters<(typeof BUILD_LOGGER)[\"ON_ERROR\"]>[0],\n \"error\" | \"nameDirect\"\n >\n >;\n onSkipping?: OmitLogActionName<\n Parameters<(typeof BUILD_LOGGER)[\"ON_SKIPPING\"]>[0]\n >;\n };\n};\n\n/** @internal Runner for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport async function runCleanBuildArtifacts({\n patterns: pattern,\n options,\n fileTest,\n logAction\n}: RunCleanBuildArtifactsParams) {\n if (!isPlainObject(options)) {\n options = DEFAULT_CLEAN_OPTION;\n } else {\n options = { ...DEFAULT_CLEAN_OPTION, ...options };\n }\n\n const {\n patternOptions,\n logLevel: loggerLevel,\n removeAdjacentEmptyLines,\n removeRegion,\n removeSourceMap\n } = options;\n\n try {\n if (canLog(loggerLevel, VERBOSE_LOG))\n console.log(joinLinesLoose(logAction.title, \"\"));\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_CLEAN_PATTERN_POLICY\n );\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_CLEAN_OPTION.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeSourceMap\",\n removeSourceMap,\n BUILD_LOGGER.SOURCE_OF(\n removeSourceMap,\n DEFAULT_CLEAN_OPTION.removeSourceMap\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeRegion\",\n removeRegion,\n BUILD_LOGGER.SOURCE_OF(removeRegion, DEFAULT_CLEAN_OPTION.removeRegion)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeAdjacentEmptyLines\",\n removeAdjacentEmptyLines,\n BUILD_LOGGER.SOURCE_OF(\n removeAdjacentEmptyLines,\n DEFAULT_CLEAN_OPTION.removeAdjacentEmptyLines\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_CLEAN_OPTION.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n ...logAction.onStart,\n actionName: logAction.actionName\n });\n }\n\n let count = 0;\n\n for (const filePath of files) {\n if (!new RegExp(fileTest).test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const lines = splitLines(content);\n\n if (!fileHasTarget(lines, options)) continue;\n\n const cleanedLines = cleanBuildArtifactsCore(lines, options);\n const finalContent = cleanedLines.join(EOL);\n\n if (finalContent === content) continue;\n\n count++;\n\n try {\n await fsExtra.promises.writeFile(filePath, finalContent, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n ...logAction.onProcess,\n actionName: logAction.actionName,\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: logAction.actionName,\n count: count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n ...logAction.onSkipping,\n actionName: logAction.actionName,\n reasonEndText: logAction.onSkipping?.reasonEndText ?? \"cleaning\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n ...logAction.onError,\n actionName: logAction.actionName,\n error\n });\n }\n }\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { StringCollection } from \"@/types\";\nimport type { CleanCoreOptions } from \"./_internal/clean-build-artifacts-types\";\n\nimport { isNonEmptyString } from \"@/_internal/utils/helper\";\nimport { JS_OUTPUT_FILE_RE } from \"@/_internal/utils/source\";\nimport { resolveLogVerbosity } from \"@/_internal/utils/log-level\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\nimport { DEFAULT_CLEAN_OPTION } from \"./_internal/clean-build-artifacts-constant\";\nimport { runCleanBuildArtifacts } from \"./_internal/clean-build-artifacts-runner\";\n\n/** Command identity associated with {@link cleanJsBuildArtifacts | **`clean-js-build-artifacts`**}. */\nexport const commandCjbaIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"clean-js-build-artifacts\"\n});\n\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`}.***\n * ----------------------------------------------------------------\n */\nexport type CleanJsArtifactsOptions = CleanCoreOptions;\n\n/** ----------------------------------------------------------------\n * * ***Removes build artifact comments from compiled JavaScript files.***\n * ----------------------------------------------------------------\n *\n * This function scans files matching the provided glob pattern(s) and removes:\n * - Source path comments.\n * - Source region comments.\n * - ESLint directive comments.\n * - Optional source map references.\n *\n * It can also remove empty lines adjacent to those comments to keep\n * output files tidy.\n *\n * @param {string | string[] | Set<string>} pattern - Glob pattern or list of patterns pointing to JS output files.\n * @param {CleanJsArtifactsOptions} options - Cleanup configuration options, see {@link CleanJsArtifactsOptions | **`CleanJsArtifactsOptions`**}.\n *\n * @example\n * ```ts\n * await cleanJsBuildArtifacts(\"dist/**\\/*.js\");\n * await cleanJsBuildArtifacts(\"dist/**\\/*.{js,cjs,mjs}\");\n * ```\n *\n * @example\n * ```ts\n * await cleanJsBuildArtifacts([\"dist/**\\/*.js\", \"build/*\\/*.mjs\"], {\n * removeSourceMap: false,\n * removeRegionComment: false,\n * removeAdjacentEmptyLines: true\n * });\n * ```\n */\nexport const cleanJsBuildArtifacts = async (\n pattern: StringCollection,\n options: CleanJsArtifactsOptions = {}\n): Promise<void> => {\n const logLevel = resolveLogVerbosity(options, DEFAULT_CLEAN_OPTION.logLevel);\n\n return await runCleanBuildArtifacts({\n patterns: pattern,\n options: { ...options, logLevel },\n fileTest: JS_OUTPUT_FILE_RE,\n logAction: {\n actionName: \"Cleaning JS Build Artifacts\",\n title: isNonEmptyString(options.__commandTitle)\n ? options.__commandTitle\n : commandCjbaIdentity.utility()\n }\n });\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { StringCollection } from \"@/types\";\nimport type { CleanCoreOptions } from \"./_internal/clean-build-artifacts-types\";\n\nimport { isNonEmptyString } from \"@/_internal/utils/helper\";\nimport { resolveLogVerbosity } from \"@/_internal/utils/log-level\";\nimport { TS_DECLARATION_FILE_RE } from \"@/_internal/utils/source\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\nimport { DEFAULT_CLEAN_OPTION } from \"./_internal/clean-build-artifacts-constant\";\nimport { runCleanBuildArtifacts } from \"./_internal/clean-build-artifacts-runner\";\n\n/** Command identity associated with {@link cleanTypesBuildArtifacts | **`clean-types-build-artifacts`**}. */\nexport const commandCtbaIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"clean-types-build-artifacts\"\n});\n\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link cleanTypesBuildArtifacts | **`cleanTypesBuildArtifacts`**}.***\n * ----------------------------------------------------------------\n */\nexport type CleanTypesArtifactsOptions = CleanCoreOptions;\n\n/** ----------------------------------------------------------------\n * * ***Removes build artifact comments from compiled Types files.***\n * ----------------------------------------------------------------\n *\n * This function scans files matching the provided glob pattern(s) and removes:\n * - Source path comments.\n * - ESLint directive comments.\n * - Optional source map references.\n *\n * It can also remove empty lines adjacent to those comments to keep\n * output files tidy.\n *\n * @param pattern - Glob pattern or list of patterns pointing to Types output files.\n * @param options - Cleanup configuration options, see {@link CleanTypesArtifactsOptions | **`CleanTypesArtifactsOptions`**}.\n *\n * @example\n * ```ts\n * await cleanTypesBuildArtifacts(\"dist/**\\/*.d.ts\");\n * await cleanTypesBuildArtifacts(\"dist/**\\/*.d.{ts,cts,mts}\");\n * ```\n *\n * @example\n * ```ts\n * await cleanTypesBuildArtifacts([\"dist/**\\/*.d.ts\", \"build/*\\/*.mts\"], {\n * removeSourceMap: false,\n * removeAdjacentEmptyLines: true\n * });\n * ```\n */\nexport const cleanTypesBuildArtifacts = async (\n pattern: StringCollection,\n options: CleanTypesArtifactsOptions = {}\n): Promise<void> => {\n const logLevel = resolveLogVerbosity(options, DEFAULT_CLEAN_OPTION.logLevel);\n\n return await runCleanBuildArtifacts({\n patterns: pattern,\n options: { ...options, logLevel },\n fileTest: TS_DECLARATION_FILE_RE,\n logAction: {\n actionName: \"Cleaning Types Build Artifacts\",\n title: isNonEmptyString(options.__commandTitle)\n ? options.__commandTitle\n : commandCtbaIdentity.utility()\n }\n });\n};\n","/* eslint-disable quotes */\nimport \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, Collection } from \"@/types\";\nimport type { OmitStrict } from \"@/_internal/types/extra\";\n\nimport path from \"node:path\";\n\nimport {\n isArray,\n isBoolean,\n isNonEmptyString,\n isNumber,\n isPlainObject,\n isSet,\n isUndefined,\n toObjectSet\n} from \"@/_internal/utils/helper\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\n\nimport {\n joinInline,\n joinLinesLoose,\n picocolors,\n plural\n} from \"@/utils/helper/formatter\";\nimport { fsExtra } from \"@/utils/server\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** @internal Default ***Options*** for {@link copyFileToDest | **`copy-file-to-dest`**}. */\nconst DEFAULT_CFTD_OPTIONS = {\n fileName: undefined,\n outputRoot: \"dist\",\n absoluteTarget: false,\n ignoreMissingSourceError: false\n} as const satisfies Omit<CopyFileToDestParam, \"source\" | \"target\">;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link copyFileToDest | **`copy-file-to-dest`**} validation args only. */\nconst validateItem = (\n item: CopyFileToDestParam,\n index?: number\n): never | void => {\n const indexText = isNumber(index) ? ` at index ${index}` : \"\";\n\n if (!isPlainObject(item)) {\n throw new TypeError(`Invalid item${indexText}: must be a 'plain object'!`);\n }\n\n if (!isNonEmptyString(item.source) && !isNonEmptyString(item.target)) {\n throw new TypeError(\n `Invalid item${indexText}: 'source' and 'target' must be 'non-empty string'!`\n );\n }\n\n if (!isNonEmptyString(item.source)) {\n throw new TypeError(\n `Invalid item${indexText}: 'source' must be 'non-empty string'!`\n );\n }\n if (!isNonEmptyString(item.target)) {\n throw new TypeError(\n `Invalid item${indexText}: 'target' must be 'non-empty string'!`\n );\n }\n\n if (!isUndefined(item.fileName) && !isNonEmptyString(item.fileName)) {\n throw new TypeError(\n `Invalid item${indexText}: 'fileName' must be 'non-empty string' if provided!`\n );\n }\n if (!isUndefined(item.outputRoot) && !isNonEmptyString(item.outputRoot)) {\n throw new TypeError(\n `Invalid item${indexText}: 'outputRoot' must be 'non-empty string' if provided!`\n );\n }\n if (!isUndefined(item.absoluteTarget) && !isBoolean(item.absoluteTarget)) {\n throw new TypeError(\n `Invalid item${indexText}: 'absoluteTarget' must be a 'boolean' if provided!`\n );\n }\n};\n/** @internal Util for {@link copyFileToDest | **`copy-file-to-dest`**}. */\nfunction buildCopySummary(\n successCount: number,\n errorCount: number,\n duplicateCount: number,\n label: string\n) {\n return picocolors.bold(\n joinLinesLoose(\n joinInline(\n picocolors.yellowBright(\"⚠\"),\n picocolors.blueBright(label) + picocolors.gray(\" -\"),\n picocolors.whiteBright(successCount > 0 ? \"Some\" : \"All\"),\n picocolors.whiteBright(\"files\"),\n picocolors.redBright(\"failed to copy\") + \":\"\n ),\n\n successCount < 1\n ? false\n : ` ${picocolors.greenBright(\"✔\")} ${picocolors.greenBright(successCount)} ${plural(successCount, \"file\")} copied.`,\n\n errorCount < 1\n ? false\n : ` ${picocolors.redBright(\"✖\")} ${picocolors.redBright(errorCount)} ${plural(errorCount, \"file\")} failed.`,\n\n duplicateCount < 1\n ? false\n : ` ${picocolors.yellowBright(\"⚠\")} ${picocolors.yellowBright(duplicateCount)} ${plural(duplicateCount, \"duplicate operation\")} skipped.`\n )\n );\n}\n/** @internal Util for {@link copyFileToDest | **`copy-file-to-dest`**}. */\nfunction buildOperationKey(item: CopyFileToDestParam) {\n return [\n item.source,\n item.target,\n item.fileName ?? \"\",\n item.outputRoot ?? DEFAULT_CFTD_OPTIONS.outputRoot,\n item.absoluteTarget ? 1 : 0\n ].join(\"|\");\n}\n\n/** ----------------------------------------------------------------\n * * ***Creates a `Set` of parameters for {@link copyFileToDest | **`copy-file-to-dest`**}.***\n * ----------------------------------------------------------------\n *\n * Utility helper to construct a `Set` of {@link CopyFileToDestParam | `CopyFileToDestParam`}\n * with proper type inference and editor autocomplete support.\n *\n * This is primarily useful when passing parameters as a `Set`,\n * since directly using `new Set([...])` may result in poor\n * TypeScript inference and missing autocomplete for object literals.\n *\n * ----------------------------------------------------------------\n * Behavior\n *\n * - Accepts a single parameter or an array of parameters.\n * - Automatically normalizes the input into a `Set`.\n *\n * ----------------------------------------------------------------\n *\n * @param items\n * A single {@link CopyFileToDestParam | `CopyFileToDestParam`} or an array of parameters.\n *\n * @returns\n * A `Set` containing the provided parameters.\n *\n * @example\n * ```ts\n * // single item\n * const setA = createCopyFileToDestParameterSet({\n * source: \"dist/index.d.ts\",\n * target: \"dist\"\n * });\n *\n * // multiple items\n * const setB = createCopyFileToDestParameterSet([\n * {\n * source: \"dist/a.d.ts\",\n * target: \"dist\"\n * },\n * {\n * source: \"dist/b.d.ts\",\n * target: \"dist\"\n * }\n * ]);\n *\n * // usage with copyFileToDest\n * await copyFileToDest(setB);\n * ```\n */\nexport function createCopyFileToDestParameterSet(\n items: CopyFileToDestParam | CopyFileToDestParam[]\n): Set<CopyFileToDestParam> {\n return new Set(isArray(items) ? items : [items]);\n}\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link copyFileToDest | **`copy-file-to-dest`**}. */\nexport const commandCftdIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"copy-file-to-dest\"\n});\n\n//? Types ----------------------------------------------------------------\n/** @internal Type for {@link copyFileToDest | **`copy-file-to-dest`**}.*/\ntype UniqueOperation = {\n item: CopyFileToDestParam;\n index: number;\n};\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link copyFileToDest | **`copy-file-to-dest`**}.***\n * ----------------------------------------------------------------\n */\nexport type CopyFileToDestOptions = OmitStrict<BaseOptions, \"patternOptions\">;\n/** ----------------------------------------------------------------\n * * ***Describes the parameter options for copying a single file to a destination path of {@link copyFileToDest | **`copy-file-to-dest`**}.***\n * ----------------------------------------------------------------\n */\nexport type CopyFileToDestParam = {\n /** ----------------------------------------------------------------\n * * ***Path to the source file to be copied.***\n * ----------------------------------------------------------------\n * Can be either an absolute path or a path relative to the project root.\n *\n * @example \"src/assets/logo.png\"\n */\n source: string;\n\n /** ----------------------------------------------------------------\n * * ***Target directory where the file will be copied.***\n * ----------------------------------------------------------------\n *\n * - When `absoluteTarget` is `false` **(default)**, this path is resolved relative to `outputRoot`.\n * - When `absoluteTarget` is `true`, this path is treated as an absolute path relative to the project root.\n *\n * @example \"assets/images\"\n */\n target: string;\n\n /** ----------------------------------------------------------------\n * * ***Optional custom file name for the copied file.***\n * ----------------------------------------------------------------\n *\n * If omitted, the original file name from `source` will be preserved.\n *\n * @example \"logo-new.png\"\n *\n * @default undefined\n */\n fileName?: string;\n\n /** ----------------------------------------------------------------\n * * ***Output root directory used when resolving the `target` path.***\n * ----------------------------------------------------------------\n *\n * When `absoluteTarget` is `false`, the final copy destination will be\n * `<project-root>/<outputRoot>/<target>`.\n *\n * @default \"dist\"\n * @example \"build\"\n */\n outputRoot?: string;\n\n /** ----------------------------------------------------------------\n * * ***When `true`, disables `outputRoot` prefixing and treats `target`\n * as an absolute path relative to the project root.***\n * ----------------------------------------------------------------\n *\n * Use this when you want to copy directly to an absolute path inside the project,\n * bypassing the `outputRoot` prefix.\n *\n * @default false\n */\n absoluteTarget?: boolean;\n\n /** ----------------------------------------------------------------\n * * ***When `true`, suppresses errors when the source file does not exist.***\n * ----------------------------------------------------------------\n *\n * - Instead of throwing or logging an error, the operation will be skipped.\n * - Useful in development or watch mode where build outputs may not be immediately available.\n *\n * @default false\n */\n ignoreMissingSourceError?: boolean;\n};\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Copy one or more files of any type into destination directories.***\n * ----------------------------------------------------------------\n *\n * This utility is **file-type agnostic** and can be used to copy any kind of asset,\n * including CSS, JavaScript, JSON, images, fonts, or other static files.\n *\n * - *The function supports:*\n * - Copying a **single file** using a single configuration object.\n * - Copying **multiple files** using an ***array*** or a ***Set*** of configuration objects.\n *\n * - When using a `Set`, it is recommended to use\n * {@link createCopyFileToDestParameterSet | **`createCopyFileToDestParameterSet`**}\n * to ensure proper TypeScript inference and autocomplete support.\n *\n * - By default, files are copied into a `dist` directory relative to the project root.\n * - This behavior can be customized per item via `outputRoot` or bypassed entirely\n * using `absoluteTarget`.\n *\n * ----------------------------------------------------------------\n *\n * @param parameter\n * A single {@link CopyFileToDestParam | **`CopyFileToDestParam`**} object,\n * an array, or a `Set` of {@link CopyFileToDestParam | **`CopyFileToDestParam`**}.\n *\n * - *When a collection is provided:*\n * - Each item is validated independently.\n * - Files are copied sequentially.\n * - Logging reflects the cumulative copy progress.\n *\n * ----------------------------------------------------------------\n *\n * @example\n * // Copy a single CSS file into \"dist/\".\n * // Result: \"dist/main.css\".\n * await copyFileToDest({\n * source: \"src/styles/main.css\",\n * target: \".\"\n * });\n *\n * @example\n * // Copy a single CSS file into \"dist/styles/\".\n * await copyFileToDest({\n * source: \"src/styles/main.css\",\n * target: \"styles\"\n * });\n *\n * @example\n * // Copy multiple files into \"dist/config/\" (using array).\n * // Result: \"dist/config/a.json\" and \"dist/config/b.json\".\n * await copyFileToDest([\n * {\n * source: \"src/config/a.json\",\n * target: \"config\"\n * },\n * {\n * source: \"src/config/b.json\",\n * target: \"config\"\n * }\n * ]);\n *\n * @example\n * // Copy multiple files into \"dist/config/\" (using Set).\n * // ⚠️ Requires explicit typing for proper inference.\n * await copyFileToDest(new Set<CopyFileToDestParam>([\n * {\n * source: \"src/config/a.json\",\n * target: \"config\"\n * },\n * {\n * source: \"src/config/b.json\",\n * target: \"config\"\n * }\n * ]));\n *\n * @example\n * // Recommended: using helper for Set (better DX).\n * await copyFileToDest(\n * createCopyFileToDestParameterSet([\n * {\n * source: \"src/config/a.json\",\n * target: \"config\"\n * },\n * {\n * source: \"src/config/b.json\",\n * target: \"config\"\n * }\n * ])\n * );\n *\n * @example\n * // Copy multiple files with a custom output root.\n * // Result: \"build/scripts/setup.js\" and \"build/scripts/runtime.js\".\n * await copyFileToDest([\n * {\n * source: \"src/scripts/setup.js\",\n * target: \"scripts\",\n * outputRoot: \"build\"\n * },\n * {\n * source: \"src/scripts/runtime.js\",\n * target: \"scripts\",\n * outputRoot: \"build\"\n * }\n * ]);\n *\n * @example\n * // Copy and rename a single file.\n * // Result: \"dist/config/app.json\".\n * await copyFileToDest({\n * source: \"src/config/app.config.json\",\n * target: \"config\",\n * fileName: \"app.json\"\n * });\n *\n * @example\n * ```ts\n * // Copy using an absolute target path (no outputRoot prefix).\n * // Result: \"<project-root>/config/runtime/config.json\".\n * await copyFileToDest({\n * source: \"src/runtime/config.json\",\n * target: \"config/runtime\",\n * absoluteTarget: true\n * });\n * ```\n *\n * ----------------------------------------------------------------\n *\n * @remarks\n * - The function ensures that all target directories exist before copying.\n * - Each item is validated to be a plain object with valid fields.\n * - The original file contents are copied without transformation.\n * - Errors during copying are caught and reported via the logger.\n */\nexport function copyFileToDest(\n parameter: CopyFileToDestParam,\n options?: CopyFileToDestOptions\n): Promise<void>;\nexport function copyFileToDest(\n parameter: CopyFileToDestParam[],\n options?: CopyFileToDestOptions\n): Promise<void>;\nexport function copyFileToDest(\n parameter: Set<CopyFileToDestParam>,\n options?: CopyFileToDestOptions\n): Promise<void>;\n// export async function copyFileToDest(\n// parameter: Collection<CopyFileToDestParam>,\n// options?: CopyFileToDestOptions\n// ): Promise<void>;\nexport async function copyFileToDest(\n parameter: Collection<CopyFileToDestParam>,\n options: CopyFileToDestOptions = {}\n) {\n const loggerLevel = resolveLogVerbosity(options);\n\n try {\n const { __commandTitle } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandCftdIdentity.utility(),\n \"\"\n )\n );\n }\n\n if (isArray(parameter) || isSet(parameter)) {\n let i = 0;\n for (const item of parameter) {\n validateItem(item, i++);\n }\n } else if (isPlainObject(parameter)) {\n validateItem(parameter);\n } else {\n throw new TypeError(\n \"Parameter argument must be a 'plain object', 'array of plain objects' or an 'set of plain objects'!\"\n );\n }\n\n const list = [...toObjectSet(parameter)];\n const uniqueLists: UniqueOperation[] = [];\n const seenOperations = new Set<string>();\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n\n list.forEach((item, i) => {\n const {\n source,\n target,\n fileName = DEFAULT_CFTD_OPTIONS.fileName,\n outputRoot = DEFAULT_CFTD_OPTIONS.outputRoot,\n absoluteTarget = DEFAULT_CFTD_OPTIONS.absoluteTarget,\n ignoreMissingSourceError = DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError\n } = item;\n\n const defaultFileName = fileName ?? path.basename(source);\n\n const indexText = list.length > 1 ? `[${i}]` : \"\";\n\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.source`,\n source,\n \"overridden\",\n true\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.target`,\n target,\n \"overridden\",\n true\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.fileName`,\n fileName || defaultFileName,\n BUILD_LOGGER.SOURCE_OF(fileName, DEFAULT_CFTD_OPTIONS.fileName)\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.outputRoot`,\n outputRoot,\n BUILD_LOGGER.SOURCE_OF(outputRoot, DEFAULT_CFTD_OPTIONS.outputRoot)\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.absoluteTarget`,\n absoluteTarget,\n BUILD_LOGGER.SOURCE_OF(\n absoluteTarget,\n DEFAULT_CFTD_OPTIONS.absoluteTarget\n )\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.ignoreMissingSourceError`,\n ignoreMissingSourceError,\n BUILD_LOGGER.SOURCE_OF(\n ignoreMissingSourceError,\n DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError\n )\n );\n\n if (i < list.length - 1) {\n console.log(\n picocolors.gray(\n \" ==========================================================================\"\n )\n );\n }\n });\n\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_LOG_LEVEL)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Copy File\",\n textDirectAction: \"action:\"\n });\n }\n\n let count = 0;\n let errorCount = 0;\n let duplicateCount = 0;\n\n for (let index = 0; index < list.length; index++) {\n const item = list[index]!;\n\n const key = buildOperationKey(item);\n\n if (seenOperations.has(key)) {\n duplicateCount++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Copy File\",\n reasonType: \"\",\n textDirectAction: \"at\",\n reasonSkipAction: \"duplicate operation\",\n reasonEndText:\n item.source +\n \" \" +\n picocolors.blueBright(\n `('parameter' index: ${picocolors.magentaBright(index)})`\n )\n });\n }\n continue;\n }\n\n seenOperations.add(key);\n uniqueLists.push({ item, index });\n }\n\n const procCwd = process.cwd();\n\n for (let i = 0; i < uniqueLists.length; i++) {\n const uniqList = uniqueLists[i]!;\n count++;\n\n const {\n source,\n target,\n fileName = DEFAULT_CFTD_OPTIONS.fileName,\n outputRoot = DEFAULT_CFTD_OPTIONS.outputRoot,\n absoluteTarget = DEFAULT_CFTD_OPTIONS.absoluteTarget,\n ignoreMissingSourceError = DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError\n } = uniqList.item;\n\n const absSource = path.resolve(procCwd, source);\n\n const exists = await fsExtra.pathExists(absSource);\n\n if (!exists) {\n if (ignoreMissingSourceError) continue;\n\n errorCount++;\n\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_PROCESS_COPY_ERROR({\n copyFrom: source,\n index: uniqList.index,\n indexKey: \"parameter\",\n count: loggerLevel === \"error\" ? errorCount : count,\n actionName: \"Failed to Copy File\",\n errorReason: \"the source file was not found\"\n });\n }\n } else {\n const absTargetDir = path.resolve(\n procCwd,\n absoluteTarget ? \"\" : outputRoot,\n target\n );\n\n const absTargetFile = path.join(\n absTargetDir,\n fileName ?? path.basename(source)\n );\n\n await fsExtra.ensureDir(absTargetDir);\n\n await fsExtra.copy(absSource, absTargetFile);\n\n const relSrc = path.relative(procCwd, absSource).replace(/\\\\/g, \"/\");\n const relDest = path\n .relative(procCwd, absTargetFile)\n .replace(/\\\\/g, \"/\");\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS_COPY({\n actionName: \"File copied\",\n count,\n copyFrom: relSrc,\n copyTo: relDest\n });\n }\n }\n }\n\n const successCount = count - errorCount;\n\n if (\n (errorCount > 0 || duplicateCount > 0) &&\n loggerLevel !== \"silent\" &&\n !canLog(loggerLevel, VERBOSE_LOG)\n ) {\n console.log(\n buildCopySummary(\n successCount,\n errorCount,\n duplicateCount,\n \"[Copy File to Dest]\"\n )\n );\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0 && errorCount === 0 && duplicateCount === 0) {\n BUILD_LOGGER.ON_FINISH({\n textSuccess: \"Successfully\",\n actionName: \"copied\",\n count: count\n });\n } else if (successCount > 0) {\n console.log(\n buildCopySummary(\n successCount,\n errorCount,\n duplicateCount,\n \"[Copy File to Dest]\"\n )\n );\n } else if (successCount === 0 && errorCount !== 0) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: '\"Copy File\"',\n reasonSkipAction: \"failed\",\n reasonEndText: `${count > 1 ? \"all \" : \"\"}files`,\n reasonType: \"to\",\n textDirectAction: \"copy\"\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: '\"Copy File\"',\n reasonSkipAction: errorCount > 0 ? \"nothing found\" : \"nothing\",\n reasonEndText: \"copy\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Copying File\",\n error\n });\n }\n }\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n detectModuleKindFromContent,\n extractAndHoistBanner,\n extractDirectives,\n JS_OUTPUT_FILE_RE,\n type ModuleKind,\n stripUseStrict\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport {\n flattenStrings,\n isArray,\n isNonEmptyString,\n toStringSet\n} from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **ensure css import** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link ensureCssImport | **`ensure-css-import`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_ECI_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **ensure css import** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link ensureCssImport | **`ensure-css-import`**}.\n */\nexport const resolvedEciPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_ECI_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link ensureCssImport | **`ensure-css-import`**}. */\nconst DEFAULT_ECI_OPTIONS = {\n cssImportPath: [] as string[],\n dedupe: true,\n sort: false,\n minify: false,\n patternOptions: resolvedEciPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies EnsureCssImportOptions;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction _normalizeBody(code: string, minify: boolean = false): string {\n let out = code.replace(/\\r\\n/g, EOL);\n out = out.replace(/\\*\\/\\n+/, `*/${EOL}`);\n out = out.replace(/(\\*\\/)([^\\n])/g, `$1${EOL}$2`);\n const directiveMatch = out.match(/^((?:\"use\\s[\\w-]+\";|'use\\s[\\w-]+';\\s*)+)/);\n if (directiveMatch) {\n const directivesBlock = directiveMatch[1] || \"\";\n const normalizedDirectives = directivesBlock.replace(/\\n+/g, EOL);\n out = out.replace(directivesBlock, normalizedDirectives + EOL);\n }\n out = out.replace(/\\n{3,}/g, `${EOL}${EOL}`);\n out = out.trimEnd() + (minify ? \"\" : EOL);\n return out;\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction inlineCssImports(code: string) {\n return code.replace(\n /((?:import\\s+[\"'][^\"']+\\.css[\"'];\\s*\\n?|require\\([\"'][^\"']+\\.css[\"']\\);\\s*\\n?){2,})/g,\n (block) =>\n block\n .split(/\\n+/)\n .map((l) => l.trim())\n .join(\"\")\n );\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction createCssStatements(kind: ModuleKind, cssImports: string[]): string[] {\n return cssImports.map((p) =>\n kind === \"cjs\" ? `require(\"${p}\");` : `import \"${p}\";`\n );\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction getMissingCssStatements(\n body: string,\n cssImports: string[],\n kind: ModuleKind,\n dedupe: boolean\n): { missing: string[]; cleanedBody: string } {\n const cleanedBody = body;\n const cssStatements = createCssStatements(kind, cssImports);\n\n const missing = dedupe\n ? cssStatements.filter((stmt) => !cleanedBody.includes(stmt))\n : cssStatements;\n\n return { missing, cleanedBody };\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction injectCssSmart({\n shebang,\n banner,\n directives,\n rest,\n cssStatements,\n kind,\n minify\n}: {\n shebang: string;\n banner: string;\n directives: string;\n rest: string;\n cssStatements: string[];\n kind: ModuleKind;\n minify?: boolean;\n}) {\n let out = minify ? shebang.trim() + EOL : shebang;\n out += minify ? banner.trim() + EOL : banner;\n let finalDirectives = stripUseStrict(directives, {\n trimEnd: minify,\n trimStart: minify\n });\n\n if (kind === \"cjs\") {\n finalDirectives = `\"use strict\";${EOL}` + finalDirectives.trimStart();\n }\n\n // finalDirectives = finalDirectives.trimStart().replace(/\\s*$/, EOL);\n\n out += finalDirectives;\n out += cssStatements.join(EOL) + (minify ? \"\" : EOL);\n out += rest.replace(/^\\n+/, minify ? \"\" : EOL);\n return out.trimStart();\n}\n/** ----------------------------------------------------------------\n * * ***Normalizes CSS import path input into a clean string array.***\n * ----------------------------------------------------------------\n *\n * Converts a `cssImportPath` option value into a normalized array\n * of non-empty strings for internal processing.\n *\n * - *Normalization rules:*\n * - Single value is wrapped into an array.\n * - Nested arrays are flattened recursively.\n * - Each string is trimmed.\n * - Empty strings are removed.\n *\n * The returned array is always a **new instance** and does not mutate\n * the original input.\n *\n * @param {EnsureCssImportOptions[\"cssImportPath\"]} input - CSS import path option.\n *\n * @returns {string[]} Normalized list of CSS import paths.\n *\n * @example\n * ```ts\n * normalizeCssImports(\"style.css\");\n * // ➔ [\"style.css\"]\n * ```\n *\n * @example\n * ```ts\n * normalizeCssImports([\" a.css \", [\"b.css\", \"\"], null]);\n * // ➔ [\"a.css\", \"b.css\"]\n * ```\n *\n * @internal Util for {@link ensureCssImport | **`ensure-css-import`**}.\n */\nfunction normalizeCssImports(\n input: EnsureCssImportOptions[\"cssImportPath\"]\n): string[] {\n return flattenStrings(isArray(input) ? input : [input])\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link ensureCssImport | **`ensure-css-import`**}. */\nexport const commandEciIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"ensure-css-import\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link ensureCssImport | **`ensure-css-import`**}.***\n * ----------------------------------------------------------------\n */\nexport type EnsureCssImportOptions = {\n /** ----------------------------------------------------------------\n * * ***CSS import path(s) to ensure exist in JS output.***\n * ----------------------------------------------------------------\n *\n * Accepts a single path or multiple paths.\n *\n * @example\n * ```ts\n * \"./search.css\"\n * ```\n *\n * @example\n * ```ts\n * [\"./search.css\", \"./theme.css\"]\n * ```\n */\n cssImportPath: string | readonly (string | readonly string[])[] | Set<string>;\n\n /** ----------------------------------------------------------------\n * * ***Remove duplicate CSS imports (recommended).***\n * ----------------------------------------------------------------\n *\n * @default true\n */\n dedupe?: boolean;\n\n /** ----------------------------------------------------------------\n * * ***Sort CSS imports alphabetically before inserting.***\n * ----------------------------------------------------------------\n *\n * @default false\n */\n sort?: boolean;\n\n /** --------------------------------------------------------\n * * ***Minify JS output (except directive prologue).***\n * --------------------------------------------------------\n *\n * - Keeps `\"use client\"` / `\"use strict\"` on separate lines.\n * - Everything else is collapsed into a single line.\n *\n * @default false\n */\n minify?: boolean;\n} & BaseOptions<\n typeof DEFAULT_ECI_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_ECI_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Ensures CSS import(s) exist in compiled JavaScript files.***\n * ----------------------------------------------------------------\n * - *Behavior:*\n * - Supports **multiple CSS imports**.\n * - Fully **idempotent**.\n * - Optional **dedupe & sorting**.\n *\n * @param {string | string[] | Set<string>} pattern\n * Glob pattern(s) pointing to compiled JS files.\n *\n * @param {EnsureCssImportOptions} options\n * Configuration options.\n *\n * @example\n * ```ts\n * await ensureCssImport(\"dist/**\\/*.js\", {\n * cssImportPath: [\"./search.css\", \"./theme.css\"],\n * dedupe: true,\n * sort: true,\n * minify: true\n * });\n * ```\n */\nexport const ensureCssImport = async (\n pattern: StringCollection,\n options: EnsureCssImportOptions\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_ECI_OPTIONS.logLevel\n );\n\n try {\n const {\n patternOptions = DEFAULT_ECI_OPTIONS.patternOptions,\n cssImportPath,\n dedupe = DEFAULT_ECI_OPTIONS.dedupe,\n sort = DEFAULT_ECI_OPTIONS.sort,\n minify = DEFAULT_ECI_OPTIONS.minify,\n __commandTitle\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandEciIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_ECI_PATTERN_POLICY\n );\n\n let cssImports = normalizeCssImports(cssImportPath);\n\n if (cssImports.length === 0) {\n throw new Error(\"`cssImportPath` option must not be empty.\");\n }\n\n if (dedupe) cssImports = Array.from(new Set(cssImports));\n\n if (sort) cssImports.sort();\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_ECI_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.cssImportPath\",\n cssImports,\n BUILD_LOGGER.SOURCE_OF(cssImports, DEFAULT_ECI_OPTIONS.cssImportPath),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.dedupe\",\n dedupe,\n BUILD_LOGGER.SOURCE_OF(dedupe, DEFAULT_ECI_OPTIONS.dedupe)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.sort\",\n sort,\n BUILD_LOGGER.SOURCE_OF(sort, DEFAULT_ECI_OPTIONS.sort)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.minify\",\n minify,\n BUILD_LOGGER.SOURCE_OF(minify, DEFAULT_ECI_OPTIONS.minify)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_ECI_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Ensuring CSS Import\"\n });\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const { banner, body, shebang } = extractAndHoistBanner(content);\n const kind = detectModuleKindFromContent(content);\n\n const { missing, cleanedBody } = getMissingCssStatements(\n body,\n cssImports,\n kind,\n dedupe\n );\n\n if (missing.length === 0) continue;\n\n const { directives, rest } = extractDirectives(cleanedBody);\n\n let updated = injectCssSmart({\n shebang,\n banner,\n directives,\n rest,\n kind,\n minify: options.minify,\n cssStatements: missing\n });\n\n if (options.minify) {\n updated = inlineCssImports(updated);\n }\n\n if (updated !== content) {\n try {\n await fsExtra.promises.writeFile(filePath, updated, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"CSS Import\",\n count,\n nameDirect: filePath\n });\n }\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Ensuring CSS Import\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Ensuring CSS Import\",\n reasonType: \"file\",\n reasonEndText: \"check\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Ensuring CSS Import\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose, picocolors } from \"@/utils/helper/formatter\";\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **ensure final newline** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link ensureFinalNewline | **`ensure-final-newline`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_EFN_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **ensure final newline** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link ensureFinalNewline | **`ensure-final-newline`**}.\n */\nexport const resolvedEfnPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_EFN_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link ensureFinalNewline | **`ensure-final-newline`**}. */\nconst DEFAULT_EFN_OPTIONS = {\n patternOptions: resolvedEfnPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies EnsureFinalNewlineOptions;\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link ensureFinalNewline | **`ensure-final-newline`**}. */\nexport const commandEfnIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"ensure-final-newline\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link ensureFinalNewline | **`ensure-final-newline`**}.***\n * ----------------------------------------------------------------\n */\nexport type EnsureFinalNewlineOptions = BaseOptions<\n typeof DEFAULT_EFN_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_EFN_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Ensure files end with exactly one final newline.***\n * ----------------------------------------------------------------\n *\n * Scans files matching the provided glob pattern(s) and ensures that\n * **each file ends with exactly one newline character**.\n *\n * - *Behavior:*\n * - Removes **all trailing newline characters** at the end of the file.\n * - Appends **exactly one** platform-consistent newline (`EOL`).\n * - Preserves all internal formatting and whitespace.\n * - Does **not** modify files that are already compliant.\n *\n * - *Newline handling:*\n * - Supports both `LF` (`\\n`) and `CRLF` (`\\r\\n`).\n * - Uses **`EOL`** to ensure consistent output across the project.\n *\n * - *Safety:*\n * - Skips non-existent paths.\n * - Skips non-file entries (directories, symlinks, etc.).\n * - Writes only when the file content actually changes.\n *\n * @param {string | string[] | Set<string>} pattern\n * Glob pattern(s) pointing to files that should be checked and normalized.\n *\n * @param {EnsureFinalNewlineOptions} [options]\n * Internal execution options (CLI vs utility context).\n *\n * @example\n * ```ts\n * await ensureFinalNewline(\"dist/**\\/*.{js,cjs,mjs,d.ts}\");\n * ```\n *\n * @example\n * ```ts\n * await ensureFinalNewline([\"dist/**\\/*.js\", \"dist/**\\/*.d.ts\"]);\n * ```\n *\n * @remarks\n * This utility is typically executed **post-build** to ensure output\n * files follow POSIX tooling expectations and common formatting conventions.\n */\nexport const ensureFinalNewline = async (\n pattern: StringCollection,\n options: EnsureFinalNewlineOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_EFN_OPTIONS.logLevel\n );\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_EFN_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandEfnIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_EFN_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_EFN_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_EFN_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Ensuring Final Newline\"\n });\n }\n\n // const files = new Set<string>();\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n // for (const file of matched.sort()) files.add(file);\n\n let count = 0;\n\n for (const filePath of files) {\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const normalized = content.replace(/(\\r?\\n)*$/, EOL);\n\n if (normalized === content) continue;\n\n try {\n await fsExtra.promises.writeFile(filePath, normalized, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"Final Newline\",\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Ensuring Final Newline\",\n count\n });\n } else if (files.length < 1) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Ensuring Final Newline\",\n reasonSkipAction: `no files found matching the pattern${picocolors.reset(\n \",\"\n )}`,\n reasonType: \"\",\n textDirectAction: \"no need to fix\",\n reasonEndText: \"end of file (EOF)\"\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Ensuring Final Newline\",\n reasonSkipAction: `all files are valid${picocolors.reset(\",\")}`,\n reasonType: \"\",\n textDirectAction: \"no need to fix\",\n reasonEndText: \"end of file (EOF)\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Ensuring Final Newline\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport path from \"node:path\";\n\nimport type { AnyString, Awaitable } from \"@/_internal/types/extra\";\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { TS_DECLARATION_FILE_RE } from \"@/_internal/utils/source\";\nimport { BUILD_LOGGER, sourceOf } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport {\n EOL,\n joinLinesLoose,\n picocolors as pcr\n} from \"@/utils/helper/formatter\";\nimport { fastGlob, fsExtra } from \"@/utils/server\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\nimport { generatePackageBanner } from \"../package-banner\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **generate reference index** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link generateReferenceIndex | **`generate-reference-index`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_GRI_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<true, true>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **generate reference index** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link generateReferenceIndex | **`generate-reference-index`**}.\n */\nexport const resolvedGriPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_GRI_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nconst DEFAULT_GRI_OPTIONS = {\n outDir: \"dist/.references\",\n outFileName: \"index.d.ts\",\n inputDirReference: \"dist\",\n withExportTypes: false,\n banner: true,\n onlyDeclarations: true,\n patternOptions: resolvedGriPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies GenerateReferenceOptions;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nfunction normalizeRelative(from: string, to: string) {\n return path\n .relative(from, to)\n .replace(/\\\\/g, \"/\")\n .replace(/^([^./])/, \"./$1\"); // ensure ./ or ../\n}\n/** @internal Util for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nconst resolveExportModulePath = (relativePath: string) => {\n const parsed = path.parse(relativePath);\n\n let baseName = parsed.name;\n\n // remove trailing \".d\" ONLY for declaration outputs\n if (baseName.endsWith(\".d\")) {\n baseName = baseName.slice(0, -2);\n }\n\n return path.join(parsed.dir, baseName).replace(/\\\\/g, \"/\");\n};\n/** ----------------------------------------------------------------\n * * ***Validated output configuration input.***\n * ----------------------------------------------------------------\n *\n * Raw configuration object passed into `validateOut`.\n *\n * - Each field will be normalized and validated before use.\n *\n * @internal Utils for {@link generateReferenceIndex | **`generate-reference-index`**}.\n */\nconst validateOut = ({\n outDir,\n outFileName,\n inputDirReference\n}: {\n /** --------------------------------------------------------------\n * * ***Output directory path.***\n * --------------------------------------------------------------\n *\n * Base directory where the generated index file will be written.\n *\n * - Leading & trailing whitespace will be trimmed.\n * - Trailing slash will be removed.\n *\n * @example\n * `\"dist/\"` ➔ `\"dist\"`\n */\n outDir: string;\n\n /** --------------------------------------------------------------\n * * ***Output declaration file name.***\n * --------------------------------------------------------------\n *\n * Must be a **file name only**, not a path.\n *\n * - ❌ `\"dist/index.d.ts\"`.\n * - ❌ `\"../index.d.ts\"`.\n * - ✅ `\"index.d.ts\"`.\n *\n * Used together with `outDir` to build the final output path.\n */\n outFileName: string;\n\n /** --------------------------------------------------------------\n * * ***Input reference base directory.***\n * --------------------------------------------------------------\n *\n * Used to strip the leading path from matched files when\n * generating reference and export paths.\n *\n * - ***Example:***\n * - inputDirReference: `\"dist\"`.\n * - file: `\"dist/utils/logger.d.ts\"`.\n * - result: `\"utils/logger.d.ts\"`.\n */\n inputDirReference: string;\n}) => {\n const normalizePath = (value: string) => {\n // if (!value) return undefined;\n\n const trimmed = value.trim();\n // if (!trimmed) return undefined;\n\n // remove trailing slash (\"/foo/bar/\" -> \"/foo/bar\")\n return trimmed.endsWith(\"/\") ? trimmed.slice(0, -1) : trimmed;\n };\n\n const normalizeFileName = (value: string) => {\n // if (!value) return undefined;\n\n const trimmed = value.trim();\n // if (!trimmed) return undefined;\n\n // optional: prevent path traversal\n if (trimmed.includes(\"/\") || trimmed.includes(\"\\\\\")) {\n throw new Error(`Invalid outFileName: \"${value}\"`);\n }\n\n return trimmed;\n };\n\n return {\n outDir: normalizePath(outDir),\n inputDirReference: normalizePath(inputDirReference),\n outFileName: normalizeFileName(outFileName)\n };\n};\n/** @internal Util for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nconst resolveBanner = async (banner: BannerInput): Promise<string> => {\n if (banner === false) return \"\";\n\n if (banner === true) {\n return (await generatePackageBanner()) + EOL;\n }\n\n const resolved = await banner;\n\n return isNonEmptyString(resolved) ? resolved : \"\";\n};\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link generateReferenceIndex | **`generate-reference-index`**}. */\nexport const commandGriIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"generate-reference-index\"\n});\n\n//? Types ----------------------------------------------------------------\n/** @internal Type for {@link generateReferenceIndex | **`generate-reference-index`**}.*/\ntype BannerInput = true | AnyString | false | Awaitable<AnyString>;\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link generateReferenceIndex | **`generate-reference-index`**}.***\n * ----------------------------------------------------------------\n */\nexport type GenerateReferenceOptions = {\n /** --------------------------------------------------------------\n * * ***Output directory.***\n * --------------------------------------------------------------\n *\n * Directory where the generated index file will be written.\n *\n * @default \"dist/.references\"\n */\n outDir?: string;\n\n /** --------------------------------------------------------------\n * * ***Output index file name.***\n * --------------------------------------------------------------\n *\n * Name of the generated `.d.ts` index file.\n *\n * @default \"index.d.ts\"\n */\n outFileName?: string;\n\n /** --------------------------------------------------------------\n * * ***Enable exported type aggregation.***\n * --------------------------------------------------------------\n *\n * When enabled, generates:\n *\n * ```ts\n * export * from \"./module\";\n * ```\n *\n * for each unique declaration entry.\n *\n * @default false\n */\n withExportTypes?: boolean;\n\n /** --------------------------------------------------------------\n * * ***Base directory for resolving reference paths.***\n * --------------------------------------------------------------\n *\n * Used to compute relative paths inside the generated index file.\n *\n * @default \"dist\"\n */\n inputDirReference?: string;\n\n /** --------------------------------------------------------------\n * * ***Restrict input to TypeScript declaration files only.***\n * --------------------------------------------------------------\n *\n * When enabled (`true`), this option filters the input files to include **only**\n * TypeScript declaration files with extensions `.d.ts`, `.d.mts`, and `.d.cts`.\n *\n * This filtering is applied **after** matching files by the provided glob patterns,\n * effectively excluding all other file types, including JavaScript outputs\n * (`.js`, `.mjs`, `.cjs`) and TypeScript source files (`.ts`, `.mts`, `.cts`).\n *\n * - *Examples:*\n * - With a pattern like `\"dist/**\\/*.d.ts\"`, enabling this option has no practical effect,\n * since the pattern already matches only declaration files.\n * - With a broader pattern such as `\"dist/**\\/*\"` or `\"dist/**\\/*.ts\"`,\n * enabling this option will exclude non-declaration files (e.g., `.ts` source files),\n * resulting in only declaration files being included.\n * - If your patterns include JavaScript outputs (`.js`, `.mjs`, `.cjs`),\n * enabling this option will exclude those files as well.\n *\n * When disabled (`false`), all matched files are included regardless of extension,\n * so JavaScript outputs and source files matching the patterns will be part of\n * the reference and export generation.\n *\n * Use this option and set to `true`, when you want to guarantee that only TypeScript declaration files\n * are included in the generated references and exports, preventing accidental\n * inclusion of source or JavaScript build output files.\n *\n * @default true\n */\n onlyDeclarations?: boolean;\n\n /** --------------------------------------------------------------\n * * ***Output banner configuration.***\n * --------------------------------------------------------------\n *\n * Controls the banner text prepended to the generated output file.\n *\n * - `true` **(default)** ➔ automatically generates banner from `package.json`\n * using {@link generatePackageBanner | `generatePackageBanner`}.\n * - `false` ➔ disables banner injection entirely.\n * - `string` ➔ uses the provided custom banner text.\n * - `Promise<string>` ➔ resolved and used as banner text.\n *\n * @default true\n */\n banner?: BannerInput;\n} & BaseOptions<\n typeof DEFAULT_GRI_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_GRI_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Generates a TypeScript reference index file (.d.ts).***\n * ----------------------------------------------------------------\n *\n * This function resolves files from the given glob pattern(s) and generates\n * a single declaration index file containing:\n *\n * - `/// \\<reference path=\"...\" />` directives.\n * - optional `export * from \"...\"` statements.\n *\n * Supported input files include declaration and JavaScript module outputs:\n * - `.d.ts`.\n * - `.js`.\n * - `.cjs`.\n * - `.mjs`.\n *\n * The output is typically used to aggregate multiple declaration or build\n * artifacts into a single entry point.\n *\n * @param pattern - Glob pattern or list of patterns used to match output files, supports `.d.ts`, `.js`, `.cjs`, and `.mjs` extensions.\n *\n * @param options - Reference index generation options, see {@link GenerateReferenceOptions | **`GenerateReferenceOptions`**}.\n *\n * @example\n * Basic usage with declaration files only:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.d.ts\");\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/post.d.ts\" />\n * ```\n *\n * @example\n * Restrict to declaration files even if pattern matches other files,\n * by default `onlyDeclarations` options is `true`:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*\", { onlyDeclarations: true });\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/post.d.cts\" />\n * ```\n *\n * @example\n * Include all matched files (source `.ts` and JS outputs) without filtering declaration files only:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*\", { onlyDeclarations: false });\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../models/order.ts\" />\n * /// \\<reference path=\"../models/user.js\" />\n * /// \\<reference path=\"../models/another.cjs\" />\n * ```\n *\n * (Here, both `.ts` source files and declaration files are\n * included if matched, because `onlyDeclarations` is `false`).\n *\n * @example\n * Include JavaScript build outputs with no declaration-only restriction:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.js\", { onlyDeclarations: false });\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../runtime/helpers.js\" />\n * /// \\<reference path=\"../runtime/constants.js\" />\n * ```\n *\n * (JavaScript files are included because `onlyDeclarations` is `false`).\n *\n * @example\n * Restrict to declaration files when pattern includes source `.ts` and JS files:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.ts\");\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../models/user.d.ts\" />\n * /// \\<reference path=\"../models/order.d.ts\" />\n * ```\n *\n * (Here `.ts` source files are ignored; only `.d.ts` declarations are included).\n *\n * ----------------------------------------------------------------\n *\n * ***--- Existing examples below remain unchanged ---***\n *\n * @example\n * Generate references from types JavaScript build outputs:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.d.{js,cjs,mjs}\");\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../runtime/helpers.d.js\" />\n * /// \\<reference path=\"../runtime/constants.d.mjs\" />\n * ```\n *\n * @example\n * Mix declaration and JavaScript module outputs:\n * ```ts\n * await generateReferenceIndex([\n * \"dist/**\\/*.d.ts\",\n * \"dist/**\\/*.d.{js,cjs,mjs}\"\n * ]);\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/post.d.mts\" />\n * /// \\<reference path=\"../runtime/helpers.d.cjs\" />\n * ```\n *\n * @example\n * Generate reference index and export all resolved modules:\n * ```ts\n * await generateReferenceIndex(\n * \"dist/**\\/*\",\n * { withExportTypes: true }\n * );\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/user.d.cts\" />\n * /// \\<reference path=\"../types/post.d.ts\" />\n * /// \\<reference path=\"../types/post.d.cts\" />\n *\n * // Exported Types:\n * export * from \"../types/user\";\n * export * from \"../types/post\";\n * ```\n *\n * @example\n * Use multiple input directories with a shared reference base:\n * ```ts\n * await generateReferenceIndex(\n * [\n * \"dist/types/**\\/*.d.ts\",\n * \"dist/generated/**\\/*.d.{js,cjs,mjs}\"\n * ],\n * {\n * inputDirReference: \"dist\",\n * withExportTypes: true\n * }\n * );\n * ```\n *\n * Result (`dist/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../data/config.d.cjs\" />\n * /// \\<reference path=\"../generated/schema.d.js\" />\n *\n * // Exported Types:\n * export * from \"../types/user\";\n * export * from \"../generated/schema\";\n * ```\n *\n * @example\n * Customize output location and file name:\n * ```ts\n * await generateReferenceIndex(\n * \"build/**\\/*\",\n * {\n * outDir: \"build/types\",\n * outFileName: \"references-types.d.ts\"\n * }\n * );\n * ```\n *\n * Result (`build/types/references-types.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../models/user.d.ts\" />\n * /// \\<reference path=\"../models/order.d.cts\" />\n * /// \\<reference path=\"../models/account.d.mts\" />\n * ```\n */\nexport const generateReferenceIndex = async (\n pattern: StringCollection,\n options: GenerateReferenceOptions = {}\n): Promise<void> => {\n let _withExportTypes: boolean = DEFAULT_GRI_OPTIONS.withExportTypes;\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_GRI_OPTIONS.logLevel\n );\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_GRI_OPTIONS.patternOptions,\n outDir: _outDir = DEFAULT_GRI_OPTIONS.outDir,\n outFileName: _outFileName = DEFAULT_GRI_OPTIONS.outFileName,\n inputDirReference:\n _inputDirReference = DEFAULT_GRI_OPTIONS.inputDirReference,\n withExportTypes = DEFAULT_GRI_OPTIONS.withExportTypes,\n banner = DEFAULT_GRI_OPTIONS.banner,\n onlyDeclarations = DEFAULT_GRI_OPTIONS.onlyDeclarations\n } = options;\n\n _withExportTypes = withExportTypes;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandGriIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_GRI_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"outDir\",\n _outDir,\n sourceOf(_outDir, DEFAULT_GRI_OPTIONS.outDir)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_GRI_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.outFileName\",\n _outFileName,\n sourceOf(_outFileName, DEFAULT_GRI_OPTIONS.outFileName)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.inputDirReference\",\n _inputDirReference,\n sourceOf(_inputDirReference, DEFAULT_GRI_OPTIONS.inputDirReference)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.withExportTypes\",\n withExportTypes,\n sourceOf(withExportTypes, DEFAULT_GRI_OPTIONS.withExportTypes)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.banner\",\n banner,\n sourceOf(banner, DEFAULT_GRI_OPTIONS.banner)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_GRI_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Generating References\"\n });\n }\n\n let files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n if (onlyDeclarations) {\n files = files.filter((file) => TS_DECLARATION_FILE_RE.test(file));\n }\n\n const { inputDirReference, outDir, outFileName } = validateOut({\n outDir: _outDir,\n outFileName: _outFileName,\n inputDirReference: _inputDirReference\n });\n\n const outDirAbs = path.resolve(outDir);\n const outFileAbs = path.join(outDirAbs, outFileName);\n\n const outFileNormalize = path\n .relative(process.cwd(), outFileAbs)\n .replace(/\\\\/g, \"/\");\n\n const lines = new Set<string>();\n let referenceCount = 0;\n\n const inputDirRefAbs = path.resolve(inputDirReference);\n\n const reference = files\n .map((f, i) => {\n const referencedAbs = path.resolve(f);\n\n if (\n !referencedAbs.startsWith(inputDirRefAbs + path.sep) ||\n referencedAbs === outFileAbs\n ) {\n return;\n }\n\n const referencePath = normalizeRelative(\n path.dirname(outFileAbs),\n referencedAbs\n );\n\n const logPath = path\n .relative(inputDirRefAbs, referencedAbs)\n .replace(/\\\\/g, \"/\");\n const displayPath = `${inputDirReference}/${logPath}`;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS_REFERENCING({\n actionName: \"Generated Reference\",\n count: i + 1,\n referenceFrom: displayPath,\n referenceTo: outFileNormalize\n });\n }\n\n referenceCount++;\n\n return `/// <reference path=\"${referencePath}\" />`;\n })\n .filter(Boolean);\n\n if (Array.isArray(reference) && reference.length > 0) {\n lines.add(\"//! References Paths:\");\n lines.add(reference.join(EOL));\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (referenceCount > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Generating Reference\",\n count: files.length,\n typeCount: \"reference\"\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Generating References\",\n reasonEndText: \"referencing\",\n reasonType: \"references\"\n });\n }\n }\n\n if (withExportTypes) {\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n pcr.bold(\n pcr.magentaBright(\n `${EOL}=======================================================================================${EOL}`\n )\n )\n );\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Adding Exported Types\"\n });\n }\n\n const exportLines = new Set<string>();\n let exportCount = 0;\n\n files.forEach((f) => {\n const referencedAbs = path.resolve(f);\n\n if (\n !referencedAbs.startsWith(inputDirRefAbs + path.sep) ||\n referencedAbs === outFileAbs\n ) {\n return;\n }\n\n const relativeToInputDirRef = path\n .relative(inputDirRefAbs, referencedAbs)\n .replace(/\\\\/g, \"/\");\n\n const exportModulePath = resolveExportModulePath(relativeToInputDirRef);\n\n const exportPath = normalizeRelative(\n path.dirname(outFileAbs),\n path.resolve(inputDirReference, exportModulePath)\n );\n\n const line = `export * from \"${exportPath}\";`;\n\n if (!exportLines.has(line)) {\n exportCount++;\n\n const logPath = path\n .relative(inputDirRefAbs, referencedAbs)\n .replace(/\\\\/g, \"/\");\n const displayPath = `${inputDirReference}/${logPath}`;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS_REFERENCING({\n actionName: \"Exported Type\",\n count: exportCount,\n referenceFrom: displayPath,\n referenceTo: outFileNormalize\n });\n }\n\n exportLines.add(line);\n }\n });\n\n if (exportLines.size > 0) {\n if (referenceCount > 0) lines.add(\"\");\n\n lines.add(\"//! Exported Types:\");\n lines.add([...exportLines].join(EOL));\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Adding Exported Types\",\n count: exportLines.size,\n typeCount: \"type\"\n });\n }\n } else {\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Adding Exported Types\",\n reasonEndText: \"exporting\",\n reasonType: \"types\"\n });\n }\n }\n }\n\n await fsExtra.ensureDir(outDirAbs);\n\n if (lines.size === 0) {\n const action = withExportTypes\n ? \"reference and type export\"\n : \"reference\";\n\n lines.add(\n `// No files matched the given patterns and input dir references, skipping ${action} generation.`\n );\n }\n\n await fsExtra.promises.writeFile(\n outFileAbs,\n (await resolveBanner(banner)) + [...lines].join(EOL) + EOL\n );\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName:\n \"Generating References\" +\n (_withExportTypes ? \" and Adding Exported Types\" : \"\"),\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n isNonEmptyString,\n isRegExp,\n toStringSet\n} from \"@/_internal/utils/helper\";\nimport {\n BANNER_RE,\n extractAndHoistBanner,\n hasExecutableCode,\n NON_COMMENTABLE_FILE_RE\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose, picocolors } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **inject banner** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link injectBanner | **`inject-banner`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_IB_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **inject banner** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link injectBanner | **`inject-banner`**}.\n */\nexport const resolvedIbPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_IB_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link injectBanner | **`inject-banner`**}. */\nconst DEFAULT_IB_OPTIONS = {\n replaceBanner: false,\n removeDuplicate: true,\n bannerPosition: \"after-existing\" as const,\n patternOptions: resolvedIbPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies InjectBannerOptions;\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link injectBanner | **`inject-banner`**}. */\nexport const commandIbIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"inject-banner\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link injectBanner | `inject-banner`}.***\n * ----------------------------------------------------------------\n */\nexport type InjectBannerOptions = {\n /** Replace existing banner block(s).\n *\n * - `false` ➔ Preserve existing banners.\n * - `true` ➔ Replace banners matching default `/^(?:\\/\\*![\\s\\S]*?\\*\\/\\s*)+/`.\n * - `RegExp` ➔ Replace banners matching provided pattern.\n *\n * Note:\n * The provided RegExp will be internally cloned without the `g` flag\n * to ensure safe `.test()` execution.\n *\n * @default false\n */\n replaceBanner?: boolean | RegExp;\n\n /** Remove duplicated banner blocks.\n *\n * Deduplication is performed using `trim()` comparison.\n *\n * @default true\n */\n removeDuplicate?: boolean;\n\n /** Control where new banner block(s) are injected.\n *\n * - `\"top\"` ➔ Place new banner before existing banner blocks.\n * - `\"after-existing\"` ➔ Append new banner after existing blocks.\n *\n * @default \"after-existing\"\n */\n bannerPosition?: \"top\" | \"after-existing\";\n} & BaseOptions<\n typeof DEFAULT_IB_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_IB_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Injects banner comments into JavaScript output files.***\n * ----------------------------------------------------------------\n *\n * Scans files that match the provided glob pattern(s) and injects one or\n * more banner comment blocks at the top of each file when applicable.\n *\n * - ***Injection Rules:***\n * - Skips files that:\n * - Are empty after trimming.\n * - Contain no executable JavaScript code.\n * - Match `NON_COMMENTABLE_FILE_RE`.\n * - Preserves existing shebang (`#!`) at the very top of the file.\n * - Existing banner blocks are detected using `BANNER_RE`.\n *\n * - ***Replace Mode:***\n * - If `options.replaceBanner` is:\n * - `true` ➔ uses default `BANNER_RE`.\n * - `RegExp` ➔ uses the provided pattern.\n * - If the existing banner matches the replace pattern,\n * it will be fully replaced with the new banner block(s).\n * - The replace pattern is executed without the `g` flag internally\n * to avoid stateful RegExp side effects.\n *\n * - ***Banner Ordering:***\n * Controlled by `options.bannerPosition`:\n * - `\"top\"` ➔ new banner is placed before existing banner blocks.\n * - `\"after-existing\"` ➔ new banner is appended after existing blocks.\n *\n * - ***Deduplication:***\n * If `options.removeDuplicate` is `true` (default):\n * - Banner blocks are deduplicated based on `trim()` comparison.\n * - Order is preserved.\n *\n * - ***Normalization:***\n * - Line endings are normalized to the internal `EOL` constant.\n * - Each banner block is ensured to end with exactly two `EOL`s.\n * - The operation is idempotent — running multiple times\n * will not change the file further.\n *\n * @example\n * Basic usage:\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `\n * /**\n * * My Library v1.0.0\n * * (c) 2026 Your Name\n * *\\/\n * `\n * );\n * ```\n *\n * @example\n * Inject multiple banner blocks:\n * ```ts\n * await injectBanner(\n * [\"dist/**\\/*.js\", \"build/**\\/*.mjs\"],\n * [\n * `/** Project: MyApp *\\/`,\n * `/** License: MIT *\\/`\n * ]\n * );\n * ```\n *\n * @example\n * Replace existing banner entirely:\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `/** Updated License Banner *\\/`,\n * { replaceBanner: true }\n * );\n * ```\n *\n * @example\n * Replace using custom RegExp:\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `/** New Banner *\\/`,\n * {\n * replaceBanner: /^\\/\\*\\*![\\s\\S]*?\\*\\/\\s*\\/,\n * }\n * );\n * ```\n *\n * @example\n * Always place banner at very top (after shebang):\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `/** Build: Production *\\/`,\n * {\n * bannerPosition: \"top\"\n * }\n * );\n * ```\n *\n * @param pattern - Glob pattern(s) pointing to target JavaScript files.\n * @param bannerText - Banner string(s) to inject.\n * @param options - Injection configuration options.\n */\nexport const injectBanner = async (\n pattern: StringCollection,\n bannerText: StringCollection,\n options: InjectBannerOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(options, DEFAULT_LOG_LEVEL);\n\n try {\n const {\n __commandTitle,\n removeDuplicate = DEFAULT_IB_OPTIONS.removeDuplicate,\n bannerPosition = DEFAULT_IB_OPTIONS.bannerPosition,\n replaceBanner = DEFAULT_IB_OPTIONS.replaceBanner,\n patternOptions = DEFAULT_IB_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandIbIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const banners = toStringSet(bannerText, {\n parameterKey: \"bannerText\"\n });\n\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_IB_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_IB_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeDuplicate\",\n removeDuplicate,\n BUILD_LOGGER.SOURCE_OF(\n removeDuplicate,\n DEFAULT_IB_OPTIONS.removeDuplicate\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.replaceBanner\",\n replaceBanner,\n BUILD_LOGGER.SOURCE_OF(replaceBanner, DEFAULT_IB_OPTIONS.replaceBanner)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.bannerPosition\",\n bannerPosition,\n BUILD_LOGGER.SOURCE_OF(\n bannerPosition,\n DEFAULT_IB_OPTIONS.bannerPosition\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_IB_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Injecting Banner\"\n });\n }\n\n if (banners.size === 0) {\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Inject Banner\",\n reasonSkipAction: \"empty bannerText\",\n reasonType: \"parameter\",\n reasonEndText: \"injecting\"\n });\n }\n return;\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (NON_COMMENTABLE_FILE_RE.test(filePath)) continue;\n let original: string;\n\n try {\n original = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (!isNonEmptyString(original)) continue;\n if (!hasExecutableCode(original)) continue;\n\n const {\n body,\n shebang,\n banner: existingBanner\n } = extractAndHoistBanner(original);\n\n const bannerRegex = new RegExp(BANNER_RE.source, \"g\");\n\n const newBlocks = [...banners];\n\n if (newBlocks.length === 0) continue;\n\n const existingBlocks = existingBanner\n ? [...existingBanner.matchAll(bannerRegex)].map((m) => m[0])\n : [];\n\n let finalBlocks: string[] = [];\n\n if (replaceBanner) {\n const replaceRegex = isRegExp(replaceBanner)\n ? replaceBanner\n : BANNER_RE;\n\n if (\n existingBanner &&\n new RegExp(\n replaceRegex.source,\n replaceRegex.flags.replace(\"g\", \"\")\n ).test(existingBanner)\n ) {\n finalBlocks = [...newBlocks];\n } else {\n finalBlocks =\n bannerPosition === \"top\"\n ? [...newBlocks, ...existingBlocks]\n : [...existingBlocks, ...newBlocks];\n }\n } else {\n const combined =\n bannerPosition === \"top\"\n ? [...newBlocks, ...existingBlocks]\n : [...existingBlocks, ...newBlocks];\n\n finalBlocks = combined;\n }\n\n if (removeDuplicate) {\n const seen = new Set<string>();\n\n finalBlocks = finalBlocks.filter((block) => {\n const normalized = block.trim();\n\n if (seen.has(normalized)) return false;\n\n seen.add(normalized);\n return true;\n });\n }\n\n const normalizedFinalBanner = finalBlocks\n .map((text) => {\n if (!text || !isNonEmptyString(text)) return \"\";\n\n let normalized = text.replace(/\\r\\n/g, EOL);\n\n return normalized.replace(/\\n+$/, \"\") + EOL + EOL;\n })\n .join(\"\");\n\n let content = shebang + normalizedFinalBanner + body;\n\n try {\n await fsExtra.promises.writeFile(filePath, content, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName:\n \"Banner Injected \" +\n picocolors.cyanBright(\n replaceBanner ? \"(replace mode)\" : \"(preserve mode)\"\n ),\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Inject Banner\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Inject Banner\",\n reasonEndText: \"injecting\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Inject Banner\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n detectModuleKindFromContent,\n extractAndHoistBanner,\n extractDirectives,\n hasExecutableCode,\n JS_OUTPUT_FILE_RE,\n stripUseStrict\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose, picocolors } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **inject directive** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link injectDirective | **`inject-directive`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_ID_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **inject directive** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link injectDirective | **`inject-directive`**}.\n */\nexport const resolvedIdPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_ID_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link injectDirective | **`inject-directive`**}. */\nconst DEFAULT_ID_OPTIONS = {\n patternOptions: resolvedIdPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies InjectDirectiveOptions;\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link injectDirective | **`inject-directive`**}. */\nexport const commandIdIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"inject-directive\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link injectDirective | **`inject-directive`**}.***\n * ----------------------------------------------------------------\n */\nexport type InjectDirectiveOptions = BaseOptions<\n typeof DEFAULT_ID_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_ID_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Injects directive statements into JavaScript output files.***\n * ----------------------------------------------------------------\n *\n * This function scans files matching the provided glob pattern(s) and\n * injects one or more directive statements (e.g. `\"use strict\"`,\n * `\"use client\"`) at the top of each file when applicable.\n *\n * - *Injection behavior:*\n * - Skips empty files.\n * - Skips files that only contain directive statements.\n * - Avoids duplicating existing directives.\n * - Preserves existing file content order.\n *\n * - *Each directive is normalized and injected as a standalone statement:*\n * ```js\n * \"directive-name\";\n * ```\n *\n * @param pattern - Glob pattern or list of patterns pointing to JS output files.\n * @param directive - Directive string(s) to inject.\n * @param options - Injection configuration options, see {@link InjectDirectiveOptions | **`InjectDirectiveOptions`**}.\n *\n * @example\n * ```ts\n * await injectDirective(\"dist/**\\/*.js\", \"use strict\");\n * ```\n *\n * @example\n * ```ts\n * await injectDirective(\"dist/**\\/*.js\", \"use client\");\n * ```\n *\n * @example\n * ```ts\n * await injectDirective(\n * [\"dist/**\\/*.js\", \"build/*\\/*.mjs\"],\n * [\"use strict\", \"use client\"]\n * );\n * ```\n */\nexport const injectDirective = async (\n pattern: StringCollection,\n directive: StringCollection,\n options: InjectDirectiveOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(options, DEFAULT_ID_OPTIONS.logLevel);\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_ID_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandIdIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_ID_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"directive\",\n directive,\n BUILD_LOGGER.SOURCE_OF(directive, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_ID_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_ID_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Inject Directive\"\n });\n }\n\n const directives = [...toStringSet(directive)];\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let original: string;\n\n try {\n original = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (!isNonEmptyString(original) || !hasExecutableCode(original)) continue;\n const { body, banner, shebang } = extractAndHoistBanner(original);\n const { directives: extractedDirectives, rest } = extractDirectives(body);\n const existing = new Set(extractedDirectives);\n let injectLines: string[] | undefined;\n\n if (detectModuleKindFromContent(rest) === \"cjs\") {\n injectLines ??= [];\n // eslint-disable-next-line quotes\n injectLines.push(`\"use strict\";`);\n }\n\n for (const d of directives) {\n const dTrim = d.trim();\n if (!dTrim || dTrim === \"use strict\") continue;\n\n const line = `\"${dTrim}\";`;\n if (!existing.has(line)) {\n injectLines ??= [];\n injectLines.push(line);\n }\n }\n\n if (!injectLines?.length) continue;\n\n const finalDirective =\n injectLines.join(EOL) + EOL + stripUseStrict(extractedDirectives);\n\n const content = shebang + banner + finalDirective + rest;\n\n try {\n await fsExtra.promises.writeFile(filePath, content, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName:\n \"Directive Injected \" +\n picocolors.cyanBright(\"(`\" + injectLines.join(\"`, `\") + \"`)\"),\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Inject Directive\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Inject Directive\",\n reasonEndText: \"injecting\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Inject Directive\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { JS_OUTPUT_FILE_RE } from \"@/_internal/utils/source\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **normalize js build newlines** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_NJBN_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **normalize js build newlines** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}.\n */\nexport const resolvedNjbnPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_NJBN_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}. */\nconst DEFAULT_NJBN_OPTIONS = {\n patternOptions: resolvedNjbnPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies NormalizeJsBuildNewlinesOptions;\n\n//? Identity -------------------------------------------------------------\n/** Generated Command Identity For {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}. */\nexport const commandNjbnIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"normalize-js-build-newlines\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link normalizeJsBuildNewlines | **`normalizeJsBuildNewlines`**}.***\n * ----------------------------------------------------------------\n */\nexport type NormalizeJsBuildNewlinesOptions = BaseOptions<\n typeof DEFAULT_NJBN_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_NJBN_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Normalizes excessive blank lines in compiled JavaScript files.***\n * ----------------------------------------------------------------\n *\n * This function scans JavaScript build output files and normalizes\n * excessive consecutive newlines.\n *\n * Any occurrence of **three or more consecutive line breaks**\n * (`\\n` or `\\r\\n`) will be collapsed into exactly **two newlines**,\n * ensuring cleaner and more readable build artifacts.\n *\n * - *The process is **non-destructive**:*\n * - Files are only rewritten if normalization is actually needed.\n * - Duplicate file paths are automatically deduplicated using {@link Set | `Set`}.\n *\n * - *Supported JavaScript output extensions:*\n * - `.js`.\n * - `.cjs`.\n * - `.mjs`.\n * - `.esm.js`.\n * - `.module.js`.\n *\n * @param pattern - Glob pattern(s) or a set of file paths pointing to JS build outputs.\n * @param options - Normalization configuration options.\n *\n * @example\n * ```ts\n * await normalizeJsBuildNewlines(\"dist/**\\/*.js\");\n * ```\n *\n * @example\n * ```ts\n * await normalizeJsBuildNewlines(\"dist/**\\/*.{js,cjs,mjs}\");\n * ```\n *\n * @example\n * ```ts\n * await normalizeJsBuildNewlines(\n * [\"dist/**\\/*.js\", \"build/**\\/*.mjs\", \"out/**\\/*.{js,mjs}\"],\n * );\n * ```\n *\n * @remarks\n * - This utility is intended for **post-build cleanup** and is safe to run\n * multiple times.\n * - Re-running it on already normalized files will result\n * in no changes.\n */\nexport const normalizeJsBuildNewlines = async (\n pattern: StringCollection,\n options: NormalizeJsBuildNewlinesOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_NJBN_OPTIONS.logLevel\n );\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_NJBN_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandNjbnIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_NJBN_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_NJBN_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_NJBN_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Normalize New Lines\"\n });\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n const filesToClean = new Set<string>();\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (!/(\\r?\\n){3,}/.test(content)) continue;\n filesToClean.add(filePath);\n }\n\n let count = 0;\n for (const [, filePath] of filesToClean.entries()) {\n count++;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const finalContent = content.replace(/(\\r?\\n){3,}/g, EOL);\n\n if (finalContent !== content) {\n try {\n await fsExtra.promises.writeFile(filePath, finalContent, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"New Line Normalized\",\n count: count,\n nameDirect: filePath\n });\n }\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (filesToClean.size > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Normalize New Lines\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Normalize New Lines\",\n reasonEndText: \"normalize\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Normalize New Lines\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseRunCommandOptions } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { spawn, type SpawnOptions, ChildProcess } from \"node:child_process\";\n\nimport {\n assertValidCommand,\n spawnWithLifecycle,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n CommandProcessError,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isCommandProcessError\n} from \"./utils\";\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Options for executing a shell command via {@link runCommand | **`runCommand`**}.***\n * ----------------------------------------------------------------\n */\nexport type RunCommandOptions = BaseRunCommandOptions;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Execute a command and stream output to the current process.***\n * ----------------------------------------------------------------\n *\n * This utility spawns a child process using\n * {@link spawn | **`child_process.spawn`**}.\n *\n * By default, it forwards `stdout` and `stderr` directly to the parent\n * process using `stdio: \"inherit\"` (real-time streaming, no buffering).\n *\n * - *Behavior:*\n * - Uses `stdio: \"inherit\"` by default (can be overridden).\n * - Does **not** buffer output.\n * - Resolves only when the process exits with code `0`.\n * - Rejects if the process exits with a non-zero code,\n * is terminated by a signal, aborted, or times out.\n *\n * - *This function is designed for:*\n * - Build steps.\n * - Post-build hooks.\n * - CLI tooling.\n * - Long-running tasks (bundlers, compilers, CSS processors).\n *\n * @param {string} command\n * The executable or command to run.\n *\n * @param {readonly string[]} [args]\n * Arguments passed to the command.\n *\n * @param {RunCommandOptions} [options]\n * Optional execution configuration.\n *\n * @returns {Promise<ChildProcess>}\n * Resolves with the spawned {@link ChildProcess | **`ChildProcess`**} instance\n * **after the process exits successfully (exit code `0`)**.\n *\n * ----------------------------------------------------------------\n * #### Error handling\n *\n * When the process fails, the promise is rejected with a\n * {@link CommandProcessError | **`CommandProcessError`**}.\n *\n * - *Error metadata:*\n * - `reason` ➔ `\"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\"`.\n * - `exitCode` ➔ Exit code (if available).\n * - `signal` ➔ Termination signal (if any).\n * - `command` ➔ Executed command (plain string, no colors).\n *\n * - *Type narrowing:*\n * - Use `instanceof CommandProcessError` to safely access metadata.\n * - Or use {@link isCommandProcessError | **`isCommandProcessError`**} as a type guard.\n *\n * - *Notes:*\n * - Metadata is available programmatically (e.g. `err.reason`).\n * - Metadata is also included in the formatted stack output\n * for CLI readability.\n *\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (err instanceof CommandProcessError) {\n * if (err.reason === \"non-zero exit code\") {\n * console.error(\"Build failed with code:\", err.exitCode);\n * }\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(err.reason);\n * }\n * }\n * ```\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * await runCommand(\"pnpm\", [\"build\"]);\n * ```\n *\n * @example\n * ```ts\n * const child = await runCommand(\"node\", [\"script.js\"]);\n * console.log(child.pid);\n * ```\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n *\n * runCommand(\"pnpm\", [\"dev\"], {\n * signal: controller.signal\n * });\n *\n * controller.abort();\n * ```\n *\n * @example\n * ```ts\n * await runCommand(\"npm\", [\"run\", \"build\"], {\n * timeout: 5000\n * });\n * ```\n *\n * @remarks\n * - **Execution model:**\n * - Uses {@link spawn | **`spawn`**} instead of `exec` to avoid\n * output buffering and support long-running processes.\n *\n * - **Output handling:**\n * - Defaults to `stdio: \"inherit\"` (streams output to parent).\n * - If `stdio` is overridden (e.g. `\"pipe\"`), output will NOT be auto-forwarded.\n *\n * - **Shell execution:**\n * - Defaults to {@link RunCommandOptions.shell | **`shell: true`**}.\n * - Required on Windows to resolve commands like `pnpm`, `npm`, `git`, etc.\n * - When `shell: false`, the command must be:\n * - An absolute path, or\n * - A directly executable binary.\n *\n * - **Abort handling:**\n * - When `signal` is provided, the process will be terminated\n * with `SIGTERM` if aborted.\n *\n * - **Timeout handling:**\n * - When `timeout` is set, the process will be terminated\n * after the specified duration.\n * - `undefined` ➔ no timeout.\n * - ⚠️ `0` ➔ immediate termination.\n *\n * - **Common errors:**\n * - **`ENOENT`** ➔ command not found:\n * - Not installed\n * - Not in `PATH`\n * - `shell: false` with non-absolute command\n *\n * - **When NOT to use this utility:**\n * - When you need to capture output programmatically.\n * - When you need advanced shell features (`|`, `>`, `&&`).\n *\n * ***In those cases, consider using `exec` or a dedicated process runner.***\n */\nexport function runCommand(\n command: string,\n args: readonly string[]\n): Promise<ChildProcess>;\nexport function runCommand(\n command: string,\n options: RunCommandOptions\n): Promise<ChildProcess>;\nexport function runCommand(\n command: string,\n args: readonly string[],\n options: RunCommandOptions\n): Promise<ChildProcess>;\nexport function runCommand(\n command: string,\n argsOrOptions: readonly string[] | RunCommandOptions = [],\n maybeOptions: RunCommandOptions = {}\n): Promise<ChildProcess> {\n assertValidCommand(command);\n\n let args: readonly string[];\n let options: RunCommandOptions;\n\n if (Array.isArray(argsOrOptions)) {\n args = argsOrOptions;\n options = maybeOptions;\n } else {\n args = [];\n options = argsOrOptions as RunCommandOptions;\n }\n\n return new Promise((resolve, reject) => {\n const {\n shell = true,\n stdio = \"inherit\",\n argv0: _argv0,\n useColors = true,\n ...restOption\n } = options as RunCommandOptions & SpawnOptions;\n\n const { child, setupLifecycle, cmdStringPlain } = spawnWithLifecycle(\n command,\n args,\n {\n ...restOption,\n stdio,\n useColors,\n shell\n },\n {\n rejectOnNonZero: true\n }\n );\n\n setupLifecycle({\n onSuccess: (code) => {\n if (code === 0) {\n resolve(child);\n } else {\n reject(new Error(`${cmdStringPlain} exited with code ${code}`));\n }\n },\n onError: reject\n });\n });\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseRunCommandOptions } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { spawn, type SpawnOptions } from \"node:child_process\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { runCommand } from \"./runCommand\";\nimport {\n assertValidCommand,\n spawnWithLifecycle,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n CommandProcessError,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isCommandProcessError\n} from \"./utils\";\n\n//? Utils ----------------------------------------------------------------\nfunction normalizeChunk(chunk: unknown): string {\n if (typeof chunk === \"string\") return chunk;\n if (Buffer.isBuffer(chunk)) return chunk.toString(\"utf8\");\n\n return String(chunk);\n}\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Result returned by {@link runCommandCapture | `runCommandCapture`}.***\n * ----------------------------------------------------------------\n *\n * Represents the captured output and execution status of a command.\n *\n * - *Behavior:*\n * - `stdout` and `stderr` are fully buffered as UTF-8 strings.\n * - `exitCode` reflects the process exit status.\n * - `ok` indicates whether the command succeeded (`exitCode === 0`).\n */\nexport type RunCommandCaptureResult = {\n /** ----------------------------------------------------------------\n * * ***Captured standard output.***\n * ----------------------------------------------------------------\n *\n * The complete `stdout` output of the process as a UTF-8 string.\n *\n * - Trailing newlines may be trimmed depending on implementation.\n */\n stdout: string;\n\n /** ----------------------------------------------------------------\n * * ***Captured standard error output.***\n * ----------------------------------------------------------------\n *\n * The complete `stderr` output of the process as a UTF-8 string.\n *\n * - Useful for debugging or logging failures.\n */\n stderr: string;\n\n /** ----------------------------------------------------------------\n * * ***Process exit code.***\n * ----------------------------------------------------------------\n *\n * The numeric exit code returned by the process.\n *\n * - `0` usually indicates success.\n * - Non-zero values usually indicate failure.\n */\n exitCode: number;\n\n /** ----------------------------------------------------------------\n * * ***Execution success flag.***\n * ----------------------------------------------------------------\n *\n * Indicates whether the command completed successfully.\n *\n * Equivalent to:\n * ```ts\n * exitCode === 0\n * ```\n */\n ok: boolean;\n};\n\n/** ----------------------------------------------------------------\n * * ***Options for executing a shell command via {@link runCommandCapture | **`runCommandCapture`**}.***\n * ----------------------------------------------------------------\n */\nexport type RunCommandCaptureOptions = Omit<BaseRunCommandOptions, \"stdio\">;\n\n/** ----------------------------------------------------------------\n * * ***Execute a command and capture its output.***\n * ----------------------------------------------------------------\n *\n * This utility spawns a child process using\n * {@link spawn | **`child_process.spawn`**} and buffers its output.\n *\n * Unlike {@link runCommand | **`runCommand`**}, this function:\n * - Captures `stdout` and `stderr` into strings.\n * - Does **not** stream output to the parent process.\n * - Always resolves (even for non-zero exit codes).\n *\n * - *Behavior:*\n * - Uses `stdio: \"pipe\"` (output is buffered).\n * - Collects `stdout` and `stderr` as UTF-8 strings.\n * - Resolves when the process exits (regardless of exit code).\n * - Rejects only on:\n * - Spawn errors.\n * - Abort signals.\n * - Timeouts.\n * - Process termination by signal.\n *\n * - *This function is designed for:*\n * - Capturing CLI output.\n * - Running commands programmatically.\n * - Parsing results (JSON, text, etc.).\n * - Testing and scripting utilities.\n *\n * @param {string} command\n * The executable or command to run.\n *\n * @param {readonly string[]} [args]\n * Arguments passed to the command.\n *\n * @param {RunCommandCaptureOptions} [options]\n * Optional execution configuration.\n *\n * @returns {Promise<RunCommandCaptureResult>}\n * Resolves with an object containing:\n * - `stdout` ➔ captured standard output.\n * - `stderr` ➔ captured standard error.\n * - `exitCode` ➔ process exit code.\n * - `ok` ➔ `true` if exit code is `0`.\n *\n * ----------------------------------------------------------------\n * #### Error handling.\n *\n * This function does NOT reject on non-zero exit codes.\n * - Instead, use:\n * - `result.ok`.\n * - `result.exitCode`.\n *\n * - However, the promise WILL reject for:\n * - spawn errors.\n * - abort signals.\n * - timeouts.\n * - termination by signal.\n *\n * In those cases, the promise is rejected with a\n * {@link CommandProcessError | **`CommandProcessError`**}.\n *\n * - *Error metadata:*\n * - `reason` ➔ `\"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\"`.\n * - `exitCode` ➔ Exit code (if available).\n * - `signal` ➔ Termination signal (if any).\n * - `command` ➔ Executed command (plain string, no colors).\n *\n * - *Type narrowing:*\n * - Use `instanceof CommandProcessError` to safely access metadata.\n * - Or use {@link isCommandProcessError | **`isCommandProcessError`**} as a type guard.\n *\n * - *Notes:*\n * - `\"non-zero exit code\"` is NOT treated as an error in this function.\n * - Metadata is available programmatically (e.g. `err.reason`).\n * - Metadata is also included in the formatted stack output\n * for CLI readability.\n *\n * @example\n * ```ts\n * try {\n * await runCommandCapture(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (err instanceof CommandProcessError) {\n * console.error(\"Command failed:\", err.reason);\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * try {\n * await runCommandCapture(\"pnpm\", [\"dev\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(err.reason);\n * }\n * }\n * ```\n * ----------------------------------------------------------------\n * @example\n * ```ts\n * const result = await runCommandCapture(\"node\", [\"--version\"]);\n *\n * console.log(result.stdout);\n * ```\n *\n * @example\n * ```ts\n * const { stdout, ok } = await runCommandCapture(\"pnpm\", [\"build\"]);\n *\n * if (!ok) {\n * console.error(\"Build failed\");\n * }\n * ```\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n *\n * runCommandCapture(\"pnpm\", [\"dev\"], {\n * signal: controller.signal\n * });\n *\n * controller.abort();\n * ```\n *\n * @remarks\n * - **Execution model:**\n * - Uses {@link spawn | **`spawn`**} to avoid output size limits\n * imposed by `exec`.\n *\n * - **Output handling:**\n * - Always uses `stdio: \"pipe\"` (cannot be overridden).\n * - Output is buffered entirely in memory.\n *\n * - **Exit behavior:**\n * - Does NOT reject on non-zero exit codes.\n * - Use `result.ok` or `result.exitCode` to handle failures.\n *\n * - **Shell execution:**\n * - Defaults to `shell: true`.\n * - Same behavior and constraints as {@link runCommand | `runCommand`}.\n *\n * - **Abort & timeout:**\n * - Abort signals and timeouts will terminate the process\n * and reject the promise.\n *\n * - **When NOT to use this utility:**\n * - When output needs to be streamed in real-time\n * - When handling very large outputs (risk of high memory usage)\n *\n * ***In those cases, use {@link runCommand | `runCommand`}.***\n */\nexport function runCommandCapture(\n command: string,\n args: readonly string[]\n): Promise<RunCommandCaptureResult>;\nexport function runCommandCapture(\n command: string,\n options: RunCommandCaptureOptions\n): Promise<RunCommandCaptureResult>;\nexport function runCommandCapture(\n command: string,\n args: readonly string[],\n options: RunCommandCaptureOptions\n): Promise<RunCommandCaptureResult>;\nexport function runCommandCapture(\n command: string,\n argsOrOptions: readonly string[] | RunCommandCaptureOptions = [],\n maybeOptions: RunCommandCaptureOptions = {}\n): Promise<RunCommandCaptureResult> {\n assertValidCommand(command);\n\n let args: readonly string[];\n let options: RunCommandCaptureOptions;\n\n if (Array.isArray(argsOrOptions)) {\n args = argsOrOptions;\n options = maybeOptions;\n } else {\n args = [];\n options = argsOrOptions as RunCommandCaptureOptions;\n }\n\n const {\n shell = true,\n signal,\n timeout,\n forceKill,\n useColors = true,\n argv0: _argv0,\n ...restOption\n } = options as RunCommandCaptureOptions & SpawnOptions;\n\n return new Promise((resolve, reject) => {\n const { child, setupLifecycle } = spawnWithLifecycle(\n command,\n args,\n {\n ...restOption,\n stdio: \"pipe\",\n shell,\n signal,\n timeout,\n forceKill,\n useColors\n },\n {\n rejectOnNonZero: false\n }\n );\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout?.on(\"data\", (chunk: unknown) => {\n stdout += normalizeChunk(chunk);\n });\n\n child.stderr?.on(\"data\", (chunk: unknown) => {\n stderr += normalizeChunk(chunk);\n });\n\n setupLifecycle({\n onSuccess: (code) => {\n resolve({\n stdout: stdout.trimEnd(),\n stderr: stderr.trimEnd(),\n exitCode: code,\n ok: code === 0\n });\n },\n onError: reject\n });\n });\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { OverrideTypes } from \"@/_internal/types/extra\";\nimport type { BaseRunCommandOptions } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { spawn, ChildProcess } from \"node:child_process\";\n\nimport {\n isNonEmptyString,\n safeStableStringify\n} from \"@/_internal/utils/helper\";\n\nimport {\n EOL,\n formatOptionValue,\n joinLinesLoose,\n picocolors\n} from \"@/utils/client\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { runCommand } from \"./runCommand\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { runCommandCapture } from \"./runCommandCapture\";\n\n/** @internal Util for {@link runCommand | `runCommand`} and {@link runCommandCapture | `runCommandCapture`}. */\nexport function formatCommand(\n command: string,\n args: readonly string[],\n { useColors = true }: Pick<BaseRunCommandOptions, \"useColors\"> = {}\n) {\n const hasArgs = args.length > 0;\n const argsString = hasArgs\n ? args.map((a) => safeStableStringify(a)).join(\" \")\n : \"\";\n\n if (useColors) {\n const cmd = picocolors.cyanBright(command);\n return hasArgs ? `${cmd} ${picocolors.gray(argsString)}` : cmd;\n }\n\n return hasArgs ? `${command} ${argsString}` : command;\n}\n\n/** @internal Util for {@link runCommand | `runCommand`} and {@link runCommandCapture | `runCommandCapture`}. */\nexport function assertValidCommand(\n command: unknown,\n { useColors = true }: Pick<BaseRunCommandOptions, \"useColors\"> = {}\n): asserts command is string {\n if (typeof command !== \"string\") {\n const errorMsg = `Invalid command: expected a string, received ${safeStableStringify(command)}`;\n throw new TypeError(useColors ? picocolors.redBright(errorMsg) : errorMsg);\n }\n\n const trimmed = command.trim();\n\n if (trimmed.length === 0) {\n const errorMsg = \"Invalid command: command cannot be empty\";\n throw new Error(useColors ? picocolors.redBright(errorMsg) : errorMsg);\n }\n\n const hasSpace = trimmed.includes(\" \");\n const hasQuotes = /['\"`]/.test(trimmed);\n const hasShellOps = /[|&;<>(){}$]/.test(trimmed);\n\n if (hasSpace || hasQuotes || hasShellOps) {\n const [cmd, ...rest] = trimmed.split(/\\s+/);\n\n const errorMsg = joinLinesLoose(\n `Invalid command: \"${trimmed}\"`,\n \"Do not pass a full shell command.\",\n `Use arguments instead: runCommand(\"${cmd}\", ${safeStableStringify(rest)})`\n );\n\n throw new Error(useColors ? picocolors.redBright(errorMsg) : errorMsg);\n }\n}\n\n/** @internal Util for local {@link createProcessError | `createProcessError`}. */\nfunction stripInternalStack(lines: string[]) {\n const blacklist = [\n \"at new Promise (<anonymous>)\",\n \"Timeout.\",\n \"ChildProcess.\",\n \"node:events:\",\n \"createProcessError\",\n \"formatError\",\n \"spawnWithLifecycle\",\n \"setupLifecycle\",\n \"node:internal\"\n ];\n\n return lines.filter((line) => {\n if (blacklist.some((key) => line.includes(key))) {\n return false;\n }\n\n const isFileFrame = line.includes(\"/build-tools/dist/\");\n const hasFunctionName = /\\bat\\s+\\S+\\s+\\(/.test(line);\n\n if (isFileFrame && !hasFunctionName) {\n return false;\n }\n\n return true;\n });\n}\n\n/** @internal Util for local {@link spawnWithLifecycle | `spawnWithLifecycle`}. */\nfunction createProcessError(\n message: string,\n {\n reason,\n exitCode,\n signal,\n command\n }: {\n reason: CommandProcessError[\"reason\"];\n exitCode?: number;\n signal?: NodeJS.Signals | null;\n command: string;\n },\n baseStack?: string\n): CommandProcessError {\n const error = new CommandProcessError(message, {\n reason,\n exitCode,\n signal,\n command\n });\n\n const currentStack = error.stack?.split(EOL) ?? [];\n const base = baseStack?.split(EOL) ?? [];\n\n const [currentHead, ...currentRest] = currentStack;\n const [, ...baseRest] = base;\n\n const cleanedCurrent = stripInternalStack(currentRest);\n const cleanedBase = stripInternalStack(baseRest);\n\n command = command.trim();\n\n error.stack = [\n currentHead,\n ...cleanedCurrent,\n ...(cleanedBase.length ? [...cleanedBase] : [])\n ].join(EOL);\n\n // error.reason = reason;\n // error.exitCode = exitCode;\n // error.signal = signal;\n // error.command = command;\n\n Object.defineProperties(error, {\n reason: { value: reason, enumerable: false },\n exitCode: { value: exitCode, enumerable: false },\n signal: { value: signal, enumerable: false },\n command: { value: command, enumerable: false }\n });\n\n error.stack += joinLinesLoose(\n \"\",\n \"meta:\",\n ` reason: ${formatOptionValue(reason)}`,\n ` exitCode: ${formatOptionValue(exitCode ?? null)}`,\n ` signal: ${formatOptionValue(signal ?? null)}`,\n ` command: ${formatOptionValue(command)}`\n );\n\n return error;\n}\n\n/** ----------------------------------------------------------------\n * * ***Represents a command execution failure.***\n * ----------------------------------------------------------------\n *\n * This error is thrown when a spawned process fails during execution\n * via {@link runCommand | **`runCommand`**}, {@link runCommandCapture | **`runCommandCapture`**} or related utilities.\n *\n * It extends the native {@link Error | `Error`} class and provides structured\n * metadata describing the failure.\n *\n * ---\n *\n * - *Failure reasons:*\n * - `\"timeout\"` ➔ The process exceeded the configured timeout.\n * - `\"abort\"` ➔ The process was aborted via an `AbortSignal`.\n * - `\"signal\"` ➔ The process was terminated by an OS signal.\n * - `\"non-zero exit code\"` ➔ The process exited with a non-zero code.\n *\n * ---\n *\n * - *Metadata:*\n * - `reason` ➔ Reason for failure.\n * - `exitCode` ➔ Exit code (if available).\n * - `signal` ➔ Termination signal (if any).\n * - `command` ➔ Executed command (plain string, no colors).\n *\n * ---\n *\n * - *Behavior:*\n * - Thrown when a process fails in {@link runCommand | `runCommand`}.\n * - May also be thrown in {@link runCommandCapture | `runCommandCapture`} for:\n * - Spawn errors.\n * - Abort signals.\n * - Timeouts.\n * - Signal termination.\n * - Includes formatted stack output for CLI readability.\n * - Metadata is available for programmatic handling.\n *\n * ----------------------------------------------------------------\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (err instanceof CommandProcessError) {\n * console.error(\"Reason:\", err.reason);\n * console.error(\"Exit code:\", err.exitCode);\n * }\n * }\n * ```\n *\n * OR with `isCommandProcessError`.\n *\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(\"Reason:\", err.reason);\n * console.error(\"Exit code:\", err.exitCode);\n * }\n * }\n * ```\n *\n * @remarks\n * - This error is designed for both:\n * - Human-readable CLI output.\n * - Programmatic error handling.\n *\n * - Metadata properties are non-enumerable to avoid duplicate\n * output when logged via `console.error`.\n */\nexport class CommandProcessError extends Error {\n reason: \"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\";\n exitCode?: number;\n signal?: NodeJS.Signals | null;\n command: string;\n\n constructor(\n message: string,\n meta: {\n reason: CommandProcessError[\"reason\"];\n exitCode?: number;\n signal?: NodeJS.Signals | null;\n command: string;\n }\n ) {\n super(message);\n\n this.name = \"CommandProcessError\";\n\n this.reason = meta.reason;\n this.exitCode = meta.exitCode;\n this.signal = meta.signal;\n this.command = meta.command;\n }\n}\n\n/** ----------------------------------------------------------------\n * * ***Type guard for `CommandProcessError`.***\n * ----------------------------------------------------------------\n *\n * Utility to check whether a given value is an instance of\n * {@link CommandProcessError | `CommandProcessError`}.\n *\n * Useful when handling unknown errors in `try/catch` blocks.\n *\n * ----------------------------------------------------------------\n * @param err\n * The unknown error value to check.\n *\n * @returns\n * `true` if the value is a `CommandProcessError`, otherwise `false`.\n *\n * ----------------------------------------------------------------\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(err.reason);\n * console.error(err.exitCode);\n * }\n * }\n * ```\n */\nexport function isCommandProcessError(\n err: unknown\n): err is CommandProcessError {\n return err instanceof CommandProcessError;\n}\n\n/** @internal Util for {@link runCommand | `runCommand`} and {@link runCommandCapture | `runCommandCapture`}. */\nexport function spawnWithLifecycle(\n command: string,\n args: readonly string[],\n options: OverrideTypes<\n BaseRunCommandOptions,\n {\n /** Whether to run the command inside a shell.\n *\n * @default false\n */\n shell: boolean;\n }\n >,\n config?: {\n /** Custom error formatter.\n *\n * Allows overriding how errors are constructed.\n *\n * @param message The error message.\n * @param meta Additional metadata about the failure.\n *\n * @returns A custom error instance.\n *\n * @example\n * ```ts\n * formatError(msg, meta) {\n * return new MyError(msg, meta.reason);\n * }\n * ```\n */\n formatError?: (\n /** The error message. */\n message: string,\n /** Additional metadata about the failure. */\n meta: {\n /** Reason for failure. */\n reason: CommandProcessError[\"reason\"];\n /** Exit code if available. */\n exitCode?: number;\n /** Termination signal if any. */\n signal?: NodeJS.Signals | null;\n /** Executed command (plain, no colors). */\n command: string;\n\n args: readonly string[];\n /** Whether colors are enabled. */\n useColors: boolean;\n }\n ) => Error;\n\n /** Reject the process when exit code is non-zero.\n *\n * When enabled:\n * - Exit codes ≠ `0` will trigger `onError`.\n *\n * @default false\n */\n rejectOnNonZero?: boolean;\n }\n) {\n const {\n useColors = true,\n timeout,\n forceKill,\n signal: abortSignal,\n ...restOption\n } = options;\n\n const baseStack = new Error().stack;\n\n const cmdString = formatCommand(command, args, { useColors });\n const cmdStringPlain = formatCommand(command, args, { useColors: false });\n\n const formatError =\n config?.formatError ??\n ((msg, meta) => {\n const metaCommand = meta.command.trim();\n const argsString =\n meta.args.length > 0\n ? meta.args.map((a) => safeStableStringify(a).trim()).join(\" \")\n : \"\";\n\n if (meta.useColors) {\n const cmd = picocolors.magentaBright(metaCommand);\n const args = argsString ? picocolors.yellowBright(argsString) : \"\";\n\n return createProcessError(\n `${cmd}${args ? \" \" + args : \"\"} ${picocolors.redBright(msg)}`,\n {\n ...meta,\n command: `${metaCommand} ${argsString}`\n },\n baseStack\n );\n }\n\n return createProcessError(\n `${metaCommand}${isNonEmptyString(argsString) ? \" \" + argsString : \"\"} ${msg}`,\n {\n ...meta,\n command: `${metaCommand} ${argsString}`\n },\n baseStack\n );\n });\n\n const rejectOnNonZero = config?.rejectOnNonZero ?? false;\n\n const child = spawn(command, [...args], restOption);\n\n let finished = false;\n\n const kill = () => {\n try {\n if (process.platform === \"win32\") {\n if (forceKill && child.pid) {\n spawn(\"taskkill\", [\"/pid\", String(child.pid), \"/f\", \"/t\"]);\n } else {\n child.kill();\n }\n } else {\n child.kill(\"SIGTERM\");\n }\n } catch {\n // noop\n }\n };\n\n return {\n /** ----------------------------------------------------------------\n * * ***The spawned child process instance.***\n * ----------------------------------------------------------------\n *\n * Direct access to the underlying {@link ChildProcess | `ChildProcess`}.\n *\n * Can be used for:\n * - Accessing `pid`\n * - Listening to additional events\n * - Manual stream handling (`stdout`, `stderr`)\n */\n child,\n\n /** ----------------------------------------------------------------\n * * ***Terminate the running process.***\n * ----------------------------------------------------------------\n *\n * Sends a termination signal to the process:\n * - On Windows:\n * - Uses `taskkill /f /t` when `forceKill` is enabled.\n * - Otherwise uses `child.kill()`.\n * - On other platforms:\n * - Sends `SIGTERM`.\n *\n * Safe to call multiple times.\n */\n kill,\n\n /** ----------------------------------------------------------------\n * * ***Formatted command string.***\n * ----------------------------------------------------------------\n *\n * Human-readable representation of the executed command.\n *\n * - May include colors depending on configuration.\n * - Intended for logging and debugging.\n *\n * @example\n * ```ts\n * console.log(cmdString);\n * ```\n */\n cmdString,\n\n /** ----------------------------------------------------------------\n * * ***Formatted command string (plain, no colors).***\n * ----------------------------------------------------------------\n *\n * Human-readable representation of the executed command\n * without any color formatting.\n *\n * - Safe for logging, serialization, and error metadata.\n * - Used internally for structured error information.\n * - Unlike `cmdString`, this value never includes ANSI color codes.\n *\n * @example\n * ```ts\n * console.log(cmdStringPlain);\n * ```\n */\n cmdStringPlain,\n\n /** ----------------------------------------------------------------\n * * ***Attach lifecycle handlers to the spawned process.***\n * ----------------------------------------------------------------\n *\n * Registers callbacks to handle the process lifecycle in a safe,\n * single-resolution manner.\n *\n * This method ensures that only one terminal state is triggered:\n * either success or failure.\n *\n * ---\n *\n * #### Success\n * Calls `onSuccess(code)` when:\n * - The process exits normally.\n * - No termination signal is received.\n * - Exit code is `0`, or `rejectOnNonZero` is disabled.\n *\n * ---\n *\n * #### Failure\n * Calls `onError(error)` when:\n * - A spawn error occurs.\n * - The process is aborted via `AbortSignal`.\n * - The process is terminated by a signal.\n * - A timeout is reached.\n * - Exit code is non-zero and `rejectOnNonZero` is enabled.\n *\n * ---\n *\n * #### Error metadata\n * The error may include additional properties:\n * - `reason` ➔ `\"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\"`.\n * - `exitCode` ➔ exit code (if available).\n * - `signal` ➔ termination signal (if any).\n * - `command` ➔ executed command (plain, no colors).\n *\n * ---\n *\n * @param handlers Lifecycle callbacks.\n * @param handlers.onSuccess Called when the process completes successfully.\n * @param handlers.onError Called when the process fails or is terminated.\n *\n * @example\n * ```ts\n * const { setupLifecycle } = spawnWithLifecycle(\"node\", [\"script.js\"], options);\n *\n * setupLifecycle({\n * onSuccess(code) {\n * console.log(\"Done:\", code);\n * },\n * onError(err) {\n * console.error(\"Failed:\", err);\n * }\n * });\n * ```\n */\n setupLifecycle({\n onSuccess,\n onError\n }: {\n /** ----------------------------------------------------------------\n * * ***Called when the process completes successfully.***\n * ----------------------------------------------------------------\n *\n * Invoked when:\n * - The process exits normally.\n * - No termination signal is received.\n * - Exit code is `0`, or `rejectOnNonZero` is disabled.\n *\n * @param code The process exit code.\n */\n onSuccess: (\n /** The process exit code. */\n code: number\n ) => void;\n\n /** ----------------------------------------------------------------\n * * ***Called when the process fails or is terminated.***\n * ----------------------------------------------------------------\n *\n * Invoked when:\n * - A spawn error occurs.\n * - The process is aborted.\n * - The process is terminated by a signal.\n * - A timeout is reached.\n * - Exit code is non-zero and `rejectOnNonZero` is enabled.\n *\n * The error may include additional metadata such as:\n * - `reason`.\n * - `exitCode`.\n * - `signal`.\n * - `command`.\n *\n * @param error The error describing the failure.\n */\n onError: (\n /** The error describing the failure. */\n error: CommandProcessError | Error\n ) => void;\n }) {\n const timeoutId =\n timeout != null\n ? setTimeout(() => {\n if (finished) return;\n kill();\n fail(\n formatError(`timed out after ${timeout}ms`, {\n reason: \"timeout\",\n command,\n args,\n useColors\n })\n );\n }, timeout)\n : null;\n\n const cleanup = () => {\n finished = true;\n if (abortSignal) {\n abortSignal.removeEventListener(\"abort\", onAbort);\n }\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n const fail = (err: Error) => {\n if (finished) return;\n cleanup();\n onError(err);\n };\n\n const succeed = (code: number) => {\n if (finished) return;\n cleanup();\n onSuccess(code);\n };\n\n const onAbort = () => {\n if (finished) return;\n kill();\n fail(\n formatError(\"aborted by signal\", {\n reason: \"abort\",\n command,\n args,\n useColors\n })\n );\n };\n\n if (abortSignal) {\n if (abortSignal.aborted) {\n onAbort();\n return;\n }\n abortSignal.addEventListener(\"abort\", onAbort);\n }\n\n child.once(\"error\", fail);\n\n child.once(\"close\", (code, signal) => {\n if (signal) {\n fail(\n formatError(`terminated by ${signal}`, {\n reason: \"signal\",\n signal,\n exitCode: code ?? undefined,\n command,\n args,\n useColors\n })\n );\n return;\n }\n\n const exitCode = code ?? 0;\n\n if (rejectOnNonZero && exitCode !== 0) {\n fail(\n formatError(`exited with code ${exitCode}`, {\n reason: \"non-zero exit code\",\n exitCode,\n command,\n args,\n useColors\n })\n );\n return;\n }\n\n succeed(exitCode);\n });\n }\n };\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport * as acorn from \"acorn\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n IMPORTANT_COMMENT,\n isTargetComment,\n JS_OUTPUT_FILE_RE,\n REGION_RE,\n shouldRemoveDocRuntime,\n SOURCE_MAP_RE\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **strip js comments** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link stripJsComments | **`strip-js-comments`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_SJC_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **strip js comments** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link stripJsComments | **`strip-js-comments`**}.\n */\nexport const resolvedSjcPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_SJC_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link stripJsComments | **`strip-js-comments`**}. */\nconst DEFAULT_SJC_OPTIONS = {\n removeSourceMap: false,\n sourceType: \"module\",\n removeRegion: true,\n ecmaVersion: \"latest\",\n patternOptions: resolvedSjcPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies StripJsCommentsOptions;\n\n/** @internal Constant for {@link stripJsComments | **`strip-js-comments`**}. */\nconst VALID_SOURCE_TYPE = new Set([\"module\", \"script\", \"commonjs\"]);\nconst VALID_ECMA_VERSION = new Set([\n \"latest\",\n 3,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 2015,\n 2016,\n 2017,\n 2018,\n 2019,\n 2020,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026\n]);\n\nconst REGION_COMMENT_RE = /^#(?:end)?region\\b/i;\nconst SOURCE_MAP_COMMENT_RE = /^[#@]\\s*sourceMappingURL=/;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link stripJsComments | **`strip-js-comments`**}. */\nfunction normalizeNewlines(code: string) {\n return code.replace(/[ \\t]+\\n/g, EOL).replace(/\\n\\s*\\n+/g, EOL);\n}\n/** @internal Util for {@link stripJsComments | **`strip-js-comments`**}. */\nfunction stripComments(\n code: string,\n {\n removeRegion,\n removeSourceMap,\n sourceType,\n ecmaVersion\n }: StripJsCommentsOptions\n) {\n const comments: [number, number][] = [];\n\n if (sourceType == null || !VALID_SOURCE_TYPE.has(sourceType)) {\n sourceType = DEFAULT_SJC_OPTIONS.sourceType;\n }\n if (ecmaVersion == null || !VALID_ECMA_VERSION.has(ecmaVersion)) {\n ecmaVersion = DEFAULT_SJC_OPTIONS.ecmaVersion;\n }\n\n try {\n acorn.parse(code, {\n sourceType,\n ecmaVersion,\n allowHashBang: true,\n onComment(block, text, start, end) {\n if (!block) {\n const value = text.trim();\n\n if (\n !REGION_COMMENT_RE.test(value) &&\n !SOURCE_MAP_COMMENT_RE.test(value)\n ) {\n return;\n }\n }\n\n const value = text.trim();\n\n const forceRemove = shouldRemoveDocRuntime(value);\n\n if (forceRemove === true) {\n comments.push([start, end]);\n return;\n }\n\n if (forceRemove === false) return;\n\n if (IMPORTANT_COMMENT.test(value)) return;\n\n // source map\n if (SOURCE_MAP_COMMENT_RE.test(value)) {\n if (removeSourceMap) comments.push([start, end]);\n return;\n }\n\n // region\n if (REGION_COMMENT_RE.test(value)) {\n if (removeRegion) comments.push([start, end]);\n return;\n }\n\n // default: ONLY block comments\n if (block) {\n comments.push([start, end]);\n }\n }\n });\n } catch {\n return code;\n }\n\n if (!comments.length) return code;\n\n const parts: string[] = [];\n let last = 0;\n\n for (const [start, end] of comments) {\n parts.push(code.slice(last, start));\n last = end;\n }\n\n parts.push(code.slice(last));\n\n const result = parts.join(\"\");\n\n const lines = result.split(/\\r?\\n/);\n const seenSourceMap = new Set<string>();\n const cleanedLines = lines\n .filter((line) => {\n if (SOURCE_MAP_RE.test(line)) {\n const key = line.trim();\n\n if (seenSourceMap.has(key)) return false;\n\n seenSourceMap.add(key);\n\n if (removeSourceMap) return false;\n\n return true;\n }\n\n if (removeRegion && REGION_RE.test(line)) return false;\n\n if (isTargetComment(line, { removeSourceMap, removeRegion }))\n return false;\n\n // if (\n // removeAdjacentEmptyLines &&\n // /^\\s*$/.test(line) &&\n // isAdjacentToTarget(arr, i, { removeSourceMap, removeRegion })\n // ) {\n // return false;\n // }\n\n return true;\n })\n .map((line) => {\n let out = line\n // remove source path comments\n .replace(\n /^[ \\t]*\\/\\/\\s*(?:\\.\\.\\/|\\.\\/)*[^ \\n]*?(?:src|node_modules)\\/[^\\n]*\\n?/gm,\n \"\"\n )\n // remove eslint comments\n .replace(/\\/\\/\\s*eslint[^\\n]*/g, \"\");\n\n // if (removeSourceMap) {\n // out = out.replace(/\\/\\/[#@]\\s*sourceMappingURL=[^\\n]*/g, \"\");\n // }\n\n out = out.replace(\n /(\\/\\/[#@]\\s*sourceMappingURL=[^\\r\\n]*)(?:\\r?\\n\\1)+/g,\n \"$1\"\n );\n\n return out;\n });\n\n return cleanedLines.join(EOL);\n}\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link stripJsComments | **`strip-js-comments`**}. */\nexport const commandSjcIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"strip-js-comments\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link stripJsComments | `strip-js-comment`}.***\n * ----------------------------------------------------------------\n */\nexport type StripJsCommentsOptions = {\n /** ----------------------------------------------------------------\n * * ***Whether to remove `sourceMappingURL` comments.***\n * ----------------------------------------------------------------\n *\n * @default false\n */\n removeSourceMap?: boolean;\n /** ----------------------------------------------------------------\n * * ***Whether to remove `region` comments.***\n * ----------------------------------------------------------------\n *\n * @default true\n */\n removeRegion?: boolean;\n\n /** ----------------------------------------------------------------\n * * ***Parsing mode used when analyzing JavaScript code.***\n * ----------------------------------------------------------------\n *\n * Determines how the source file should be interpreted by the parser.\n * This affects strict mode behavior and how `import` / `export`\n * statements are handled.\n *\n *\n * Possible values:\n *\n * - `\"module\"` **(default)** ➔ Parse as an ES module.\n * - `\"script\"` ➔ Parse as a classic script.\n * - `\"commonjs\"` ➔ Parse using CommonJS semantics.\n *\n * ----------------------------------------------------------------\n *\n * ⚠️ Fallback to default, is invalid input.\n *\n *\n * @default \"module\"\n *\n */\n sourceType?: acorn.Options[\"sourceType\"];\n\n /** ----------------------------------------------------------------\n * * ***ECMAScript version used for parsing.***\n * ----------------------------------------------------------------\n *\n * Specifies the ECMAScript syntax version supported by the parser.\n * This determines which language features are recognized during parsing.\n *\n * Examples:\n *\n * - `5` ➔ ES5\n * - `2020` ➔ ES2020\n * - `\"latest\"` ➔ Latest supported version\n *\n * ----------------------------------------------------------------\n *\n * ⚠️ Invalid values will fallback to the default behavior.\n *\n * @default \"latest\"\n */\n ecmaVersion?: acorn.ecmaVersion;\n} & BaseOptions<\n typeof DEFAULT_SJC_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_SJC_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Strip comments from JavaScript output files.***\n * ----------------------------------------------------------------\n *\n * Scans files matching the provided glob pattern(s) and removes\n * non-essential comments from JavaScript output.\n *\n * The process preserves important comments such as:\n *\n * - `/*! ... *\\/` (bang / license comments)\n * - `@license`\n * - `@preserve`\n * - `@copyright`\n * - `@cc_on`\n * - `@__PURE__`\n * - `@__INLINE__`\n * - `@__NOINLINE__`\n * - `@__NO_SIDE_EFFECTS__`\n *\n * unless explicitly overridden by the `@removeDocRuntime` directive.\n *\n * ----------------------------------------------------------------\n *\n * **Supported Features**\n *\n * - Removes regular block comments from compiled JS files.\n * - Optionally removes `sourceMappingURL` comments.\n * - Optionally removes `region` comments such as:\n * - `// #region`\n * - `// #endregion`\n * - Supports runtime directives inside comments:\n * - `@keepDocRuntime`\n * - `@removeDocRuntime`\n *\n * ----------------------------------------------------------------\n *\n * @param pattern - Glob pattern(s) or a set of patterns pointing to\n * files whose comments should be stripped.\n *\n * @param options - Optional configuration controlling how comments\n * are removed.\n *\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * await stripJsComments(\"dist/**\\/*.js\");\n * ```\n *\n * @example\n * ```ts\n * await stripJsComments([\"dist/**\\/*.js\", \"build/**\\/*.mjs\"], {\n * removeSourceMap: true,\n * removeRegion: true\n * });\n * ```\n *\n * ----------------------------------------------------------------\n *\n * @removeDocRuntime\n */\nexport const stripJsComments = async (\n pattern: StringCollection,\n options: StripJsCommentsOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_SJC_OPTIONS.logLevel\n );\n\n try {\n const {\n patternOptions = DEFAULT_SJC_OPTIONS.patternOptions,\n removeSourceMap = DEFAULT_SJC_OPTIONS.removeSourceMap,\n removeRegion = DEFAULT_SJC_OPTIONS.removeRegion,\n sourceType = DEFAULT_SJC_OPTIONS.sourceType,\n ecmaVersion = DEFAULT_SJC_OPTIONS.ecmaVersion,\n __commandTitle\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandSjcIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_SJC_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_SJC_OPTIONS.patternOptions\n )\n );\n\n BUILD_LOGGER.OPTIONS(\n \"options.removeSourceMap\",\n removeSourceMap,\n BUILD_LOGGER.SOURCE_OF(\n removeSourceMap,\n DEFAULT_SJC_OPTIONS.removeSourceMap\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeRegion\",\n removeRegion,\n BUILD_LOGGER.SOURCE_OF(removeRegion, DEFAULT_SJC_OPTIONS.removeRegion)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.sourceType\",\n sourceType,\n BUILD_LOGGER.SOURCE_OF(sourceType, DEFAULT_SJC_OPTIONS.sourceType)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.ecmaVersion\",\n ecmaVersion,\n BUILD_LOGGER.SOURCE_OF(ecmaVersion, DEFAULT_SJC_OPTIONS.ecmaVersion)\n );\n\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_SJC_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Stripping JS Comments\"\n });\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n let output = content;\n\n if (!/\\/[/*]/.test(content)) continue;\n\n output = stripComments(content, {\n removeRegion,\n removeSourceMap,\n sourceType,\n ecmaVersion\n });\n output = normalizeNewlines(output).trim() + EOL;\n\n if (output !== content) {\n try {\n await fsExtra.promises.writeFile(filePath, output, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"JS Comment Stripping\",\n count,\n nameDirect: filePath\n });\n }\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Stripping JS Comments\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Stripping JS Comments\",\n reasonType: \"file\",\n reasonEndText: \"processing\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Stripping JS Comments\",\n error\n });\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,WAAW,OAAmC;AAC5D,QAAO,OAAO,UAAU,YAAY,SAAS;;;;;;;;;;;;;;AAe/C,MAAa,oBAAoB;;;;;;;;;;;;;AAcjC,MAAa,cAAc,CAAC,QAAQ,QAAQ;;;;;;;AAQ5C,MAAa,qBAAqB,OAAO,OAAO;CAC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AGR;AAEA,QAAI,OAAO,aAAa,YAAY,CAClC,cAAa,WAAW;KACtB,YAAY;KACZ;KACA,YAAY;KACb,CAAC;;;AAKR,MAAI,OAAO,aAAa,YAAY,CAClC,KAAI,QAAQ,EACV,cAAa,UAAU;GACrB,YAAY;GACZ;GACD,CAAC;MAEF,cAAa,YAAY;GACvB,YAAY;GACZ,YAAY;GACZ,eAAe;GAChB,CAAC;UAGC,OAAO;AACd,MAAI,gBAAgB,SAClB,cAAa,SAAS;GACpB,YAAY;GACZ;GACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["isString","isArray","resolvePatternOptions","defaultPatternOptions","isNonEmptyString","traverseImport","t","picocolors","normalizeSpaces","formatOptionValue","ICONS","isNonEmptyString","isError","joinLines","isNumber","isPlainObject","joinLinesLoose","toStringSet","resolvePatternOptions","fastGlob","sourceOfPatternOptions","fsExtra","EOL","CommandIdentity","isNonEmptyString","CommandIdentity","isNonEmptyString","isNumber","isPlainObject","isNonEmptyString","isUndefined","isBoolean","picocolors","joinLinesLoose","joinInline","plural","isArray","CommandIdentity","isSet","toObjectSet","path","fsExtra","resolvePatternOptions","defaultPatternOptions","EOL","flattenStrings","isArray","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","EOL","picocolors","resolvePatternOptions","defaultPatternOptions","path","generatePackageBanner","EOL","isNonEmptyString","CommandIdentity","joinLinesLoose","toStringSet","sourceOfPatternOptions","fastGlob","pcr","fsExtra","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","isRegExp","EOL","picocolors","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","EOL","picocolors","resolvePatternOptions","defaultPatternOptions","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra","EOL","safeStableStringify","picocolors","joinLinesLoose","EOL","formatOptionValue","isNonEmptyString","resolvePatternOptions","defaultPatternOptions","EOL","CommandIdentity","joinLinesLoose","isNonEmptyString","toStringSet","sourceOfPatternOptions","fastGlob","fsExtra"],"sources":["../src/_internal/utils/log-level.ts","../src/core/clean/_internal/clean-build-artifacts-constant.ts","../src/_internal/utils/source.ts","../src/_internal/utils/logger-builder.ts","../src/core/clean/_internal/clean-build-artifacts-utils.ts","../src/core/clean/_internal/clean-build-artifacts-core.ts","../src/core/clean/_internal/clean-build-artifacts-runner.ts","../src/core/clean/clean-js-build-artifacts.ts","../src/core/clean/clean-types-build-artifacts.ts","../src/core/copy/file-to-dest/index.ts","../src/core/ensure/css-import/index.ts","../src/core/ensure/final-newline/index.ts","../src/core/generate/reference-index/index.ts","../src/core/inject/banner/index.ts","../src/core/inject/directive/index.ts","../src/core/normalize/js-build-newlines/index.ts","../src/core/run/command/runCommand.ts","../src/core/run/command/runCommandCapture.ts","../src/core/run/command/utils.ts","../src/core/strip/js-comments/index.ts"],"sourcesContent":["import type { LoggingOptions, LogLevel } from \"@/types\";\n\nimport { isArray, isString } from \"./helper\";\n\n/** ----------------------------------------------------------------\n * * ***Type guard to check if a value is a valid LogLevel.***\n * ----------------------------------------------------------------\n *\n * Checks if the given `value` is a string and corresponds to one\n * of the valid log levels defined in `LOG_LEVEL_PRIORITY`.\n *\n * - **Valid log levels:**\n * - `\"silent\"`.\n * - `\"error\"`.\n * - `\"info\"`.\n * - `\"debug\"`.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is a valid `LogLevel`, `false` otherwise.\n *\n * @example\n * ```ts\n * isLogLevel(\"info\"); // ➔ true\n * isLogLevel(\"verbose\"); // ➔ false\n * isLogLevel(123); // ➔ false\n * ```\n *\n * @internal\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && value in LOG_LEVEL_PRIORITY;\n}\n\n/** ----------------------------------------------------------------\n * * ***Default log level constant.***\n * ----------------------------------------------------------------\n *\n * Defines the default log level to be used when no explicit log level\n * is provided or fallback values are invalid.\n *\n * - Value: `\"info\"`.\n * - Guaranteed to be a valid `LogLevel`.\n *\n * @internal\n */\nexport const DEFAULT_LOG_LEVEL = \"info\" satisfies LogLevel;\n\n/** ----------------------------------------------------------------\n * * ***Verbose log levels array.***\n * ----------------------------------------------------------------\n *\n * Defines log levels considered verbose for more detailed logging.\n *\n * - Includes: `\"info\"` and `\"debug\"`.\n * - Used for enabling detailed log output in verbose modes.\n * - Readonly tuple of type `readonly LogLevel[]`.\n *\n * @internal\n */\nexport const VERBOSE_LOG = [\"info\", \"debug\"] as const;\n\n/** ----------------------------------------------------------------\n * * ***Log level priority mapping.***\n * ----------------------------------------------------------------\n *\n * @internal\n */\nexport const LOG_LEVEL_PRIORITY = Object.freeze({\n silent: 0,\n error: 1,\n info: 2,\n debug: 3\n});\n\n/** ----------------------------------------------------------------\n * * ***Resolves the effective log verbosity level.***\n * ----------------------------------------------------------------\n *\n * Resolves the final log level used by the logger in a **fully defensive**\n * manner.\n *\n * - **Behavior:**\n * - Uses the user-provided `logLevel` **only if it is a valid `LogLevel`**.\n * - Falls back when:\n * - `logLevel` is `undefined`.\n * - `logLevel` is invalid or unsupported.\n *\n * - **Fallback guarantees:**\n * - If the provided `fallback` is **also invalid**, the resolver\n * **forcibly falls back to the built-in default** (`\"info\"`).\n * - This ensures the logger **never operates with an invalid log level**.\n *\n * - **Resolution order (highest priority ➔ lowest):**\n * 1. Valid public option (`options.logLevel`).\n * 2. Valid fallback parameter (`fallback`).\n * 3. Built-in default (`\"info\"`).\n *\n * @remarks\n * This function is intentionally strict to prevent misconfiguration\n * from silencing logs or breaking log-level comparisons at runtime.\n *\n * @internal\n */\nexport function resolveLogVerbosity(\n options?: LoggingOptions,\n fallback: LogLevel = DEFAULT_LOG_LEVEL\n): LogLevel {\n const input = options?.logLevel;\n\n if (isLogLevel(input)) return input;\n\n return isLogLevel(fallback) ? fallback : DEFAULT_LOG_LEVEL;\n}\n\n/** ----------------------------------------------------------------\n * * ***Checks whether a log at a given level should be emitted.***\n * ----------------------------------------------------------------\n *\n * Determines whether a log message should be emitted based on\n * the **resolved current log verbosity level**.\n *\n * - **Behavior:**\n * - Supports a single target level or multiple target levels.\n * - The `current` level is used **only if it is a valid `LogLevel`**.\n * - When `current` is invalid:\n * - Falls back to `fallbackIfInvalid`.\n * - If `fallbackIfInvalid` is also invalid, it is **forcibly**\n * resolved to the built-in default (`\"info\"`).\n *\n * - **Emission rule:**\n * - A log is emitted when the resolved current level's priority\n * is **greater than or equal to** any of the target level priorities.\n *\n * - **Guarantees:**\n * - This function **never compares invalid log levels**.\n * - Priority lookup is always safe and deterministic.\n *\n * @remarks\n * This strict resolution prevents misconfiguration from silently\n * disabling logs or causing invalid priority comparisons.\n *\n * @internal\n */\nexport function canLog(\n current: LogLevel,\n target: LogLevel | readonly LogLevel[],\n fallbackIfInvalid: LogLevel = DEFAULT_LOG_LEVEL\n): boolean {\n const fallbackLog = isLogLevel(fallbackIfInvalid)\n ? fallbackIfInvalid\n : DEFAULT_LOG_LEVEL;\n const resolvedCurrent: LogLevel = isLogLevel(current) ? current : fallbackLog;\n\n const targets = isString(target)\n ? [target]\n : isArray(target)\n ? target\n : [fallbackLog];\n\n return targets.some(\n (level) => LOG_LEVEL_PRIORITY[resolvedCurrent] >= LOG_LEVEL_PRIORITY[level]\n );\n}\n","// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n defaultPatternOptions,\n type PatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport { DEFAULT_LOG_LEVEL } from \"@/_internal/utils/log-level\";\n\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **clean build artifact** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`}.\n * - {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_CLEAN_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **clean build artifact** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`}.\n * - {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}.\n */\nexport const resolvedCleanPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_CLEAN_PATTERN_POLICY);\n\n/** @internal Default Options for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport const DEFAULT_CLEAN_OPTION = {\n removeSourceMap: false,\n removeRegion: true,\n removeAdjacentEmptyLines: false,\n patternOptions: resolvedCleanPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies CleanCoreOptions;\n","import type { NodePath } from \"@babel/traverse\";\n\nimport * as t from \"@babel/types\";\nimport { parse } from \"@babel/parser\";\nimport traverseImport from \"@babel/traverse\";\n\nimport { isNonEmptyString } from \"@/_internal/utils/helper\";\n\n/** @internal */\nexport const USE_STRICT_RE = /^['\"]use strict['\"];?\\s*$/gm;\n/** @internal */\nexport const SHEBANG_RE = /^#![^\\r\\n]*\\r?\\n/;\n/** @internal */\nexport const BANNER_RE = /^(?:\\/\\*![\\s\\S]*?\\*\\/\\s*)+/;\n\n/** ----------------------------------------------------------------\n * * ***Matches JavaScript build output files.***\n * ----------------------------------------------------------------\n *\n * Includes common formats such as:\n * `.js`, `.mjs`, `.cjs`, `.esm.js`, and `.module.js`.\n *\n * @internal\n */\nexport const JS_OUTPUT_FILE_RE = /\\.(?:js|mjs|cjs|esm\\.js|module\\.js)$/i;\n\n/** ----------------------------------------------------------------\n * * ***Matches canonical JavaScript module output extensions.***\n * ----------------------------------------------------------------\n *\n * Matches Node.js standard module formats:\n * - `.js`.\n * - `.mjs`.\n * - `.cjs`.\n *\n * ⚠️ This regex also technically matches `.cmjs`,\n * though such files are extremely rare in practice.\n *\n * - ***Intended for:***\n * - strict Node.js module outputs.\n * - internal tooling where minimal matching is desired.\n *\n * @internal\n */\nexport const JS_MODULE_OUTPUT_FILE_RE = /\\.(?:c?m?js)$/i;\n\n/** ----------------------------------------------------------------\n * * ***Matches TypeScript declaration output files.***\n * ----------------------------------------------------------------\n *\n * Includes standard declaration formats:\n * `.d.ts`, `.d.mts`, and `.d.cts`.\n *\n * @internal\n */\nexport const TS_DECLARATION_FILE_RE = /\\.d\\.(?:ts|mts|cts)$/i;\n\n/** ----------------------------------------------------------------\n * * ***Matches region marker comments in source files.***\n * ----------------------------------------------------------------\n *\n * Regular expression that detects single-line region marker comments\n * commonly used for code folding and logical section grouping.\n *\n * - ***Supported markers:***\n * - `// #region`.\n * - `// #endregion`.\n *\n * - ***Matching behavior:***\n * - Allows any number of leading spaces or tabs.\n * - Requires a single-line comment prefix (`//`).\n * - Allows zero or more spaces between `//` and `#`\n * (e.g. `//#region` and `// #region` are both valid).\n * - Matches both opening (`#region`) and closing (`#endregion`) markers.\n * - Uses a word boundary (`\\b`) after `region` to prevent\n * false positives such as `#regionX`.\n * - Does **not** require the marker to be at the end of the line;\n * trailing text is allowed.\n *\n * - ***Typical use cases:***\n * - Parsing generated source files.\n * - Preserving or removing code folding regions.\n * - Detecting logical boundaries during code cleanup.\n *\n * @example\n * ```ts\n * REGION_RE.test(\"//#region\");\n * // ➔ true\n *\n * REGION_RE.test(\"// #region utils\");\n * // ➔ true\n *\n * REGION_RE.test(\" //#endregion helpers\");\n * // ➔ true\n *\n * REGION_RE.test(\"// #regionX\");\n * // ➔ false\n * ```\n *\n * @internal\n */\nexport const REGION_RE = /^[ \\t]*\\/\\/\\s*#(?:end)?region\\b.*$/i;\n// export const REGION_RE = /^[ \\t]*\\/\\/\\s*#(?:end)?region\\b/;\n\n/** ----------------------------------------------------------------\n * * ***Matches source path comments emitted by bundlers or transpilers.***\n * ----------------------------------------------------------------\n *\n * Example:\n * ```js\n * // src/index.ts\n * // node_modules/react/index.js\n * ```\n *\n * @internal\n */\nexport const SOURCE_PATH_RE =\n /^[ \\t]*\\/\\/\\s*(?:\\.\\.\\/|\\.\\/)*[^ \\n]*?(?:src|node_modules)\\//;\n\n/** ----------------------------------------------------------------\n * * ***Matches ESLint directive comments.***\n * ----------------------------------------------------------------\n *\n * Example:\n * ```js\n * // eslint-disable-next-line\n * ```\n *\n * @internal\n */\nexport const ESLINT_RE = /^[ \\t]*\\/\\/\\s*eslint/;\n\n/** ----------------------------------------------------------------\n * * ***Matches source map reference comments.***\n * ----------------------------------------------------------------\n *\n * Example:\n * ```js\n * //# sourceMappingURL=index.js.map\n * //@ sourceMappingURL=index.js.map\n * //@ sourceMappingURL=index.d.ts.map\n * //# sourceMappingURL=index.d.cts.map\n * //# sourceMappingURL=index.d.mts.map\n * ```\n *\n * @internal\n */\nexport const SOURCE_MAP_RE = /^[ \\t]*\\/\\/[#@]\\s*sourceMappingURL=\\S+\\s*$/;\n\n/** ----------------------------------------------------------------\n * * ***Matches important comments that must be preserved.***\n * ----------------------------------------------------------------\n *\n * Regular expression that detects comments which **must not be removed**\n * during comment stripping or source cleanup.\n *\n * These comments are typically required for **legal compliance** or\n * **bundler/minifier optimizations** and therefore should be preserved\n * when generating distributable JavaScript.\n *\n * - ***Supported comment annotations:***\n * - `/*! ... *\\/`\n * Important \"bang\" comments typically used for license banners.\n *\n * - `@license`\n * - `@preserve`\n * - `@copyright`\n * - Legal or attribution metadata that must remain in distributed code.\n *\n * - `@cc_on`\n * Legacy Internet Explorer conditional compilation directive.\n *\n * - `@__PURE__`\n * - `@__INLINE__`\n * - `@__NOINLINE__`\n * - `@__NO_SIDE_EFFECTS__`\n * Optimization hints used by bundlers and minifiers for\n * tree-shaking and inlining decisions.\n *\n * - ***Matching behavior:***\n * - Detects \"bang comments\" beginning with `!` inside block comments.\n * - Matches important license or preservation annotations.\n * - Detects bundler optimization directives.\n * - Intended for use in comment-stripping utilities.\n *\n * - ***Typical use cases:***\n * - Stripping non-essential comments during build.\n * - Preserving license banners in distributed packages.\n * - Keeping optimization hints for bundlers and minifiers.\n * - Maintaining compatibility with tooling such as Rollup,\n * Webpack, Terser, and esbuild.\n *\n * @example\n * ```ts\n * IMPORTANT_COMMENT.test(\"! my-lib v1.0\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"@license MIT\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"@__PURE__\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"@__NO_SIDE_EFFECTS__\");\n * // ➔ true\n *\n * IMPORTANT_COMMENT.test(\"random comment\");\n * // ➔ false\n * ```\n *\n * @internal\n * @removeDocRuntime\n */\nexport const IMPORTANT_COMMENT =\n /^!|@license|@preserve|@copyright|@cc_on|@__(PURE|INLINE|NOINLINE|NO_SIDE_EFFECTS)__/;\n\n/** ----------------------------------------------------------------\n * * ***Matches empty or whitespace-only lines.***\n * ----------------------------------------------------------------\n *\n * Regular expression used to detect lines that contain **no visible\n * characters**, only whitespace or nothing at all.\n *\n * - ***Matching rules:***\n * - Matches an empty string.\n * - Matches lines containing only whitespace characters.\n * - Accepts spaces, tabs, and other standard whitespace.\n * - Rejects any line containing visible characters.\n *\n * This regex is typically used for **filtering or skipping blank lines**\n * during text or source code processing.\n *\n * @internal\n */\nexport const EMPTY_LINE_RE = /^\\s*$/;\n\n/** ----------------------------------------------------------------\n * * ***Matches documentation comments marked as removable.***\n * ----------------------------------------------------------------\n *\n * Regular expression that detects **documentation comments explicitly\n * marked for removal** during build output cleanup.\n *\n * This is intended for stripping development-only documentation from\n * compiled JavaScript while keeping important comments intact.\n *\n * ----------------------------------------------------------------\n *\n * - ***Supported directive tags***\n *\n * - `@removeDoc`\n * Marks a documentation block as **safe to remove** during\n * build cleanup.\n *\n * - `@keepDoc`\n * Explicitly marks a documentation block that **must be preserved**.\n *\n * ----------------------------------------------------------------\n *\n * - ***Matching behavior***\n *\n * - Matches block documentation comments containing `@removeDoc`.\n * - Ignores documentation blocks containing `@keepDoc`.\n * - Intended for use in **comment stripping utilities**.\n *\n * ----------------------------------------------------------------\n *\n * - ***Typical use cases***\n *\n * - Removing internal documentation from distributed builds.\n * - Keeping only public-facing documentation comments.\n * - Reducing bundle size while preserving intentional comments.\n *\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * REMOVABLE_DOC_COMMENT.test(\"/** \\\\@removeDoc internal helper *\\/\");\n * // ➔ true\n *\n * REMOVABLE_DOC_COMMENT.test(\"/** \\\\@keepDoc public API *\\/\");\n * // ➔ false\n *\n * REMOVABLE_DOC_COMMENT.test(\"/** normal doc comment *\\/\");\n * // ➔ false\n * ```\n *\n * @internal\n * @removeDocRuntime\n */\nexport const REMOVABLE_DOC_COMMENT =\n /^\\/\\*\\*(?![\\s\\S]*@keepDoc)[\\s\\S]*@removeDoc[\\s\\S]*?\\*\\//;\n\n/** ----------------------------------------------------------------\n * * ***Determine if a comment should be removed based on directives runtime.***\n * ----------------------------------------------------------------\n *\n * This helper ensures that the directive detection only runs **inside\n * comment text**, not raw source. It applies the following logic:\n *\n * 1. `@keepDocRuntime` ➔ always force keep.\n * 2. `@removeDocRuntime` ➔ always force remove.\n * 3. No tag ➔ leave as default (undefined).\n *\n * ----------------------------------------------------------------\n *\n * @param commentText - inner text of the comment (from parser like Acorn)\n * @returns `true` if forced to remove, `false` if forced to keep, `undefined` if default\n *\n * @example\n * ```ts\n * const commentText = \"* \\\\@removeDocRuntime Internal helper\";\n * const result = shouldRemoveDocRuntime(commentText);\n * console.log(result); // true\n *\n * const keepText = \"* \\\\@keepDoc public API\";\n * console.log(shouldRemoveDocRuntime(keepText)); // false\n *\n * const normalText = \"* normal comment\";\n * console.log(shouldRemoveDocRuntime(normalText)); // undefined\n * ```\n *\n * @internal\n * @removeDocRuntime\n */\nexport function shouldRemoveDocRuntime(\n commentText: string\n): boolean | undefined {\n const text = commentText.trim();\n\n const hasRemoveDocRuntime = /[@]removeDocRuntime\\b/.test(text);\n const hasKeepDocRuntime = /[@]keepDocRuntime\\b/.test(text);\n\n if (hasRemoveDocRuntime && hasKeepDocRuntime) {\n return true; // force remove\n }\n\n if (hasKeepDocRuntime) {\n return false; // force keep\n }\n\n if (hasRemoveDocRuntime) {\n return true; // force remove\n }\n\n return undefined; // default behavior\n}\n/** ----------------------------------------------------------------\n * * ***Matches files containing only top-level `\"use *\"` directives.***\n * ----------------------------------------------------------------\n *\n * Regular expression used to verify whether a source file consists\n * exclusively of one or more `\"use <directive>\"` statements.\n *\n * - ***Matching rules:***\n * - Matches one or more `\"use *\"` directives.\n * - Supports single or double quoted directives.\n * - Allows optional semicolons and trailing whitespace.\n * - Rejects any executable code or non-directive content.\n *\n * This regex is intended for **heuristic internal validation**\n * and does not perform full JavaScript parsing.\n *\n * @internal\n */\nexport const DIRECTIVE_RE = /^((?:(?:\"use\\s+\\w+\"|'use\\s+\\w+');\\s*)+)/;\n\n/** ----------------------------------------------------------------\n * * ***Matches executable code following top-level `\"use *\"` directives.***\n * ----------------------------------------------------------------\n *\n * Regular expression used to detect whether a source file contains\n * any content **after** one or more leading `\"use <directive>\"`\n * statements.\n *\n * - ***Matching rules:***\n * - Requires at least one `\"use <word>\"` directive at the start.\n * - Supports single or double quoted directives.\n * - Allows optional semicolons and trailing whitespace.\n * - Matches any remaining content after the directives.\n *\n * This regex is intended for **heuristic internal checks** and does\n * not perform full JavaScript syntax validation.\n *\n * @internal\n */\nexport const CODE_AFTER_DIRECTIVE_RE = /^(['\"]use\\s+\\w+['\"];?\\s*)+[\\s\\S]+$/;\n\n/** ----------------------------------------------------------------\n * * ***Matches files that MUST NOT contain comments.***\n * ----------------------------------------------------------------\n *\n * Identifies structured, machine-generated, or strict-spec files\n * that do NOT support JavaScript-style comments and should never\n * be mutated by comment injectors or build transformers.\n *\n * ----------------------------------------------------------------\n * Included Categories\n *\n * 1) Strict JSON Specification (RFC 8259 compliant):\n * - `.json`.\n * - `.map` (Source maps).\n * - `.webmanifest`.\n * - `.har`.\n * - `.geojson`.\n * - `.topojson`.\n *\n * 2) Lock-files & Dependency Metadata (machine-generated):\n * - `package-lock.json`.\n * - `composer.lock`.\n * - `bun.lockb`.\n *\n * 3) Tooling / Compiler Artifacts:\n * - `.tsbuildinfo`.\n *\n * ----------------------------------------------------------------\n * Important Notes\n *\n * - JSON strictly disallows comments.\n * - Source maps are JSON and must remain spec-compliant.\n * - Lock-files must never be altered by formatters or comment injectors.\n * - This regex is intentionally defensive for build tooling contexts.\n *\n * ----------------------------------------------------------------\n * Explicitly NOT Included:\n *\n * - `.jsonc` (supports comments).\n * - `.yaml` / `.yml` (supports comments).\n * - `.toml` (supports comments).\n * - `.xml` (supports comments).\n *\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * if (NON_COMMENTABLE_FILE_RE.test(filePath)) {\n * // skip comment injection / stripping\n * }\n * ```\n *\n * @internal\n */\nexport const NON_COMMENTABLE_FILE_RE =\n /(?:^|[\\\\/])(?:package-lock\\.json|composer\\.lock|bun\\.lockb)$|\\.(?:json|map|webmanifest|har|geojson|topojson|tsbuildinfo)$/i;\n// export const NON_COMMENTABLE_FILE_RE =\n// /(?:^|[\\\\/])(?:package-lock\\.json|composer\\.lock|bun\\.lockb)$|(?:\\.(?:json|map|webmanifest|har|geojson|topojson|tsbuildinfo))$/i;\n\n/** ----------------------------------------------------------------\n * * ***Checks whether a file contains only directive statements.***\n * ----------------------------------------------------------------\n *\n * Determines if the provided source content is composed solely of\n * top-level `\"use *\"` directives, or is effectively empty.\n *\n * - ***Evaluation rules:***\n * - Empty or whitespace-only content is considered valid.\n * - Content containing only `\"use *\"` directives returns `true`.\n * - Any additional code or statements cause a `false` result.\n *\n * This utility is primarily used to decide whether a file is\n * **directive-only** and safe for directive injection or hoisting.\n *\n * @param {string} content - JavaScript source content.\n *\n * @returns {boolean}\n * `true` if the file contains only directives or is empty,\n * otherwise `false`.\n *\n * @example\n * ```ts\n * isDirectiveOnlyFile('\"use strict\";\\n\"use client\";');\n * // ➔ true\n * ```\n *\n * @example\n * ```ts\n * isDirectiveOnlyFile('\"use client\";\\nconst a = 1;');\n * // ➔ false\n * ```\n *\n * @internal\n */\nexport function isDirectiveOnlyFile(content: string): boolean {\n const trimmed = content.trim();\n if (!trimmed) return true;\n\n const { body } = extractAndHoistBanner(trimmed);\n const { directives, rest } = extractDirectives(body);\n\n return isNonEmptyString(directives) && !isNonEmptyString(rest);\n}\n\n/** ----------------------------------------------------------------\n * * ***Determines whether executable code exists beyond directives.***\n * ----------------------------------------------------------------\n *\n * Checks if a source file contains **executable JavaScript code**\n * after removing non-executable preamble content.\n *\n * - ***The following elements are ignored during evaluation:***\n * - Leading shebang (if present).\n * - Banner comments (`/*! ... *\\/`).\n * - Top-level `\"use *\"` directive statements.\n *\n * - ***Evaluation rules:***\n * - Empty or whitespace-only files are treated as **executable**.\n * - Files containing only directives and/or banners return `false`.\n * - Any remaining non-empty content is considered executable code.\n *\n * This utility performs **structural heuristics** and does not\n * rely on full JavaScript parsing.\n *\n * @param {string} content - JavaScript source content.\n *\n * @returns {boolean}\n * `true` if executable code exists after directives,\n * otherwise `false`.\n *\n * @example\n * ```ts\n * hasExecutableCode('#!/usr/bin/env node\\n\"use strict\";\\nconst a = 1;');\n * // ➔ true\n * ```\n *\n * @example\n * ```ts\n * hasExecutableCode('\"use client\";\\n/*! banner *\\/');\n * // ➔ false\n * ```\n *\n * @internal\n */\nexport function hasExecutableCode(content: string): boolean {\n const trimmed = content.trim();\n\n const { body } = extractAndHoistBanner(trimmed);\n const { rest } = extractDirectives(body);\n\n return isNonEmptyString(rest);\n}\n\n/** @internal */\nexport type RemoveCommentsOptions = {\n /** Whether source map comments should be considered removable.\n *\n * @default false\n */\n removeSourceMap?: boolean;\n\n /** Whether source region comments should be considered removable.\n *\n * @default true\n */\n removeRegion?: boolean;\n};\n\nexport const defaultCommentOptions: RemoveCommentsOptions = {\n removeRegion: true,\n removeSourceMap: false\n};\n\n/** ----------------------------------------------------------------\n * * ***Determines whether a line is a removable build artifact comment.***\n * ----------------------------------------------------------------\n *\n * - ***This includes:***\n * - source path comments (`// src/...`, `// node_modules/...`).\n * - source region comments,\n * see {@link REGION_RE | `REGION_RE`}.\n * - ESLint directive comments.\n * - source map comments (optional).\n *\n * @param {string|null|undefined} line - A single line of file content.\n * @param {RemoveCommentsOptions} options - Options to check target comment.\n * @returns `true` if the line matches a removable comment pattern.\n *\n * @internal\n */\nexport const isTargetComment = (\n line: string | null | undefined,\n options: RemoveCommentsOptions = defaultCommentOptions\n) => {\n if (!isNonEmptyString(line)) return false;\n if (SOURCE_PATH_RE.test(line)) return true;\n if (ESLINT_RE.test(line)) return true;\n if (options.removeRegion && REGION_RE.test(line)) return true;\n if (options.removeSourceMap && SOURCE_MAP_RE.test(line)) return true;\n return false;\n};\n\n/** ----------------------------------------------------------------\n * * ***Checks whether a line is directly adjacent to a removable comment line.***\n * ----------------------------------------------------------------\n *\n * Used to optionally remove empty lines surrounding build artifact comments\n * to avoid leaving unnecessary visual gaps.\n *\n * @param {string[]} arr - Array of file lines.\n * @param {number} index - Current line index.\n * @param {RemoveCommentsOptions} options - Options to check target comment.\n * @returns `true` if an adjacent line matches a removable comment.\n *\n * @internal\n */\nexport const isAdjacentToTarget = (\n arr: string[],\n index: number,\n options: RemoveCommentsOptions = defaultCommentOptions\n) => {\n return (\n isTargetComment(arr[index - 1], options) ||\n isTargetComment(arr[index + 1], options)\n );\n};\n\n/** ----------------------------------------------------------------\n * * ***Represents supported JavaScript module kinds.***\n * ----------------------------------------------------------------\n *\n * Describes the detected module system of a JavaScript file.\n * Used internally to distinguish runtime module boundaries.\n *\n * @remarks\n * The classification is heuristic-based and intended primarily for\n * compiled or bundled output, not strict spec validation.\n *\n * @example\n * \"esm\" // ECMAScript module using `import` / `export`\n * \"cjs\" // CommonJS module using `require` / `module.exports`\n * \"umd\" // Universal Module Definition wrapper\n * \"iife\" // Immediately Invoked Function Expression bundle\n *\n * @internal\n */\nexport type ModuleKind = \"esm\" | \"cjs\" | \"umd\" | \"iife\";\n\n/** ----------------------------------------------------------------\n * * ***Detects module kind from JavaScript source content.***\n * ----------------------------------------------------------------\n *\n * Heuristic-based module format detection optimized for **compiled,\n * transpiled, or bundled JavaScript output**.\n *\n * This function analyzes the AST and attempts to infer the effective\n * runtime module boundary rather than relying purely on syntax shape.\n *\n * ----------------------------------------------------------------\n * #### 🔎 Priority Rules (highest ➔ lowest).\n * ----------------------------------------------------------------\n * 1. UMD environment wrapper detection\n * (`typeof exports` / `typeof module` + optional `define`) ➔ `\"umd\"`.\n *\n * 2. Runtime mutation of `module.exports` or `exports.*` ➔ `\"cjs\"`.\n *\n * 3. Real ESM `export` declarations ➔ `\"esm\"`.\n *\n * 4. ESM `import` declarations ➔ `\"esm\"`.\n *\n * 5. Top-level IIFE bundle without module system markers ➔ `\"iife\"`.\n *\n * 6. `require()` usage without explicit ESM ➔ `\"cjs\"`.\n *\n * 7. Fallback ➔ `\"esm\"`.\n *\n * ----------------------------------------------------------------\n * #### ⚠️ Limitations & Heuristic Caveats.\n * ----------------------------------------------------------------\n *\n * - Detection is heuristic-based and **not spec-guaranteed**.\n * - Designed primarily for bundled or transpiled build outputs.\n *\n * - UMD detection may fail when:\n * - The environment wrapper is heavily minified or obfuscated.\n * - `typeof exports` / `typeof module` checks are removed or transformed.\n * - The wrapper does not follow conventional UMD patterns.\n *\n * In such cases, UMD may be treated as `\"cjs\"`.\n *\n * - IIFE detection is intentionally conservative:\n * - Only top-level immediately-invoked function expressions are considered.\n * - If CommonJS mutations are present inside the IIFE,\n * the module will be classified as `\"cjs\"`.\n *\n * Therefore, certain bundled IIFE outputs may be classified as `\"cjs\"`\n * rather than `\"iife\"`.\n *\n * - Hybrid bundles (e.g. CJS wrapped in IIFE) are classified based on\n * detected runtime export behavior.\n *\n * ----------------------------------------------------------------\n * #### 🎯 Design Philosophy.\n * ----------------------------------------------------------------\n * This function favors **runtime export boundary detection**\n * over superficial syntax appearance.\n *\n * The goal is to determine how the file behaves when executed,\n * not how it was originally authored.\n *\n * @param code - JavaScript source code to analyze.\n * @returns Detected module kind:\n * `\"esm\"` | `\"cjs\"` | `\"umd\"` | `\"iife\"`.\n *\n * @internal\n */\nexport function detectModuleKindFromContent(code: string): ModuleKind {\n let hasImport = false;\n let hasExport = false;\n\n let hasModuleExports = false;\n let hasExportsMutation = false;\n let hasRequire = false;\n\n let hasDefine = false;\n let hasUMDEnvCheck = false;\n\n let hasTopLevelIIFE = false;\n\n const ast = parse(code, {\n sourceType: \"unambiguous\",\n plugins: [\"typescript\", \"jsx\"]\n });\n\n const traverse: typeof traverseImport =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (traverseImport as any).default ?? traverseImport;\n\n traverse(ast, {\n Program(path) {\n for (const node of path.node.body) {\n if (\n t.isExpressionStatement(node) &&\n t.isCallExpression(node.expression) &&\n (t.isFunctionExpression(node.expression.callee) ||\n t.isArrowFunctionExpression(node.expression.callee))\n ) {\n hasTopLevelIIFE = true;\n }\n\n if (t.isVariableDeclaration(node)) {\n for (const decl of node.declarations) {\n if (\n decl.init &&\n t.isCallExpression(decl.init) &&\n (t.isFunctionExpression(decl.init.callee) ||\n t.isArrowFunctionExpression(decl.init.callee))\n ) {\n hasTopLevelIIFE = true;\n }\n }\n }\n }\n },\n\n ImportDeclaration() {\n hasImport = true;\n },\n\n ExportNamedDeclaration() {\n hasExport = true;\n },\n\n ExportDefaultDeclaration() {\n hasExport = true;\n },\n\n AssignmentExpression(path: NodePath<t.AssignmentExpression>) {\n const left = path.node.left;\n\n if (t.isMemberExpression(left)) {\n if (t.isIdentifier(left.object) && t.isIdentifier(left.property)) {\n if (\n left.object.name === \"module\" &&\n left.property.name === \"exports\"\n ) {\n hasModuleExports = true;\n }\n\n if (left.object.name === \"exports\") {\n hasExportsMutation = true;\n }\n }\n }\n },\n\n CallExpression(path) {\n const { callee, arguments: args } = path.node;\n\n // Detect CJS-style export mutation\n if (\n args.length > 0 &&\n t.isIdentifier(args[0]) &&\n args[0].name === \"exports\"\n ) {\n hasExportsMutation = true;\n }\n\n if (t.isIdentifier(callee)) {\n // require()\n if (callee.name === \"require\") {\n hasRequire = true;\n }\n\n // define() for AMD/UMD\n if (callee.name === \"define\") {\n hasDefine = true;\n }\n }\n },\n\n UnaryExpression(path) {\n if (\n path.node.operator === \"typeof\" &&\n t.isIdentifier(path.node.argument) &&\n (path.node.argument.name === \"exports\" ||\n path.node.argument.name === \"module\")\n ) {\n hasUMDEnvCheck = true;\n }\n }\n });\n\n // -------------------------\n // FINAL CLASSIFICATION\n // -------------------------\n\n const isCJS = hasModuleExports || hasExportsMutation;\n const isUMD = hasUMDEnvCheck && (hasDefine || isCJS);\n\n // 1. UMD\n if (isUMD) return \"umd\";\n\n // 2. CJS\n if (isCJS) return \"cjs\";\n\n // 3. ESM\n if (hasExport || hasImport) return \"esm\";\n\n // 4. Pure IIFE (NO module system inside)\n if (hasTopLevelIIFE && !isCJS && !hasImport && !hasExport) {\n return \"iife\";\n }\n\n // 5. require-only fallback\n if (hasRequire) return \"cjs\";\n\n return \"esm\";\n}\n\n/** @deprecated use `detectModuleKind` instead.\n *\n * @internal\n */\nexport function detectModuleKindFromContent_(code: string): ModuleKind {\n // /* -------------------------------------------------------------\n // * Detect UMD wrapper (environment branching)\n // * ------------------------------------------------------------- */\n\n // if (/\\bmodule\\.exports\\s*=\\s*factory/.test(code) && /\\bdefine\\.amd\\b/.test(code)) {\n // return \"umd\";\n // }\n\n // const HAS_TYPEOF_EXPORTS = /\\btypeof\\s+exports\\b/;\n // const HAS_TYPEOF_MODULE = /\\btypeof\\s+module\\b/;\n // const HAS_DEFINE_AMD = /\\bdefine\\s*\\(\\s*\\[\\s*\\]|\\bdefine\\.amd\\b/;\n\n // if (\n // (HAS_TYPEOF_EXPORTS.test(code) && HAS_TYPEOF_MODULE.test(code)) ||\n // HAS_DEFINE_AMD.test(code)\n // ) {\n // return \"umd\";\n // }\n\n // /* -------------------------------------------------------------\n // * Detect top-level assigned IIFE bundle\n // * ------------------------------------------------------------- */\n\n // const IIFE_RE =\n // /\\(\\s*(?:async\\s*)?(?:function\\b|\\([\\w\\s,]*\\)\\s*=>)[\\s\\S]*?\\)\\s*\\(\\s*[\\s\\S]*?\\s*\\)\\s*;?/;\n\n // if (IIFE_RE.test(code)) {\n // return \"iife\";\n // }\n\n /* -------------------------------------------------------------\n * STRONGEST: CommonJS runtime export mutation\n * ------------------------------------------------------------- */\n\n const CJS_EXPORT_MUTATION_RE =\n /\\bmodule\\.exports\\s*=|\\bexports\\s*(?:\\.|\\[|\\?\\.)\\s*[\\w\"'`]+\\s*=|\\bObject\\.(?:definePropert(?:y|ies)|assign)\\s*\\(\\s*exports\\b|\\bReflect\\.defineProperty\\s*\\(\\s*exports\\b|\\b__export(?:Star)?\\s*\\(\\s*(?:\\w+\\s*,\\s*)?exports\\b/;\n\n if (CJS_EXPORT_MUTATION_RE.test(code)) {\n return \"cjs\";\n }\n\n /* -------------------------------------------------------------\n * TRUE ESM boundary (syntax-level)\n * ------------------------------------------------------------- */\n\n const ESM_EXPORT_RE =\n /^\\s*export\\s+(?:default|const|let|var|function|class|type|interface|enum|{)/m;\n\n if (ESM_EXPORT_RE.test(code)) {\n return \"esm\";\n }\n\n /* -------------------------------------------------------------\n * import syntax (weak signal, but valid if no mutation)\n * ------------------------------------------------------------- */\n\n const ESM_IMPORT_RE = /^\\s*import\\s+(?:[\\w*\\s{},]+?\\s+from\\s+)?['\"]/m;\n\n if (ESM_IMPORT_RE.test(code)) {\n return \"esm\";\n }\n\n /* -------------------------------------------------------------\n * require() fallback\n * ------------------------------------------------------------- */\n\n if (/\\brequire\\s*\\(/.test(code)) {\n return \"cjs\";\n }\n\n /* -------------------------------------------------------------\n * Default assumption\n * ------------------------------------------------------------- */\n\n return \"esm\";\n}\n\n/** ----------------------------------------------------------------\n * * ***Extracts and hoists leading shebang and banner comments.***\n * ----------------------------------------------------------------\n *\n * Extracts a Unix shebang (`#!...`) and the first `/*! ... *\\/`\n * style banner comment from the beginning of a source file,\n * separating them from the remaining body content.\n *\n * - ***Extraction rules:***\n * - Shebang is extracted first if present.\n * - Only the first banner comment is extracted.\n * - Order is preserved: shebang ➔ banner ➔ body.\n * - Remaining content is trimmed of leading whitespace.\n *\n * If neither shebang nor banner is found, the original content\n * is returned unchanged as the body.\n *\n * @param {string} content - Full file content.\n *\n * @returns {{\n * shebang: string;\n * banner: string;\n * body: string;\n * }}\n * An object containing the extracted shebang, banner, and remaining body.\n *\n * @example\n * ```ts\n * extractAndHoistBanner('#!/usr/bin/env node\\n/*! banner *\\/\\nconst a = 1;');\n * // ➔ {\n * // shebang: '#!/usr/bin/env node\\n',\n * // banner: '/*! banner *\\/',\n * // body: 'const a = 1;'\n * // }\n * ```\n *\n * @internal\n */\nexport function extractAndHoistBanner(content: string): {\n shebang: string;\n banner: string;\n body: string;\n} {\n let rest = content;\n let shebang = \"\";\n let banner = \"\";\n\n const shebangMatch = rest.match(SHEBANG_RE);\n if (shebangMatch && shebangMatch.index === 0) {\n shebang = shebangMatch[0];\n rest = rest.slice(shebang.length);\n }\n\n const bannerMatch = rest.match(BANNER_RE);\n if (bannerMatch && bannerMatch.index === 0) {\n banner = bannerMatch[0];\n rest = rest.slice(banner.length);\n }\n\n return {\n shebang,\n banner,\n body: rest.replace(/^\\s+/, \"\")\n };\n}\n\n/** ----------------------------------------------------------------\n * * ***Extracts top-level `\"use *\"` directives from source code.***\n * ----------------------------------------------------------------\n *\n * Collects consecutive `\"use <directive>\"` statements located\n * at the very beginning of the file.\n *\n * - ***Extraction rules:***\n * - Matches both single and double quoted directives.\n * - Stops at the first non-directive statement.\n * - Preserves original directive formatting.\n *\n * - ***The returned object splits the code into:***\n * - `directives` ➔ raw directive string.\n * - `rest` ➔ remaining source code.\n *\n * @param {string} code - JavaScript source code.\n *\n * @returns {{ directives: string; rest: string }}\n * Extracted directives and remaining code.\n *\n * @example\n * ```ts\n * extractDirectives('\"use strict\"; \"use client\"; const a = 1;');\n * // ➔ { directives: '\"use strict\"; \"use client\";', rest: 'const a = 1;' }\n * ```\n *\n * @internal\n */\nexport function extractDirectives(code: string): {\n directives: string;\n rest: string;\n} {\n const match = code.match(/^((?:(?:\"use\\s+\\w+\"|'use\\s+\\w+');\\s*)+)/);\n\n return {\n directives: match?.[1] ?? \"\",\n rest: code.slice(match?.[1]?.length ?? 0)\n };\n}\n\n/** ----------------------------------------------------------------\n * * ***Removes `\"use strict\"` directives from source content.***\n * ----------------------------------------------------------------\n *\n * Strips all standalone `\"use strict\"` directive statements from\n * the provided content while preserving other directives such as\n * `\"use client\"`.\n *\n * - ***Removal rules:***\n * - Matches both single and double quoted `\"use strict\"`.\n * - Only removes full directive lines (line-anchored).\n * - Supports optional trailing semicolon.\n *\n * By default, leading whitespace is trimmed after removal to keep\n * the resulting content properly aligned for further processing.\n *\n * @param {string} content - Source content containing directive statements.\n *\n * @param {object} [options] - Behavior configuration.\n * @param {boolean} [options.trimStart=true]\n * Whether to trim leading whitespace after stripping directives.\n *\n * @returns {string} Content with `\"use strict\"` directives removed.\n *\n * @example\n * ```ts\n * stripUseStrict('\"use strict\";\\n\"use client\";');\n * // ➔ '\"use client\";'\n * ```\n *\n * @example\n * ```ts\n * stripUseStrict('\"use strict\";\\n\\nconst a = 1;', { trimStart: false });\n * // ➔ '\\n\\nconst a = 1;'\n * ```\n *\n * @internal\n */\nexport function stripUseStrict(\n content: string,\n {\n trimStart = true,\n trimEnd = false\n }: {\n /** @default true */\n trimStart?: boolean;\n /** @default false */\n trimEnd?: boolean;\n } = {}\n): string {\n const result = content.replace(USE_STRICT_RE, \"\");\n if (trimStart) result.trimStart();\n if (trimEnd) result.trimEnd();\n\n return result;\n}\n\n/** ----------------------------------------------------------------\n * * ***Determines the correct insertion index for injected code.***\n * ----------------------------------------------------------------\n *\n * Calculates the byte index in source code where new content\n * (such as directives or imports) should be safely inserted.\n *\n * - ***Insertion rules:***\n * - Skips over a leading shebang (`#!...`) if present.\n * - Skips over a leading banner comment (`/*! ... *\\/`) if present.\n * - Preserves original file ordering and semantics.\n *\n * The returned index points to the position **after** any detected\n * shebang or banner, making it safe for code injection.\n *\n * @param {string} code - JavaScript source code.\n *\n * @returns {number}\n * Index position suitable for inserting additional code.\n *\n * @example\n * ```ts\n * findInsertIndex('#!/usr/bin/env node\\n/*! banner *\\/\\nconst a = 1;');\n * // ➔ index after shebang and banner.\n * ```\n *\n * @internal\n */\nexport function findInsertIndex(code: string): number {\n let index = 0;\n\n const shebang = code.match(SHEBANG_RE);\n if (shebang) index += shebang[0].length;\n\n const banner = code.slice(index).match(BANNER_RE);\n if (banner) index += banner[0].length;\n\n return index;\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { AnyString } from \"@/_internal/types/extra\";\n\nimport { isDeepStrictEqual } from \"node:util\";\n\nimport {\n isError,\n isNonEmptyString,\n isNumber,\n normalizeSpaces\n} from \"@/_internal/utils/helper\";\n\nimport {\n formatOptionValue,\n joinLines,\n picocolors\n} from \"@/utils/helper/formatter\";\nimport { ICONS } from \"@/utils/helper/icons\";\n\n/** -------------------------------------------------------------------\n * * ***Determines whether an option value comes from the default configuration\n * or has been explicitly overridden by the user.***\n * -------------------------------------------------------------------\n *\n * This utility is primarily intended for logging and debugging purposes,\n * especially in CLI tools or build pipelines where distinguishing between\n * default and user-provided values is important.\n *\n * The comparison is performed using `Object.is` to ensure accurate detection,\n * including edge cases such as:\n * - `NaN` vs `NaN`.\n * - `-0` vs `+0`.\n *\n * @template T - The type of the option value being compared.\n *\n * @param {unknown} value - The actual value used at runtime.\n * @param {unknown} defaultValue - The default value defined by the tool.\n *\n * @returns\n * A string indicating the source of the value:\n *\n * - `\"default\"` when `value` is strictly equal to `defaultValue`.\n * - `\"overridden\"` when the value differs from the default.\n *\n * @example\n * ```ts\n * sourceOf(\"dist\", \"dist\"); // ➔ \"default\"\n * sourceOf(\"dist/types\", \"dist\"); // ➔ \"overridden\"\n * ```\n *\n * @example\n * ***CLI-style option logging:***\n * ```ts\n * BUILD_LOGGER.OPTIONS(\n * \"outDir\",\n * outDir,\n * sourceOf(outDir, DEFAULTS.outDir)\n * );\n * ```\n */\nexport const sourceOf = <T>(\n value: T,\n defaultValue: T\n): \"default\" | \"overridden\" => {\n return Object.is(value, defaultValue) ? \"default\" : \"overridden\";\n};\n\n/** ----------------------------------------------------------------\n * * ***Deep default source detector.***\n * ----------------------------------------------------------------\n *\n * Determines whether a given value is structurally identical\n * to its default value using deep comparison.\n *\n * Unlike `Object.is`, this utility compares object contents\n * recursively rather than checking reference identity.\n *\n * Intended for configuration systems where option objects\n * may be cloned or reconstructed but still represent the\n * default state.\n *\n * @template T - Value type being compared.\n *\n * @param value - Current runtime value.\n * @param defaultValue - Default reference value.\n *\n * @returns\n * - `\"default\"` ➔ If values are deeply equal.\n * - `\"overridden\"` ➔ If values differ.\n *\n * @example\n * ```ts\n * sourceOfIsDeepStrictEqual(\n * { onlyFiles: true },\n * { onlyFiles: true }\n * );\n * // \"default\"\n * ```\n */\nexport const sourceOfIsDeepStrictEqual = <T>(\n value: T,\n defaultValue: T\n): \"default\" | \"overridden\" => {\n return isDeepStrictEqual(value, defaultValue) ? \"default\" : \"overridden\";\n};\n\n/** -------------------------------------------------------------------\n * * ***Structured build-time console logger with consistent formatting,\n * icons, and colorized output.***\n * --------------------------------------------------------------------\n *\n * `BUILD_LOGGER` provides a collection of standardized logging helpers\n * intended for **CLI tools, build scripts, and Node.js-based workflows**.\n *\n * - **It ensures:**\n * - Consistent log structure across different build phases.\n * - Clear visual distinction between states (start, success, skip, error).\n * - Emoji or ASCII icon support depending on environment configuration.\n * - Readable, colorized output via `picocolors`.\n *\n * Emoji usage is controlled via the environment variable:\n *\n * ```\n * FORCE_EMOJI=1\n * ```\n *\n * When disabled, all icons gracefully fall back to ASCII-safe symbols.\n *\n * ---\n *\n * - **Behavior:**\n * - Uses emoji icons when `FORCE_EMOJI === \"1\"`.\n * - Falls back to ASCII symbols otherwise.\n * - Applies consistent spacing, bulleting, and indentation.\n * - Formats messages using `picocolors` for visibility.\n * - Safely extracts error messages from unknown error values.\n *\n * ---\n *\n * - **Available log actions:**\n * - `SOURCE_OF`:\n * - See {@link sourceOf | **`sourceOf`**} helpers.\n *\n * - `OPTIONS({ label, value, source, isRequired })`:\n * - Logs the options argument function using\n * {@link sourceOf | **`sourceOf`**} helper.\n *\n * - `NEW_LINE()`:\n * - *Inserts an empty line in the console output.*\n *\n * - `ON_STARTING({ actionName })`:\n * - *Logs the start of a build or processing action.*\n *\n * - `ON_FINISH({ actionName, count })`:\n * - *Logs successful completion with item count.*\n *\n * - `ON_SKIPPING({ actionName, reasonEndText })`:\n * - *Logs skipped actions with human-readable reasons.*\n *\n * - `ON_ERROR({ actionName, error })`:\n * - *Logs formatted error output with extracted message.*\n *\n * - `ON_PROCESS_COPY({ actionName, copyFrom, copyTo })`:\n * - *Logs file copy operations.*\n *\n * - `ON_PROCESS({ actionName, nameDirect })`:\n * - *Logs generic processing steps.*\n *\n * - `ON_PROCESS_REFERENCING({ actionName, referenceFrom, referenceTo })`:\n * - *Logs reference or linking operations.*\n *\n * ---\n *\n * This logger is intentionally **side-effectful** and writes directly\n * to `console.log` / `console.error`.\n *\n * It is designed for **human-readable output**, not structured logging\n * or machine parsing.\n */\nexport const BUILD_LOGGER = {\n /** -------------------------------------------------------------------\n * * ***Determines whether an option value comes from the default configuration\n * or has been explicitly overridden by the user.***\n * -------------------------------------------------------------------\n *\n * This utility is primarily intended for logging and debugging purposes,\n * especially in CLI tools or build pipelines where distinguishing between\n * default and user-provided values is important.\n *\n * The comparison is performed using `Object.is` to ensure accurate detection,\n * including edge cases such as:\n * - `NaN` vs `NaN`.\n * - `-0` vs `+0`.\n *\n * @template T - The type of the option value being compared.\n *\n * @param value - The actual value used at runtime.\n * @param defaultValue - The default value defined by the tool.\n *\n * @returns\n * A colorized string indicating the source of the value:\n *\n * - `\"default\"` when `value` is strictly equal to `defaultValue`.\n * - `\"overridden\"` when the value differs from the default.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.SOURCE_OF(\"dist\", \"dist\"); // ➔ \"default\"\n * BUILD_LOGGER.SOURCE_OF(\"dist/types\", \"dist\"); // ➔ \"overridden\"\n * ```\n *\n * @example\n * ***CLI-style option logging:***\n * ```ts\n * BUILD_LOGGER.OPTIONS(\n * \"outDir\",\n * outDir,\n * BUILD_LOGGER.SOURCE_OF(outDir, DEFAULTS.outDir)\n * );\n * ```\n */\n SOURCE_OF: sourceOf,\n /** -------------------------------------------------------------------\n * * ***Logs a single option entry in a formatted, human-readable CLI style.***\n * -------------------------------------------------------------------\n *\n * This helper is used to display resolved configuration values along with\n * their origin (default or overridden), making it easier to debug and\n * understand how final options are derived.\n *\n * - **Output format example:**\n * ```bash\n * - outDir: dist/types (overridden)\n * - withExportTypes: false (default)\n * - inputDirReference: dist\n * ```\n *\n * - **Formatting rules:**\n * - Indented with a leading dash (`-`).\n * - Label is rendered in **bold**.\n * - Value is rendered in **cyan**.\n * - Source indicator (`default` / `overridden`) is **dimmed**.\n * - Arrays are stringified using a stable JSON formatter.\n * - When an option is marked as required, the source indicator is omitted.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @param {string} label - Human-readable option name\n * (e.g. `\"outDir\"`, `\"withExportTypes\"`, `\"inputDirReference\"`).\n *\n * @param {unknown} value - The resolved option value to display.\n * Can be of any type; arrays are stringified automatically.\n *\n * @param {\"default\" | \"overridden\" | ({} & string)} source - A value indicating whether the option comes from\n * the default configuration or was overridden by user input, typically\n * produced by {@link sourceOf | **`sourceOf`**}.\n *\n * @param {boolean | undefined} isRequired - When set to `true`, marks\n * the option as required and suppresses the source indicator in the output,\n * defaults to `false`.\n *\n * @example\n * ```ts\n * OPTIONS(\n * \"outDir\",\n * outDir,\n * sourceOf(outDir, DEFAULTS.outDir)\n * );\n * ```\n *\n * @example\n * Logging multiple options.\n * ```ts\n * OPTIONS(\n * \"outFileName\",\n * outFileName,\n * sourceOf(outFileName, DEFAULTS.outFileName)\n * );\n * OPTIONS(\n * \"inputDirReference\",\n * inputDirReference,\n * sourceOf(inputDirReference, DEFAULTS.inputDirReference)\n * );\n * OPTIONS(\n * \"withExportTypes\",\n * withExportTypes,\n * sourceOf(withExportTypes, DEFAULTS.withExportTypes)\n * );\n * ```\n *\n * @example\n * Logging a required option.\n * ```ts\n * OPTIONS(\n * \"input\",\n * inputPath,\n * sourceOf(inputPath, undefined),\n * true\n * );\n * ```\n */\n OPTIONS(\n label: string,\n value: unknown,\n source: ReturnType<typeof sourceOf> | AnyString,\n isRequired?: boolean\n ) {\n const sourceLabel =\n !isRequired && source\n ? source === \"default\"\n ? picocolors.blueBright(` (${source})`)\n : picocolors.yellowBright(` (${source})`)\n : \"\";\n\n console.log(\n picocolors.dim(\" - \") +\n normalizeSpaces(\n picocolors.bold(label || \"`⚠️ Label Unset!!!`\") +\n picocolors.dim(\": \") +\n formatOptionValue(value) +\n picocolors.italic(sourceLabel)\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a subsection title for grouped log output.***\n * -------------------------------------------------------------------\n *\n * Used to visually separate logical blocks such as:\n * - Arguments.\n * - Options.\n * - Configuration.\n * - Resolved Values.\n *\n * This improves readability when logging many related entries.\n *\n * @param {string} title - Section title text (e.g. \"Options\", \"Arguments\").\n * @param {{ icon?: string; indent?: string; }} options - Optional icon override.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.SECTION(\"Options\");\n * BUILD_LOGGER.SECTION(\"Arguments\", { icon: ICONS.folder });\n * ```\n */\n SECTION(title: string, options: LoggerBuilderSection = {}) {\n const { icon = ICONS.config, indent = \"\" } = options;\n\n console.log(\n picocolors.bold(\n `${indent}${picocolors.whiteBright(icon)} ${picocolors.underline(picocolors.cyanBright(title || \"`⚠️ Unset Title!!!`\"))}:`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Prints a single empty line to the console.***\n * -------------------------------------------------------------------\n *\n * Writes a newline to standard output, typically used as a visual\n * separator between log sections to improve CLI readability.\n *\n * If a string value is provided, it will be printed instead of an\n * empty line.\n *\n * @param {string} [value=\"\"] - Optional text to print. Defaults to an\n * empty string, resulting in a blank line.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.NEW_LINE();\n * ```\n *\n * @example\n * ```ts\n * BUILD_LOGGER.NEW_LINE(\" \");\n * ```\n */\n NEW_LINE(value: string = \"\") {\n return console.log(value);\n },\n /** -------------------------------------------------------------------\n * * ***Logs a starting action message.***\n * -------------------------------------------------------------------\n *\n * Used to indicate that a process or action has just started.\n * Typically printed once before any processing begins.\n *\n * - **Output format example:**\n * ```bash\n * ▶ Starting to generate-types.\n * ```\n *\n * - **Formatting rules:**\n * - Start icon is displayed.\n * - \"Starting\" keyword is highlighted.\n * - Action name is underlined and colored.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_STARTING({ actionName: \"build references\" });\n * ```\n */\n ON_STARTING: (options: LoggerBuilderOnStarting) => {\n const { actionName, textDirectAction = \"to\" } = options;\n\n console.log(\n picocolors.bold(\n `${picocolors.whiteBright(ICONS.start)} ${picocolors.cyanBright(\n \"Starting\"\n )} ${normalizeSpaces(`${textDirectAction} ${picocolors.underline(picocolors.blueBright(actionName))}`)}.`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a successful completion message.***\n * -------------------------------------------------------------------\n *\n * Used to indicate that an action has finished successfully,\n * including a summary count of processed items.\n *\n * - **Output format example:**\n * ```bash\n * ✔ Success generate-types (12 files).\n * ```\n *\n * - **Formatting rules:**\n * - Success icon and green highlight.\n * - Action name is underlined.\n * - Count is highlighted in yellow.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_FINISH({\n * actionName: \"generate references\",\n * count: 5\n * });\n * ```\n */\n ON_FINISH: (options: LoggerBuilderOnFinish) => {\n const {\n actionName,\n count,\n typeCount = \"file\",\n progress,\n textSuccess = \"Success\"\n } = options;\n\n console.log(\n picocolors.bold(\n `${picocolors.greenBright(ICONS.success)} ${picocolors.greenBright(textSuccess)} ${normalizeSpaces(\n `${picocolors.underline(\n picocolors.blueBright(actionName)\n )} (${picocolors.yellowBright(`${isNonEmptyString(progress) ? progress : count} ${typeCount}${count > 1 ? \"(s)\" : \"\"}`)}`\n )}).`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a skipped action with a detailed reason.***\n * -------------------------------------------------------------------\n *\n * Used when an action is intentionally skipped due to\n * unmet conditions or no remaining work.\n *\n * - **Output format example:**\n * ```bash\n * ⚠ Skipping generate-types because nothing left files to process.\n * ```\n *\n * - **Formatting rules:**\n * - Warning icon with yellow highlight.\n * - Action name is underlined.\n * - Skip reason is emphasized in red.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_SKIPPING({\n * actionName: \"generate references\",\n * reasonEndText: \"process\"\n * });\n * ```\n */\n ON_SKIPPING: (options: LoggerBuilderOnSkipping) => {\n const {\n actionName,\n reasonEndText,\n reasonSkipAction = \"nothing left\",\n reasonTitle = \"because\",\n reasonType = \"files\",\n textDirectAction = \"to\"\n } = options;\n\n console.log(\n picocolors.bold(\n `${picocolors.yellowBright(ICONS.warn)} ${picocolors.yellowBright(\"Skipping\")} ${normalizeSpaces(\n `${picocolors.underline(\n picocolors.blueBright(actionName)\n )} ${picocolors.white(reasonTitle)} ${picocolors.redBright(\n reasonSkipAction\n )} ${reasonType} ${textDirectAction} ${picocolors.redBright(reasonEndText)}`\n )}.`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs an error occurring during an action.***\n * -------------------------------------------------------------------\n *\n * Used to report fatal or recoverable errors during execution.\n * Automatically extracts the message from an `Error` instance.\n *\n * - **Output format example:**\n * ```bash\n * ✖ Error to generate-types,\n * ➜ Something went wrong\n * ```\n *\n * - **Formatting rules:**\n * - Error icon and red highlight.\n * - Action name is underlined.\n * - Error message is inverted for emphasis.\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stderr`.\n *\n * @example\n * ```ts\n * BUILD_LOGGER.ON_ERROR({\n * actionName: \"copy files\",\n * error: err\n * });\n * ```\n */\n ON_ERROR: (options: LoggerBuilderOnError) => {\n const { actionName, textDirectAction = \"to\", error } = options;\n\n const errorMsg = isError(error) ? error.message : \"Something went wrong\";\n\n console.error(\n picocolors.bold(\n `${picocolors.redBright(ICONS.error)} ${picocolors.redBright(\"Error\")} ${normalizeSpaces(\n `${textDirectAction} ${picocolors.underline(picocolors.blueBright(actionName))},`\n )} ${joinLines(\"because: \", \"\", ` ${picocolors.bold(picocolors.red(ICONS.arrowRight))} ${picocolors.inverse(picocolors.red(normalizeSpaces(errorMsg)))}`)}`\n )\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a generic processing step.***\n * -------------------------------------------------------------------\n *\n * Used for logging step-by-step progress inside a process,\n * typically for folders or grouped actions.\n *\n * - **Output format example:**\n * ```bash\n * • 2. Generating in dist/types.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS: (options: LoggerBuilderOnProcess) => {\n const { actionName, count, nameDirect, textDirectFolder = \"in\" } = options;\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.white(actionName)} ${picocolors.magentaBright(\n textDirectFolder\n )} ${picocolors.bold(picocolors.underline(picocolors.blue(nameDirect)))}.`\n )}`\n )}`\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a copy process entry.***\n * -------------------------------------------------------------------\n *\n * Used to log a file or directory copy operation as part\n * of a larger process.\n *\n * - **Output format example:**\n * ```bash\n * • 1. Copy from 'src/types' ➔ 'dist/types'.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS_COPY: (options: LoggerBuilderOnProcessCopy) => {\n const {\n actionName,\n count,\n copyTo,\n copyFrom,\n textFrom = \"from\",\n textArrow = \"➔\"\n } = options;\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.white(actionName)} ${picocolors.yellow(\n textFrom\n )} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyFrom)))}' ${picocolors.bold(\n picocolors.gray(textArrow)\n )} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyTo)))}'.`\n )}`\n )}`\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a copy process entry.***\n * -------------------------------------------------------------------\n *\n * Used to log a file or directory copy operation as part\n * of a larger process.\n *\n * - **Output format example:**\n * ```bash\n * • 1. Failed Copying from 'src/types' because source file not found.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS_COPY_ERROR: (options: LoggerBuilderOnProcessCopyError) => {\n const {\n actionName,\n count,\n errorReason,\n copyFrom,\n index,\n indexKey,\n textFrom = \"from\",\n textReason = \"because\"\n } = options;\n\n const errorReasonText = isError(errorReason)\n ? errorReason.message\n : String(errorReason);\n\n const atIndexText = isNumber(index)\n ? picocolors.blueBright(\n ` (at${isNonEmptyString(indexKey) ? ` '${indexKey}' ` : \" \"}index: ${picocolors.magentaBright(index)}) `\n )\n : \" \";\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.redBright(actionName)} ${picocolors.yellow(\n textFrom\n )} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyFrom)))}'${atIndexText}${picocolors.bold(\n picocolors.gray(textReason)\n )} ${picocolors.redBright(errorReasonText)}.`\n )}`\n )}`\n );\n },\n /** -------------------------------------------------------------------\n * * ***Logs a reference linking process.***\n * -------------------------------------------------------------------\n *\n * Used to indicate that a reference is being created\n * from one location to another.\n *\n * - **Output format example:**\n * ```bash\n * • 3. Referencing from src/index.ts ➔ dist/index.d.ts.\n * ```\n *\n * This function performs **no mutation** and has **no side effects**\n * other than writing to `stdout`.\n */\n ON_PROCESS_REFERENCING: (options: LoggerBuilderOnProcessReferencing) => {\n const {\n actionName,\n count,\n referenceTo,\n referenceFrom,\n textFrom = \"from\",\n textArrow = \"➔\"\n } = options;\n\n console.log(\n `${picocolors.bold(\" \" + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(\n `${picocolors.white(count + \".\")} ${normalizeSpaces(\n `${picocolors.white(actionName)} ${picocolors.magentaBright(\n textFrom\n )} ${picocolors.bold(picocolors.underline(picocolors.cyanBright(referenceFrom)))} ${picocolors.bold(\n picocolors.gray(textArrow)\n )} ${picocolors.bold(picocolors.underline(picocolors.blueBright(referenceTo)))}.`\n )}`\n )}`\n );\n }\n};\n\ntype LoggerBuilderSection = {\n /**\n * @default ICON.config\n */\n icon?: string;\n /**\n * @default \"\"\n */\n indent?: string;\n};\ntype LoggerBuilderOnStarting = {\n /** The name of the action being started.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Connector word used before the action name.\n *\n * @default\n * \"to\"\n */\n textDirectAction?: string;\n};\ntype LoggerBuilderOnFinish = {\n /** The name of the completed action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** The success text.\n *\n * @default\n * @default \"Success\"\n */\n textSuccess?: string;\n /** Label for the count unit.\n *\n * @default\n * \"file\"\n */\n typeCount?: string;\n /** Number of processed items.\n *\n * @default\n * undefined\n */\n count: number;\n /** Progress of processed items (e.g. `2/7`).\n *\n * Represents how many items have been processed relative to the total.\n *\n * @example\n * \"2/7\"\n */\n progress?: string;\n};\ntype LoggerBuilderOnSkipping = {\n /** The name of the skipped action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Connector word explaining the reason.\n *\n * @default\n * \"because\"\n */\n reasonTitle?: string;\n /** Short reason phrase.\n *\n * @default\n * \"nothing left\"\n */\n reasonSkipAction?: string;\n /** Contextual explanation for the skip.\n *\n * @default\n * undefined\n */\n reasonEndText: string;\n /** Type of resource involved.\n *\n * @default\n * \"files\"\n */\n reasonType?: string;\n /** Connector word before the target.\n *\n * @default\n * \"to\"\n */\n textDirectAction?: string;\n};\ntype LoggerBuilderOnError = {\n /** The name of the action that failed.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Connector word before the action name.\n *\n * @default\n * \"to\"\n */\n textDirectAction?: string;\n /** Unknown error object or `Error` instance.\n *\n */\n error: unknown;\n};\ntype LoggerBuilderOnProcess = {\n /** Description of the process.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number.\n *\n * @default\n * undefined\n */\n count: number;\n /** Connector word before the target.\n *\n * @default\n * \"in\"\n */\n textDirectFolder?: string;\n /** Target name or location.\n *\n * @default\n * undefined\n */\n nameDirect: string;\n};\ntype LoggerBuilderOnProcessCopy = {\n /** The name of the action being the copy action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number of the process.\n *\n * @default\n * undefined\n */\n count: number;\n /** Connector text before source path.\n *\n * @default\n * \"from\"\n */\n textFrom?: string;\n /** Source path.\n *\n * @default\n * undefined\n */\n copyFrom: string;\n /** Destination path.\n *\n * @default\n * undefined\n */\n copyTo: string;\n /** Arrow symbol between paths.\n *\n * @default\n * \"➔\"\n */\n textArrow?: string;\n};\ntype LoggerBuilderOnProcessCopyError = {\n /** The name of the action being the error copy action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number of the process.\n *\n * @default\n * undefined\n */\n count: number;\n /** Index number parameter.\n *\n * @default\n * undefined\n */\n index?: number;\n /** Index key name for parameter.\n *\n * @default\n * undefined\n */\n indexKey?: string;\n /** Connector text before source path.\n *\n * @default\n * \"from\"\n */\n textFrom?: string;\n /** Source path.\n *\n * @default\n * undefined\n */\n copyFrom: string;\n /** The reason error on copying.\n *\n * @default\n * undefined\n */\n errorReason: string | Error;\n /** Connector word explaining the reason.\n *\n * @default\n * \"because\"\n */\n textReason?: string;\n};\ntype LoggerBuilderOnProcessReferencing = {\n /** The name of the action being the referencing action.\n *\n * @default\n * undefined\n */\n actionName: string;\n /** Sequence number.\n *\n * @default\n * undefined\n */\n count: number;\n /** Connector text before source.\n *\n * @default\n * \"from\"\n */\n textFrom?: string;\n /** Source reference path.\n *\n * @default\n * undefined\n */\n referenceFrom: string;\n /** Target reference path.\n *\n * @default\n * undefined\n */\n referenceTo: string;\n /** Arrow symbol between references.\n *\n * @default\n * \"➔\"\n */\n textArrow?: string;\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n EMPTY_LINE_RE,\n isAdjacentToTarget,\n isTargetComment\n} from \"@/_internal/utils/source\";\n\n/** @internal Util for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function stripLineArtifacts(line: string, options: CleanCoreOptions) {\n let out = line\n // remove source path comments\n .replace(\n /^[ \\t]*\\/\\/\\s*(?:\\.\\.\\/|\\.\\/)*[^ \\n]*?(?:src|node_modules)\\/[^\\n]*\\n?/gm,\n \"\"\n )\n // remove eslint comments\n .replace(/\\/\\/\\s*eslint[^\\n]*/g, \"\");\n\n if (options.removeSourceMap) {\n // Remove all `sourceMappingURL` comments.\n out = out.replace(\n /^[ \\t]*\\/\\/[#@]\\s*sourceMappingURL\\s*=\\s*\\S+/gm,\n // /\\/\\/[#@]\\s*sourceMappingURL=[^\\n]*/g,\n \"\"\n );\n }\n\n // Collapse duplicate `sourceMappingURL` comments into a single one.\n out = out.replace(\n /(^[ \\t]*\\/\\/[#@]\\s*sourceMappingURL\\s*=\\s*\\S+)(?:\\r?\\n\\1)+/gm,\n // /(\\/\\/[#@]\\s*sourceMappingURL=[^\\r\\n]*)(?:\\r?\\n\\1)+/g,\n \"$1\"\n );\n\n return out;\n}\n\n/** @internal Util for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function splitLines(content: string) {\n return content.split(/\\r\\n|\\n/);\n}\n\n/** @internal Util for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function fileHasTarget(lines: string[], options: CleanCoreOptions) {\n return lines.some((line, i, arr) => {\n if (isTargetComment(line, options)) return true;\n\n if (\n options.removeAdjacentEmptyLines &&\n EMPTY_LINE_RE.test(line) &&\n isAdjacentToTarget(arr, i, options)\n ) {\n return true;\n }\n\n return false;\n });\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n EMPTY_LINE_RE,\n isAdjacentToTarget,\n isTargetComment,\n REGION_RE,\n SOURCE_MAP_RE\n} from \"@/_internal/utils/source\";\n\nimport { stripLineArtifacts } from \"./clean-build-artifacts-utils\";\n\n/** @internal Core for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport function cleanBuildArtifactsCore(\n lines: string[],\n options: CleanCoreOptions\n) {\n const seenSourceMap = new Set<string>();\n\n return lines\n .filter((line, i, arr) => {\n if (SOURCE_MAP_RE.test(line)) {\n const key = line.trim();\n if (seenSourceMap.has(key)) return false;\n seenSourceMap.add(key);\n if (options.removeSourceMap) return false;\n\n return true;\n }\n\n if (options.removeRegion && REGION_RE.test(line)) return false;\n\n if (isTargetComment(line, options)) return false;\n\n if (\n options.removeAdjacentEmptyLines &&\n EMPTY_LINE_RE.test(line) &&\n isAdjacentToTarget(arr, i, options)\n ) {\n return false;\n }\n\n return true;\n })\n .map((line) => stripLineArtifacts(line, options));\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { RequiredOnly } from \"@/_internal/types/extra\";\nimport type { StringCollection } from \"@/types\";\nimport type { CleanCoreOptions } from \"./clean-build-artifacts-types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanJsBuildArtifacts } from \"../clean-js-build-artifacts\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { cleanTypesBuildArtifacts } from \"../clean-types-build-artifacts\";\n\nimport {\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport { canLog, VERBOSE_LOG } from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isPlainObject, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/client\";\n\nimport { cleanBuildArtifactsCore } from \"./clean-build-artifacts-core\";\nimport { fileHasTarget, splitLines } from \"./clean-build-artifacts-utils\";\nimport {\n DEFAULT_CLEAN_OPTION,\n DEFAULT_CLEAN_PATTERN_POLICY\n} from \"./clean-build-artifacts-constant\";\n\ntype OmitLogActionName<T> = Omit<T, \"actionName\">;\ntype RunCleanBuildArtifactsParams = {\n patterns: StringCollection;\n options: RequiredOnly<CleanCoreOptions, \"logLevel\">;\n\n fileTest: RegExp;\n\n logAction: {\n title: string;\n actionName: string;\n onStart?: OmitLogActionName<\n Parameters<(typeof BUILD_LOGGER)[\"ON_STARTING\"]>[0]\n >;\n onProcess?: OmitLogActionName<\n Omit<\n Parameters<(typeof BUILD_LOGGER)[\"ON_PROCESS\"]>[0],\n \"count\" | \"nameDirect\"\n >\n >;\n onError?: OmitLogActionName<\n Omit<\n Parameters<(typeof BUILD_LOGGER)[\"ON_ERROR\"]>[0],\n \"error\" | \"nameDirect\"\n >\n >;\n onSkipping?: OmitLogActionName<\n Parameters<(typeof BUILD_LOGGER)[\"ON_SKIPPING\"]>[0]\n >;\n };\n};\n\n/** @internal Runner for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`} and {@link cleanTypesBuildArtifacts | `clean-types-build-artifacts`}. */\nexport async function runCleanBuildArtifacts({\n patterns: pattern,\n options,\n fileTest,\n logAction\n}: RunCleanBuildArtifactsParams) {\n if (!isPlainObject(options)) {\n options = DEFAULT_CLEAN_OPTION;\n } else {\n options = { ...DEFAULT_CLEAN_OPTION, ...options };\n }\n\n const {\n patternOptions,\n logLevel: loggerLevel,\n removeAdjacentEmptyLines,\n removeRegion,\n removeSourceMap\n } = options;\n\n try {\n if (canLog(loggerLevel, VERBOSE_LOG))\n console.log(joinLinesLoose(logAction.title, \"\"));\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_CLEAN_PATTERN_POLICY\n );\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_CLEAN_OPTION.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeSourceMap\",\n removeSourceMap,\n BUILD_LOGGER.SOURCE_OF(\n removeSourceMap,\n DEFAULT_CLEAN_OPTION.removeSourceMap\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeRegion\",\n removeRegion,\n BUILD_LOGGER.SOURCE_OF(removeRegion, DEFAULT_CLEAN_OPTION.removeRegion)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeAdjacentEmptyLines\",\n removeAdjacentEmptyLines,\n BUILD_LOGGER.SOURCE_OF(\n removeAdjacentEmptyLines,\n DEFAULT_CLEAN_OPTION.removeAdjacentEmptyLines\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_CLEAN_OPTION.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n ...logAction.onStart,\n actionName: logAction.actionName\n });\n }\n\n let count = 0;\n\n for (const filePath of files) {\n if (!new RegExp(fileTest).test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const lines = splitLines(content);\n\n if (!fileHasTarget(lines, options)) continue;\n\n const cleanedLines = cleanBuildArtifactsCore(lines, options);\n const finalContent = cleanedLines.join(EOL);\n\n if (finalContent === content) continue;\n\n count++;\n\n try {\n await fsExtra.promises.writeFile(filePath, finalContent, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n ...logAction.onProcess,\n actionName: logAction.actionName,\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: logAction.actionName,\n count: count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n ...logAction.onSkipping,\n actionName: logAction.actionName,\n reasonEndText: logAction.onSkipping?.reasonEndText ?? \"cleaning\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n ...logAction.onError,\n actionName: logAction.actionName,\n error\n });\n }\n }\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { StringCollection } from \"@/types\";\nimport type { CleanCoreOptions } from \"./_internal/clean-build-artifacts-types\";\n\nimport { isNonEmptyString } from \"@/_internal/utils/helper\";\nimport { JS_OUTPUT_FILE_RE } from \"@/_internal/utils/source\";\nimport { resolveLogVerbosity } from \"@/_internal/utils/log-level\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\nimport { DEFAULT_CLEAN_OPTION } from \"./_internal/clean-build-artifacts-constant\";\nimport { runCleanBuildArtifacts } from \"./_internal/clean-build-artifacts-runner\";\n\n/** Command identity associated with {@link cleanJsBuildArtifacts | **`clean-js-build-artifacts`**}. */\nexport const commandCjbaIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"clean-js-build-artifacts\"\n});\n\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link cleanJsBuildArtifacts | `clean-js-build-artifacts`}.***\n * ----------------------------------------------------------------\n */\nexport type CleanJsArtifactsOptions = CleanCoreOptions;\n\n/** ----------------------------------------------------------------\n * * ***Removes build artifact comments from compiled JavaScript files.***\n * ----------------------------------------------------------------\n *\n * This function scans files matching the provided glob pattern(s) and removes:\n * - Source path comments.\n * - Source region comments.\n * - ESLint directive comments.\n * - Optional source map references.\n *\n * It can also remove empty lines adjacent to those comments to keep\n * output files tidy.\n *\n * @param {string | string[] | Set<string>} pattern - Glob pattern or list of patterns pointing to JS output files.\n * @param {CleanJsArtifactsOptions} options - Cleanup configuration options, see {@link CleanJsArtifactsOptions | **`CleanJsArtifactsOptions`**}.\n *\n * @example\n * ```ts\n * await cleanJsBuildArtifacts(\"dist/**\\/*.js\");\n * await cleanJsBuildArtifacts(\"dist/**\\/*.{js,cjs,mjs}\");\n * ```\n *\n * @example\n * ```ts\n * await cleanJsBuildArtifacts([\"dist/**\\/*.js\", \"build/*\\/*.mjs\"], {\n * removeSourceMap: false,\n * removeRegionComment: false,\n * removeAdjacentEmptyLines: true\n * });\n * ```\n */\nexport const cleanJsBuildArtifacts = async (\n pattern: StringCollection,\n options: CleanJsArtifactsOptions = {}\n): Promise<void> => {\n const logLevel = resolveLogVerbosity(options, DEFAULT_CLEAN_OPTION.logLevel);\n\n return await runCleanBuildArtifacts({\n patterns: pattern,\n options: { ...options, logLevel },\n fileTest: JS_OUTPUT_FILE_RE,\n logAction: {\n actionName: \"Cleaning JS Build Artifacts\",\n title: isNonEmptyString(options.__commandTitle)\n ? options.__commandTitle\n : commandCjbaIdentity.utility()\n }\n });\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { StringCollection } from \"@/types\";\nimport type { CleanCoreOptions } from \"./_internal/clean-build-artifacts-types\";\n\nimport { isNonEmptyString } from \"@/_internal/utils/helper\";\nimport { resolveLogVerbosity } from \"@/_internal/utils/log-level\";\nimport { TS_DECLARATION_FILE_RE } from \"@/_internal/utils/source\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\nimport { DEFAULT_CLEAN_OPTION } from \"./_internal/clean-build-artifacts-constant\";\nimport { runCleanBuildArtifacts } from \"./_internal/clean-build-artifacts-runner\";\n\n/** Command identity associated with {@link cleanTypesBuildArtifacts | **`clean-types-build-artifacts`**}. */\nexport const commandCtbaIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"clean-types-build-artifacts\"\n});\n\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link cleanTypesBuildArtifacts | **`cleanTypesBuildArtifacts`**}.***\n * ----------------------------------------------------------------\n */\nexport type CleanTypesArtifactsOptions = CleanCoreOptions;\n\n/** ----------------------------------------------------------------\n * * ***Removes build artifact comments from compiled Types files.***\n * ----------------------------------------------------------------\n *\n * This function scans files matching the provided glob pattern(s) and removes:\n * - Source path comments.\n * - ESLint directive comments.\n * - Optional source map references.\n *\n * It can also remove empty lines adjacent to those comments to keep\n * output files tidy.\n *\n * @param pattern - Glob pattern or list of patterns pointing to Types output files.\n * @param options - Cleanup configuration options, see {@link CleanTypesArtifactsOptions | **`CleanTypesArtifactsOptions`**}.\n *\n * @example\n * ```ts\n * await cleanTypesBuildArtifacts(\"dist/**\\/*.d.ts\");\n * await cleanTypesBuildArtifacts(\"dist/**\\/*.d.{ts,cts,mts}\");\n * ```\n *\n * @example\n * ```ts\n * await cleanTypesBuildArtifacts([\"dist/**\\/*.d.ts\", \"build/*\\/*.mts\"], {\n * removeSourceMap: false,\n * removeAdjacentEmptyLines: true\n * });\n * ```\n */\nexport const cleanTypesBuildArtifacts = async (\n pattern: StringCollection,\n options: CleanTypesArtifactsOptions = {}\n): Promise<void> => {\n const logLevel = resolveLogVerbosity(options, DEFAULT_CLEAN_OPTION.logLevel);\n\n return await runCleanBuildArtifacts({\n patterns: pattern,\n options: { ...options, logLevel },\n fileTest: TS_DECLARATION_FILE_RE,\n logAction: {\n actionName: \"Cleaning Types Build Artifacts\",\n title: isNonEmptyString(options.__commandTitle)\n ? options.__commandTitle\n : commandCtbaIdentity.utility()\n }\n });\n};\n","/* eslint-disable quotes */\nimport \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, Collection } from \"@/types\";\nimport type { OmitStrict } from \"@/_internal/types/extra\";\n\nimport path from \"node:path\";\n\nimport {\n isArray,\n isBoolean,\n isNonEmptyString,\n isNumber,\n isPlainObject,\n isSet,\n isUndefined,\n toObjectSet\n} from \"@/_internal/utils/helper\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\n\nimport {\n joinInline,\n joinLinesLoose,\n picocolors,\n plural\n} from \"@/utils/helper/formatter\";\nimport { fsExtra } from \"@/utils/server\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** @internal Default ***Options*** for {@link copyFileToDest | **`copy-file-to-dest`**}. */\nconst DEFAULT_CFTD_OPTIONS = {\n fileName: undefined,\n outputRoot: \"dist\",\n absoluteTarget: false,\n ignoreMissingSourceError: false\n} as const satisfies Omit<CopyFileToDestParam, \"source\" | \"target\">;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link copyFileToDest | **`copy-file-to-dest`**} validation args only. */\nconst validateItem = (\n item: CopyFileToDestParam,\n index?: number\n): never | void => {\n const indexText = isNumber(index) ? ` at index ${index}` : \"\";\n\n if (!isPlainObject(item)) {\n throw new TypeError(`Invalid item${indexText}: must be a 'plain object'!`);\n }\n\n if (!isNonEmptyString(item.source) && !isNonEmptyString(item.target)) {\n throw new TypeError(\n `Invalid item${indexText}: 'source' and 'target' must be 'non-empty string'!`\n );\n }\n\n if (!isNonEmptyString(item.source)) {\n throw new TypeError(\n `Invalid item${indexText}: 'source' must be 'non-empty string'!`\n );\n }\n if (!isNonEmptyString(item.target)) {\n throw new TypeError(\n `Invalid item${indexText}: 'target' must be 'non-empty string'!`\n );\n }\n\n if (!isUndefined(item.fileName) && !isNonEmptyString(item.fileName)) {\n throw new TypeError(\n `Invalid item${indexText}: 'fileName' must be 'non-empty string' if provided!`\n );\n }\n if (!isUndefined(item.outputRoot) && !isNonEmptyString(item.outputRoot)) {\n throw new TypeError(\n `Invalid item${indexText}: 'outputRoot' must be 'non-empty string' if provided!`\n );\n }\n if (!isUndefined(item.absoluteTarget) && !isBoolean(item.absoluteTarget)) {\n throw new TypeError(\n `Invalid item${indexText}: 'absoluteTarget' must be a 'boolean' if provided!`\n );\n }\n};\n/** @internal Util for {@link copyFileToDest | **`copy-file-to-dest`**}. */\nfunction buildCopySummary(\n successCount: number,\n errorCount: number,\n duplicateCount: number,\n label: string\n) {\n return picocolors.bold(\n joinLinesLoose(\n joinInline(\n picocolors.yellowBright(\"⚠\"),\n picocolors.blueBright(label) + picocolors.gray(\" -\"),\n picocolors.whiteBright(successCount > 0 ? \"Some\" : \"All\"),\n picocolors.whiteBright(\"files\"),\n picocolors.redBright(\"failed to copy\") + \":\"\n ),\n\n successCount < 1\n ? false\n : ` ${picocolors.greenBright(\"✔\")} ${picocolors.greenBright(successCount)} ${plural(successCount, \"file\")} copied.`,\n\n errorCount < 1\n ? false\n : ` ${picocolors.redBright(\"✖\")} ${picocolors.redBright(errorCount)} ${plural(errorCount, \"file\")} failed.`,\n\n duplicateCount < 1\n ? false\n : ` ${picocolors.yellowBright(\"⚠\")} ${picocolors.yellowBright(duplicateCount)} ${plural(duplicateCount, \"duplicate operation\")} skipped.`\n )\n );\n}\n/** @internal Util for {@link copyFileToDest | **`copy-file-to-dest`**}. */\nfunction buildOperationKey(item: CopyFileToDestParam) {\n return [\n item.source,\n item.target,\n item.fileName ?? \"\",\n item.outputRoot ?? DEFAULT_CFTD_OPTIONS.outputRoot,\n item.absoluteTarget ? 1 : 0\n ].join(\"|\");\n}\n\n/** ----------------------------------------------------------------\n * * ***Creates a `Set` of parameters for {@link copyFileToDest | **`copy-file-to-dest`**}.***\n * ----------------------------------------------------------------\n *\n * Utility helper to construct a `Set` of {@link CopyFileToDestParam | `CopyFileToDestParam`}\n * with proper type inference and editor autocomplete support.\n *\n * This is primarily useful when passing parameters as a `Set`,\n * since directly using `new Set([...])` may result in poor\n * TypeScript inference and missing autocomplete for object literals.\n *\n * ----------------------------------------------------------------\n * Behavior\n *\n * - Accepts a single parameter or an array of parameters.\n * - Automatically normalizes the input into a `Set`.\n *\n * ----------------------------------------------------------------\n *\n * @param items\n * A single {@link CopyFileToDestParam | `CopyFileToDestParam`} or an array of parameters.\n *\n * @returns\n * A `Set` containing the provided parameters.\n *\n * @example\n * ```ts\n * // single item\n * const setA = createCopyFileToDestParameterSet({\n * source: \"dist/index.d.ts\",\n * target: \"dist\"\n * });\n *\n * // multiple items\n * const setB = createCopyFileToDestParameterSet([\n * {\n * source: \"dist/a.d.ts\",\n * target: \"dist\"\n * },\n * {\n * source: \"dist/b.d.ts\",\n * target: \"dist\"\n * }\n * ]);\n *\n * // usage with copyFileToDest\n * await copyFileToDest(setB);\n * ```\n */\nexport function createCopyFileToDestParameterSet(\n items: CopyFileToDestParam | CopyFileToDestParam[]\n): Set<CopyFileToDestParam> {\n return new Set(isArray(items) ? items : [items]);\n}\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link copyFileToDest | **`copy-file-to-dest`**}. */\nexport const commandCftdIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"copy-file-to-dest\"\n});\n\n//? Types ----------------------------------------------------------------\n/** @internal Type for {@link copyFileToDest | **`copy-file-to-dest`**}.*/\ntype UniqueOperation = {\n item: CopyFileToDestParam;\n index: number;\n};\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link copyFileToDest | **`copy-file-to-dest`**}.***\n * ----------------------------------------------------------------\n */\nexport type CopyFileToDestOptions = OmitStrict<BaseOptions, \"patternOptions\">;\n/** ----------------------------------------------------------------\n * * ***Describes the parameter options for copying a single file to a destination path of {@link copyFileToDest | **`copy-file-to-dest`**}.***\n * ----------------------------------------------------------------\n */\nexport type CopyFileToDestParam = {\n /** ----------------------------------------------------------------\n * * ***Path to the source file to be copied.***\n * ----------------------------------------------------------------\n * Can be either an absolute path or a path relative to the project root.\n *\n * @example \"src/assets/logo.png\"\n */\n source: string;\n\n /** ----------------------------------------------------------------\n * * ***Target directory where the file will be copied.***\n * ----------------------------------------------------------------\n *\n * - When `absoluteTarget` is `false` **(default)**, this path is resolved relative to `outputRoot`.\n * - When `absoluteTarget` is `true`, this path is treated as an absolute path relative to the project root.\n *\n * @example \"assets/images\"\n */\n target: string;\n\n /** ----------------------------------------------------------------\n * * ***Optional custom file name for the copied file.***\n * ----------------------------------------------------------------\n *\n * If omitted, the original file name from `source` will be preserved.\n *\n * @example \"logo-new.png\"\n *\n * @default undefined\n */\n fileName?: string;\n\n /** ----------------------------------------------------------------\n * * ***Output root directory used when resolving the `target` path.***\n * ----------------------------------------------------------------\n *\n * When `absoluteTarget` is `false`, the final copy destination will be\n * `<project-root>/<outputRoot>/<target>`.\n *\n * @default \"dist\"\n * @example \"build\"\n */\n outputRoot?: string;\n\n /** ----------------------------------------------------------------\n * * ***When `true`, disables `outputRoot` prefixing and treats `target`\n * as an absolute path relative to the project root.***\n * ----------------------------------------------------------------\n *\n * Use this when you want to copy directly to an absolute path inside the project,\n * bypassing the `outputRoot` prefix.\n *\n * @default false\n */\n absoluteTarget?: boolean;\n\n /** ----------------------------------------------------------------\n * * ***When `true`, suppresses errors when the source file does not exist.***\n * ----------------------------------------------------------------\n *\n * - Instead of throwing or logging an error, the operation will be skipped.\n * - Useful in development or watch mode where build outputs may not be immediately available.\n *\n * @default false\n */\n ignoreMissingSourceError?: boolean;\n};\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Copy one or more files of any type into destination directories.***\n * ----------------------------------------------------------------\n *\n * This utility is **file-type agnostic** and can be used to copy any kind of asset,\n * including CSS, JavaScript, JSON, images, fonts, or other static files.\n *\n * - *The function supports:*\n * - Copying a **single file** using a single configuration object.\n * - Copying **multiple files** using an ***array*** or a ***Set*** of configuration objects.\n *\n * - When using a `Set`, it is recommended to use\n * {@link createCopyFileToDestParameterSet | **`createCopyFileToDestParameterSet`**}\n * to ensure proper TypeScript inference and autocomplete support.\n *\n * - By default, files are copied into a `dist` directory relative to the project root.\n * - This behavior can be customized per item via `outputRoot` or bypassed entirely\n * using `absoluteTarget`.\n *\n * ----------------------------------------------------------------\n *\n * @param parameter\n * A single {@link CopyFileToDestParam | **`CopyFileToDestParam`**} object,\n * an array, or a `Set` of {@link CopyFileToDestParam | **`CopyFileToDestParam`**}.\n *\n * - *When a collection is provided:*\n * - Each item is validated independently.\n * - Files are copied sequentially.\n * - Logging reflects the cumulative copy progress.\n *\n * ----------------------------------------------------------------\n *\n * @example\n * // Copy a single CSS file into \"dist/\".\n * // Result: \"dist/main.css\".\n * await copyFileToDest({\n * source: \"src/styles/main.css\",\n * target: \".\"\n * });\n *\n * @example\n * // Copy a single CSS file into \"dist/styles/\".\n * await copyFileToDest({\n * source: \"src/styles/main.css\",\n * target: \"styles\"\n * });\n *\n * @example\n * // Copy multiple files into \"dist/config/\" (using array).\n * // Result: \"dist/config/a.json\" and \"dist/config/b.json\".\n * await copyFileToDest([\n * {\n * source: \"src/config/a.json\",\n * target: \"config\"\n * },\n * {\n * source: \"src/config/b.json\",\n * target: \"config\"\n * }\n * ]);\n *\n * @example\n * // Copy multiple files into \"dist/config/\" (using Set).\n * // ⚠️ Requires explicit typing for proper inference.\n * await copyFileToDest(new Set<CopyFileToDestParam>([\n * {\n * source: \"src/config/a.json\",\n * target: \"config\"\n * },\n * {\n * source: \"src/config/b.json\",\n * target: \"config\"\n * }\n * ]));\n *\n * @example\n * // Recommended: using helper for Set (better DX).\n * await copyFileToDest(\n * createCopyFileToDestParameterSet([\n * {\n * source: \"src/config/a.json\",\n * target: \"config\"\n * },\n * {\n * source: \"src/config/b.json\",\n * target: \"config\"\n * }\n * ])\n * );\n *\n * @example\n * // Copy multiple files with a custom output root.\n * // Result: \"build/scripts/setup.js\" and \"build/scripts/runtime.js\".\n * await copyFileToDest([\n * {\n * source: \"src/scripts/setup.js\",\n * target: \"scripts\",\n * outputRoot: \"build\"\n * },\n * {\n * source: \"src/scripts/runtime.js\",\n * target: \"scripts\",\n * outputRoot: \"build\"\n * }\n * ]);\n *\n * @example\n * // Copy and rename a single file.\n * // Result: \"dist/config/app.json\".\n * await copyFileToDest({\n * source: \"src/config/app.config.json\",\n * target: \"config\",\n * fileName: \"app.json\"\n * });\n *\n * @example\n * ```ts\n * // Copy using an absolute target path (no outputRoot prefix).\n * // Result: \"<project-root>/config/runtime/config.json\".\n * await copyFileToDest({\n * source: \"src/runtime/config.json\",\n * target: \"config/runtime\",\n * absoluteTarget: true\n * });\n * ```\n *\n * ----------------------------------------------------------------\n *\n * @remarks\n * - The function ensures that all target directories exist before copying.\n * - Each item is validated to be a plain object with valid fields.\n * - The original file contents are copied without transformation.\n * - Errors during copying are caught and reported via the logger.\n */\nexport function copyFileToDest(\n parameter: CopyFileToDestParam,\n options?: CopyFileToDestOptions\n): Promise<void>;\nexport function copyFileToDest(\n parameter: CopyFileToDestParam[],\n options?: CopyFileToDestOptions\n): Promise<void>;\nexport function copyFileToDest(\n parameter: Set<CopyFileToDestParam>,\n options?: CopyFileToDestOptions\n): Promise<void>;\n// export async function copyFileToDest(\n// parameter: Collection<CopyFileToDestParam>,\n// options?: CopyFileToDestOptions\n// ): Promise<void>;\nexport async function copyFileToDest(\n parameter: Collection<CopyFileToDestParam>,\n options: CopyFileToDestOptions = {}\n) {\n const loggerLevel = resolveLogVerbosity(options);\n\n try {\n const { __commandTitle } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandCftdIdentity.utility(),\n \"\"\n )\n );\n }\n\n if (isArray(parameter) || isSet(parameter)) {\n let i = 0;\n for (const item of parameter) {\n validateItem(item, i++);\n }\n } else if (isPlainObject(parameter)) {\n validateItem(parameter);\n } else {\n throw new TypeError(\n \"Parameter argument must be a 'plain object', 'array of plain objects' or an 'set of plain objects'!\"\n );\n }\n\n const list = [...toObjectSet(parameter)];\n const uniqueLists: UniqueOperation[] = [];\n const seenOperations = new Set<string>();\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n\n list.forEach((item, i) => {\n const {\n source,\n target,\n fileName = DEFAULT_CFTD_OPTIONS.fileName,\n outputRoot = DEFAULT_CFTD_OPTIONS.outputRoot,\n absoluteTarget = DEFAULT_CFTD_OPTIONS.absoluteTarget,\n ignoreMissingSourceError = DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError\n } = item;\n\n const defaultFileName = fileName ?? path.basename(source);\n\n const indexText = list.length > 1 ? `[${i}]` : \"\";\n\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.source`,\n source,\n \"overridden\",\n true\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.target`,\n target,\n \"overridden\",\n true\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.fileName`,\n fileName || defaultFileName,\n BUILD_LOGGER.SOURCE_OF(fileName, DEFAULT_CFTD_OPTIONS.fileName)\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.outputRoot`,\n outputRoot,\n BUILD_LOGGER.SOURCE_OF(outputRoot, DEFAULT_CFTD_OPTIONS.outputRoot)\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.absoluteTarget`,\n absoluteTarget,\n BUILD_LOGGER.SOURCE_OF(\n absoluteTarget,\n DEFAULT_CFTD_OPTIONS.absoluteTarget\n )\n );\n BUILD_LOGGER.OPTIONS(\n `options.copy${indexText}.ignoreMissingSourceError`,\n ignoreMissingSourceError,\n BUILD_LOGGER.SOURCE_OF(\n ignoreMissingSourceError,\n DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError\n )\n );\n\n if (i < list.length - 1) {\n console.log(\n picocolors.gray(\n \" ==========================================================================\"\n )\n );\n }\n });\n\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_LOG_LEVEL)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Copy File\",\n textDirectAction: \"action:\"\n });\n }\n\n let count = 0;\n let errorCount = 0;\n let duplicateCount = 0;\n\n for (let index = 0; index < list.length; index++) {\n const item = list[index]!;\n\n const key = buildOperationKey(item);\n\n if (seenOperations.has(key)) {\n duplicateCount++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Copy File\",\n reasonType: \"\",\n textDirectAction: \"at\",\n reasonSkipAction: \"duplicate operation\",\n reasonEndText:\n item.source +\n \" \" +\n picocolors.blueBright(\n `('parameter' index: ${picocolors.magentaBright(index)})`\n )\n });\n }\n continue;\n }\n\n seenOperations.add(key);\n uniqueLists.push({ item, index });\n }\n\n const procCwd = process.cwd();\n\n for (let i = 0; i < uniqueLists.length; i++) {\n const uniqList = uniqueLists[i]!;\n count++;\n\n const {\n source,\n target,\n fileName = DEFAULT_CFTD_OPTIONS.fileName,\n outputRoot = DEFAULT_CFTD_OPTIONS.outputRoot,\n absoluteTarget = DEFAULT_CFTD_OPTIONS.absoluteTarget,\n ignoreMissingSourceError = DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError\n } = uniqList.item;\n\n const absSource = path.resolve(procCwd, source);\n\n const exists = await fsExtra.pathExists(absSource);\n\n if (!exists) {\n if (ignoreMissingSourceError) continue;\n\n errorCount++;\n\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_PROCESS_COPY_ERROR({\n copyFrom: source,\n index: uniqList.index,\n indexKey: \"parameter\",\n count: loggerLevel === \"error\" ? errorCount : count,\n actionName: \"Failed to Copy File\",\n errorReason: \"the source file was not found\"\n });\n }\n } else {\n const absTargetDir = path.resolve(\n procCwd,\n absoluteTarget ? \"\" : outputRoot,\n target\n );\n\n const absTargetFile = path.join(\n absTargetDir,\n fileName ?? path.basename(source)\n );\n\n await fsExtra.ensureDir(absTargetDir);\n\n await fsExtra.copy(absSource, absTargetFile);\n\n const relSrc = path.relative(procCwd, absSource).replace(/\\\\/g, \"/\");\n const relDest = path\n .relative(procCwd, absTargetFile)\n .replace(/\\\\/g, \"/\");\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS_COPY({\n actionName: \"File copied\",\n count,\n copyFrom: relSrc,\n copyTo: relDest\n });\n }\n }\n }\n\n const successCount = count - errorCount;\n\n if (\n (errorCount > 0 || duplicateCount > 0) &&\n loggerLevel !== \"silent\" &&\n !canLog(loggerLevel, VERBOSE_LOG)\n ) {\n console.log(\n buildCopySummary(\n successCount,\n errorCount,\n duplicateCount,\n \"[Copy File to Dest]\"\n )\n );\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0 && errorCount === 0 && duplicateCount === 0) {\n BUILD_LOGGER.ON_FINISH({\n textSuccess: \"Successfully\",\n actionName: \"copied\",\n count: count\n });\n } else if (successCount > 0) {\n console.log(\n buildCopySummary(\n successCount,\n errorCount,\n duplicateCount,\n \"[Copy File to Dest]\"\n )\n );\n } else if (successCount === 0 && errorCount !== 0) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: '\"Copy File\"',\n reasonSkipAction: \"failed\",\n reasonEndText: `${count > 1 ? \"all \" : \"\"}files`,\n reasonType: \"to\",\n textDirectAction: \"copy\"\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: '\"Copy File\"',\n reasonSkipAction: errorCount > 0 ? \"nothing found\" : \"nothing\",\n reasonEndText: \"copy\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Copying File\",\n error\n });\n }\n }\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n detectModuleKindFromContent,\n extractAndHoistBanner,\n extractDirectives,\n JS_OUTPUT_FILE_RE,\n type ModuleKind,\n stripUseStrict\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport {\n flattenStrings,\n isArray,\n isNonEmptyString,\n toStringSet\n} from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **ensure css import** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link ensureCssImport | **`ensure-css-import`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_ECI_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **ensure css import** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link ensureCssImport | **`ensure-css-import`**}.\n */\nexport const resolvedEciPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_ECI_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link ensureCssImport | **`ensure-css-import`**}. */\nconst DEFAULT_ECI_OPTIONS = {\n cssImportPath: [] as string[],\n dedupe: true,\n sort: false,\n minify: false,\n patternOptions: resolvedEciPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies EnsureCssImportOptions;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction _normalizeBody(code: string, minify: boolean = false): string {\n let out = code.replace(/\\r\\n/g, EOL);\n out = out.replace(/\\*\\/\\n+/, `*/${EOL}`);\n out = out.replace(/(\\*\\/)([^\\n])/g, `$1${EOL}$2`);\n const directiveMatch = out.match(/^((?:\"use\\s[\\w-]+\";|'use\\s[\\w-]+';\\s*)+)/);\n if (directiveMatch) {\n const directivesBlock = directiveMatch[1] || \"\";\n const normalizedDirectives = directivesBlock.replace(/\\n+/g, EOL);\n out = out.replace(directivesBlock, normalizedDirectives + EOL);\n }\n out = out.replace(/\\n{3,}/g, `${EOL}${EOL}`);\n out = out.trimEnd() + (minify ? \"\" : EOL);\n return out;\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction inlineCssImports(code: string) {\n return code.replace(\n /((?:import\\s+[\"'][^\"']+\\.css[\"'];\\s*\\n?|require\\([\"'][^\"']+\\.css[\"']\\);\\s*\\n?){2,})/g,\n (block) =>\n block\n .split(/\\n+/)\n .map((l) => l.trim())\n .join(\"\")\n );\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction createCssStatements(kind: ModuleKind, cssImports: string[]): string[] {\n return cssImports.map((p) =>\n kind === \"cjs\" ? `require(\"${p}\");` : `import \"${p}\";`\n );\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction getMissingCssStatements(\n body: string,\n cssImports: string[],\n kind: ModuleKind,\n dedupe: boolean\n): { missing: string[]; cleanedBody: string } {\n const cleanedBody = body;\n const cssStatements = createCssStatements(kind, cssImports);\n\n const missing = dedupe\n ? cssStatements.filter((stmt) => !cleanedBody.includes(stmt))\n : cssStatements;\n\n return { missing, cleanedBody };\n}\n/** @internal Util for {@link ensureCssImport | **`ensure-css-import`**}. */\nfunction injectCssSmart({\n shebang,\n banner,\n directives,\n rest,\n cssStatements,\n kind,\n minify\n}: {\n shebang: string;\n banner: string;\n directives: string;\n rest: string;\n cssStatements: string[];\n kind: ModuleKind;\n minify?: boolean;\n}) {\n let out = minify ? shebang.trim() + EOL : shebang;\n out += minify ? banner.trim() + EOL : banner;\n let finalDirectives = stripUseStrict(directives, {\n trimEnd: minify,\n trimStart: minify\n });\n\n if (kind === \"cjs\") {\n finalDirectives = `\"use strict\";${EOL}` + finalDirectives.trimStart();\n }\n\n // finalDirectives = finalDirectives.trimStart().replace(/\\s*$/, EOL);\n\n out += finalDirectives;\n out += cssStatements.join(EOL) + (minify ? \"\" : EOL);\n out += rest.replace(/^\\n+/, minify ? \"\" : EOL);\n return out.trimStart();\n}\n/** ----------------------------------------------------------------\n * * ***Normalizes CSS import path input into a clean string array.***\n * ----------------------------------------------------------------\n *\n * Converts a `cssImportPath` option value into a normalized array\n * of non-empty strings for internal processing.\n *\n * - *Normalization rules:*\n * - Single value is wrapped into an array.\n * - Nested arrays are flattened recursively.\n * - Each string is trimmed.\n * - Empty strings are removed.\n *\n * The returned array is always a **new instance** and does not mutate\n * the original input.\n *\n * @param {EnsureCssImportOptions[\"cssImportPath\"]} input - CSS import path option.\n *\n * @returns {string[]} Normalized list of CSS import paths.\n *\n * @example\n * ```ts\n * normalizeCssImports(\"style.css\");\n * // ➔ [\"style.css\"]\n * ```\n *\n * @example\n * ```ts\n * normalizeCssImports([\" a.css \", [\"b.css\", \"\"], null]);\n * // ➔ [\"a.css\", \"b.css\"]\n * ```\n *\n * @internal Util for {@link ensureCssImport | **`ensure-css-import`**}.\n */\nfunction normalizeCssImports(\n input: EnsureCssImportOptions[\"cssImportPath\"]\n): string[] {\n return flattenStrings(isArray(input) ? input : [input])\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link ensureCssImport | **`ensure-css-import`**}. */\nexport const commandEciIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"ensure-css-import\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link ensureCssImport | **`ensure-css-import`**}.***\n * ----------------------------------------------------------------\n */\nexport type EnsureCssImportOptions = {\n /** ----------------------------------------------------------------\n * * ***CSS import path(s) to ensure exist in JS output.***\n * ----------------------------------------------------------------\n *\n * Accepts a single path or multiple paths.\n *\n * @example\n * ```ts\n * \"./search.css\"\n * ```\n *\n * @example\n * ```ts\n * [\"./search.css\", \"./theme.css\"]\n * ```\n */\n cssImportPath: string | readonly (string | readonly string[])[] | Set<string>;\n\n /** ----------------------------------------------------------------\n * * ***Remove duplicate CSS imports (recommended).***\n * ----------------------------------------------------------------\n *\n * @default true\n */\n dedupe?: boolean;\n\n /** ----------------------------------------------------------------\n * * ***Sort CSS imports alphabetically before inserting.***\n * ----------------------------------------------------------------\n *\n * @default false\n */\n sort?: boolean;\n\n /** --------------------------------------------------------\n * * ***Minify JS output (except directive prologue).***\n * --------------------------------------------------------\n *\n * - Keeps `\"use client\"` / `\"use strict\"` on separate lines.\n * - Everything else is collapsed into a single line.\n *\n * @default false\n */\n minify?: boolean;\n} & BaseOptions<\n typeof DEFAULT_ECI_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_ECI_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Ensures CSS import(s) exist in compiled JavaScript files.***\n * ----------------------------------------------------------------\n * - *Behavior:*\n * - Supports **multiple CSS imports**.\n * - Fully **idempotent**.\n * - Optional **dedupe & sorting**.\n *\n * @param {string | string[] | Set<string>} pattern\n * Glob pattern(s) pointing to compiled JS files.\n *\n * @param {EnsureCssImportOptions} options\n * Configuration options.\n *\n * @example\n * ```ts\n * await ensureCssImport(\"dist/**\\/*.js\", {\n * cssImportPath: [\"./search.css\", \"./theme.css\"],\n * dedupe: true,\n * sort: true,\n * minify: true\n * });\n * ```\n */\nexport const ensureCssImport = async (\n pattern: StringCollection,\n options: EnsureCssImportOptions\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_ECI_OPTIONS.logLevel\n );\n\n try {\n const {\n patternOptions = DEFAULT_ECI_OPTIONS.patternOptions,\n cssImportPath,\n dedupe = DEFAULT_ECI_OPTIONS.dedupe,\n sort = DEFAULT_ECI_OPTIONS.sort,\n minify = DEFAULT_ECI_OPTIONS.minify,\n __commandTitle\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandEciIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_ECI_PATTERN_POLICY\n );\n\n let cssImports = normalizeCssImports(cssImportPath);\n\n if (cssImports.length === 0) {\n throw new Error(\"`cssImportPath` option must not be empty.\");\n }\n\n if (dedupe) cssImports = Array.from(new Set(cssImports));\n\n if (sort) cssImports.sort();\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_ECI_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.cssImportPath\",\n cssImports,\n BUILD_LOGGER.SOURCE_OF(cssImports, DEFAULT_ECI_OPTIONS.cssImportPath),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.dedupe\",\n dedupe,\n BUILD_LOGGER.SOURCE_OF(dedupe, DEFAULT_ECI_OPTIONS.dedupe)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.sort\",\n sort,\n BUILD_LOGGER.SOURCE_OF(sort, DEFAULT_ECI_OPTIONS.sort)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.minify\",\n minify,\n BUILD_LOGGER.SOURCE_OF(minify, DEFAULT_ECI_OPTIONS.minify)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_ECI_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Ensuring CSS Import\"\n });\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const { banner, body, shebang } = extractAndHoistBanner(content);\n const kind = detectModuleKindFromContent(content);\n\n const { missing, cleanedBody } = getMissingCssStatements(\n body,\n cssImports,\n kind,\n dedupe\n );\n\n if (missing.length === 0) continue;\n\n const { directives, rest } = extractDirectives(cleanedBody);\n\n let updated = injectCssSmart({\n shebang,\n banner,\n directives,\n rest,\n kind,\n minify: options.minify,\n cssStatements: missing\n });\n\n if (options.minify) {\n updated = inlineCssImports(updated);\n }\n\n if (updated !== content) {\n try {\n await fsExtra.promises.writeFile(filePath, updated, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"CSS Import\",\n count,\n nameDirect: filePath\n });\n }\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Ensuring CSS Import\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Ensuring CSS Import\",\n reasonType: \"file\",\n reasonEndText: \"check\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Ensuring CSS Import\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose, picocolors } from \"@/utils/helper/formatter\";\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **ensure final newline** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link ensureFinalNewline | **`ensure-final-newline`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_EFN_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **ensure final newline** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link ensureFinalNewline | **`ensure-final-newline`**}.\n */\nexport const resolvedEfnPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_EFN_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link ensureFinalNewline | **`ensure-final-newline`**}. */\nconst DEFAULT_EFN_OPTIONS = {\n patternOptions: resolvedEfnPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies EnsureFinalNewlineOptions;\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link ensureFinalNewline | **`ensure-final-newline`**}. */\nexport const commandEfnIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"ensure-final-newline\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link ensureFinalNewline | **`ensure-final-newline`**}.***\n * ----------------------------------------------------------------\n */\nexport type EnsureFinalNewlineOptions = BaseOptions<\n typeof DEFAULT_EFN_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_EFN_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Ensure files end with exactly one final newline.***\n * ----------------------------------------------------------------\n *\n * Scans files matching the provided glob pattern(s) and ensures that\n * **each file ends with exactly one newline character**.\n *\n * - *Behavior:*\n * - Removes **all trailing newline characters** at the end of the file.\n * - Appends **exactly one** platform-consistent newline (`EOL`).\n * - Preserves all internal formatting and whitespace.\n * - Does **not** modify files that are already compliant.\n *\n * - *Newline handling:*\n * - Supports both `LF` (`\\n`) and `CRLF` (`\\r\\n`).\n * - Uses **`EOL`** to ensure consistent output across the project.\n *\n * - *Safety:*\n * - Skips non-existent paths.\n * - Skips non-file entries (directories, symlinks, etc.).\n * - Writes only when the file content actually changes.\n *\n * @param {string | string[] | Set<string>} pattern\n * Glob pattern(s) pointing to files that should be checked and normalized.\n *\n * @param {EnsureFinalNewlineOptions} [options]\n * Internal execution options (CLI vs utility context).\n *\n * @example\n * ```ts\n * await ensureFinalNewline(\"dist/**\\/*.{js,cjs,mjs,d.ts}\");\n * ```\n *\n * @example\n * ```ts\n * await ensureFinalNewline([\"dist/**\\/*.js\", \"dist/**\\/*.d.ts\"]);\n * ```\n *\n * @remarks\n * This utility is typically executed **post-build** to ensure output\n * files follow POSIX tooling expectations and common formatting conventions.\n */\nexport const ensureFinalNewline = async (\n pattern: StringCollection,\n options: EnsureFinalNewlineOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_EFN_OPTIONS.logLevel\n );\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_EFN_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandEfnIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_EFN_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_EFN_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_EFN_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Ensuring Final Newline\"\n });\n }\n\n // const files = new Set<string>();\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n // for (const file of matched.sort()) files.add(file);\n\n let count = 0;\n\n for (const filePath of files) {\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const normalized = content.replace(/(\\r?\\n)*$/, EOL);\n\n if (normalized === content) continue;\n\n try {\n await fsExtra.promises.writeFile(filePath, normalized, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"Final Newline\",\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Ensuring Final Newline\",\n count\n });\n } else if (files.length < 1) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Ensuring Final Newline\",\n reasonSkipAction: `no files found matching the pattern${picocolors.reset(\n \",\"\n )}`,\n reasonType: \"\",\n textDirectAction: \"no need to fix\",\n reasonEndText: \"end of file (EOF)\"\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Ensuring Final Newline\",\n reasonSkipAction: `all files are valid${picocolors.reset(\",\")}`,\n reasonType: \"\",\n textDirectAction: \"no need to fix\",\n reasonEndText: \"end of file (EOF)\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Ensuring Final Newline\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport path from \"node:path\";\n\nimport type { AnyString, Awaitable } from \"@/_internal/types/extra\";\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { TS_DECLARATION_FILE_RE } from \"@/_internal/utils/source\";\nimport { BUILD_LOGGER, sourceOf } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport {\n EOL,\n joinLinesLoose,\n picocolors as pcr\n} from \"@/utils/helper/formatter\";\nimport { fastGlob, fsExtra } from \"@/utils/server\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\nimport { generatePackageBanner } from \"../package-banner\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **generate reference index** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link generateReferenceIndex | **`generate-reference-index`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_GRI_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<true, true>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **generate reference index** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link generateReferenceIndex | **`generate-reference-index`**}.\n */\nexport const resolvedGriPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_GRI_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nconst DEFAULT_GRI_OPTIONS = {\n outDir: \"dist/.references\",\n outFileName: \"index.d.ts\",\n inputDirReference: \"dist\",\n withExportTypes: false,\n banner: true,\n onlyDeclarations: true,\n patternOptions: resolvedGriPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies GenerateReferenceOptions;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nfunction normalizeRelative(from: string, to: string) {\n return path\n .relative(from, to)\n .replace(/\\\\/g, \"/\")\n .replace(/^([^./])/, \"./$1\"); // ensure ./ or ../\n}\n/** @internal Util for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nconst resolveExportModulePath = (relativePath: string) => {\n const parsed = path.parse(relativePath);\n\n let baseName = parsed.name;\n\n // remove trailing \".d\" ONLY for declaration outputs\n if (baseName.endsWith(\".d\")) {\n baseName = baseName.slice(0, -2);\n }\n\n return path.join(parsed.dir, baseName).replace(/\\\\/g, \"/\");\n};\n/** ----------------------------------------------------------------\n * * ***Validated output configuration input.***\n * ----------------------------------------------------------------\n *\n * Raw configuration object passed into `validateOut`.\n *\n * - Each field will be normalized and validated before use.\n *\n * @internal Utils for {@link generateReferenceIndex | **`generate-reference-index`**}.\n */\nconst validateOut = ({\n outDir,\n outFileName,\n inputDirReference\n}: {\n /** --------------------------------------------------------------\n * * ***Output directory path.***\n * --------------------------------------------------------------\n *\n * Base directory where the generated index file will be written.\n *\n * - Leading & trailing whitespace will be trimmed.\n * - Trailing slash will be removed.\n *\n * @example\n * `\"dist/\"` ➔ `\"dist\"`\n */\n outDir: string;\n\n /** --------------------------------------------------------------\n * * ***Output declaration file name.***\n * --------------------------------------------------------------\n *\n * Must be a **file name only**, not a path.\n *\n * - ❌ `\"dist/index.d.ts\"`.\n * - ❌ `\"../index.d.ts\"`.\n * - ✅ `\"index.d.ts\"`.\n *\n * Used together with `outDir` to build the final output path.\n */\n outFileName: string;\n\n /** --------------------------------------------------------------\n * * ***Input reference base directory.***\n * --------------------------------------------------------------\n *\n * Used to strip the leading path from matched files when\n * generating reference and export paths.\n *\n * - ***Example:***\n * - inputDirReference: `\"dist\"`.\n * - file: `\"dist/utils/logger.d.ts\"`.\n * - result: `\"utils/logger.d.ts\"`.\n */\n inputDirReference: string;\n}) => {\n const normalizePath = (value: string) => {\n // if (!value) return undefined;\n\n const trimmed = value.trim();\n // if (!trimmed) return undefined;\n\n // remove trailing slash (\"/foo/bar/\" -> \"/foo/bar\")\n return trimmed.endsWith(\"/\") ? trimmed.slice(0, -1) : trimmed;\n };\n\n const normalizeFileName = (value: string) => {\n // if (!value) return undefined;\n\n const trimmed = value.trim();\n // if (!trimmed) return undefined;\n\n // optional: prevent path traversal\n if (trimmed.includes(\"/\") || trimmed.includes(\"\\\\\")) {\n throw new Error(`Invalid outFileName: \"${value}\"`);\n }\n\n return trimmed;\n };\n\n return {\n outDir: normalizePath(outDir),\n inputDirReference: normalizePath(inputDirReference),\n outFileName: normalizeFileName(outFileName)\n };\n};\n/** @internal Util for {@link generateReferenceIndex | **`generate-reference-index`**}. */\nconst resolveBanner = async (banner: BannerInput): Promise<string> => {\n if (banner === false) return \"\";\n\n if (banner === true) {\n return (await generatePackageBanner()) + EOL;\n }\n\n const resolved = await banner;\n\n return isNonEmptyString(resolved) ? resolved : \"\";\n};\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link generateReferenceIndex | **`generate-reference-index`**}. */\nexport const commandGriIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"generate-reference-index\"\n});\n\n//? Types ----------------------------------------------------------------\n/** @internal Type for {@link generateReferenceIndex | **`generate-reference-index`**}.*/\ntype BannerInput = true | AnyString | false | Awaitable<AnyString>;\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link generateReferenceIndex | **`generate-reference-index`**}.***\n * ----------------------------------------------------------------\n */\nexport type GenerateReferenceOptions = {\n /** --------------------------------------------------------------\n * * ***Output directory.***\n * --------------------------------------------------------------\n *\n * Directory where the generated index file will be written.\n *\n * @default \"dist/.references\"\n */\n outDir?: string;\n\n /** --------------------------------------------------------------\n * * ***Output index file name.***\n * --------------------------------------------------------------\n *\n * Name of the generated `.d.ts` index file.\n *\n * @default \"index.d.ts\"\n */\n outFileName?: string;\n\n /** --------------------------------------------------------------\n * * ***Enable exported type aggregation.***\n * --------------------------------------------------------------\n *\n * When enabled, generates:\n *\n * ```ts\n * export * from \"./module\";\n * ```\n *\n * for each unique declaration entry.\n *\n * @default false\n */\n withExportTypes?: boolean;\n\n /** --------------------------------------------------------------\n * * ***Base directory for resolving reference paths.***\n * --------------------------------------------------------------\n *\n * Used to compute relative paths inside the generated index file.\n *\n * @default \"dist\"\n */\n inputDirReference?: string;\n\n /** --------------------------------------------------------------\n * * ***Restrict input to TypeScript declaration files only.***\n * --------------------------------------------------------------\n *\n * When enabled (`true`), this option filters the input files to include **only**\n * TypeScript declaration files with extensions `.d.ts`, `.d.mts`, and `.d.cts`.\n *\n * This filtering is applied **after** matching files by the provided glob patterns,\n * effectively excluding all other file types, including JavaScript outputs\n * (`.js`, `.mjs`, `.cjs`) and TypeScript source files (`.ts`, `.mts`, `.cts`).\n *\n * - *Examples:*\n * - With a pattern like `\"dist/**\\/*.d.ts\"`, enabling this option has no practical effect,\n * since the pattern already matches only declaration files.\n * - With a broader pattern such as `\"dist/**\\/*\"` or `\"dist/**\\/*.ts\"`,\n * enabling this option will exclude non-declaration files (e.g., `.ts` source files),\n * resulting in only declaration files being included.\n * - If your patterns include JavaScript outputs (`.js`, `.mjs`, `.cjs`),\n * enabling this option will exclude those files as well.\n *\n * When disabled (`false`), all matched files are included regardless of extension,\n * so JavaScript outputs and source files matching the patterns will be part of\n * the reference and export generation.\n *\n * Use this option and set to `true`, when you want to guarantee that only TypeScript declaration files\n * are included in the generated references and exports, preventing accidental\n * inclusion of source or JavaScript build output files.\n *\n * @default true\n */\n onlyDeclarations?: boolean;\n\n /** --------------------------------------------------------------\n * * ***Output banner configuration.***\n * --------------------------------------------------------------\n *\n * Controls the banner text prepended to the generated output file.\n *\n * - `true` **(default)** ➔ automatically generates banner from `package.json`\n * using {@link generatePackageBanner | `generatePackageBanner`}.\n * - `false` ➔ disables banner injection entirely.\n * - `string` ➔ uses the provided custom banner text.\n * - `Promise<string>` ➔ resolved and used as banner text.\n *\n * @default true\n */\n banner?: BannerInput;\n} & BaseOptions<\n typeof DEFAULT_GRI_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_GRI_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Generates a TypeScript reference index file (.d.ts).***\n * ----------------------------------------------------------------\n *\n * This function resolves files from the given glob pattern(s) and generates\n * a single declaration index file containing:\n *\n * - `/// \\<reference path=\"...\" />` directives.\n * - optional `export * from \"...\"` statements.\n *\n * Supported input files include declaration and JavaScript module outputs:\n * - `.d.ts`.\n * - `.js`.\n * - `.cjs`.\n * - `.mjs`.\n *\n * The output is typically used to aggregate multiple declaration or build\n * artifacts into a single entry point.\n *\n * @param pattern - Glob pattern or list of patterns used to match output files, supports `.d.ts`, `.js`, `.cjs`, and `.mjs` extensions.\n *\n * @param options - Reference index generation options, see {@link GenerateReferenceOptions | **`GenerateReferenceOptions`**}.\n *\n * @example\n * Basic usage with declaration files only:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.d.ts\");\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/post.d.ts\" />\n * ```\n *\n * @example\n * Restrict to declaration files even if pattern matches other files,\n * by default `onlyDeclarations` options is `true`:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*\", { onlyDeclarations: true });\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/post.d.cts\" />\n * ```\n *\n * @example\n * Include all matched files (source `.ts` and JS outputs) without filtering declaration files only:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*\", { onlyDeclarations: false });\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../models/order.ts\" />\n * /// \\<reference path=\"../models/user.js\" />\n * /// \\<reference path=\"../models/another.cjs\" />\n * ```\n *\n * (Here, both `.ts` source files and declaration files are\n * included if matched, because `onlyDeclarations` is `false`).\n *\n * @example\n * Include JavaScript build outputs with no declaration-only restriction:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.js\", { onlyDeclarations: false });\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../runtime/helpers.js\" />\n * /// \\<reference path=\"../runtime/constants.js\" />\n * ```\n *\n * (JavaScript files are included because `onlyDeclarations` is `false`).\n *\n * @example\n * Restrict to declaration files when pattern includes source `.ts` and JS files:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.ts\");\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../models/user.d.ts\" />\n * /// \\<reference path=\"../models/order.d.ts\" />\n * ```\n *\n * (Here `.ts` source files are ignored; only `.d.ts` declarations are included).\n *\n * ----------------------------------------------------------------\n *\n * ***--- Existing examples below remain unchanged ---***\n *\n * @example\n * Generate references from types JavaScript build outputs:\n * ```ts\n * await generateReferenceIndex(\"dist/**\\/*.d.{js,cjs,mjs}\");\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../runtime/helpers.d.js\" />\n * /// \\<reference path=\"../runtime/constants.d.mjs\" />\n * ```\n *\n * @example\n * Mix declaration and JavaScript module outputs:\n * ```ts\n * await generateReferenceIndex([\n * \"dist/**\\/*.d.ts\",\n * \"dist/**\\/*.d.{js,cjs,mjs}\"\n * ]);\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/post.d.mts\" />\n * /// \\<reference path=\"../runtime/helpers.d.cjs\" />\n * ```\n *\n * @example\n * Generate reference index and export all resolved modules:\n * ```ts\n * await generateReferenceIndex(\n * \"dist/**\\/*\",\n * { withExportTypes: true }\n * );\n * ```\n *\n * Result (`dist/.references/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../types/user.d.cts\" />\n * /// \\<reference path=\"../types/post.d.ts\" />\n * /// \\<reference path=\"../types/post.d.cts\" />\n *\n * // Exported Types:\n * export * from \"../types/user\";\n * export * from \"../types/post\";\n * ```\n *\n * @example\n * Use multiple input directories with a shared reference base:\n * ```ts\n * await generateReferenceIndex(\n * [\n * \"dist/types/**\\/*.d.ts\",\n * \"dist/generated/**\\/*.d.{js,cjs,mjs}\"\n * ],\n * {\n * inputDirReference: \"dist\",\n * withExportTypes: true\n * }\n * );\n * ```\n *\n * Result (`dist/index.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../types/user.d.ts\" />\n * /// \\<reference path=\"../data/config.d.cjs\" />\n * /// \\<reference path=\"../generated/schema.d.js\" />\n *\n * // Exported Types:\n * export * from \"../types/user\";\n * export * from \"../generated/schema\";\n * ```\n *\n * @example\n * Customize output location and file name:\n * ```ts\n * await generateReferenceIndex(\n * \"build/**\\/*\",\n * {\n * outDir: \"build/types\",\n * outFileName: \"references-types.d.ts\"\n * }\n * );\n * ```\n *\n * Result (`build/types/references-types.d.ts`):\n * ```ts\n * // References Paths:\n * /// \\<reference path=\"../models/user.d.ts\" />\n * /// \\<reference path=\"../models/order.d.cts\" />\n * /// \\<reference path=\"../models/account.d.mts\" />\n * ```\n */\nexport const generateReferenceIndex = async (\n pattern: StringCollection,\n options: GenerateReferenceOptions = {}\n): Promise<void> => {\n let _withExportTypes: boolean = DEFAULT_GRI_OPTIONS.withExportTypes;\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_GRI_OPTIONS.logLevel\n );\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_GRI_OPTIONS.patternOptions,\n outDir: _outDir = DEFAULT_GRI_OPTIONS.outDir,\n outFileName: _outFileName = DEFAULT_GRI_OPTIONS.outFileName,\n inputDirReference:\n _inputDirReference = DEFAULT_GRI_OPTIONS.inputDirReference,\n withExportTypes = DEFAULT_GRI_OPTIONS.withExportTypes,\n banner = DEFAULT_GRI_OPTIONS.banner,\n onlyDeclarations = DEFAULT_GRI_OPTIONS.onlyDeclarations\n } = options;\n\n _withExportTypes = withExportTypes;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandGriIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_GRI_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"outDir\",\n _outDir,\n sourceOf(_outDir, DEFAULT_GRI_OPTIONS.outDir)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_GRI_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.outFileName\",\n _outFileName,\n sourceOf(_outFileName, DEFAULT_GRI_OPTIONS.outFileName)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.inputDirReference\",\n _inputDirReference,\n sourceOf(_inputDirReference, DEFAULT_GRI_OPTIONS.inputDirReference)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.withExportTypes\",\n withExportTypes,\n sourceOf(withExportTypes, DEFAULT_GRI_OPTIONS.withExportTypes)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.banner\",\n banner,\n sourceOf(banner, DEFAULT_GRI_OPTIONS.banner)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_GRI_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Generating References\"\n });\n }\n\n let files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n if (onlyDeclarations) {\n files = files.filter((file) => TS_DECLARATION_FILE_RE.test(file));\n }\n\n const { inputDirReference, outDir, outFileName } = validateOut({\n outDir: _outDir,\n outFileName: _outFileName,\n inputDirReference: _inputDirReference\n });\n\n const outDirAbs = path.resolve(outDir);\n const outFileAbs = path.join(outDirAbs, outFileName);\n\n const outFileNormalize = path\n .relative(process.cwd(), outFileAbs)\n .replace(/\\\\/g, \"/\");\n\n const lines = new Set<string>();\n let referenceCount = 0;\n\n const inputDirRefAbs = path.resolve(inputDirReference);\n\n const reference = files\n .map((f, i) => {\n const referencedAbs = path.resolve(f);\n\n if (\n !referencedAbs.startsWith(inputDirRefAbs + path.sep) ||\n referencedAbs === outFileAbs\n ) {\n return;\n }\n\n const referencePath = normalizeRelative(\n path.dirname(outFileAbs),\n referencedAbs\n );\n\n const logPath = path\n .relative(inputDirRefAbs, referencedAbs)\n .replace(/\\\\/g, \"/\");\n const displayPath = `${inputDirReference}/${logPath}`;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS_REFERENCING({\n actionName: \"Generated Reference\",\n count: i + 1,\n referenceFrom: displayPath,\n referenceTo: outFileNormalize\n });\n }\n\n referenceCount++;\n\n return `/// <reference path=\"${referencePath}\" />`;\n })\n .filter(Boolean);\n\n if (Array.isArray(reference) && reference.length > 0) {\n lines.add(\"//! References Paths:\");\n lines.add(reference.join(EOL));\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (referenceCount > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Generating Reference\",\n count: files.length,\n typeCount: \"reference\"\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Generating References\",\n reasonEndText: \"referencing\",\n reasonType: \"references\"\n });\n }\n }\n\n if (withExportTypes) {\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n pcr.bold(\n pcr.magentaBright(\n `${EOL}=======================================================================================${EOL}`\n )\n )\n );\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Adding Exported Types\"\n });\n }\n\n const exportLines = new Set<string>();\n let exportCount = 0;\n\n files.forEach((f) => {\n const referencedAbs = path.resolve(f);\n\n if (\n !referencedAbs.startsWith(inputDirRefAbs + path.sep) ||\n referencedAbs === outFileAbs\n ) {\n return;\n }\n\n const relativeToInputDirRef = path\n .relative(inputDirRefAbs, referencedAbs)\n .replace(/\\\\/g, \"/\");\n\n const exportModulePath = resolveExportModulePath(relativeToInputDirRef);\n\n const exportPath = normalizeRelative(\n path.dirname(outFileAbs),\n path.resolve(inputDirReference, exportModulePath)\n );\n\n const line = `export * from \"${exportPath}\";`;\n\n if (!exportLines.has(line)) {\n exportCount++;\n\n const logPath = path\n .relative(inputDirRefAbs, referencedAbs)\n .replace(/\\\\/g, \"/\");\n const displayPath = `${inputDirReference}/${logPath}`;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS_REFERENCING({\n actionName: \"Exported Type\",\n count: exportCount,\n referenceFrom: displayPath,\n referenceTo: outFileNormalize\n });\n }\n\n exportLines.add(line);\n }\n });\n\n if (exportLines.size > 0) {\n if (referenceCount > 0) lines.add(\"\");\n\n lines.add(\"//! Exported Types:\");\n lines.add([...exportLines].join(EOL));\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Adding Exported Types\",\n count: exportLines.size,\n typeCount: \"type\"\n });\n }\n } else {\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Adding Exported Types\",\n reasonEndText: \"exporting\",\n reasonType: \"types\"\n });\n }\n }\n }\n\n await fsExtra.ensureDir(outDirAbs);\n\n if (lines.size === 0) {\n const action = withExportTypes\n ? \"reference and type export\"\n : \"reference\";\n\n lines.add(\n `// No files matched the given patterns and input dir references, skipping ${action} generation.`\n );\n }\n\n await fsExtra.promises.writeFile(\n outFileAbs,\n (await resolveBanner(banner)) + [...lines].join(EOL) + EOL\n );\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName:\n \"Generating References\" +\n (_withExportTypes ? \" and Adding Exported Types\" : \"\"),\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n isNonEmptyString,\n isRegExp,\n toStringSet\n} from \"@/_internal/utils/helper\";\nimport {\n BANNER_RE,\n extractAndHoistBanner,\n hasExecutableCode,\n NON_COMMENTABLE_FILE_RE\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose, picocolors } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **inject banner** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link injectBanner | **`inject-banner`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_IB_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **inject banner** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link injectBanner | **`inject-banner`**}.\n */\nexport const resolvedIbPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_IB_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link injectBanner | **`inject-banner`**}. */\nconst DEFAULT_IB_OPTIONS = {\n replaceBanner: false,\n removeDuplicate: true,\n bannerPosition: \"after-existing\" as const,\n patternOptions: resolvedIbPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies InjectBannerOptions;\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link injectBanner | **`inject-banner`**}. */\nexport const commandIbIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"inject-banner\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link injectBanner | `inject-banner`}.***\n * ----------------------------------------------------------------\n */\nexport type InjectBannerOptions = {\n /** Replace existing banner block(s).\n *\n * - `false` ➔ Preserve existing banners.\n * - `true` ➔ Replace banners matching default `/^(?:\\/\\*![\\s\\S]*?\\*\\/\\s*)+/`.\n * - `RegExp` ➔ Replace banners matching provided pattern.\n *\n * Note:\n * The provided RegExp will be internally cloned without the `g` flag\n * to ensure safe `.test()` execution.\n *\n * @default false\n */\n replaceBanner?: boolean | RegExp;\n\n /** Remove duplicated banner blocks.\n *\n * Deduplication is performed using `trim()` comparison.\n *\n * @default true\n */\n removeDuplicate?: boolean;\n\n /** Control where new banner block(s) are injected.\n *\n * - `\"top\"` ➔ Place new banner before existing banner blocks.\n * - `\"after-existing\"` ➔ Append new banner after existing blocks.\n *\n * @default \"after-existing\"\n */\n bannerPosition?: \"top\" | \"after-existing\";\n} & BaseOptions<\n typeof DEFAULT_IB_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_IB_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Injects banner comments into JavaScript output files.***\n * ----------------------------------------------------------------\n *\n * Scans files that match the provided glob pattern(s) and injects one or\n * more banner comment blocks at the top of each file when applicable.\n *\n * - ***Injection Rules:***\n * - Skips files that:\n * - Are empty after trimming.\n * - Contain no executable JavaScript code.\n * - Match `NON_COMMENTABLE_FILE_RE`.\n * - Preserves existing shebang (`#!`) at the very top of the file.\n * - Existing banner blocks are detected using `BANNER_RE`.\n *\n * - ***Replace Mode:***\n * - If `options.replaceBanner` is:\n * - `true` ➔ uses default `BANNER_RE`.\n * - `RegExp` ➔ uses the provided pattern.\n * - If the existing banner matches the replace pattern,\n * it will be fully replaced with the new banner block(s).\n * - The replace pattern is executed without the `g` flag internally\n * to avoid stateful RegExp side effects.\n *\n * - ***Banner Ordering:***\n * Controlled by `options.bannerPosition`:\n * - `\"top\"` ➔ new banner is placed before existing banner blocks.\n * - `\"after-existing\"` ➔ new banner is appended after existing blocks.\n *\n * - ***Deduplication:***\n * If `options.removeDuplicate` is `true` (default):\n * - Banner blocks are deduplicated based on `trim()` comparison.\n * - Order is preserved.\n *\n * - ***Normalization:***\n * - Line endings are normalized to the internal `EOL` constant.\n * - Each banner block is ensured to end with exactly two `EOL`s.\n * - The operation is idempotent — running multiple times\n * will not change the file further.\n *\n * @example\n * Basic usage:\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `\n * /**\n * * My Library v1.0.0\n * * (c) 2026 Your Name\n * *\\/\n * `\n * );\n * ```\n *\n * @example\n * Inject multiple banner blocks:\n * ```ts\n * await injectBanner(\n * [\"dist/**\\/*.js\", \"build/**\\/*.mjs\"],\n * [\n * `/** Project: MyApp *\\/`,\n * `/** License: MIT *\\/`\n * ]\n * );\n * ```\n *\n * @example\n * Replace existing banner entirely:\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `/** Updated License Banner *\\/`,\n * { replaceBanner: true }\n * );\n * ```\n *\n * @example\n * Replace using custom RegExp:\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `/** New Banner *\\/`,\n * {\n * replaceBanner: /^\\/\\*\\*![\\s\\S]*?\\*\\/\\s*\\/,\n * }\n * );\n * ```\n *\n * @example\n * Always place banner at very top (after shebang):\n * ```ts\n * await injectBanner(\n * \"dist/**\\/*.js\",\n * `/** Build: Production *\\/`,\n * {\n * bannerPosition: \"top\"\n * }\n * );\n * ```\n *\n * @param pattern - Glob pattern(s) pointing to target JavaScript files.\n * @param bannerText - Banner string(s) to inject.\n * @param options - Injection configuration options.\n */\nexport const injectBanner = async (\n pattern: StringCollection,\n bannerText: StringCollection,\n options: InjectBannerOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(options, DEFAULT_LOG_LEVEL);\n\n try {\n const {\n __commandTitle,\n removeDuplicate = DEFAULT_IB_OPTIONS.removeDuplicate,\n bannerPosition = DEFAULT_IB_OPTIONS.bannerPosition,\n replaceBanner = DEFAULT_IB_OPTIONS.replaceBanner,\n patternOptions = DEFAULT_IB_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandIbIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const banners = toStringSet(bannerText, {\n parameterKey: \"bannerText\"\n });\n\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_IB_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_IB_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeDuplicate\",\n removeDuplicate,\n BUILD_LOGGER.SOURCE_OF(\n removeDuplicate,\n DEFAULT_IB_OPTIONS.removeDuplicate\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.replaceBanner\",\n replaceBanner,\n BUILD_LOGGER.SOURCE_OF(replaceBanner, DEFAULT_IB_OPTIONS.replaceBanner)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.bannerPosition\",\n bannerPosition,\n BUILD_LOGGER.SOURCE_OF(\n bannerPosition,\n DEFAULT_IB_OPTIONS.bannerPosition\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_IB_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Injecting Banner\"\n });\n }\n\n if (banners.size === 0) {\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Inject Banner\",\n reasonSkipAction: \"empty bannerText\",\n reasonType: \"parameter\",\n reasonEndText: \"injecting\"\n });\n }\n return;\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (NON_COMMENTABLE_FILE_RE.test(filePath)) continue;\n let original: string;\n\n try {\n original = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (!isNonEmptyString(original)) continue;\n if (!hasExecutableCode(original)) continue;\n\n const {\n body,\n shebang,\n banner: existingBanner\n } = extractAndHoistBanner(original);\n\n const bannerRegex = new RegExp(BANNER_RE.source, \"g\");\n\n const newBlocks = [...banners];\n\n if (newBlocks.length === 0) continue;\n\n const existingBlocks = existingBanner\n ? [...existingBanner.matchAll(bannerRegex)].map((m) => m[0])\n : [];\n\n let finalBlocks: string[] = [];\n\n if (replaceBanner) {\n const replaceRegex = isRegExp(replaceBanner)\n ? replaceBanner\n : BANNER_RE;\n\n if (\n existingBanner &&\n new RegExp(\n replaceRegex.source,\n replaceRegex.flags.replace(\"g\", \"\")\n ).test(existingBanner)\n ) {\n finalBlocks = [...newBlocks];\n } else {\n finalBlocks =\n bannerPosition === \"top\"\n ? [...newBlocks, ...existingBlocks]\n : [...existingBlocks, ...newBlocks];\n }\n } else {\n const combined =\n bannerPosition === \"top\"\n ? [...newBlocks, ...existingBlocks]\n : [...existingBlocks, ...newBlocks];\n\n finalBlocks = combined;\n }\n\n if (removeDuplicate) {\n const seen = new Set<string>();\n\n finalBlocks = finalBlocks.filter((block) => {\n const normalized = block.trim();\n\n if (seen.has(normalized)) return false;\n\n seen.add(normalized);\n return true;\n });\n }\n\n const normalizedFinalBanner = finalBlocks\n .map((text) => {\n if (!text || !isNonEmptyString(text)) return \"\";\n\n let normalized = text.replace(/\\r\\n/g, EOL);\n\n return normalized.replace(/\\n+$/, \"\") + EOL + EOL;\n })\n .join(\"\");\n\n let content = shebang + normalizedFinalBanner + body;\n\n try {\n await fsExtra.promises.writeFile(filePath, content, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName:\n \"Banner Injected \" +\n picocolors.cyanBright(\n replaceBanner ? \"(replace mode)\" : \"(preserve mode)\"\n ),\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Inject Banner\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Inject Banner\",\n reasonEndText: \"injecting\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Inject Banner\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n detectModuleKindFromContent,\n extractAndHoistBanner,\n extractDirectives,\n hasExecutableCode,\n JS_OUTPUT_FILE_RE,\n stripUseStrict\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose, picocolors } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **inject directive** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link injectDirective | **`inject-directive`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_ID_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **inject directive** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link injectDirective | **`inject-directive`**}.\n */\nexport const resolvedIdPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_ID_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link injectDirective | **`inject-directive`**}. */\nconst DEFAULT_ID_OPTIONS = {\n patternOptions: resolvedIdPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies InjectDirectiveOptions;\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link injectDirective | **`inject-directive`**}. */\nexport const commandIdIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"inject-directive\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link injectDirective | **`inject-directive`**}.***\n * ----------------------------------------------------------------\n */\nexport type InjectDirectiveOptions = BaseOptions<\n typeof DEFAULT_ID_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_ID_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Injects directive statements into JavaScript output files.***\n * ----------------------------------------------------------------\n *\n * This function scans files matching the provided glob pattern(s) and\n * injects one or more directive statements (e.g. `\"use strict\"`,\n * `\"use client\"`) at the top of each file when applicable.\n *\n * - *Injection behavior:*\n * - Skips empty files.\n * - Skips files that only contain directive statements.\n * - Avoids duplicating existing directives.\n * - Preserves existing file content order.\n *\n * - *Each directive is normalized and injected as a standalone statement:*\n * ```js\n * \"directive-name\";\n * ```\n *\n * @param pattern - Glob pattern or list of patterns pointing to JS output files.\n * @param directive - Directive string(s) to inject.\n * @param options - Injection configuration options, see {@link InjectDirectiveOptions | **`InjectDirectiveOptions`**}.\n *\n * @example\n * ```ts\n * await injectDirective(\"dist/**\\/*.js\", \"use strict\");\n * ```\n *\n * @example\n * ```ts\n * await injectDirective(\"dist/**\\/*.js\", \"use client\");\n * ```\n *\n * @example\n * ```ts\n * await injectDirective(\n * [\"dist/**\\/*.js\", \"build/*\\/*.mjs\"],\n * [\"use strict\", \"use client\"]\n * );\n * ```\n */\nexport const injectDirective = async (\n pattern: StringCollection,\n directive: StringCollection,\n options: InjectDirectiveOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(options, DEFAULT_ID_OPTIONS.logLevel);\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_ID_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandIdIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_ID_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"directive\",\n directive,\n BUILD_LOGGER.SOURCE_OF(directive, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_ID_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_ID_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Inject Directive\"\n });\n }\n\n const directives = [...toStringSet(directive)];\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let original: string;\n\n try {\n original = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (!isNonEmptyString(original) || !hasExecutableCode(original)) continue;\n const { body, banner, shebang } = extractAndHoistBanner(original);\n const { directives: extractedDirectives, rest } = extractDirectives(body);\n const existing = new Set(extractedDirectives);\n let injectLines: string[] | undefined;\n\n if (detectModuleKindFromContent(rest) === \"cjs\") {\n injectLines ??= [];\n // eslint-disable-next-line quotes\n injectLines.push(`\"use strict\";`);\n }\n\n for (const d of directives) {\n const dTrim = d.trim();\n if (!dTrim || dTrim === \"use strict\") continue;\n\n const line = `\"${dTrim}\";`;\n if (!existing.has(line)) {\n injectLines ??= [];\n injectLines.push(line);\n }\n }\n\n if (!injectLines?.length) continue;\n\n const finalDirective =\n injectLines.join(EOL) + EOL + stripUseStrict(extractedDirectives);\n\n const content = shebang + banner + finalDirective + rest;\n\n try {\n await fsExtra.promises.writeFile(filePath, content, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName:\n \"Directive Injected \" +\n picocolors.cyanBright(\"(`\" + injectLines.join(\"`, `\") + \"`)\"),\n count,\n nameDirect: filePath\n });\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Inject Directive\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Inject Directive\",\n reasonEndText: \"injecting\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Inject Directive\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { JS_OUTPUT_FILE_RE } from \"@/_internal/utils/source\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **normalize js build newlines** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_NJBN_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **normalize js build newlines** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}.\n */\nexport const resolvedNjbnPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_NJBN_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}. */\nconst DEFAULT_NJBN_OPTIONS = {\n patternOptions: resolvedNjbnPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies NormalizeJsBuildNewlinesOptions;\n\n//? Identity -------------------------------------------------------------\n/** Generated Command Identity For {@link normalizeJsBuildNewlines | **`normalize-js-build-newlines`**}. */\nexport const commandNjbnIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"normalize-js-build-newlines\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link normalizeJsBuildNewlines | **`normalizeJsBuildNewlines`**}.***\n * ----------------------------------------------------------------\n */\nexport type NormalizeJsBuildNewlinesOptions = BaseOptions<\n typeof DEFAULT_NJBN_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_NJBN_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Normalizes excessive blank lines in compiled JavaScript files.***\n * ----------------------------------------------------------------\n *\n * This function scans JavaScript build output files and normalizes\n * excessive consecutive newlines.\n *\n * Any occurrence of **three or more consecutive line breaks**\n * (`\\n` or `\\r\\n`) will be collapsed into exactly **two newlines**,\n * ensuring cleaner and more readable build artifacts.\n *\n * - *The process is **non-destructive**:*\n * - Files are only rewritten if normalization is actually needed.\n * - Duplicate file paths are automatically deduplicated using {@link Set | `Set`}.\n *\n * - *Supported JavaScript output extensions:*\n * - `.js`.\n * - `.cjs`.\n * - `.mjs`.\n * - `.esm.js`.\n * - `.module.js`.\n *\n * @param pattern - Glob pattern(s) or a set of file paths pointing to JS build outputs.\n * @param options - Normalization configuration options.\n *\n * @example\n * ```ts\n * await normalizeJsBuildNewlines(\"dist/**\\/*.js\");\n * ```\n *\n * @example\n * ```ts\n * await normalizeJsBuildNewlines(\"dist/**\\/*.{js,cjs,mjs}\");\n * ```\n *\n * @example\n * ```ts\n * await normalizeJsBuildNewlines(\n * [\"dist/**\\/*.js\", \"build/**\\/*.mjs\", \"out/**\\/*.{js,mjs}\"],\n * );\n * ```\n *\n * @remarks\n * - This utility is intended for **post-build cleanup** and is safe to run\n * multiple times.\n * - Re-running it on already normalized files will result\n * in no changes.\n */\nexport const normalizeJsBuildNewlines = async (\n pattern: StringCollection,\n options: NormalizeJsBuildNewlinesOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_NJBN_OPTIONS.logLevel\n );\n\n try {\n const {\n __commandTitle,\n patternOptions = DEFAULT_NJBN_OPTIONS.patternOptions\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandNjbnIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_NJBN_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_NJBN_OPTIONS.patternOptions\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_NJBN_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Normalize New Lines\"\n });\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n const filesToClean = new Set<string>();\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (!/(\\r?\\n){3,}/.test(content)) continue;\n filesToClean.add(filePath);\n }\n\n let count = 0;\n for (const [, filePath] of filesToClean.entries()) {\n count++;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n const finalContent = content.replace(/(\\r?\\n){3,}/g, EOL);\n\n if (finalContent !== content) {\n try {\n await fsExtra.promises.writeFile(filePath, finalContent, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"New Line Normalized\",\n count: count,\n nameDirect: filePath\n });\n }\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (filesToClean.size > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Normalize New Lines\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Normalize New Lines\",\n reasonEndText: \"normalize\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Normalize New Lines\",\n error\n });\n }\n }\n};\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseRunCommandOptions } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { spawn, type SpawnOptions, ChildProcess } from \"node:child_process\";\n\nimport {\n assertValidCommand,\n spawnWithLifecycle,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n CommandProcessError,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isCommandProcessError\n} from \"./utils\";\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Options for executing a shell command via {@link runCommand | **`runCommand`**}.***\n * ----------------------------------------------------------------\n */\nexport type RunCommandOptions = BaseRunCommandOptions;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Execute a command and stream output to the current process.***\n * ----------------------------------------------------------------\n *\n * This utility spawns a child process using\n * {@link spawn | **`child_process.spawn`**}.\n *\n * By default, it forwards `stdout` and `stderr` directly to the parent\n * process using `stdio: \"inherit\"` (real-time streaming, no buffering).\n *\n * - *Behavior:*\n * - Uses `stdio: \"inherit\"` by default (can be overridden).\n * - Does **not** buffer output.\n * - Resolves only when the process exits with code `0`.\n * - Rejects if the process exits with a non-zero code,\n * is terminated by a signal, aborted, or times out.\n *\n * - *This function is designed for:*\n * - Build steps.\n * - Post-build hooks.\n * - CLI tooling.\n * - Long-running tasks (bundlers, compilers, CSS processors).\n *\n * @param {string} command\n * The executable or command to run.\n *\n * @param {readonly string[]} [args]\n * Arguments passed to the command.\n *\n * @param {RunCommandOptions} [options]\n * Optional execution configuration.\n *\n * @returns {Promise<ChildProcess>}\n * Resolves with the spawned {@link ChildProcess | **`ChildProcess`**} instance\n * **after the process exits successfully (exit code `0`)**.\n *\n * ----------------------------------------------------------------\n * #### Error handling\n *\n * When the process fails, the promise is rejected with a\n * {@link CommandProcessError | **`CommandProcessError`**}.\n *\n * - *Error metadata:*\n * - `reason` ➔ `\"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\"`.\n * - `exitCode` ➔ Exit code (if available).\n * - `signal` ➔ Termination signal (if any).\n * - `command` ➔ Executed command (plain string, no colors).\n *\n * - *Type narrowing:*\n * - Use `instanceof CommandProcessError` to safely access metadata.\n * - Or use {@link isCommandProcessError | **`isCommandProcessError`**} as a type guard.\n *\n * - *Notes:*\n * - Metadata is available programmatically (e.g. `err.reason`).\n * - Metadata is also included in the formatted stack output\n * for CLI readability.\n *\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (err instanceof CommandProcessError) {\n * if (err.reason === \"non-zero exit code\") {\n * console.error(\"Build failed with code:\", err.exitCode);\n * }\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(err.reason);\n * }\n * }\n * ```\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * await runCommand(\"pnpm\", [\"build\"]);\n * ```\n *\n * @example\n * ```ts\n * const child = await runCommand(\"node\", [\"script.js\"]);\n * console.log(child.pid);\n * ```\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n *\n * runCommand(\"pnpm\", [\"dev\"], {\n * signal: controller.signal\n * });\n *\n * controller.abort();\n * ```\n *\n * @example\n * ```ts\n * await runCommand(\"npm\", [\"run\", \"build\"], {\n * timeout: 5000\n * });\n * ```\n *\n * @remarks\n * - **Execution model:**\n * - Uses {@link spawn | **`spawn`**} instead of `exec` to avoid\n * output buffering and support long-running processes.\n *\n * - **Output handling:**\n * - Defaults to `stdio: \"inherit\"` (streams output to parent).\n * - If `stdio` is overridden (e.g. `\"pipe\"`), output will NOT be auto-forwarded.\n *\n * - **Shell execution:**\n * - Defaults to {@link RunCommandOptions.shell | **`shell: true`**}.\n * - Required on Windows to resolve commands like `pnpm`, `npm`, `git`, etc.\n * - When `shell: false`, the command must be:\n * - An absolute path, or\n * - A directly executable binary.\n *\n * - **Abort handling:**\n * - When `signal` is provided, the process will be terminated\n * with `SIGTERM` if aborted.\n *\n * - **Timeout handling:**\n * - When `timeout` is set, the process will be terminated\n * after the specified duration.\n * - `undefined` ➔ no timeout.\n * - ⚠️ `0` ➔ immediate termination.\n *\n * - **Common errors:**\n * - **`ENOENT`** ➔ command not found:\n * - Not installed\n * - Not in `PATH`\n * - `shell: false` with non-absolute command\n *\n * - **When NOT to use this utility:**\n * - When you need to capture output programmatically.\n * - When you need advanced shell features (`|`, `>`, `&&`).\n *\n * ***In those cases, consider using `exec` or a dedicated process runner.***\n */\nexport function runCommand(\n command: string,\n args: readonly string[]\n): Promise<ChildProcess>;\nexport function runCommand(\n command: string,\n options: RunCommandOptions\n): Promise<ChildProcess>;\nexport function runCommand(\n command: string,\n args: readonly string[],\n options: RunCommandOptions\n): Promise<ChildProcess>;\nexport function runCommand(\n command: string,\n argsOrOptions: readonly string[] | RunCommandOptions = [],\n maybeOptions: RunCommandOptions = {}\n): Promise<ChildProcess> {\n assertValidCommand(command);\n\n let args: readonly string[];\n let options: RunCommandOptions;\n\n if (Array.isArray(argsOrOptions)) {\n args = argsOrOptions;\n options = maybeOptions;\n } else {\n args = [];\n options = argsOrOptions as RunCommandOptions;\n }\n\n return new Promise((resolve, reject) => {\n const {\n shell = true,\n stdio = \"inherit\",\n argv0: _argv0,\n useColors = true,\n ...restOption\n } = options as RunCommandOptions & SpawnOptions;\n\n const { child, setupLifecycle, cmdStringPlain } = spawnWithLifecycle(\n command,\n args,\n {\n ...restOption,\n stdio,\n useColors,\n shell\n },\n {\n rejectOnNonZero: true\n }\n );\n\n setupLifecycle({\n onSuccess: (code) => {\n if (code === 0) {\n resolve(child);\n } else {\n reject(new Error(`${cmdStringPlain} exited with code ${code}`));\n }\n },\n onError: reject\n });\n });\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseRunCommandOptions } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { spawn, type SpawnOptions } from \"node:child_process\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { runCommand } from \"./runCommand\";\nimport {\n assertValidCommand,\n spawnWithLifecycle,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n CommandProcessError,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isCommandProcessError\n} from \"./utils\";\n\n//? Utils ----------------------------------------------------------------\nfunction normalizeChunk(chunk: unknown): string {\n if (typeof chunk === \"string\") return chunk;\n if (Buffer.isBuffer(chunk)) return chunk.toString(\"utf8\");\n\n return String(chunk);\n}\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Result returned by {@link runCommandCapture | `runCommandCapture`}.***\n * ----------------------------------------------------------------\n *\n * Represents the captured output and execution status of a command.\n *\n * - *Behavior:*\n * - `stdout` and `stderr` are fully buffered as UTF-8 strings.\n * - `exitCode` reflects the process exit status.\n * - `ok` indicates whether the command succeeded (`exitCode === 0`).\n */\nexport type RunCommandCaptureResult = {\n /** ----------------------------------------------------------------\n * * ***Captured standard output.***\n * ----------------------------------------------------------------\n *\n * The complete `stdout` output of the process as a UTF-8 string.\n *\n * - Trailing newlines may be trimmed depending on implementation.\n */\n stdout: string;\n\n /** ----------------------------------------------------------------\n * * ***Captured standard error output.***\n * ----------------------------------------------------------------\n *\n * The complete `stderr` output of the process as a UTF-8 string.\n *\n * - Useful for debugging or logging failures.\n */\n stderr: string;\n\n /** ----------------------------------------------------------------\n * * ***Process exit code.***\n * ----------------------------------------------------------------\n *\n * The numeric exit code returned by the process.\n *\n * - `0` usually indicates success.\n * - Non-zero values usually indicate failure.\n */\n exitCode: number;\n\n /** ----------------------------------------------------------------\n * * ***Execution success flag.***\n * ----------------------------------------------------------------\n *\n * Indicates whether the command completed successfully.\n *\n * Equivalent to:\n * ```ts\n * exitCode === 0\n * ```\n */\n ok: boolean;\n};\n\n/** ----------------------------------------------------------------\n * * ***Options for executing a shell command via {@link runCommandCapture | **`runCommandCapture`**}.***\n * ----------------------------------------------------------------\n */\nexport type RunCommandCaptureOptions = Omit<BaseRunCommandOptions, \"stdio\">;\n\n/** ----------------------------------------------------------------\n * * ***Execute a command and capture its output.***\n * ----------------------------------------------------------------\n *\n * This utility spawns a child process using\n * {@link spawn | **`child_process.spawn`**} and buffers its output.\n *\n * Unlike {@link runCommand | **`runCommand`**}, this function:\n * - Captures `stdout` and `stderr` into strings.\n * - Does **not** stream output to the parent process.\n * - Always resolves (even for non-zero exit codes).\n *\n * - *Behavior:*\n * - Uses `stdio: \"pipe\"` (output is buffered).\n * - Collects `stdout` and `stderr` as UTF-8 strings.\n * - Resolves when the process exits (regardless of exit code).\n * - Rejects only on:\n * - Spawn errors.\n * - Abort signals.\n * - Timeouts.\n * - Process termination by signal.\n *\n * - *This function is designed for:*\n * - Capturing CLI output.\n * - Running commands programmatically.\n * - Parsing results (JSON, text, etc.).\n * - Testing and scripting utilities.\n *\n * @param {string} command\n * The executable or command to run.\n *\n * @param {readonly string[]} [args]\n * Arguments passed to the command.\n *\n * @param {RunCommandCaptureOptions} [options]\n * Optional execution configuration.\n *\n * @returns {Promise<RunCommandCaptureResult>}\n * Resolves with an object containing:\n * - `stdout` ➔ captured standard output.\n * - `stderr` ➔ captured standard error.\n * - `exitCode` ➔ process exit code.\n * - `ok` ➔ `true` if exit code is `0`.\n *\n * ----------------------------------------------------------------\n * #### Error handling.\n *\n * This function does NOT reject on non-zero exit codes.\n * - Instead, use:\n * - `result.ok`.\n * - `result.exitCode`.\n *\n * - However, the promise WILL reject for:\n * - spawn errors.\n * - abort signals.\n * - timeouts.\n * - termination by signal.\n *\n * In those cases, the promise is rejected with a\n * {@link CommandProcessError | **`CommandProcessError`**}.\n *\n * - *Error metadata:*\n * - `reason` ➔ `\"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\"`.\n * - `exitCode` ➔ Exit code (if available).\n * - `signal` ➔ Termination signal (if any).\n * - `command` ➔ Executed command (plain string, no colors).\n *\n * - *Type narrowing:*\n * - Use `instanceof CommandProcessError` to safely access metadata.\n * - Or use {@link isCommandProcessError | **`isCommandProcessError`**} as a type guard.\n *\n * - *Notes:*\n * - `\"non-zero exit code\"` is NOT treated as an error in this function.\n * - Metadata is available programmatically (e.g. `err.reason`).\n * - Metadata is also included in the formatted stack output\n * for CLI readability.\n *\n * @example\n * ```ts\n * try {\n * await runCommandCapture(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (err instanceof CommandProcessError) {\n * console.error(\"Command failed:\", err.reason);\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * try {\n * await runCommandCapture(\"pnpm\", [\"dev\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(err.reason);\n * }\n * }\n * ```\n * ----------------------------------------------------------------\n * @example\n * ```ts\n * const result = await runCommandCapture(\"node\", [\"--version\"]);\n *\n * console.log(result.stdout);\n * ```\n *\n * @example\n * ```ts\n * const { stdout, ok } = await runCommandCapture(\"pnpm\", [\"build\"]);\n *\n * if (!ok) {\n * console.error(\"Build failed\");\n * }\n * ```\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n *\n * runCommandCapture(\"pnpm\", [\"dev\"], {\n * signal: controller.signal\n * });\n *\n * controller.abort();\n * ```\n *\n * @remarks\n * - **Execution model:**\n * - Uses {@link spawn | **`spawn`**} to avoid output size limits\n * imposed by `exec`.\n *\n * - **Output handling:**\n * - Always uses `stdio: \"pipe\"` (cannot be overridden).\n * - Output is buffered entirely in memory.\n *\n * - **Exit behavior:**\n * - Does NOT reject on non-zero exit codes.\n * - Use `result.ok` or `result.exitCode` to handle failures.\n *\n * - **Shell execution:**\n * - Defaults to `shell: true`.\n * - Same behavior and constraints as {@link runCommand | `runCommand`}.\n *\n * - **Abort & timeout:**\n * - Abort signals and timeouts will terminate the process\n * and reject the promise.\n *\n * - **When NOT to use this utility:**\n * - When output needs to be streamed in real-time\n * - When handling very large outputs (risk of high memory usage)\n *\n * ***In those cases, use {@link runCommand | `runCommand`}.***\n */\nexport function runCommandCapture(\n command: string,\n args: readonly string[]\n): Promise<RunCommandCaptureResult>;\nexport function runCommandCapture(\n command: string,\n options: RunCommandCaptureOptions\n): Promise<RunCommandCaptureResult>;\nexport function runCommandCapture(\n command: string,\n args: readonly string[],\n options: RunCommandCaptureOptions\n): Promise<RunCommandCaptureResult>;\nexport function runCommandCapture(\n command: string,\n argsOrOptions: readonly string[] | RunCommandCaptureOptions = [],\n maybeOptions: RunCommandCaptureOptions = {}\n): Promise<RunCommandCaptureResult> {\n assertValidCommand(command);\n\n let args: readonly string[];\n let options: RunCommandCaptureOptions;\n\n if (Array.isArray(argsOrOptions)) {\n args = argsOrOptions;\n options = maybeOptions;\n } else {\n args = [];\n options = argsOrOptions as RunCommandCaptureOptions;\n }\n\n const {\n shell = true,\n signal,\n timeout,\n forceKill,\n useColors = true,\n argv0: _argv0,\n ...restOption\n } = options as RunCommandCaptureOptions & SpawnOptions;\n\n return new Promise((resolve, reject) => {\n const { child, setupLifecycle } = spawnWithLifecycle(\n command,\n args,\n {\n ...restOption,\n stdio: \"pipe\",\n shell,\n signal,\n timeout,\n forceKill,\n useColors\n },\n {\n rejectOnNonZero: false\n }\n );\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout?.on(\"data\", (chunk: unknown) => {\n stdout += normalizeChunk(chunk);\n });\n\n child.stderr?.on(\"data\", (chunk: unknown) => {\n stderr += normalizeChunk(chunk);\n });\n\n setupLifecycle({\n onSuccess: (code) => {\n resolve({\n stdout: stdout.trimEnd(),\n stderr: stderr.trimEnd(),\n exitCode: code,\n ok: code === 0\n });\n },\n onError: reject\n });\n });\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { OverrideTypes } from \"@/_internal/types/extra\";\nimport type { BaseRunCommandOptions } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { spawn, ChildProcess } from \"node:child_process\";\n\nimport {\n isNonEmptyString,\n safeStableStringify\n} from \"@/_internal/utils/helper\";\n\nimport {\n EOL,\n formatOptionValue,\n joinLinesLoose,\n picocolors\n} from \"@/utils/client\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { runCommand } from \"./runCommand\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { runCommandCapture } from \"./runCommandCapture\";\n\n/** @internal Util for {@link runCommand | `runCommand`} and {@link runCommandCapture | `runCommandCapture`}. */\nexport function formatCommand(\n command: string,\n args: readonly string[],\n { useColors = true }: Pick<BaseRunCommandOptions, \"useColors\"> = {}\n) {\n const hasArgs = args.length > 0;\n const argsString = hasArgs\n ? args.map((a) => safeStableStringify(a)).join(\" \")\n : \"\";\n\n if (useColors) {\n const cmd = picocolors.cyanBright(command);\n return hasArgs ? `${cmd} ${picocolors.gray(argsString)}` : cmd;\n }\n\n return hasArgs ? `${command} ${argsString}` : command;\n}\n\n/** @internal Util for {@link runCommand | `runCommand`} and {@link runCommandCapture | `runCommandCapture`}. */\nexport function assertValidCommand(\n command: unknown,\n { useColors = true }: Pick<BaseRunCommandOptions, \"useColors\"> = {}\n): asserts command is string {\n if (typeof command !== \"string\") {\n const errorMsg = `Invalid command: expected a string, received ${safeStableStringify(command)}`;\n throw new TypeError(useColors ? picocolors.redBright(errorMsg) : errorMsg);\n }\n\n const trimmed = command.trim();\n\n if (trimmed.length === 0) {\n const errorMsg = \"Invalid command: command cannot be empty\";\n throw new Error(useColors ? picocolors.redBright(errorMsg) : errorMsg);\n }\n\n const hasSpace = trimmed.includes(\" \");\n const hasQuotes = /['\"`]/.test(trimmed);\n const hasShellOps = /[|&;<>(){}$]/.test(trimmed);\n\n if (hasSpace || hasQuotes || hasShellOps) {\n const [cmd, ...rest] = trimmed.split(/\\s+/);\n\n const errorMsg = joinLinesLoose(\n `Invalid command: \"${trimmed}\"`,\n \"Do not pass a full shell command.\",\n `Use arguments instead: runCommand(\"${cmd}\", ${safeStableStringify(rest)})`\n );\n\n throw new Error(useColors ? picocolors.redBright(errorMsg) : errorMsg);\n }\n}\n\n/** @internal Util for local {@link createProcessError | `createProcessError`}. */\nfunction stripInternalStack(lines: string[]) {\n const blacklist = [\n \"at new Promise (<anonymous>)\",\n \"Timeout.\",\n \"ChildProcess.\",\n \"node:events:\",\n \"createProcessError\",\n \"formatError\",\n \"spawnWithLifecycle\",\n \"setupLifecycle\",\n \"node:internal\"\n ];\n\n return lines.filter((line) => {\n if (blacklist.some((key) => line.includes(key))) {\n return false;\n }\n\n const isFileFrame = line.includes(\"/build-tools/dist/\");\n const hasFunctionName = /\\bat\\s+\\S+\\s+\\(/.test(line);\n\n if (isFileFrame && !hasFunctionName) {\n return false;\n }\n\n return true;\n });\n}\n\n/** @internal Util for local {@link spawnWithLifecycle | `spawnWithLifecycle`}. */\nfunction createProcessError(\n message: string,\n {\n reason,\n exitCode,\n signal,\n command\n }: {\n reason: CommandProcessError[\"reason\"];\n exitCode?: number;\n signal?: NodeJS.Signals | null;\n command: string;\n },\n baseStack?: string\n): CommandProcessError {\n const error = new CommandProcessError(message, {\n reason,\n exitCode,\n signal,\n command\n });\n\n const currentStack = error.stack?.split(EOL) ?? [];\n const base = baseStack?.split(EOL) ?? [];\n\n const [currentHead, ...currentRest] = currentStack;\n const [, ...baseRest] = base;\n\n const cleanedCurrent = stripInternalStack(currentRest);\n const cleanedBase = stripInternalStack(baseRest);\n\n command = command.trim();\n\n error.stack = [\n currentHead,\n ...cleanedCurrent,\n ...(cleanedBase.length ? [...cleanedBase] : [])\n ].join(EOL);\n\n // error.reason = reason;\n // error.exitCode = exitCode;\n // error.signal = signal;\n // error.command = command;\n\n Object.defineProperties(error, {\n reason: { value: reason, enumerable: false },\n exitCode: { value: exitCode, enumerable: false },\n signal: { value: signal, enumerable: false },\n command: { value: command, enumerable: false }\n });\n\n error.stack += joinLinesLoose(\n \"\",\n \"meta:\",\n ` reason: ${formatOptionValue(reason)}`,\n ` exitCode: ${formatOptionValue(exitCode ?? null)}`,\n ` signal: ${formatOptionValue(signal ?? null)}`,\n ` command: ${formatOptionValue(command)}`\n );\n\n return error;\n}\n\n/** ----------------------------------------------------------------\n * * ***Represents a command execution failure.***\n * ----------------------------------------------------------------\n *\n * This error is thrown when a spawned process fails during execution\n * via {@link runCommand | **`runCommand`**}, {@link runCommandCapture | **`runCommandCapture`**} or related utilities.\n *\n * It extends the native {@link Error | `Error`} class and provides structured\n * metadata describing the failure.\n *\n * ---\n *\n * - *Failure reasons:*\n * - `\"timeout\"` ➔ The process exceeded the configured timeout.\n * - `\"abort\"` ➔ The process was aborted via an `AbortSignal`.\n * - `\"signal\"` ➔ The process was terminated by an OS signal.\n * - `\"non-zero exit code\"` ➔ The process exited with a non-zero code.\n *\n * ---\n *\n * - *Metadata:*\n * - `reason` ➔ Reason for failure.\n * - `exitCode` ➔ Exit code (if available).\n * - `signal` ➔ Termination signal (if any).\n * - `command` ➔ Executed command (plain string, no colors).\n *\n * ---\n *\n * - *Behavior:*\n * - Thrown when a process fails in {@link runCommand | `runCommand`}.\n * - May also be thrown in {@link runCommandCapture | `runCommandCapture`} for:\n * - Spawn errors.\n * - Abort signals.\n * - Timeouts.\n * - Signal termination.\n * - Includes formatted stack output for CLI readability.\n * - Metadata is available for programmatic handling.\n *\n * ----------------------------------------------------------------\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (err instanceof CommandProcessError) {\n * console.error(\"Reason:\", err.reason);\n * console.error(\"Exit code:\", err.exitCode);\n * }\n * }\n * ```\n *\n * OR with `isCommandProcessError`.\n *\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(\"Reason:\", err.reason);\n * console.error(\"Exit code:\", err.exitCode);\n * }\n * }\n * ```\n *\n * @remarks\n * - This error is designed for both:\n * - Human-readable CLI output.\n * - Programmatic error handling.\n *\n * - Metadata properties are non-enumerable to avoid duplicate\n * output when logged via `console.error`.\n */\nexport class CommandProcessError extends Error {\n reason: \"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\";\n exitCode?: number;\n signal?: NodeJS.Signals | null;\n command: string;\n\n constructor(\n message: string,\n meta: {\n reason: CommandProcessError[\"reason\"];\n exitCode?: number;\n signal?: NodeJS.Signals | null;\n command: string;\n }\n ) {\n super(message);\n\n this.name = \"CommandProcessError\";\n\n this.reason = meta.reason;\n this.exitCode = meta.exitCode;\n this.signal = meta.signal;\n this.command = meta.command;\n }\n}\n\n/** ----------------------------------------------------------------\n * * ***Type guard for `CommandProcessError`.***\n * ----------------------------------------------------------------\n *\n * Utility to check whether a given value is an instance of\n * {@link CommandProcessError | `CommandProcessError`}.\n *\n * Useful when handling unknown errors in `try/catch` blocks.\n *\n * ----------------------------------------------------------------\n * @param err\n * The unknown error value to check.\n *\n * @returns\n * `true` if the value is a `CommandProcessError`, otherwise `false`.\n *\n * ----------------------------------------------------------------\n * @example\n * ```ts\n * try {\n * await runCommand(\"pnpm\", [\"build\"]);\n * } catch (err) {\n * if (isCommandProcessError(err)) {\n * console.error(err.reason);\n * console.error(err.exitCode);\n * }\n * }\n * ```\n */\nexport function isCommandProcessError(\n err: unknown\n): err is CommandProcessError {\n return err instanceof CommandProcessError;\n}\n\n/** @internal Util for {@link runCommand | `runCommand`} and {@link runCommandCapture | `runCommandCapture`}. */\nexport function spawnWithLifecycle(\n command: string,\n args: readonly string[],\n options: OverrideTypes<\n BaseRunCommandOptions,\n {\n /** Whether to run the command inside a shell.\n *\n * @default false\n */\n shell: boolean;\n }\n >,\n config?: {\n /** Custom error formatter.\n *\n * Allows overriding how errors are constructed.\n *\n * @param message The error message.\n * @param meta Additional metadata about the failure.\n *\n * @returns A custom error instance.\n *\n * @example\n * ```ts\n * formatError(msg, meta) {\n * return new MyError(msg, meta.reason);\n * }\n * ```\n */\n formatError?: (\n /** The error message. */\n message: string,\n /** Additional metadata about the failure. */\n meta: {\n /** Reason for failure. */\n reason: CommandProcessError[\"reason\"];\n /** Exit code if available. */\n exitCode?: number;\n /** Termination signal if any. */\n signal?: NodeJS.Signals | null;\n /** Executed command (plain, no colors). */\n command: string;\n\n args: readonly string[];\n /** Whether colors are enabled. */\n useColors: boolean;\n }\n ) => Error;\n\n /** Reject the process when exit code is non-zero.\n *\n * When enabled:\n * - Exit codes ≠ `0` will trigger `onError`.\n *\n * @default false\n */\n rejectOnNonZero?: boolean;\n }\n) {\n const {\n useColors = true,\n timeout,\n forceKill,\n signal: abortSignal,\n ...restOption\n } = options;\n\n const baseStack = new Error().stack;\n\n const cmdString = formatCommand(command, args, { useColors });\n const cmdStringPlain = formatCommand(command, args, { useColors: false });\n\n const formatError =\n config?.formatError ??\n ((msg, meta) => {\n const metaCommand = meta.command.trim();\n const argsString =\n meta.args.length > 0\n ? meta.args.map((a) => safeStableStringify(a).trim()).join(\" \")\n : \"\";\n\n if (meta.useColors) {\n const cmd = picocolors.magentaBright(metaCommand);\n const args = argsString ? picocolors.yellowBright(argsString) : \"\";\n\n return createProcessError(\n `${cmd}${args ? \" \" + args : \"\"} ${picocolors.redBright(msg)}`,\n {\n ...meta,\n command: `${metaCommand} ${argsString}`\n },\n baseStack\n );\n }\n\n return createProcessError(\n `${metaCommand}${isNonEmptyString(argsString) ? \" \" + argsString : \"\"} ${msg}`,\n {\n ...meta,\n command: `${metaCommand} ${argsString}`\n },\n baseStack\n );\n });\n\n const rejectOnNonZero = config?.rejectOnNonZero ?? false;\n\n const child = spawn(command, [...args], restOption);\n\n let finished = false;\n\n const kill = () => {\n try {\n if (process.platform === \"win32\") {\n if (forceKill && child.pid) {\n spawn(\"taskkill\", [\"/pid\", String(child.pid), \"/f\", \"/t\"]);\n } else {\n child.kill();\n }\n } else {\n child.kill(\"SIGTERM\");\n }\n } catch {\n // noop\n }\n };\n\n return {\n /** ----------------------------------------------------------------\n * * ***The spawned child process instance.***\n * ----------------------------------------------------------------\n *\n * Direct access to the underlying {@link ChildProcess | `ChildProcess`}.\n *\n * Can be used for:\n * - Accessing `pid`\n * - Listening to additional events\n * - Manual stream handling (`stdout`, `stderr`)\n */\n child,\n\n /** ----------------------------------------------------------------\n * * ***Terminate the running process.***\n * ----------------------------------------------------------------\n *\n * Sends a termination signal to the process:\n * - On Windows:\n * - Uses `taskkill /f /t` when `forceKill` is enabled.\n * - Otherwise uses `child.kill()`.\n * - On other platforms:\n * - Sends `SIGTERM`.\n *\n * Safe to call multiple times.\n */\n kill,\n\n /** ----------------------------------------------------------------\n * * ***Formatted command string.***\n * ----------------------------------------------------------------\n *\n * Human-readable representation of the executed command.\n *\n * - May include colors depending on configuration.\n * - Intended for logging and debugging.\n *\n * @example\n * ```ts\n * console.log(cmdString);\n * ```\n */\n cmdString,\n\n /** ----------------------------------------------------------------\n * * ***Formatted command string (plain, no colors).***\n * ----------------------------------------------------------------\n *\n * Human-readable representation of the executed command\n * without any color formatting.\n *\n * - Safe for logging, serialization, and error metadata.\n * - Used internally for structured error information.\n * - Unlike `cmdString`, this value never includes ANSI color codes.\n *\n * @example\n * ```ts\n * console.log(cmdStringPlain);\n * ```\n */\n cmdStringPlain,\n\n /** ----------------------------------------------------------------\n * * ***Attach lifecycle handlers to the spawned process.***\n * ----------------------------------------------------------------\n *\n * Registers callbacks to handle the process lifecycle in a safe,\n * single-resolution manner.\n *\n * This method ensures that only one terminal state is triggered:\n * either success or failure.\n *\n * ---\n *\n * #### Success\n * Calls `onSuccess(code)` when:\n * - The process exits normally.\n * - No termination signal is received.\n * - Exit code is `0`, or `rejectOnNonZero` is disabled.\n *\n * ---\n *\n * #### Failure\n * Calls `onError(error)` when:\n * - A spawn error occurs.\n * - The process is aborted via `AbortSignal`.\n * - The process is terminated by a signal.\n * - A timeout is reached.\n * - Exit code is non-zero and `rejectOnNonZero` is enabled.\n *\n * ---\n *\n * #### Error metadata\n * The error may include additional properties:\n * - `reason` ➔ `\"timeout\" | \"abort\" | \"signal\" | \"non-zero exit code\"`.\n * - `exitCode` ➔ exit code (if available).\n * - `signal` ➔ termination signal (if any).\n * - `command` ➔ executed command (plain, no colors).\n *\n * ---\n *\n * @param handlers Lifecycle callbacks.\n * @param handlers.onSuccess Called when the process completes successfully.\n * @param handlers.onError Called when the process fails or is terminated.\n *\n * @example\n * ```ts\n * const { setupLifecycle } = spawnWithLifecycle(\"node\", [\"script.js\"], options);\n *\n * setupLifecycle({\n * onSuccess(code) {\n * console.log(\"Done:\", code);\n * },\n * onError(err) {\n * console.error(\"Failed:\", err);\n * }\n * });\n * ```\n */\n setupLifecycle({\n onSuccess,\n onError\n }: {\n /** ----------------------------------------------------------------\n * * ***Called when the process completes successfully.***\n * ----------------------------------------------------------------\n *\n * Invoked when:\n * - The process exits normally.\n * - No termination signal is received.\n * - Exit code is `0`, or `rejectOnNonZero` is disabled.\n *\n * @param code The process exit code.\n */\n onSuccess: (\n /** The process exit code. */\n code: number\n ) => void;\n\n /** ----------------------------------------------------------------\n * * ***Called when the process fails or is terminated.***\n * ----------------------------------------------------------------\n *\n * Invoked when:\n * - A spawn error occurs.\n * - The process is aborted.\n * - The process is terminated by a signal.\n * - A timeout is reached.\n * - Exit code is non-zero and `rejectOnNonZero` is enabled.\n *\n * The error may include additional metadata such as:\n * - `reason`.\n * - `exitCode`.\n * - `signal`.\n * - `command`.\n *\n * @param error The error describing the failure.\n */\n onError: (\n /** The error describing the failure. */\n error: CommandProcessError | Error\n ) => void;\n }) {\n const timeoutId =\n timeout != null\n ? setTimeout(() => {\n if (finished) return;\n kill();\n fail(\n formatError(`timed out after ${timeout}ms`, {\n reason: \"timeout\",\n command,\n args,\n useColors\n })\n );\n }, timeout)\n : null;\n\n const cleanup = () => {\n finished = true;\n if (abortSignal) {\n abortSignal.removeEventListener(\"abort\", onAbort);\n }\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n const fail = (err: Error) => {\n if (finished) return;\n cleanup();\n onError(err);\n };\n\n const succeed = (code: number) => {\n if (finished) return;\n cleanup();\n onSuccess(code);\n };\n\n const onAbort = () => {\n if (finished) return;\n kill();\n fail(\n formatError(\"aborted by signal\", {\n reason: \"abort\",\n command,\n args,\n useColors\n })\n );\n };\n\n if (abortSignal) {\n if (abortSignal.aborted) {\n onAbort();\n return;\n }\n abortSignal.addEventListener(\"abort\", onAbort);\n }\n\n child.once(\"error\", fail);\n\n child.once(\"close\", (code, signal) => {\n if (signal) {\n fail(\n formatError(`terminated by ${signal}`, {\n reason: \"signal\",\n signal,\n exitCode: code ?? undefined,\n command,\n args,\n useColors\n })\n );\n return;\n }\n\n const exitCode = code ?? 0;\n\n if (rejectOnNonZero && exitCode !== 0) {\n fail(\n formatError(`exited with code ${exitCode}`, {\n reason: \"non-zero exit code\",\n exitCode,\n command,\n args,\n useColors\n })\n );\n return;\n }\n\n succeed(exitCode);\n });\n }\n };\n}\n","import \"@rzl-zone/node-only\";\n\nimport type { BaseOptions, PatternOptions, StringCollection } from \"@/types\";\n\nimport * as acorn from \"acorn\";\n\nimport {\n defaultPatternOptions,\n type PatternRuntimePolicy,\n resolvePatternOptions,\n sourceOfPatternOptions\n} from \"@/_internal/libs/fast-globe-options\";\n\nimport {\n IMPORTANT_COMMENT,\n isTargetComment,\n JS_OUTPUT_FILE_RE,\n REGION_RE,\n shouldRemoveDocRuntime,\n SOURCE_MAP_RE\n} from \"@/_internal/utils/source\";\nimport {\n canLog,\n DEFAULT_LOG_LEVEL,\n resolveLogVerbosity,\n VERBOSE_LOG\n} from \"@/_internal/utils/log-level\";\nimport { BUILD_LOGGER } from \"@/_internal/utils/logger-builder\";\nimport { isNonEmptyString, toStringSet } from \"@/_internal/utils/helper\";\n\nimport { fastGlob, fsExtra } from \"@/utils/server\";\nimport { EOL, joinLinesLoose } from \"@/utils/helper/formatter\";\n\nimport { CommandIdentity } from \"@/commander-kit/identity\";\n\n//? Constant -------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Default Pattern Policy for **strip js comments** operations.***\n * ----------------------------------------------------------------\n *\n * Defines the runtime behavior for pattern resolution used by:\n * - {@link stripJsComments | **`strip-js-comments`**}.\n *\n * @remarks\n * - `filesOnly`: Ensures only files are matched.\n * - `forceUnique`: Deduplicates matched results.\n */\nexport const DEFAULT_SJC_PATTERN_POLICY = {\n filesOnly: true,\n forceUnique: true\n} as const satisfies PatternRuntimePolicy<boolean, boolean>;\n\n/** ----------------------------------------------------------------\n * * ***Resolved Pattern Options for **strip js comments** operations.***\n * ----------------------------------------------------------------\n *\n * Pattern options used by:\n * - {@link stripJsComments | **`strip-js-comments`**}.\n */\nexport const resolvedSjcPatternOption: PatternOptions<true, true> =\n resolvePatternOptions(defaultPatternOptions, DEFAULT_SJC_PATTERN_POLICY);\n\n/** @internal Default ***Options*** for {@link stripJsComments | **`strip-js-comments`**}. */\nconst DEFAULT_SJC_OPTIONS = {\n removeSourceMap: false,\n sourceType: \"module\",\n removeRegion: true,\n ecmaVersion: \"latest\",\n patternOptions: resolvedSjcPatternOption,\n logLevel: DEFAULT_LOG_LEVEL\n} as const satisfies StripJsCommentsOptions;\n\n/** @internal Constant for {@link stripJsComments | **`strip-js-comments`**}. */\nconst VALID_SOURCE_TYPE = new Set([\"module\", \"script\", \"commonjs\"]);\nconst VALID_ECMA_VERSION = new Set([\n \"latest\",\n 3,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 2015,\n 2016,\n 2017,\n 2018,\n 2019,\n 2020,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026\n]);\n\nconst REGION_COMMENT_RE = /^#(?:end)?region\\b/i;\nconst SOURCE_MAP_COMMENT_RE = /^[#@]\\s*sourceMappingURL=/;\n\n//? Utils ----------------------------------------------------------------\n/** @internal Util for {@link stripJsComments | **`strip-js-comments`**}. */\nfunction normalizeNewlines(code: string) {\n return code.replace(/[ \\t]+\\n/g, EOL).replace(/\\n\\s*\\n+/g, EOL);\n}\n/** @internal Util for {@link stripJsComments | **`strip-js-comments`**}. */\nfunction stripComments(\n code: string,\n {\n removeRegion,\n removeSourceMap,\n sourceType,\n ecmaVersion\n }: StripJsCommentsOptions\n) {\n const comments: [number, number][] = [];\n\n if (sourceType == null || !VALID_SOURCE_TYPE.has(sourceType)) {\n sourceType = DEFAULT_SJC_OPTIONS.sourceType;\n }\n if (ecmaVersion == null || !VALID_ECMA_VERSION.has(ecmaVersion)) {\n ecmaVersion = DEFAULT_SJC_OPTIONS.ecmaVersion;\n }\n\n try {\n acorn.parse(code, {\n sourceType,\n ecmaVersion,\n allowHashBang: true,\n onComment(block, text, start, end) {\n if (!block) {\n const value = text.trim();\n\n if (\n !REGION_COMMENT_RE.test(value) &&\n !SOURCE_MAP_COMMENT_RE.test(value)\n ) {\n return;\n }\n }\n\n const value = text.trim();\n\n const forceRemove = shouldRemoveDocRuntime(value);\n\n if (forceRemove === true) {\n comments.push([start, end]);\n return;\n }\n\n if (forceRemove === false) return;\n\n if (IMPORTANT_COMMENT.test(value)) return;\n\n // source map\n if (SOURCE_MAP_COMMENT_RE.test(value)) {\n if (removeSourceMap) comments.push([start, end]);\n return;\n }\n\n // region\n if (REGION_COMMENT_RE.test(value)) {\n if (removeRegion) comments.push([start, end]);\n return;\n }\n\n // default: ONLY block comments\n if (block) {\n comments.push([start, end]);\n }\n }\n });\n } catch {\n return code;\n }\n\n if (!comments.length) return code;\n\n const parts: string[] = [];\n let last = 0;\n\n for (const [start, end] of comments) {\n parts.push(code.slice(last, start));\n last = end;\n }\n\n parts.push(code.slice(last));\n\n const result = parts.join(\"\");\n\n const lines = result.split(/\\r?\\n/);\n const seenSourceMap = new Set<string>();\n const cleanedLines = lines\n .filter((line) => {\n if (SOURCE_MAP_RE.test(line)) {\n const key = line.trim();\n\n if (seenSourceMap.has(key)) return false;\n\n seenSourceMap.add(key);\n\n if (removeSourceMap) return false;\n\n return true;\n }\n\n if (removeRegion && REGION_RE.test(line)) return false;\n\n if (isTargetComment(line, { removeSourceMap, removeRegion }))\n return false;\n\n // if (\n // removeAdjacentEmptyLines &&\n // /^\\s*$/.test(line) &&\n // isAdjacentToTarget(arr, i, { removeSourceMap, removeRegion })\n // ) {\n // return false;\n // }\n\n return true;\n })\n .map((line) => {\n let out = line\n // remove source path comments\n .replace(\n /^[ \\t]*\\/\\/\\s*(?:\\.\\.\\/|\\.\\/)*[^ \\n]*?(?:src|node_modules)\\/[^\\n]*\\n?/gm,\n \"\"\n )\n // remove eslint comments\n .replace(/\\/\\/\\s*eslint[^\\n]*/g, \"\");\n\n // if (removeSourceMap) {\n // out = out.replace(/\\/\\/[#@]\\s*sourceMappingURL=[^\\n]*/g, \"\");\n // }\n\n out = out.replace(\n /(\\/\\/[#@]\\s*sourceMappingURL=[^\\r\\n]*)(?:\\r?\\n\\1)+/g,\n \"$1\"\n );\n\n return out;\n });\n\n return cleanedLines.join(EOL);\n}\n\n//? Identity -------------------------------------------------------------\n/** Command identity associated with {@link stripJsComments | **`strip-js-comments`**}. */\nexport const commandSjcIdentity: CommandIdentity = new CommandIdentity({\n defaultCommandName: \"strip-js-comments\"\n});\n\n//? Types ----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Configuration options for {@link stripJsComments | `strip-js-comment`}.***\n * ----------------------------------------------------------------\n */\nexport type StripJsCommentsOptions = {\n /** ----------------------------------------------------------------\n * * ***Whether to remove `sourceMappingURL` comments.***\n * ----------------------------------------------------------------\n *\n * @default false\n */\n removeSourceMap?: boolean;\n /** ----------------------------------------------------------------\n * * ***Whether to remove `region` comments.***\n * ----------------------------------------------------------------\n *\n * @default true\n */\n removeRegion?: boolean;\n\n /** ----------------------------------------------------------------\n * * ***Parsing mode used when analyzing JavaScript code.***\n * ----------------------------------------------------------------\n *\n * Determines how the source file should be interpreted by the parser.\n * This affects strict mode behavior and how `import` / `export`\n * statements are handled.\n *\n *\n * Possible values:\n *\n * - `\"module\"` **(default)** ➔ Parse as an ES module.\n * - `\"script\"` ➔ Parse as a classic script.\n * - `\"commonjs\"` ➔ Parse using CommonJS semantics.\n *\n * ----------------------------------------------------------------\n *\n * ⚠️ Fallback to default, is invalid input.\n *\n *\n * @default \"module\"\n *\n */\n sourceType?: acorn.Options[\"sourceType\"];\n\n /** ----------------------------------------------------------------\n * * ***ECMAScript version used for parsing.***\n * ----------------------------------------------------------------\n *\n * Specifies the ECMAScript syntax version supported by the parser.\n * This determines which language features are recognized during parsing.\n *\n * Examples:\n *\n * - `5` ➔ ES5\n * - `2020` ➔ ES2020\n * - `\"latest\"` ➔ Latest supported version\n *\n * ----------------------------------------------------------------\n *\n * ⚠️ Invalid values will fallback to the default behavior.\n *\n * @default \"latest\"\n */\n ecmaVersion?: acorn.ecmaVersion;\n} & BaseOptions<\n typeof DEFAULT_SJC_PATTERN_POLICY.filesOnly,\n typeof DEFAULT_SJC_PATTERN_POLICY.forceUnique\n>;\n\n//? Main -----------------------------------------------------------------\n/** ----------------------------------------------------------------\n * * ***Strip comments from JavaScript output files.***\n * ----------------------------------------------------------------\n *\n * Scans files matching the provided glob pattern(s) and removes\n * non-essential comments from JavaScript output.\n *\n * The process preserves important comments such as:\n *\n * - `/*! ... *\\/` (bang / license comments)\n * - `@license`\n * - `@preserve`\n * - `@copyright`\n * - `@cc_on`\n * - `@__PURE__`\n * - `@__INLINE__`\n * - `@__NOINLINE__`\n * - `@__NO_SIDE_EFFECTS__`\n *\n * unless explicitly overridden by the `@removeDocRuntime` directive.\n *\n * ----------------------------------------------------------------\n *\n * **Supported Features**\n *\n * - Removes regular block comments from compiled JS files.\n * - Optionally removes `sourceMappingURL` comments.\n * - Optionally removes `region` comments such as:\n * - `// #region`\n * - `// #endregion`\n * - Supports runtime directives inside comments:\n * - `@keepDocRuntime`\n * - `@removeDocRuntime`\n *\n * ----------------------------------------------------------------\n *\n * @param pattern - Glob pattern(s) or a set of patterns pointing to\n * files whose comments should be stripped.\n *\n * @param options - Optional configuration controlling how comments\n * are removed.\n *\n * ----------------------------------------------------------------\n *\n * @example\n * ```ts\n * await stripJsComments(\"dist/**\\/*.js\");\n * ```\n *\n * @example\n * ```ts\n * await stripJsComments([\"dist/**\\/*.js\", \"build/**\\/*.mjs\"], {\n * removeSourceMap: true,\n * removeRegion: true\n * });\n * ```\n *\n * ----------------------------------------------------------------\n *\n * @removeDocRuntime\n */\nexport const stripJsComments = async (\n pattern: StringCollection,\n options: StripJsCommentsOptions = {}\n): Promise<void> => {\n const loggerLevel = resolveLogVerbosity(\n options,\n DEFAULT_SJC_OPTIONS.logLevel\n );\n\n try {\n const {\n patternOptions = DEFAULT_SJC_OPTIONS.patternOptions,\n removeSourceMap = DEFAULT_SJC_OPTIONS.removeSourceMap,\n removeRegion = DEFAULT_SJC_OPTIONS.removeRegion,\n sourceType = DEFAULT_SJC_OPTIONS.sourceType,\n ecmaVersion = DEFAULT_SJC_OPTIONS.ecmaVersion,\n __commandTitle\n } = options;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n console.log(\n joinLinesLoose(\n isNonEmptyString(__commandTitle)\n ? __commandTitle\n : commandSjcIdentity.utility(),\n \"\"\n )\n );\n }\n\n const patterns = [...toStringSet(pattern)];\n const cleanPatternOptions = resolvePatternOptions(\n patternOptions,\n DEFAULT_SJC_PATTERN_POLICY\n );\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.SECTION(\"Options\", { icon: \"⚙️ \" });\n\n BUILD_LOGGER.OPTIONS(\n \"pattern\",\n patterns,\n BUILD_LOGGER.SOURCE_OF(patterns, undefined),\n true\n );\n\n BUILD_LOGGER.OPTIONS(\n \"options.patternOptions\",\n cleanPatternOptions,\n sourceOfPatternOptions(\n cleanPatternOptions,\n DEFAULT_SJC_OPTIONS.patternOptions\n )\n );\n\n BUILD_LOGGER.OPTIONS(\n \"options.removeSourceMap\",\n removeSourceMap,\n BUILD_LOGGER.SOURCE_OF(\n removeSourceMap,\n DEFAULT_SJC_OPTIONS.removeSourceMap\n )\n );\n BUILD_LOGGER.OPTIONS(\n \"options.removeRegion\",\n removeRegion,\n BUILD_LOGGER.SOURCE_OF(removeRegion, DEFAULT_SJC_OPTIONS.removeRegion)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.sourceType\",\n sourceType,\n BUILD_LOGGER.SOURCE_OF(sourceType, DEFAULT_SJC_OPTIONS.sourceType)\n );\n BUILD_LOGGER.OPTIONS(\n \"options.ecmaVersion\",\n ecmaVersion,\n BUILD_LOGGER.SOURCE_OF(ecmaVersion, DEFAULT_SJC_OPTIONS.ecmaVersion)\n );\n\n BUILD_LOGGER.OPTIONS(\n \"options.logLevel\",\n loggerLevel,\n BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_SJC_OPTIONS.logLevel)\n );\n\n BUILD_LOGGER.NEW_LINE();\n\n BUILD_LOGGER.ON_STARTING({\n actionName: \"Stripping JS Comments\"\n });\n }\n\n const files = (await fastGlob(patterns, cleanPatternOptions)).sort();\n\n let count = 0;\n\n for (const filePath of files) {\n if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;\n\n let content: string;\n\n try {\n content = await fsExtra.promises.readFile(filePath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n let output = content;\n\n if (!/\\/[/*]/.test(content)) continue;\n\n output = stripComments(content, {\n removeRegion,\n removeSourceMap,\n sourceType,\n ecmaVersion\n });\n output = normalizeNewlines(output).trim() + EOL;\n\n if (output !== content) {\n try {\n await fsExtra.promises.writeFile(filePath, output, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n\n count++;\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n BUILD_LOGGER.ON_PROCESS({\n actionName: \"JS Comment Stripping\",\n count,\n nameDirect: filePath\n });\n }\n }\n }\n\n if (canLog(loggerLevel, VERBOSE_LOG)) {\n if (count > 0) {\n BUILD_LOGGER.ON_FINISH({\n actionName: \"Stripping JS Comments\",\n count\n });\n } else {\n BUILD_LOGGER.ON_SKIPPING({\n actionName: \"Stripping JS Comments\",\n reasonType: \"file\",\n reasonEndText: \"processing\"\n });\n }\n }\n } catch (error) {\n if (loggerLevel !== \"silent\") {\n BUILD_LOGGER.ON_ERROR({\n actionName: \"Stripping JS Comments\",\n error\n });\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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