@socketsecurity/lib 2.8.2 → 2.8.4
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/CHANGELOG.md +21 -0
- package/dist/dlx-binary.d.ts +22 -0
- package/dist/dlx-binary.js +1 -1
- package/dist/dlx-binary.js.map +3 -3
- package/dist/logger.js +1 -1
- package/dist/logger.js.map +3 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,27 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [2.8.4](https://github.com/SocketDev/socket-lib/releases/tag/v2.8.4) - 2025-10-30
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **DLX binary helper functions mirror dlx-package pattern**
|
|
13
|
+
- `downloadBinary`: Download binary with caching (without execution)
|
|
14
|
+
- `executeBinary`: Execute cached binary without re-downloading
|
|
15
|
+
- Renamed internal `downloadBinary` to `downloadBinaryFile` to avoid naming conflicts
|
|
16
|
+
- Maintains feature parity with `downloadPackage`/`executePackage` from dlx-package
|
|
17
|
+
|
|
18
|
+
## [2.8.3](https://github.com/SocketDev/socket-lib/releases/tag/v2.8.3) - 2025-10-30
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- **Logger now fully defers all console access for Node.js internal bootstrap compatibility**: Completed lazy initialization to prevent ERR_CONSOLE_WRITABLE_STREAM errors
|
|
23
|
+
- Deferred `Object.getOwnPropertySymbols(console)` call until first logger use
|
|
24
|
+
- Deferred `kGroupIndentationWidth` symbol lookup
|
|
25
|
+
- Deferred `Object.entries(console)` and prototype method initialization
|
|
26
|
+
- Ensures logger can be safely imported in Node.js internal bootstrap contexts (e.g., `lib/internal/bootstrap/*.js`) before stdout is initialized
|
|
27
|
+
- Builds on v2.8.2 console deferring to complete early bootstrap compatibility
|
|
28
|
+
|
|
8
29
|
## [2.8.2](https://github.com/SocketDev/socket-lib/releases/tag/v2.8.2) - 2025-10-29
|
|
9
30
|
|
|
10
31
|
### Changed
|
package/dist/dlx-binary.d.ts
CHANGED
|
@@ -30,6 +30,28 @@ export declare function cleanDlxCache(maxAge?: number): Promise<number>;
|
|
|
30
30
|
* Download and execute a binary from a URL with caching.
|
|
31
31
|
*/
|
|
32
32
|
export declare function dlxBinary(args: readonly string[] | string[], options?: DlxBinaryOptions | undefined, spawnExtra?: SpawnExtra | undefined): Promise<DlxBinaryResult>;
|
|
33
|
+
/**
|
|
34
|
+
* Download a binary from a URL with caching (without execution).
|
|
35
|
+
* Similar to downloadPackage from dlx-package.
|
|
36
|
+
*
|
|
37
|
+
* @returns Object containing the path to the cached binary and whether it was downloaded
|
|
38
|
+
*/
|
|
39
|
+
export declare function downloadBinary(options: Omit<DlxBinaryOptions, 'spawnOptions'>): Promise<{
|
|
40
|
+
binaryPath: string;
|
|
41
|
+
downloaded: boolean;
|
|
42
|
+
}>;
|
|
43
|
+
/**
|
|
44
|
+
* Execute a cached binary without re-downloading.
|
|
45
|
+
* Similar to executePackage from dlx-package.
|
|
46
|
+
* Binary must have been previously downloaded via downloadBinary or dlxBinary.
|
|
47
|
+
*
|
|
48
|
+
* @param binaryPath Path to the cached binary (from downloadBinary result)
|
|
49
|
+
* @param args Arguments to pass to the binary
|
|
50
|
+
* @param spawnOptions Spawn options for execution
|
|
51
|
+
* @param spawnExtra Extra spawn configuration
|
|
52
|
+
* @returns The spawn promise for the running process
|
|
53
|
+
*/
|
|
54
|
+
export declare function executeBinary(binaryPath: string, args: readonly string[] | string[], spawnOptions?: SpawnOptions | undefined, spawnExtra?: SpawnExtra | undefined): ReturnType<typeof spawn>;
|
|
33
55
|
/**
|
|
34
56
|
* Get the DLX binary cache directory path.
|
|
35
57
|
* Returns normalized path for cross-platform compatibility.
|
package/dist/dlx-binary.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var z=Object.create;var k=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var X=(t,n)=>{for(var e in n)k(t,e,{get:n[e],enumerable:!0})},S=(t,n,e,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of q(n))!W.call(t,r)&&r!==e&&k(t,r,{get:()=>n[r],enumerable:!(i=Y(n,r))||i.enumerable});return t};var j=(t,n,e)=>(e=t!=null?z(K(t)):{},S(n||!t||!t.__esModule?k(e,"default",{value:t,enumerable:!0}):e,t)),J=t=>S(k({},"__esModule",{value:!0}),t);var Z={};X(Z,{cleanDlxCache:()=>M,dlxBinary:()=>V,downloadBinary:()=>G,executeBinary:()=>Q,getDlxCachePath:()=>D,listDlxCache:()=>U});module.exports=J(Z);var B=require("node:crypto"),s=require("node:fs"),b=j(require("node:os")),l=j(require("node:path")),_=require("#constants/platform"),$=require("./dlx"),C=require("./download-lock"),f=require("./fs"),R=require("./objects"),A=require("./path"),v=require("./paths"),O=require("./spawn");function x(t){return l.default.join(t,".dlx-metadata.json")}async function E(t,n){try{const e=x(t);if(!(0,s.existsSync)(e))return!1;const i=await(0,f.readJson)(e,{throws:!1});if(!(0,R.isObjectObject)(i))return!1;const r=Date.now(),a=i.timestamp;return typeof a!="number"||a<=0?!1:r-a<n}catch{return!1}}async function N(t,n,e){await(0,C.downloadWithLock)(t,n,{staleTimeout:1e4,lockTimeout:12e4});const i=await s.promises.readFile(n),r=(0,B.createHash)("sha256");r.update(i);const a=r.digest("hex");if(e&&a!==e)throw await(0,f.safeDelete)(n),new Error(`Checksum mismatch: expected ${e}, got ${a}`);return _.WIN32||await s.promises.chmod(n,493),a}async function I(t,n,e){const i=x(t),r={arch:b.default.arch(),checksum:e,platform:b.default.platform(),timestamp:Date.now(),url:n,version:"1.0.0"};await s.promises.writeFile(i,JSON.stringify(r,null,2))}async function M(t=require("#constants/time").DLX_BINARY_CACHE_TTL){const n=D();if(!(0,s.existsSync)(n))return 0;let e=0;const i=Date.now(),r=await s.promises.readdir(n);for(const a of r){const o=l.default.join(n,a),c=x(o);try{if(!await(0,f.isDir)(o))continue;const u=await(0,f.readJson)(c,{throws:!1});if(!u||typeof u!="object"||Array.isArray(u))continue;const p=u.timestamp;(typeof p=="number"&&p>0?i-p:Number.POSITIVE_INFINITY)>t&&(await(0,f.safeDelete)(o,{force:!0,recursive:!0}),e+=1)}catch{try{(await s.promises.readdir(o)).length||(await(0,f.safeDelete)(o),e+=1)}catch{}}}return e}async function V(t,n,e){const{cacheTtl:i=require("#constants/time").DLX_BINARY_CACHE_TTL,checksum:r,force:a=!1,name:o,spawnOptions:c,url:u}={__proto__:null,...n},p=D(),m=o||`binary-${process.platform}-${b.default.arch()}`,w=`${u}:${m}`,d=(0,$.generateCacheKey)(w),h=l.default.join(p,d),P=(0,A.normalizePath)(l.default.join(h,m));let y=!1,T=r;if(!a&&(0,s.existsSync)(h)&&await E(h,i))try{const F=x(h),g=await(0,f.readJson)(F,{throws:!1});g&&typeof g=="object"&&!Array.isArray(g)&&typeof g.checksum=="string"?T=g.checksum:y=!0}catch{y=!0}else y=!0;y&&(await s.promises.mkdir(h,{recursive:!0}),T=await N(u,P,r),await I(h,u,T||""));const H=_.WIN32&&/\.(?:bat|cmd|ps1)$/i.test(P)?{...c,env:{...c?.env,PATH:`${h}${l.default.delimiter}${process.env.PATH||""}`},shell:!0}:c,L=(0,O.spawn)(P,t,H,e);return{binaryPath:P,downloaded:y,spawnPromise:L}}async function G(t){const{cacheTtl:n=require("#constants/time").DLX_BINARY_CACHE_TTL,checksum:e,force:i=!1,name:r,url:a}={__proto__:null,...t},o=D(),c=r||`binary-${process.platform}-${b.default.arch()}`,u=`${a}:${c}`,p=(0,$.generateCacheKey)(u),m=l.default.join(o,p),w=(0,A.normalizePath)(l.default.join(m,c));let d=!1;if(!i&&(0,s.existsSync)(m)&&await E(m,n))d=!1;else{await s.promises.mkdir(m,{recursive:!0});const h=await N(a,w,e);await I(m,a,h||""),d=!0}return{binaryPath:w,downloaded:d}}function Q(t,n,e,i){const r=_.WIN32&&/\.(?:bat|cmd|ps1)$/i.test(t),a=l.default.dirname(t),o=r?{...e,env:{...e?.env,PATH:`${a}${l.default.delimiter}${process.env.PATH||""}`},shell:!0}:e;return(0,O.spawn)(t,n,o,i)}function D(){return(0,v.getSocketDlxDir)()}async function U(){const t=D();if(!(0,s.existsSync)(t))return[];const n=[],e=Date.now(),i=await s.promises.readdir(t);for(const r of i){const a=l.default.join(t,r);try{if(!await(0,f.isDir)(a))continue;const o=x(a),c=await(0,f.readJson)(o,{throws:!1});if(!c||typeof c!="object"||Array.isArray(c))continue;const p=(await s.promises.readdir(a)).find(m=>!m.startsWith("."));if(p){const m=l.default.join(a,p),w=await s.promises.stat(m),d=c;n.push({age:e-(d.timestamp||0),arch:d.arch||"unknown",checksum:d.checksum||"",name:p,platform:d.platform||"unknown",size:w.size,url:d.url||""})}}catch{}}return n}0&&(module.exports={cleanDlxCache,dlxBinary,downloadBinary,executeBinary,getDlxCachePath,listDlxCache});
|
|
3
3
|
//# sourceMappingURL=dlx-binary.js.map
|
package/dist/dlx-binary.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/dlx-binary.ts"],
|
|
4
|
-
"sourcesContent": ["/** @fileoverview DLX binary execution utilities for Socket ecosystem. */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport { WIN32 } from '#constants/platform'\n\nimport { generateCacheKey } from './dlx'\nimport { downloadWithLock } from './download-lock'\nimport { isDir, readJson, safeDelete } from './fs'\nimport { isObjectObject } from './objects'\nimport { normalizePath } from './path'\nimport { getSocketDlxDir } from './paths'\nimport type { SpawnExtra, SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\nexport interface DlxBinaryOptions {\n /** URL to download the binary from. */\n url: string\n /** Optional name for the cached binary (defaults to URL hash). */\n name?: string | undefined\n /** Expected checksum (sha256) for verification. */\n checksum?: string | undefined\n /** Cache TTL in milliseconds (default: 7 days). */\n cacheTtl?: number | undefined\n /** Force re-download even if cached. */\n force?: boolean | undefined\n /** Additional spawn options. */\n spawnOptions?: SpawnOptions | undefined\n}\n\nexport interface DlxBinaryResult {\n /** Path to the cached binary. */\n binaryPath: string\n /** Whether the binary was newly downloaded. */\n downloaded: boolean\n /** The spawn promise for the running process. */\n spawnPromise: ReturnType<typeof spawn>\n}\n\n/**\n * Get metadata file path for a cached binary.\n */\nfunction getMetadataPath(cacheEntryPath: string): string {\n return path.join(cacheEntryPath, '.dlx-metadata.json')\n}\n\n/**\n * Check if a cached binary is still valid.\n */\nasync function isCacheValid(\n cacheEntryPath: string,\n cacheTtl: number,\n): Promise<boolean> {\n try {\n const metaPath = getMetadataPath(cacheEntryPath)\n if (!existsSync(metaPath)) {\n return false\n }\n\n const metadata = await readJson(metaPath, { throws: false })\n if (!isObjectObject(metadata)) {\n return false\n }\n const now = Date.now()\n const timestamp = (metadata as Record<string, unknown>)['timestamp']\n // If timestamp is missing or invalid, cache is invalid\n if (typeof timestamp !== 'number' || timestamp <= 0) {\n return false\n }\n const age = now - timestamp\n\n return age < cacheTtl\n } catch {\n return false\n }\n}\n\n/**\n * Download a file from a URL with integrity checking and concurrent download protection.\n * Uses downloadWithLock to prevent multiple processes from downloading the same binary simultaneously.\n */\nasync function downloadBinary(\n url: string,\n destPath: string,\n checksum?: string | undefined,\n): Promise<string> {\n // Use downloadWithLock to handle concurrent download protection.\n // This prevents corruption when multiple processes try to download the same binary.\n await downloadWithLock(url, destPath, {\n // Align with npm's npx locking strategy.\n staleTimeout: 10_000,\n // Allow up to 2 minutes for large binary downloads.\n lockTimeout: 120_000,\n })\n\n // Compute checksum of downloaded file.\n const fileBuffer = await fs.readFile(destPath)\n const hasher = createHash('sha256')\n hasher.update(fileBuffer)\n const actualChecksum = hasher.digest('hex')\n\n // Verify checksum if provided.\n if (checksum && actualChecksum !== checksum) {\n // Clean up invalid file.\n await safeDelete(destPath)\n throw new Error(\n `Checksum mismatch: expected ${checksum}, got ${actualChecksum}`,\n )\n }\n\n // Make executable on POSIX systems.\n if (!WIN32) {\n await fs.chmod(destPath, 0o755)\n }\n\n return actualChecksum\n}\n\n/**\n * Write metadata for a cached binary.\n */\nasync function writeMetadata(\n cacheEntryPath: string,\n url: string,\n checksum: string,\n): Promise<void> {\n const metaPath = getMetadataPath(cacheEntryPath)\n const metadata = {\n arch: os.arch(),\n checksum,\n platform: os.platform(),\n timestamp: Date.now(),\n url,\n version: '1.0.0',\n }\n await fs.writeFile(metaPath, JSON.stringify(metadata, null, 2))\n}\n\n/**\n * Clean expired entries from the DLX cache.\n */\nexport async function cleanDlxCache(\n maxAge: number = /*@__INLINE__*/ require('#constants/time').DLX_BINARY_CACHE_TTL,\n): Promise<number> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return 0\n }\n\n let cleaned = 0\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n const metaPath = getMetadataPath(entryPath)\n\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n const timestamp = (metadata as Record<string, unknown>)['timestamp']\n // If timestamp is missing or invalid, treat as expired (age = infinity)\n const age =\n typeof timestamp === 'number' && timestamp > 0\n ? now - timestamp\n : Number.POSITIVE_INFINITY\n\n if (age > maxAge) {\n // Remove entire cache entry directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath, { force: true, recursive: true })\n cleaned += 1\n }\n } catch {\n // If we can't read metadata, check if directory is empty or corrupted.\n try {\n // eslint-disable-next-line no-await-in-loop\n const contents = await fs.readdir(entryPath)\n if (!contents.length) {\n // Remove empty directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath)\n cleaned += 1\n }\n } catch {}\n }\n }\n\n return cleaned\n}\n\n/**\n * Download and execute a binary from a URL with caching.\n */\nexport async function dlxBinary(\n args: readonly string[] | string[],\n options?: DlxBinaryOptions | undefined,\n spawnExtra?: SpawnExtra | undefined,\n): Promise<DlxBinaryResult> {\n const {\n cacheTtl = /*@__INLINE__*/ require('#constants/time').DLX_BINARY_CACHE_TTL,\n checksum,\n force = false,\n name,\n spawnOptions,\n url,\n } = { __proto__: null, ...options } as DlxBinaryOptions\n\n // Generate cache paths similar to pnpm/npx structure.\n const cacheDir = getDlxCachePath()\n const binaryName = name || `binary-${process.platform}-${os.arch()}`\n // Create spec from URL and binary name for unique cache identity.\n const spec = `${url}:${binaryName}`\n const cacheKey = generateCacheKey(spec)\n const cacheEntryDir = path.join(cacheDir, cacheKey)\n const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))\n\n let downloaded = false\n let computedChecksum = checksum\n\n // Check if we need to download.\n if (\n !force &&\n existsSync(cacheEntryDir) &&\n (await isCacheValid(cacheEntryDir, cacheTtl))\n ) {\n // Binary is cached and valid, read the checksum from metadata.\n try {\n const metaPath = getMetadataPath(cacheEntryDir)\n const metadata = await readJson(metaPath, { throws: false })\n if (\n metadata &&\n typeof metadata === 'object' &&\n !Array.isArray(metadata) &&\n typeof (metadata as Record<string, unknown>)['checksum'] === 'string'\n ) {\n computedChecksum = (metadata as Record<string, unknown>)[\n 'checksum'\n ] as string\n } else {\n // If metadata is invalid, re-download.\n downloaded = true\n }\n } catch {\n // If we can't read metadata, re-download.\n downloaded = true\n }\n } else {\n downloaded = true\n }\n\n if (downloaded) {\n // Ensure cache directory exists.\n await fs.mkdir(cacheEntryDir, { recursive: true })\n\n // Download the binary.\n computedChecksum = await downloadBinary(url, binaryPath, checksum)\n await writeMetadata(cacheEntryDir, url, computedChecksum || '')\n }\n\n // Execute the binary.\n // On Windows, script files (.bat, .cmd, .ps1) require shell: true because\n // they are not executable on their own and must be run through cmd.exe.\n // Note: .exe files are actual binaries and don't need shell mode.\n const needsShell = WIN32 && /\\.(?:bat|cmd|ps1)$/i.test(binaryPath)\n // Windows cmd.exe PATH resolution behavior:\n // When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically\n // strip the full path down to just the basename without extension (e.g.,\n // C:\\cache\\test.cmd becomes just \"test\"). Windows cmd.exe then searches for \"test\"\n // in directories listed in PATH, trying each extension from PATHEXT environment\n // variable (.COM, .EXE, .BAT, .CMD, etc.) until it finds a match.\n //\n // Since our binaries are downloaded to a custom cache directory that's not in PATH\n // (unlike system package managers like npm/pnpm/yarn which are already in PATH),\n // we must prepend the cache directory to PATH so cmd.exe can locate the binary.\n //\n // This approach is consistent with how other tools handle Windows command execution:\n // - npm's promise-spawn: uses which.sync() to find commands in PATH\n // - cross-spawn: spawns cmd.exe with escaped arguments\n // - Node.js spawn with shell: true: delegates to cmd.exe which uses PATH\n const finalSpawnOptions = needsShell\n ? {\n ...spawnOptions,\n env: {\n ...spawnOptions?.env,\n PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,\n },\n shell: true,\n }\n : spawnOptions\n const spawnPromise = spawn(binaryPath, args, finalSpawnOptions, spawnExtra)\n\n return {\n binaryPath,\n downloaded,\n spawnPromise,\n }\n}\n\n/**\n * Get the DLX binary cache directory path.\n * Returns normalized path for cross-platform compatibility.\n * Uses same directory as dlx-package for unified DLX storage.\n */\nexport function getDlxCachePath(): string {\n return getSocketDlxDir()\n}\n\n/**\n * Get information about cached binaries.\n */\nexport async function listDlxCache(): Promise<\n Array<{\n age: number\n arch: string\n checksum: string\n name: string\n platform: string\n size: number\n url: string\n }>\n> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return []\n }\n\n const results = []\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n const metaPath = getMetadataPath(entryPath)\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n\n // Find the binary file in the directory.\n // eslint-disable-next-line no-await-in-loop\n const files = await fs.readdir(entryPath)\n const binaryFile = files.find(f => !f.startsWith('.'))\n\n if (binaryFile) {\n const binaryPath = path.join(entryPath, binaryFile)\n // eslint-disable-next-line no-await-in-loop\n const binaryStats = await fs.stat(binaryPath)\n\n const metaObj = metadata as Record<string, unknown>\n results.push({\n age: now - ((metaObj['timestamp'] as number) || 0),\n arch: (metaObj['arch'] as string) || 'unknown',\n checksum: (metaObj['checksum'] as string) || '',\n name: binaryFile,\n platform: (metaObj['platform'] as string) || 'unknown',\n size: binaryStats.size,\n url: (metaObj['url'] as string) || '',\n })\n }\n } catch {}\n }\n\n return results\n}\n"],
|
|
5
|
-
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,cAAAC,EAAA,oBAAAC,EAAA,iBAAAC,IAAA,eAAAC,
|
|
6
|
-
"names": ["dlx_binary_exports", "__export", "cleanDlxCache", "dlxBinary", "getDlxCachePath", "listDlxCache", "__toCommonJS", "import_node_crypto", "import_node_fs", "import_node_os", "import_node_path", "import_platform", "import_dlx", "import_download_lock", "import_fs", "import_objects", "import_path", "import_paths", "import_spawn", "getMetadataPath", "cacheEntryPath", "path", "isCacheValid", "cacheTtl", "metaPath", "metadata", "now", "timestamp", "
|
|
4
|
+
"sourcesContent": ["/** @fileoverview DLX binary execution utilities for Socket ecosystem. */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport { WIN32 } from '#constants/platform'\n\nimport { generateCacheKey } from './dlx'\nimport { downloadWithLock } from './download-lock'\nimport { isDir, readJson, safeDelete } from './fs'\nimport { isObjectObject } from './objects'\nimport { normalizePath } from './path'\nimport { getSocketDlxDir } from './paths'\nimport type { SpawnExtra, SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\nexport interface DlxBinaryOptions {\n /** URL to download the binary from. */\n url: string\n /** Optional name for the cached binary (defaults to URL hash). */\n name?: string | undefined\n /** Expected checksum (sha256) for verification. */\n checksum?: string | undefined\n /** Cache TTL in milliseconds (default: 7 days). */\n cacheTtl?: number | undefined\n /** Force re-download even if cached. */\n force?: boolean | undefined\n /** Additional spawn options. */\n spawnOptions?: SpawnOptions | undefined\n}\n\nexport interface DlxBinaryResult {\n /** Path to the cached binary. */\n binaryPath: string\n /** Whether the binary was newly downloaded. */\n downloaded: boolean\n /** The spawn promise for the running process. */\n spawnPromise: ReturnType<typeof spawn>\n}\n\n/**\n * Get metadata file path for a cached binary.\n */\nfunction getMetadataPath(cacheEntryPath: string): string {\n return path.join(cacheEntryPath, '.dlx-metadata.json')\n}\n\n/**\n * Check if a cached binary is still valid.\n */\nasync function isCacheValid(\n cacheEntryPath: string,\n cacheTtl: number,\n): Promise<boolean> {\n try {\n const metaPath = getMetadataPath(cacheEntryPath)\n if (!existsSync(metaPath)) {\n return false\n }\n\n const metadata = await readJson(metaPath, { throws: false })\n if (!isObjectObject(metadata)) {\n return false\n }\n const now = Date.now()\n const timestamp = (metadata as Record<string, unknown>)['timestamp']\n // If timestamp is missing or invalid, cache is invalid\n if (typeof timestamp !== 'number' || timestamp <= 0) {\n return false\n }\n const age = now - timestamp\n\n return age < cacheTtl\n } catch {\n return false\n }\n}\n\n/**\n * Download a file from a URL with integrity checking and concurrent download protection.\n * Uses downloadWithLock to prevent multiple processes from downloading the same binary simultaneously.\n * Internal helper function for downloading binary files.\n */\nasync function downloadBinaryFile(\n url: string,\n destPath: string,\n checksum?: string | undefined,\n): Promise<string> {\n // Use downloadWithLock to handle concurrent download protection.\n // This prevents corruption when multiple processes try to download the same binary.\n await downloadWithLock(url, destPath, {\n // Align with npm's npx locking strategy.\n staleTimeout: 10_000,\n // Allow up to 2 minutes for large binary downloads.\n lockTimeout: 120_000,\n })\n\n // Compute checksum of downloaded file.\n const fileBuffer = await fs.readFile(destPath)\n const hasher = createHash('sha256')\n hasher.update(fileBuffer)\n const actualChecksum = hasher.digest('hex')\n\n // Verify checksum if provided.\n if (checksum && actualChecksum !== checksum) {\n // Clean up invalid file.\n await safeDelete(destPath)\n throw new Error(\n `Checksum mismatch: expected ${checksum}, got ${actualChecksum}`,\n )\n }\n\n // Make executable on POSIX systems.\n if (!WIN32) {\n await fs.chmod(destPath, 0o755)\n }\n\n return actualChecksum\n}\n\n/**\n * Write metadata for a cached binary.\n */\nasync function writeMetadata(\n cacheEntryPath: string,\n url: string,\n checksum: string,\n): Promise<void> {\n const metaPath = getMetadataPath(cacheEntryPath)\n const metadata = {\n arch: os.arch(),\n checksum,\n platform: os.platform(),\n timestamp: Date.now(),\n url,\n version: '1.0.0',\n }\n await fs.writeFile(metaPath, JSON.stringify(metadata, null, 2))\n}\n\n/**\n * Clean expired entries from the DLX cache.\n */\nexport async function cleanDlxCache(\n maxAge: number = /*@__INLINE__*/ require('#constants/time').DLX_BINARY_CACHE_TTL,\n): Promise<number> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return 0\n }\n\n let cleaned = 0\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n const metaPath = getMetadataPath(entryPath)\n\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n const timestamp = (metadata as Record<string, unknown>)['timestamp']\n // If timestamp is missing or invalid, treat as expired (age = infinity)\n const age =\n typeof timestamp === 'number' && timestamp > 0\n ? now - timestamp\n : Number.POSITIVE_INFINITY\n\n if (age > maxAge) {\n // Remove entire cache entry directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath, { force: true, recursive: true })\n cleaned += 1\n }\n } catch {\n // If we can't read metadata, check if directory is empty or corrupted.\n try {\n // eslint-disable-next-line no-await-in-loop\n const contents = await fs.readdir(entryPath)\n if (!contents.length) {\n // Remove empty directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath)\n cleaned += 1\n }\n } catch {}\n }\n }\n\n return cleaned\n}\n\n/**\n * Download and execute a binary from a URL with caching.\n */\nexport async function dlxBinary(\n args: readonly string[] | string[],\n options?: DlxBinaryOptions | undefined,\n spawnExtra?: SpawnExtra | undefined,\n): Promise<DlxBinaryResult> {\n const {\n cacheTtl = /*@__INLINE__*/ require('#constants/time').DLX_BINARY_CACHE_TTL,\n checksum,\n force = false,\n name,\n spawnOptions,\n url,\n } = { __proto__: null, ...options } as DlxBinaryOptions\n\n // Generate cache paths similar to pnpm/npx structure.\n const cacheDir = getDlxCachePath()\n const binaryName = name || `binary-${process.platform}-${os.arch()}`\n // Create spec from URL and binary name for unique cache identity.\n const spec = `${url}:${binaryName}`\n const cacheKey = generateCacheKey(spec)\n const cacheEntryDir = path.join(cacheDir, cacheKey)\n const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))\n\n let downloaded = false\n let computedChecksum = checksum\n\n // Check if we need to download.\n if (\n !force &&\n existsSync(cacheEntryDir) &&\n (await isCacheValid(cacheEntryDir, cacheTtl))\n ) {\n // Binary is cached and valid, read the checksum from metadata.\n try {\n const metaPath = getMetadataPath(cacheEntryDir)\n const metadata = await readJson(metaPath, { throws: false })\n if (\n metadata &&\n typeof metadata === 'object' &&\n !Array.isArray(metadata) &&\n typeof (metadata as Record<string, unknown>)['checksum'] === 'string'\n ) {\n computedChecksum = (metadata as Record<string, unknown>)[\n 'checksum'\n ] as string\n } else {\n // If metadata is invalid, re-download.\n downloaded = true\n }\n } catch {\n // If we can't read metadata, re-download.\n downloaded = true\n }\n } else {\n downloaded = true\n }\n\n if (downloaded) {\n // Ensure cache directory exists.\n await fs.mkdir(cacheEntryDir, { recursive: true })\n\n // Download the binary.\n computedChecksum = await downloadBinaryFile(url, binaryPath, checksum)\n await writeMetadata(cacheEntryDir, url, computedChecksum || '')\n }\n\n // Execute the binary.\n // On Windows, script files (.bat, .cmd, .ps1) require shell: true because\n // they are not executable on their own and must be run through cmd.exe.\n // Note: .exe files are actual binaries and don't need shell mode.\n const needsShell = WIN32 && /\\.(?:bat|cmd|ps1)$/i.test(binaryPath)\n // Windows cmd.exe PATH resolution behavior:\n // When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically\n // strip the full path down to just the basename without extension (e.g.,\n // C:\\cache\\test.cmd becomes just \"test\"). Windows cmd.exe then searches for \"test\"\n // in directories listed in PATH, trying each extension from PATHEXT environment\n // variable (.COM, .EXE, .BAT, .CMD, etc.) until it finds a match.\n //\n // Since our binaries are downloaded to a custom cache directory that's not in PATH\n // (unlike system package managers like npm/pnpm/yarn which are already in PATH),\n // we must prepend the cache directory to PATH so cmd.exe can locate the binary.\n //\n // This approach is consistent with how other tools handle Windows command execution:\n // - npm's promise-spawn: uses which.sync() to find commands in PATH\n // - cross-spawn: spawns cmd.exe with escaped arguments\n // - Node.js spawn with shell: true: delegates to cmd.exe which uses PATH\n const finalSpawnOptions = needsShell\n ? {\n ...spawnOptions,\n env: {\n ...spawnOptions?.env,\n PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,\n },\n shell: true,\n }\n : spawnOptions\n const spawnPromise = spawn(binaryPath, args, finalSpawnOptions, spawnExtra)\n\n return {\n binaryPath,\n downloaded,\n spawnPromise,\n }\n}\n\n/**\n * Download a binary from a URL with caching (without execution).\n * Similar to downloadPackage from dlx-package.\n *\n * @returns Object containing the path to the cached binary and whether it was downloaded\n */\nexport async function downloadBinary(\n options: Omit<DlxBinaryOptions, 'spawnOptions'>,\n): Promise<{ binaryPath: string; downloaded: boolean }> {\n const {\n cacheTtl = /*@__INLINE__*/ require('#constants/time').DLX_BINARY_CACHE_TTL,\n checksum,\n force = false,\n name,\n url,\n } = { __proto__: null, ...options } as DlxBinaryOptions\n\n // Generate cache paths similar to pnpm/npx structure.\n const cacheDir = getDlxCachePath()\n const binaryName = name || `binary-${process.platform}-${os.arch()}`\n // Create spec from URL and binary name for unique cache identity.\n const spec = `${url}:${binaryName}`\n const cacheKey = generateCacheKey(spec)\n const cacheEntryDir = path.join(cacheDir, cacheKey)\n const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))\n\n let downloaded = false\n\n // Check if we need to download.\n if (\n !force &&\n existsSync(cacheEntryDir) &&\n (await isCacheValid(cacheEntryDir, cacheTtl))\n ) {\n // Binary is cached and valid.\n downloaded = false\n } else {\n // Ensure cache directory exists.\n await fs.mkdir(cacheEntryDir, { recursive: true })\n\n // Download the binary.\n const computedChecksum = await downloadBinaryFile(url, binaryPath, checksum)\n await writeMetadata(cacheEntryDir, url, computedChecksum || '')\n downloaded = true\n }\n\n return {\n binaryPath,\n downloaded,\n }\n}\n\n/**\n * Execute a cached binary without re-downloading.\n * Similar to executePackage from dlx-package.\n * Binary must have been previously downloaded via downloadBinary or dlxBinary.\n *\n * @param binaryPath Path to the cached binary (from downloadBinary result)\n * @param args Arguments to pass to the binary\n * @param spawnOptions Spawn options for execution\n * @param spawnExtra Extra spawn configuration\n * @returns The spawn promise for the running process\n */\nexport function executeBinary(\n binaryPath: string,\n args: readonly string[] | string[],\n spawnOptions?: SpawnOptions | undefined,\n spawnExtra?: SpawnExtra | undefined,\n): ReturnType<typeof spawn> {\n // On Windows, script files (.bat, .cmd, .ps1) require shell: true because\n // they are not executable on their own and must be run through cmd.exe.\n // Note: .exe files are actual binaries and don't need shell mode.\n const needsShell = WIN32 && /\\.(?:bat|cmd|ps1)$/i.test(binaryPath)\n\n // Windows cmd.exe PATH resolution behavior:\n // When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically\n // strip the full path down to just the basename without extension. Windows cmd.exe\n // then searches for the binary in directories listed in PATH.\n //\n // Since our binaries are downloaded to a custom cache directory that's not in PATH,\n // we must prepend the cache directory to PATH so cmd.exe can locate the binary.\n const cacheEntryDir = path.dirname(binaryPath)\n const finalSpawnOptions = needsShell\n ? {\n ...spawnOptions,\n env: {\n ...spawnOptions?.env,\n PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,\n },\n shell: true,\n }\n : spawnOptions\n\n return spawn(binaryPath, args, finalSpawnOptions, spawnExtra)\n}\n\n/**\n * Get the DLX binary cache directory path.\n * Returns normalized path for cross-platform compatibility.\n * Uses same directory as dlx-package for unified DLX storage.\n */\nexport function getDlxCachePath(): string {\n return getSocketDlxDir()\n}\n\n/**\n * Get information about cached binaries.\n */\nexport async function listDlxCache(): Promise<\n Array<{\n age: number\n arch: string\n checksum: string\n name: string\n platform: string\n size: number\n url: string\n }>\n> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return []\n }\n\n const results = []\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n const metaPath = getMetadataPath(entryPath)\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n\n // Find the binary file in the directory.\n // eslint-disable-next-line no-await-in-loop\n const files = await fs.readdir(entryPath)\n const binaryFile = files.find(f => !f.startsWith('.'))\n\n if (binaryFile) {\n const binaryPath = path.join(entryPath, binaryFile)\n // eslint-disable-next-line no-await-in-loop\n const binaryStats = await fs.stat(binaryPath)\n\n const metaObj = metadata as Record<string, unknown>\n results.push({\n age: now - ((metaObj['timestamp'] as number) || 0),\n arch: (metaObj['arch'] as string) || 'unknown',\n checksum: (metaObj['checksum'] as string) || '',\n name: binaryFile,\n platform: (metaObj['platform'] as string) || 'unknown',\n size: binaryStats.size,\n url: (metaObj['url'] as string) || '',\n })\n }\n } catch {}\n }\n\n return results\n}\n"],
|
|
5
|
+
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,cAAAC,EAAA,mBAAAC,EAAA,kBAAAC,EAAA,oBAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAR,GAEA,IAAAS,EAA2B,uBAC3BC,EAA2C,mBAC3CC,EAAe,sBACfC,EAAiB,wBAEjBC,EAAsB,+BAEtBC,EAAiC,iBACjCC,EAAiC,2BACjCC,EAA4C,gBAC5CC,EAA+B,qBAC/BC,EAA8B,kBAC9BC,EAAgC,mBAEhCC,EAAsB,mBA6BtB,SAASC,EAAgBC,EAAgC,CACvD,OAAO,EAAAC,QAAK,KAAKD,EAAgB,oBAAoB,CACvD,CAKA,eAAeE,EACbF,EACAG,EACkB,CAClB,GAAI,CACF,MAAMC,EAAWL,EAAgBC,CAAc,EAC/C,GAAI,IAAC,cAAWI,CAAQ,EACtB,MAAO,GAGT,MAAMC,EAAW,QAAM,YAASD,EAAU,CAAE,OAAQ,EAAM,CAAC,EAC3D,GAAI,IAAC,kBAAeC,CAAQ,EAC1B,MAAO,GAET,MAAMC,EAAM,KAAK,IAAI,EACfC,EAAaF,EAAqC,UAExD,OAAI,OAAOE,GAAc,UAAYA,GAAa,EACzC,GAEGD,EAAMC,EAELJ,CACf,MAAQ,CACN,MAAO,EACT,CACF,CAOA,eAAeK,EACbC,EACAC,EACAC,EACiB,CAGjB,QAAM,oBAAiBF,EAAKC,EAAU,CAEpC,aAAc,IAEd,YAAa,IACf,CAAC,EAGD,MAAME,EAAa,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,MAAsB,UACrC,SAAWA,EAAQ,UAA0B,GAC7C,KAAMH,EACN,SAAWG,EAAQ,UAA0B,UAC7C,KAAMD,EAAY,KAClB,IAAMC,EAAQ,KAAqB,EACrC,CAAC,CACH,CACF,MAAQ,CAAC,CACX,CAEA,OAAOJ,CACT",
|
|
6
|
+
"names": ["dlx_binary_exports", "__export", "cleanDlxCache", "dlxBinary", "downloadBinary", "executeBinary", "getDlxCachePath", "listDlxCache", "__toCommonJS", "import_node_crypto", "import_node_fs", "import_node_os", "import_node_path", "import_platform", "import_dlx", "import_download_lock", "import_fs", "import_objects", "import_path", "import_paths", "import_spawn", "getMetadataPath", "cacheEntryPath", "path", "isCacheValid", "cacheTtl", "metaPath", "metadata", "now", "timestamp", "downloadBinaryFile", "url", "destPath", "checksum", "fileBuffer", "fs", "hasher", "actualChecksum", "writeMetadata", "os", "maxAge", "cacheDir", "cleaned", "entries", "entry", "entryPath", "args", "options", "spawnExtra", "force", "name", "spawnOptions", "binaryName", "spec", "cacheKey", "cacheEntryDir", "binaryPath", "downloaded", "computedChecksum", "finalSpawnOptions", "spawnPromise", "needsShell", "results", "binaryFile", "f", "binaryStats", "metaObj"]
|
|
7
7
|
}
|
package/dist/logger.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var j=Object.create;var p=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var K=(o,t)=>{for(var s in t)p(o,s,{get:t[s],enumerable:!0})},T=(o,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of B(t))!$.call(o,e)&&e!==s&&p(o,e,{get:()=>t[e],enumerable:!(n=E(t,e))||n.enumerable});return o};var R=(o,t,s)=>(s=o!=null?j(M(o)):{},T(t||!o||!o.__esModule?p(s,"default",{value:o,enumerable:!0}):s,o)),G=o=>T(p({},"__esModule",{value:!0}),o);var D={};K(D,{LOG_SYMBOLS:()=>y,Logger:()=>h,incLogCallCountSymbol:()=>u,lastWasBlankSymbol:()=>i,logger:()=>F});module.exports=G(D);var I=R(require("./external/@socketregistry/is-unicode-supported")),O=R(require("./external/yoctocolors-cjs")),m=require("./objects"),a=require("./strings");const g=console,_=Reflect.apply,Y=Reflect.construct;let S;function w(...o){return S===void 0&&(S=require("node:console").Console),Y(S,o)}function v(){return O.default}const y=(()=>{const o={__proto__:null},t={__proto__:null},s=()=>{const n=(0,I.default)(),e=v();(0,m.objectAssign)(o,{fail:e.red(n?"\u2716":"\xD7"),info:e.blue(n?"\u2139":"i"),step:e.cyan(n?"\u2192":">"),success:e.green(n?"\u2714":"\u221A"),warn:e.yellow(n?"\u26A0":"\u203C")}),(0,m.objectFreeze)(o);for(const r in t)delete t[r]};for(const n of Reflect.ownKeys(Reflect)){const e=Reflect[n];typeof e=="function"&&(t[n]=(...r)=>(s(),e(...r)))}return new Proxy(o,t)})(),P=["_stderrErrorHandler","_stdoutErrorHandler","assert","clear","count","countReset","createTask","debug","dir","dirxml","error","info","log","table","time","timeEnd","timeLog","trace","warn"].filter(o=>typeof g[o]=="function").map(o=>[o,g[o].bind(g)]),A={__proto__:null,writable:!0,enumerable:!1,configurable:!0},H=1e3,k=new WeakMap,l=new WeakMap;let C;function N(){return C===void 0&&(C=Object.getOwnPropertySymbols(g)),C}const u=Symbol.for("logger.logCallCount++");let L;function x(){return L===void 0&&(L=N().find(o=>o.label==="kGroupIndentWidth")??Symbol("kGroupIndentWidth")),L}const i=Symbol.for("logger.lastWasBlank");class h{static LOG_SYMBOLS=y;#c;#s;#l;#h;#g="";#f="";#p=!1;#y=!1;#a=0;#o;#w;constructor(...t){l.set(this,t);const s=t[0];typeof s=="object"&&s!==null?(this.#o={__proto__:null,...s},this.#w=s.stdout):this.#o={__proto__:null}}#t(){z();let t=k.get(this);if(!t){const s=l.get(this)??[];if(s.length)t=w(...s);else{t=w({stdout:process.stdout,stderr:process.stderr});for(const{0:n,1:e}of P)t[n]=e}k.set(this,t),l.delete(this)}return t}get stderr(){if(!this.#l){const t=l.get(this)??[],s=new h(...t);s.#c=this,s.#s="stderr",s.#o={__proto__:null,...this.#o},this.#l=s}return this.#l}get stdout(){if(!this.#h){const t=l.get(this)??[],s=new h(...t);s.#c=this,s.#s="stdout",s.#o={__proto__:null,...this.#o},this.#h=s}return this.#h}#r(){return this.#c||this}#n(t){const s=this.#r();return t==="stderr"?s.#g:s.#f}#e(t,s){const n=this.#r();t==="stderr"?n.#g=s:n.#f=s}#d(t){const s=this.#r();return t==="stderr"?s.#p:s.#y}#u(t,s){const n=this.#r();t==="stderr"?n.#p=s:n.#y=s}#k(){return this.#s||"stderr"}#m(t,s,n){const e=this.#t(),r=s.at(0),c=typeof r=="string",d=n||(t==="log"?"stdout":"stderr"),b=this.#n(d),f=c?[(0,a.applyLinePrefix)(r,{prefix:b}),...s.slice(1)]:s;return _(e[t],e,f),this[i](c&&(0,a.isBlankString)(f[0]),d),this[u](),this}#b(t){return t.replace(/^[✖✗×⚠‼✔✓√ℹ→]\uFE0F?\s*/u,"")}#i(t,s){const n=this.#t();let e=s.at(0),r;typeof e=="string"?(e=this.#b(e),r=s.slice(1)):(r=s,e="");const c=this.#n("stderr");return n.error((0,a.applyLinePrefix)(`${y[t]} ${e}`,{prefix:c}),...r),this[i](!1,"stderr"),this[u](),this}get logCallCount(){return this.#r().#a}[u](){const t=this.#r();return t.#a+=1,this}[i](t,s){return s?this.#u(s,!!t):this.#s?this.#u(this.#s,!!t):(this.#u("stderr",!!t),this.#u("stdout",!!t)),this}assert(t,...s){return this.#t().assert(t,s[0],...s.slice(1)),this[i](!1),t?this:this[u]()}clearVisible(){if(this.#s)throw new Error("clearVisible() is only available on the main logger instance, not on stream-bound instances");const t=this.#t();return t.clear(),t._stdout.isTTY&&(this[i](!0),this.#a=0),this}count(t){return this.#t().count(t),this[i](!1),this[u]()}createTask(t){return{run:s=>{this.log(`Starting task: ${t}`);const n=s();return this.log(`Completed task: ${t}`),n}}}dedent(t=2){if(this.#s){const s=this.#n(this.#s);this.#e(this.#s,s.slice(0,-t))}else{const s=this.#n("stderr"),n=this.#n("stdout");this.#e("stderr",s.slice(0,-t)),this.#e("stdout",n.slice(0,-t))}return this}dir(t,s){return this.#t().dir(t,s),this[i](!1),this[u]()}dirxml(...t){return this.#t().dirxml(t),this[i](!1),this[u]()}error(...t){return this.#m("error",t)}errorNewline(){return this.#d("stderr")?this:this.error("")}fail(...t){return this.#i("fail",t)}group(...t){const{length:s}=t;return s&&_(this.log,this,t),this.indent(this[x()]),s&&(this[i](!1),this[u]()),this}groupCollapsed(...t){return _(this.group,this,t)}groupEnd(){return this.dedent(this[x()]),this}indent(t=2){const s=" ".repeat(Math.min(t,H));if(this.#s){const n=this.#n(this.#s);this.#e(this.#s,n+s)}else{const n=this.#n("stderr"),e=this.#n("stdout");this.#e("stderr",n+s),this.#e("stdout",e+s)}return this}info(...t){return this.#i("info",t)}log(...t){return this.#m("log",t)}logNewline(){return this.#d("stdout")?this:this.log("")}resetIndent(){return this.#s?this.#e(this.#s,""):(this.#e("stderr",""),this.#e("stdout","")),this}step(t,...s){this.#d("stdout")||this.log("");const n=this.#b(t),e=this.#n("stdout");return this.#t().log((0,a.applyLinePrefix)(`${y.step} ${n}`,{prefix:e}),...s),this[i](!1,"stdout"),this[u](),this}substep(t,...s){const n=` ${t}`;return this.log(n,...s)}success(...t){return this.#i("success",t)}done(...t){return this.#i("success",t)}table(t,s){return this.#t().table(t,s),this[i](!1),this[u]()}timeEnd(t){return this.#t().timeEnd(t),this[i](!1),this[u]()}timeLog(t,...s){return this.#t().timeLog(t,...s),this[i](!1),this[u]()}trace(t,...s){return this.#t().trace(t,...s),this[i](!1),this[u]()}warn(...t){return this.#i("warn",t)}write(t){const s=this.#t(),n=l.get(this)??[];return(this.#w||n[0]?.stdout||s._stdout).write(t),this[i](!1),this}progress(t){const s=this.#t();return(this.#k()==="stderr"?s._stderr:s._stdout).write(`\u2234 ${t}`),this[i](!1),this}clearLine(){const t=this.#t(),n=this.#k()==="stderr"?t._stderr:t._stdout;return n.isTTY?(n.cursorTo(0),n.clearLine(0)):n.write("\r\x1B[K"),this}}let W=!1;function z(){if(W)return;W=!0;const o=[[x(),{...A,value:2}],[Symbol.toStringTag,{__proto__:null,configurable:!0,value:"logger"}]];for(const{0:t,1:s}of Object.entries(g))if(!h.prototype[t]&&typeof s=="function"){const{[t]:n}={[t](...e){let r=k.get(this);if(r===void 0){const d=l.get(this)??[];if(l.delete(this),d.length)r=w(...d);else{r=w({stdout:process.stdout,stderr:process.stderr});for(const{0:b,1:f}of P)r[b]=f}k.set(this,r)}const c=r[t](...e);return c===void 0||c===r?this:c}};o.push([t,{...A,value:n}])}Object.defineProperties(h.prototype,Object.fromEntries(o))}const F=new h;0&&(module.exports={LOG_SYMBOLS,Logger,incLogCallCountSymbol,lastWasBlankSymbol,logger});
|
|
3
3
|
//# sourceMappingURL=logger.js.map
|
package/dist/logger.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/logger.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Console logging utilities with line prefix support.\n * Provides enhanced console methods with formatted output capabilities.\n */\n\nimport isUnicodeSupported from './external/@socketregistry/is-unicode-supported'\nimport yoctocolorsCjs from './external/yoctocolors-cjs'\nimport { objectAssign, objectFreeze } from './objects'\nimport { applyLinePrefix, isBlankString } from './strings'\n\n/**\n * Log symbols for terminal output with colored indicators.\n *\n * Each symbol provides visual feedback for different message types, with\n * Unicode and ASCII fallback support.\n *\n * @example\n * ```typescript\n * import { LOG_SYMBOLS } from '@socketsecurity/lib'\n *\n * console.log(`${LOG_SYMBOLS.success} Operation completed`)\n * console.log(`${LOG_SYMBOLS.fail} Operation failed`)\n * console.log(`${LOG_SYMBOLS.warn} Warning message`)\n * console.log(`${LOG_SYMBOLS.info} Information message`)\n * console.log(`${LOG_SYMBOLS.step} Processing step`)\n * ```\n */\ntype LogSymbols = {\n /** Red colored failure symbol (\u2716 or \u00D7 in ASCII) */\n fail: string\n /** Blue colored information symbol (\u2139 or i in ASCII) */\n info: string\n /** Cyan colored step symbol (\u2192 or > in ASCII) */\n step: string\n /** Green colored success symbol (\u2714 or \u221A in ASCII) */\n success: string\n /** Yellow colored warning symbol (\u26A0 or \u203C in ASCII) */\n warn: string\n}\n\n/**\n * Type definition for logger methods that mirror console methods.\n *\n * All methods return the logger instance for method chaining.\n */\ntype LoggerMethods = {\n [K in keyof typeof console]: (typeof console)[K] extends (\n ...args: infer A\n ) => any\n ? (...args: A) => Logger\n : (typeof console)[K]\n}\n\n/**\n * A task that can be executed with automatic start/complete logging.\n *\n * @example\n * ```typescript\n * const task = logger.createTask('Database migration')\n * task.run(() => {\n * // Migration logic here\n * })\n * // Logs: \"Starting task: Database migration\"\n * // Logs: \"Completed task: Database migration\"\n * ```\n */\ninterface Task {\n /**\n * Executes the task function with automatic logging.\n *\n * @template T - The return type of the task function\n * @param f - The function to execute\n * @returns The result of the task function\n */\n run<T>(f: () => T): T\n}\n\nexport type { LogSymbols, LoggerMethods, Task }\n\nconst globalConsole = console\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\n// tsgo has a bug that incorrectly transpiles destructured exports, resulting in\n// `exports.SomeName = void 0;` which causes runtime errors.\n// See: https://github.com/SocketDev/socket-packageurl-js/issues/3\nconst ReflectApply = Reflect.apply\nconst ReflectConstruct = Reflect.construct\n\nlet _Console: typeof import('console').Console | undefined\n/**\n * Construct a new Console instance.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction constructConsole(...args: unknown[]) {\n if (_Console === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n const nodeConsole = /*@__PURE__*/ require('node:console')\n _Console = nodeConsole.Console\n }\n return ReflectConstruct(\n _Console! as new (\n ...args: unknown[]\n ) => Console, // eslint-disable-line no-undef\n args,\n )\n}\n\n/**\n * Get the yoctocolors module for terminal colors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getYoctocolors() {\n return yoctocolorsCjs\n}\n\n/**\n * Log symbols for terminal output with colored indicators.\n *\n * Provides colored Unicode symbols (\u2714, \u2716, \u26A0, \u2139, \u2192) with ASCII fallbacks (\u221A, \u00D7, \u203C, i, >)\n * for terminals that don't support Unicode. Symbols are color-coded: green for\n * success, red for failure, yellow for warnings, blue for info, cyan for step.\n *\n * The symbols are lazily initialized on first access and then frozen for immutability.\n *\n * @example\n * ```typescript\n * import { LOG_SYMBOLS } from '@socketsecurity/lib'\n *\n * console.log(`${LOG_SYMBOLS.success} Build completed`) // Green \u2714\n * console.log(`${LOG_SYMBOLS.fail} Build failed`) // Red \u2716\n * console.log(`${LOG_SYMBOLS.warn} Deprecated API used`) // Yellow \u26A0\n * console.log(`${LOG_SYMBOLS.info} Starting process`) // Blue \u2139\n * console.log(`${LOG_SYMBOLS.step} Processing files`) // Cyan \u2192\n * ```\n */\nexport const LOG_SYMBOLS = /*@__PURE__*/ (() => {\n const target: Record<string, string> = {\n __proto__: null,\n } as unknown as Record<string, string>\n // Mutable handler to simulate a frozen target.\n const handler: ProxyHandler<Record<string, string>> = {\n __proto__: null,\n } as unknown as ProxyHandler<Record<string, string>>\n const init = () => {\n const supported = isUnicodeSupported()\n const colors = getYoctocolors()\n objectAssign(target, {\n fail: colors.red(supported ? '\u2716' : '\u00D7'),\n info: colors.blue(supported ? '\u2139' : 'i'),\n step: colors.cyan(supported ? '\u2192' : '>'),\n success: colors.green(supported ? '\u2714' : '\u221A'),\n warn: colors.yellow(supported ? '\u26A0' : '\u203C'),\n })\n objectFreeze(target)\n // The handler of a Proxy is mutable after proxy instantiation.\n // We delete the traps to defer to native behavior.\n for (const trapName in handler) {\n delete handler[trapName as keyof ProxyHandler<Record<string, string>>]\n }\n }\n for (const trapName of Reflect.ownKeys(Reflect)) {\n const fn = (Reflect as Record<PropertyKey, unknown>)[trapName]\n if (typeof fn === 'function') {\n ;(handler as Record<string, (...args: unknown[]) => unknown>)[\n trapName as string\n ] = (...args: unknown[]) => {\n init()\n return fn(...args)\n }\n }\n }\n return new Proxy(target, handler)\n})()\n\nconst boundConsoleEntries = [\n // Add bound properties from console[kBindProperties](ignoreErrors, colorMode, groupIndentation).\n // https://github.com/nodejs/node/blob/v24.0.1/lib/internal/console/constructor.js#L230-L265\n '_stderrErrorHandler',\n '_stdoutErrorHandler',\n // Add methods that need to be bound to function properly.\n 'assert',\n 'clear',\n 'count',\n 'countReset',\n 'createTask',\n 'debug',\n 'dir',\n 'dirxml',\n 'error',\n // Skip group methods because in at least Node 20 with the Node --frozen-intrinsics\n // flag it triggers a readonly property for Symbol(kGroupIndent). Instead, we\n // implement these methods ourselves.\n //'group',\n //'groupCollapsed',\n //'groupEnd',\n 'info',\n 'log',\n 'table',\n 'time',\n 'timeEnd',\n 'timeLog',\n 'trace',\n 'warn',\n]\n .filter(n => typeof (globalConsole as any)[n] === 'function')\n .map(n => [n, (globalConsole as any)[n].bind(globalConsole)])\n\nconst consolePropAttributes = {\n __proto__: null,\n writable: true,\n enumerable: false,\n configurable: true,\n}\nconst maxIndentation = 1000\n\n/**\n * WeakMap storing the Console instance for each Logger.\n *\n * Console creation is lazy - deferred until first logging method call.\n * This allows logger to be imported during early Node.js bootstrap before\n * stdout is ready, avoiding ERR_CONSOLE_WRITABLE_STREAM errors.\n */\nconst privateConsole = new WeakMap()\n\n/**\n * WeakMap storing constructor arguments for lazy Console initialization.\n *\n * WeakMap is required instead of a private field (#constructorArgs) because:\n * 1. Private fields can't be accessed from dynamically created functions\n * 2. Logger adds console methods dynamically to its prototype (lines 1560+)\n * 3. These dynamic methods need constructor args for lazy initialization\n * 4. WeakMap allows both regular methods and dynamic functions to access args\n *\n * The args are deleted from the WeakMap after Console is created (memory cleanup).\n */\nconst privateConstructorArgs = new WeakMap()\n\nconst consoleSymbols = Object.getOwnPropertySymbols(globalConsole)\n\n/**\n * Symbol for incrementing the internal log call counter.\n *\n * This is an internal symbol used to track the number of times logging\n * methods have been called on a logger instance.\n */\nexport const incLogCallCountSymbol = Symbol.for('logger.logCallCount++')\n\nconst kGroupIndentationWidthSymbol =\n consoleSymbols.find(s => (s as any).label === 'kGroupIndentWidth') ??\n Symbol('kGroupIndentWidth')\n\n/**\n * Symbol for tracking whether the last logged line was blank.\n *\n * This is used internally to prevent multiple consecutive blank lines\n * and to determine whether to add spacing before certain messages.\n */\nexport const lastWasBlankSymbol = Symbol.for('logger.lastWasBlank')\n\n/**\n * Enhanced console logger with indentation, colored symbols, and stream management.\n *\n * Provides a fluent API for logging with automatic indentation tracking, colored\n * status symbols, separate stderr/stdout management, and method chaining. All\n * methods return `this` for easy chaining.\n *\n * Features:\n * - Automatic line prefixing with indentation\n * - Colored status symbols (success, fail, warn, info)\n * - Separate indentation tracking for stderr and stdout\n * - Stream-bound logger instances via `.stderr` and `.stdout`\n * - Group/indentation management\n * - Progress indicators with clearable lines\n * - Task execution with automatic logging\n *\n * @example\n * ```typescript\n * import { logger } from '@socketsecurity/lib'\n *\n * // Basic logging with symbols\n * logger.success('Build completed')\n * logger.fail('Build failed')\n * logger.warn('Deprecated API')\n * logger.info('Starting process')\n *\n * // Indentation and grouping\n * logger.log('Processing files:')\n * logger.indent()\n * logger.log('file1.js')\n * logger.log('file2.js')\n * logger.dedent()\n *\n * // Method chaining\n * logger\n * .log('Step 1')\n * .indent()\n * .log('Substep 1.1')\n * .log('Substep 1.2')\n * .dedent()\n * .log('Step 2')\n *\n * // Stream-specific logging\n * logger.stdout.log('Normal output')\n * logger.stderr.error('Error message')\n *\n * // Progress indicators\n * logger.progress('Processing...')\n * // ... do work ...\n * logger.clearLine()\n * logger.success('Done')\n *\n * // Task execution\n * const task = logger.createTask('Migration')\n * task.run(() => {\n * // Migration logic\n * })\n * ```\n */\n/*@__PURE__*/\nexport class Logger {\n /**\n * Static reference to log symbols for convenience.\n *\n * @example\n * ```typescript\n * console.log(`${Logger.LOG_SYMBOLS.success} Done`)\n * ```\n */\n static LOG_SYMBOLS = LOG_SYMBOLS\n\n #parent?: Logger\n #boundStream?: 'stderr' | 'stdout'\n #stderrLogger?: Logger\n #stdoutLogger?: Logger\n #stderrIndention = ''\n #stdoutIndention = ''\n #stderrLastWasBlank = false\n #stdoutLastWasBlank = false\n #logCallCount = 0\n #options: Record<string, unknown>\n #originalStdout?: any\n\n /**\n * Creates a new Logger instance.\n *\n * When called without arguments, creates a logger using the default\n * `process.stdout` and `process.stderr` streams. Can accept custom\n * console constructor arguments for advanced use cases.\n *\n * @param args - Optional console constructor arguments\n *\n * @example\n * ```typescript\n * // Default logger\n * const logger = new Logger()\n *\n * // Custom streams (advanced)\n * const customLogger = new Logger({\n * stdout: customWritableStream,\n * stderr: customErrorStream\n * })\n * ```\n */\n constructor(...args: unknown[]) {\n // Store constructor args for lazy Console initialization.\n privateConstructorArgs.set(this, args)\n\n // Store options if provided (for future extensibility)\n const options = args['0']\n if (typeof options === 'object' && options !== null) {\n this.#options = { __proto__: null, ...options }\n // Store reference to original stdout stream to bypass Console formatting\n this.#originalStdout = (options as any).stdout\n } else {\n this.#options = { __proto__: null }\n }\n\n // Note: Console initialization is now lazy (happens on first use).\n // This allows logger to be imported during early bootstrap before\n // stdout is ready, avoiding ERR_CONSOLE_WRITABLE_STREAM errors.\n }\n\n /**\n * Get the Console instance for this logger, creating it lazily on first access.\n *\n * This lazy initialization allows the logger to be imported during early\n * Node.js bootstrap before stdout is ready, avoiding Console initialization\n * errors (ERR_CONSOLE_WRITABLE_STREAM).\n *\n * @private\n */\n #getConsole(): typeof console & Record<string, unknown> {\n let con = privateConsole.get(this)\n if (!con) {\n // Lazy initialization - create Console on first use.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n if (ctorArgs.length) {\n con = constructConsole(...ctorArgs)\n } else {\n // Create a new console that acts like the builtin one so that it will\n // work with Node's --frozen-intrinsics flag.\n con = constructConsole({\n stdout: process.stdout,\n stderr: process.stderr,\n }) as typeof console & Record<string, unknown>\n for (const { 0: key, 1: method } of boundConsoleEntries) {\n con[key] = method\n }\n }\n privateConsole.set(this, con)\n // Clean up constructor args - no longer needed after Console creation.\n privateConstructorArgs.delete(this)\n }\n return con\n }\n\n /**\n * Gets a logger instance bound exclusively to stderr.\n *\n * All logging operations on this instance will write to stderr only.\n * Indentation is tracked separately from stdout. The instance is\n * cached and reused on subsequent accesses.\n *\n * @returns A logger instance bound to stderr\n *\n * @example\n * ```typescript\n * // Write errors to stderr\n * logger.stderr.error('Configuration invalid')\n * logger.stderr.warn('Using fallback settings')\n *\n * // Indent only affects stderr\n * logger.stderr.indent()\n * logger.stderr.error('Nested error details')\n * logger.stderr.dedent()\n * ```\n */\n get stderr(): Logger {\n if (!this.#stderrLogger) {\n // Pass parent's constructor args to maintain config.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n const instance = new Logger(...ctorArgs)\n instance.#parent = this\n instance.#boundStream = 'stderr'\n instance.#options = { __proto__: null, ...this.#options }\n this.#stderrLogger = instance\n }\n return this.#stderrLogger\n }\n\n /**\n * Gets a logger instance bound exclusively to stdout.\n *\n * All logging operations on this instance will write to stdout only.\n * Indentation is tracked separately from stderr. The instance is\n * cached and reused on subsequent accesses.\n *\n * @returns A logger instance bound to stdout\n *\n * @example\n * ```typescript\n * // Write normal output to stdout\n * logger.stdout.log('Processing started')\n * logger.stdout.log('Items processed: 42')\n *\n * // Indent only affects stdout\n * logger.stdout.indent()\n * logger.stdout.log('Detailed output')\n * logger.stdout.dedent()\n * ```\n */\n get stdout(): Logger {\n if (!this.#stdoutLogger) {\n // Pass parent's constructor args to maintain config.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n const instance = new Logger(...ctorArgs)\n instance.#parent = this\n instance.#boundStream = 'stdout'\n instance.#options = { __proto__: null, ...this.#options }\n this.#stdoutLogger = instance\n }\n return this.#stdoutLogger\n }\n\n /**\n * Get the root logger (for accessing shared indentation state).\n * @private\n */\n #getRoot(): Logger {\n return this.#parent || this\n }\n\n /**\n * Get indentation for a specific stream.\n * @private\n */\n #getIndent(stream: 'stderr' | 'stdout'): string {\n const root = this.#getRoot()\n return stream === 'stderr' ? root.#stderrIndention : root.#stdoutIndention\n }\n\n /**\n * Set indentation for a specific stream.\n * @private\n */\n #setIndent(stream: 'stderr' | 'stdout', value: string): void {\n const root = this.#getRoot()\n if (stream === 'stderr') {\n root.#stderrIndention = value\n } else {\n root.#stdoutIndention = value\n }\n }\n\n /**\n * Get lastWasBlank state for a specific stream.\n * @private\n */\n #getLastWasBlank(stream: 'stderr' | 'stdout'): boolean {\n const root = this.#getRoot()\n return stream === 'stderr'\n ? root.#stderrLastWasBlank\n : root.#stdoutLastWasBlank\n }\n\n /**\n * Set lastWasBlank state for a specific stream.\n * @private\n */\n #setLastWasBlank(stream: 'stderr' | 'stdout', value: boolean): void {\n const root = this.#getRoot()\n if (stream === 'stderr') {\n root.#stderrLastWasBlank = value\n } else {\n root.#stdoutLastWasBlank = value\n }\n }\n\n /**\n * Get the target stream for this logger instance.\n * @private\n */\n #getTargetStream(): 'stderr' | 'stdout' {\n return this.#boundStream || 'stderr'\n }\n\n /**\n * Apply a console method with indentation.\n * @private\n */\n #apply(\n methodName: string,\n args: unknown[],\n stream?: 'stderr' | 'stdout',\n ): this {\n const con = this.#getConsole()\n const text = args.at(0)\n const hasText = typeof text === 'string'\n // Determine which stream this method writes to\n const targetStream = stream || (methodName === 'log' ? 'stdout' : 'stderr')\n const indent = this.#getIndent(targetStream)\n const logArgs = hasText\n ? [applyLinePrefix(text, { prefix: indent }), ...args.slice(1)]\n : args\n ReflectApply(\n con[methodName] as (...args: unknown[]) => unknown,\n con,\n logArgs,\n )\n this[lastWasBlankSymbol](hasText && isBlankString(logArgs[0]), targetStream)\n ;(this as any)[incLogCallCountSymbol]()\n return this\n }\n\n /**\n * Strip log symbols from the start of text.\n * @private\n */\n #stripSymbols(text: string): string {\n // Strip both unicode and emoji forms of log symbols from the start.\n // Matches: \u2716, \u2717, \u00D7, \u2716\uFE0F, \u26A0, \u203C, \u26A0\uFE0F, \u2714, \u2713, \u221A, \u2714\uFE0F, \u2713\uFE0F, \u2139, \u2139\uFE0F, \u2192, >\n // Also handles variation selectors (U+FE0F) and whitespace after symbol.\n // Note: We don't strip standalone 'i' or '>' to avoid breaking words.\n return text.replace(/^[\u2716\u2717\u00D7\u26A0\u203C\u2714\u2713\u221A\u2139\u2192]\\uFE0F?\\s*/u, '')\n }\n\n /**\n * Apply a method with a symbol prefix.\n * @private\n */\n #symbolApply(symbolType: string, args: unknown[]): this {\n const con = this.#getConsole()\n let text = args.at(0)\n // biome-ignore lint/suspicious/noImplicitAnyLet: Flexible argument handling.\n let extras\n if (typeof text === 'string') {\n text = this.#stripSymbols(text)\n extras = args.slice(1)\n } else {\n extras = args\n text = ''\n }\n // Note: Meta status messages (info/fail/etc) always go to stderr.\n const indent = this.#getIndent('stderr')\n con.error(\n applyLinePrefix(`${LOG_SYMBOLS[symbolType]} ${text}`, {\n prefix: indent,\n }),\n ...extras,\n )\n this[lastWasBlankSymbol](false, 'stderr')\n ;(this as any)[incLogCallCountSymbol]()\n return this\n }\n\n /**\n * Gets the total number of log calls made on this logger instance.\n *\n * Tracks all logging method calls including `log()`, `error()`, `warn()`,\n * `success()`, `fail()`, etc. Useful for testing and monitoring logging activity.\n *\n * @returns The number of times logging methods have been called\n *\n * @example\n * ```typescript\n * logger.log('Message 1')\n * logger.error('Message 2')\n * console.log(logger.logCallCount) // 2\n * ```\n */\n get logCallCount() {\n const root = this.#getRoot()\n return root.#logCallCount\n }\n\n /**\n * Increments the internal log call counter.\n *\n * This is called automatically by logging methods and should not\n * be called directly in normal usage.\n *\n * @returns The logger instance for chaining\n */\n [incLogCallCountSymbol]() {\n const root = this.#getRoot()\n root.#logCallCount += 1\n return this\n }\n\n /**\n * Sets whether the last logged line was blank.\n *\n * Used internally to track blank lines and prevent duplicate spacing.\n * This is called automatically by logging methods.\n *\n * @param value - Whether the last line was blank\n * @param stream - Optional stream to update (defaults to both streams if not bound, or target stream if bound)\n * @returns The logger instance for chaining\n */\n [lastWasBlankSymbol](value: unknown, stream?: 'stderr' | 'stdout'): this {\n if (stream) {\n // Explicit stream specified\n this.#setLastWasBlank(stream, !!value)\n } else if (this.#boundStream) {\n // Stream-bound logger - affect only the bound stream\n this.#setLastWasBlank(this.#boundStream, !!value)\n } else {\n // Root logger with no stream specified - affect both streams\n this.#setLastWasBlank('stderr', !!value)\n this.#setLastWasBlank('stdout', !!value)\n }\n return this\n }\n\n /**\n * Logs an assertion failure message if the value is falsy.\n *\n * Works like `console.assert()` but returns the logger for chaining.\n * If the value is truthy, nothing is logged. If falsy, logs an error\n * message with an assertion failure.\n *\n * @param value - The value to test\n * @param message - Optional message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.assert(true, 'This will not log')\n * logger.assert(false, 'Assertion failed: value is false')\n * logger.assert(items.length > 0, 'No items found')\n * ```\n */\n assert(value: unknown, ...message: unknown[]): this {\n const con = this.#getConsole()\n con.assert(value, message[0] as string, ...message.slice(1))\n this[lastWasBlankSymbol](false)\n return value ? this : this[incLogCallCountSymbol]()\n }\n\n /**\n * Clears the visible terminal screen.\n *\n * Only available on the main logger instance, not on stream-bound instances\n * (`.stderr` or `.stdout`). Resets the log call count and blank line tracking\n * if the output is a TTY.\n *\n * @returns The logger instance for chaining\n * @throws {Error} If called on a stream-bound logger instance\n *\n * @example\n * ```typescript\n * logger.log('Some output')\n * logger.clearVisible() // Screen is now clear\n *\n * // Error: Can't call on stream-bound instance\n * logger.stderr.clearVisible() // throws\n * ```\n */\n clearVisible() {\n if (this.#boundStream) {\n throw new Error(\n 'clearVisible() is only available on the main logger instance, not on stream-bound instances',\n )\n }\n const con = this.#getConsole()\n con.clear()\n if ((con as any)._stdout.isTTY) {\n ;(this as any)[lastWasBlankSymbol](true)\n this.#logCallCount = 0\n }\n return this\n }\n\n /**\n * Increments and logs a counter for the given label.\n *\n * Each unique label maintains its own counter. Works like `console.count()`.\n *\n * @param label - Optional label for the counter\n * @default 'default'\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.count('requests') // requests: 1\n * logger.count('requests') // requests: 2\n * logger.count('errors') // errors: 1\n * logger.count() // default: 1\n * ```\n */\n count(label?: string | undefined): this {\n const con = this.#getConsole()\n con.count(label)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Creates a task that logs start and completion messages automatically.\n *\n * Returns a task object with a `run()` method that executes the provided\n * function and logs \"Starting task: {name}\" before execution and\n * \"Completed task: {name}\" after completion.\n *\n * @param name - The name of the task\n * @returns A task object with a `run()` method\n *\n * @example\n * ```typescript\n * const task = logger.createTask('Database Migration')\n * const result = task.run(() => {\n * // Logs: \"Starting task: Database Migration\"\n * migrateDatabase()\n * return 'success'\n * // Logs: \"Completed task: Database Migration\"\n * })\n * console.log(result) // 'success'\n * ```\n */\n createTask(name: string): Task {\n return {\n run: <T>(f: () => T): T => {\n this.log(`Starting task: ${name}`)\n const result = f()\n this.log(`Completed task: ${name}`)\n return result\n },\n }\n }\n\n /**\n * Decreases the indentation level by removing spaces from the prefix.\n *\n * When called on the main logger, affects both stderr and stdout indentation.\n * When called on a stream-bound logger (`.stderr` or `.stdout`), affects\n * only that stream's indentation.\n *\n * @param spaces - Number of spaces to remove from indentation\n * @default 2\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.indent()\n * logger.log('Indented')\n * logger.dedent()\n * logger.log('Back to normal')\n *\n * // Remove custom amount\n * logger.indent(4)\n * logger.log('Four spaces')\n * logger.dedent(4)\n *\n * // Stream-specific dedent\n * logger.stdout.indent()\n * logger.stdout.log('Indented stdout')\n * logger.stdout.dedent()\n * ```\n */\n dedent(spaces = 2) {\n if (this.#boundStream) {\n // Only affect bound stream\n const current = this.#getIndent(this.#boundStream)\n this.#setIndent(this.#boundStream, current.slice(0, -spaces))\n } else {\n // Affect both streams\n const stderrCurrent = this.#getIndent('stderr')\n const stdoutCurrent = this.#getIndent('stdout')\n this.#setIndent('stderr', stderrCurrent.slice(0, -spaces))\n this.#setIndent('stdout', stdoutCurrent.slice(0, -spaces))\n }\n return this\n }\n\n /**\n * Displays an object's properties in a formatted way.\n *\n * Works like `console.dir()` with customizable options for depth,\n * colors, etc. Useful for inspecting complex objects.\n *\n * @param obj - The object to display\n * @param options - Optional formatting options (Node.js inspect options)\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * const obj = { a: 1, b: { c: 2, d: { e: 3 } } }\n * logger.dir(obj)\n * logger.dir(obj, { depth: 1 }) // Limit nesting depth\n * logger.dir(obj, { colors: true }) // Enable colors\n * ```\n */\n dir(obj: unknown, options?: unknown | undefined): this {\n const con = this.#getConsole()\n con.dir(obj, options)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Displays data as XML/HTML in a formatted way.\n *\n * Works like `console.dirxml()`. In Node.js, behaves the same as `dir()`.\n *\n * @param data - The data to display\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.dirxml(document.body) // In browser environments\n * logger.dirxml(xmlObject) // In Node.js\n * ```\n */\n dirxml(...data: unknown[]): this {\n const con = this.#getConsole()\n con.dirxml(data)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs an error message to stderr.\n *\n * Automatically applies current indentation. All arguments are formatted\n * and logged like `console.error()`.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.error('Build failed')\n * logger.error('Error code:', 500)\n * logger.error('Details:', { message: 'Not found' })\n * ```\n */\n error(...args: unknown[]): this {\n return this.#apply('error', args)\n }\n\n /**\n * Logs a newline to stderr only if the last line wasn't already blank.\n *\n * Prevents multiple consecutive blank lines. Useful for adding spacing\n * between sections without creating excessive whitespace.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.error('Error message')\n * logger.errorNewline() // Adds blank line\n * logger.errorNewline() // Does nothing (already blank)\n * logger.error('Next section')\n * ```\n */\n errorNewline() {\n return this.#getLastWasBlank('stderr') ? this : this.error('')\n }\n\n /**\n * Logs a failure message with a red colored fail symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.fail` (red \u2716).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.fail('Build failed')\n * logger.fail('Test suite failed:', { passed: 5, failed: 3 })\n * ```\n */\n fail(...args: unknown[]): this {\n return this.#symbolApply('fail', args)\n }\n\n /**\n * Starts a new indented log group.\n *\n * If a label is provided, it's logged before increasing indentation.\n * Groups can be nested. Each group increases indentation by the\n * `kGroupIndentWidth` (default 2 spaces). Call `groupEnd()` to close.\n *\n * @param label - Optional label to display before the group\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.group('Processing files:')\n * logger.log('file1.js')\n * logger.log('file2.js')\n * logger.groupEnd()\n *\n * // Nested groups\n * logger.group('Outer')\n * logger.log('Outer content')\n * logger.group('Inner')\n * logger.log('Inner content')\n * logger.groupEnd()\n * logger.groupEnd()\n * ```\n */\n group(...label: unknown[]): this {\n const { length } = label\n if (length) {\n ReflectApply(this.log, this, label)\n }\n this.indent((this as any)[kGroupIndentationWidthSymbol])\n if (length) {\n ;(this as any)[lastWasBlankSymbol](false)\n ;(this as any)[incLogCallCountSymbol]()\n }\n return this\n }\n\n /**\n * Starts a new collapsed log group (alias for `group()`).\n *\n * In browser consoles, this creates a collapsed group. In Node.js,\n * it behaves identically to `group()`.\n *\n * @param label - Optional label to display before the group\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.groupCollapsed('Details')\n * logger.log('Hidden by default in browsers')\n * logger.groupEnd()\n * ```\n */\n // groupCollapsed is an alias of group.\n // https://nodejs.org/api/console.html#consolegroupcollapsed\n groupCollapsed(...label: unknown[]): this {\n return ReflectApply(this.group, this, label)\n }\n\n /**\n * Ends the current log group and decreases indentation.\n *\n * Must be called once for each `group()` or `groupCollapsed()` call\n * to properly close the group and restore indentation.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.group('Group 1')\n * logger.log('Content')\n * logger.groupEnd() // Closes 'Group 1'\n * ```\n */\n groupEnd() {\n this.dedent((this as any)[kGroupIndentationWidthSymbol])\n return this\n }\n\n /**\n * Increases the indentation level by adding spaces to the prefix.\n *\n * When called on the main logger, affects both stderr and stdout indentation.\n * When called on a stream-bound logger (`.stderr` or `.stdout`), affects\n * only that stream's indentation. Maximum indentation is 1000 spaces.\n *\n * @param spaces - Number of spaces to add to indentation\n * @default 2\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Level 0')\n * logger.indent()\n * logger.log('Level 1')\n * logger.indent()\n * logger.log('Level 2')\n * logger.dedent()\n * logger.dedent()\n *\n * // Custom indent amount\n * logger.indent(4)\n * logger.log('Indented 4 spaces')\n * logger.dedent(4)\n *\n * // Stream-specific indent\n * logger.stdout.indent()\n * logger.stdout.log('Only stdout is indented')\n * ```\n */\n indent(spaces = 2) {\n const spacesToAdd = ' '.repeat(Math.min(spaces, maxIndentation))\n if (this.#boundStream) {\n // Only affect bound stream\n const current = this.#getIndent(this.#boundStream)\n this.#setIndent(this.#boundStream, current + spacesToAdd)\n } else {\n // Affect both streams\n const stderrCurrent = this.#getIndent('stderr')\n const stdoutCurrent = this.#getIndent('stdout')\n this.#setIndent('stderr', stderrCurrent + spacesToAdd)\n this.#setIndent('stdout', stdoutCurrent + spacesToAdd)\n }\n return this\n }\n\n /**\n * Logs an informational message with a blue colored info symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.info` (blue \u2139).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.info('Starting build process')\n * logger.info('Configuration loaded:', config)\n * logger.info('Using cache directory:', cacheDir)\n * ```\n */\n info(...args: unknown[]): this {\n return this.#symbolApply('info', args)\n }\n\n /**\n * Logs a message to stdout.\n *\n * Automatically applies current indentation. All arguments are formatted\n * and logged like `console.log()`. This is the primary method for\n * standard output.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Processing complete')\n * logger.log('Items processed:', 42)\n * logger.log('Results:', { success: true, count: 10 })\n *\n * // Method chaining\n * logger.log('Step 1').log('Step 2').log('Step 3')\n * ```\n */\n log(...args: unknown[]): this {\n return this.#apply('log', args)\n }\n\n /**\n * Logs a newline to stdout only if the last line wasn't already blank.\n *\n * Prevents multiple consecutive blank lines. Useful for adding spacing\n * between sections without creating excessive whitespace.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Section 1')\n * logger.logNewline() // Adds blank line\n * logger.logNewline() // Does nothing (already blank)\n * logger.log('Section 2')\n * ```\n */\n logNewline() {\n return this.#getLastWasBlank('stdout') ? this : this.log('')\n }\n\n /**\n * Resets all indentation to zero.\n *\n * When called on the main logger, resets both stderr and stdout indentation.\n * When called on a stream-bound logger (`.stderr` or `.stdout`), resets\n * only that stream's indentation.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.indent().indent().indent()\n * logger.log('Very indented')\n * logger.resetIndent()\n * logger.log('Back to zero indentation')\n *\n * // Reset only stdout\n * logger.stdout.resetIndent()\n * ```\n */\n resetIndent() {\n if (this.#boundStream) {\n // Only reset bound stream\n this.#setIndent(this.#boundStream, '')\n } else {\n // Reset both streams\n this.#setIndent('stderr', '')\n this.#setIndent('stdout', '')\n }\n return this\n }\n\n /**\n * Logs a main step message with a cyan arrow symbol and blank line before it.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.step` (cyan \u2192) and\n * adds a blank line before the message unless the last line was already blank.\n * Useful for marking major steps in a process with clear visual separation.\n * Always outputs to stdout. If the message starts with an existing symbol,\n * it will be stripped and replaced.\n *\n * @param msg - The step message to log\n * @param extras - Additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.step('Building project')\n * logger.log('Compiling TypeScript...')\n * logger.step('Running tests')\n * logger.log('Running test suite...')\n * // Output:\n * // [blank line]\n * // \u2192 Building project\n * // Compiling TypeScript...\n * // [blank line]\n * // \u2192 Running tests\n * // Running test suite...\n * ```\n */\n step(msg: string, ...extras: unknown[]): this {\n // Add blank line before the step message.\n if (!this.#getLastWasBlank('stdout')) {\n // Use this.log() to properly track the blank line.\n this.log('')\n }\n // Strip existing symbols from the message.\n const text = this.#stripSymbols(msg)\n // Note: Step messages always go to stdout (unlike info/fail/etc which go to stderr).\n const indent = this.#getIndent('stdout')\n const con = this.#getConsole() as typeof console & Record<string, unknown>\n con.log(\n applyLinePrefix(`${LOG_SYMBOLS.step} ${text}`, {\n prefix: indent,\n }),\n ...extras,\n )\n this[lastWasBlankSymbol](false, 'stdout')\n ;(this as any)[incLogCallCountSymbol]()\n return this\n }\n\n /**\n * Logs an indented substep message (stateless).\n *\n * Adds a 2-space indent to the message without affecting the logger's\n * indentation state. Useful for showing sub-items under a main step.\n *\n * @param msg - The substep message to log\n * @param extras - Additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Installing dependencies:')\n * logger.substep('Installing react')\n * logger.substep('Installing typescript')\n * logger.substep('Installing eslint')\n * // Output:\n * // Installing dependencies:\n * // Installing react\n * // Installing typescript\n * // Installing eslint\n * ```\n */\n substep(msg: string, ...extras: unknown[]): this {\n // Add 2-space indent to the message.\n const indentedMsg = ` ${msg}`\n // Let log() handle all tracking.\n return this.log(indentedMsg, ...extras)\n }\n\n /**\n * Logs a success message with a green colored success symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.success` (green \u2714).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.success('Build completed')\n * logger.success('Tests passed:', { total: 42, passed: 42 })\n * logger.success('Deployment successful')\n * ```\n */\n success(...args: unknown[]): this {\n return this.#symbolApply('success', args)\n }\n\n /**\n * Logs a completion message with a success symbol (alias for `success()`).\n *\n * Provides semantic clarity when marking something as \"done\". Does NOT\n * automatically clear the current line - call `clearLine()` first if\n * needed after using `progress()`.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.done('Task completed')\n *\n * // After progress indicator\n * logger.progress('Processing...')\n * // ... do work ...\n * logger.clearLine()\n * logger.done('Processing complete')\n * ```\n */\n done(...args: unknown[]): this {\n return this.#symbolApply('success', args)\n }\n\n /**\n * Displays data in a table format.\n *\n * Works like `console.table()`. Accepts arrays of objects or\n * objects with nested objects. Optionally specify which properties\n * to include in the table.\n *\n * @param tabularData - The data to display as a table\n * @param properties - Optional array of property names to include\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * // Array of objects\n * logger.table([\n * { name: 'Alice', age: 30 },\n * { name: 'Bob', age: 25 }\n * ])\n *\n * // Specify properties to show\n * logger.table(users, ['name', 'email'])\n *\n * // Object with nested objects\n * logger.table({\n * user1: { name: 'Alice', age: 30 },\n * user2: { name: 'Bob', age: 25 }\n * })\n * ```\n */\n table(\n tabularData: unknown,\n properties?: readonly string[] | undefined,\n ): this {\n const con = this.#getConsole()\n con.table(tabularData, properties)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Ends a timer and logs the elapsed time.\n *\n * Logs the duration since `console.time()` was called with the same\n * label. The timer is stopped and removed.\n *\n * @param label - Optional label for the timer\n * @default 'default'\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * console.time('operation')\n * // ... do work ...\n * logger.timeEnd('operation')\n * // Logs: \"operation: 123.456ms\"\n *\n * console.time()\n * // ... do work ...\n * logger.timeEnd()\n * // Logs: \"default: 123.456ms\"\n * ```\n */\n timeEnd(label?: string | undefined): this {\n const con = this.#getConsole()\n con.timeEnd(label)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs the current value of a timer without stopping it.\n *\n * Logs the duration since `console.time()` was called with the same\n * label, but keeps the timer running. Can include additional data\n * to log alongside the time.\n *\n * @param label - Optional label for the timer\n * @param data - Additional data to log with the time\n * @default 'default'\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * console.time('process')\n * // ... partial work ...\n * logger.timeLog('process', 'Checkpoint 1')\n * // Logs: \"process: 123.456ms Checkpoint 1\"\n * // ... more work ...\n * logger.timeLog('process', 'Checkpoint 2')\n * // Logs: \"process: 234.567ms Checkpoint 2\"\n * console.timeEnd('process')\n * ```\n */\n timeLog(label?: string | undefined, ...data: unknown[]): this {\n const con = this.#getConsole()\n con.timeLog(label, ...data)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs a stack trace to the console.\n *\n * Works like `console.trace()`. Shows the call stack leading to\n * where this method was called. Useful for debugging.\n *\n * @param message - Optional message to display with the trace\n * @param args - Additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * function debugFunction() {\n * logger.trace('Debug point reached')\n * }\n *\n * logger.trace('Trace from here')\n * logger.trace('Error context:', { userId: 123 })\n * ```\n */\n trace(message?: unknown | undefined, ...args: unknown[]): this {\n const con = this.#getConsole()\n con.trace(message, ...args)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs a warning message with a yellow colored warning symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.warn` (yellow \u26A0).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.warn('Deprecated API used')\n * logger.warn('Low memory:', { available: '100MB' })\n * logger.warn('Missing optional configuration')\n * ```\n */\n warn(...args: unknown[]): this {\n return this.#symbolApply('warn', args)\n }\n\n /**\n * Writes text directly to stdout without a newline or indentation.\n *\n * Useful for progress indicators or custom formatting where you need\n * low-level control. Does not apply any indentation or formatting.\n *\n * @param text - The text to write\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.write('Processing... ')\n * // ... do work ...\n * logger.write('done\\n')\n *\n * // Build a line incrementally\n * logger.write('Step 1')\n * logger.write('... Step 2')\n * logger.write('... Step 3\\n')\n * ```\n */\n write(text: string): this {\n const con = this.#getConsole()\n // Write directly to the original stdout stream to bypass Console formatting\n // (e.g., group indentation). Try multiple approaches to get the raw stream:\n // 1. Use stored reference from constructor options\n // 2. Try to get from constructor args\n // 3. Fall back to con._stdout (which applies formatting)\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n const stdout =\n this.#originalStdout || (ctorArgs[0] as any)?.stdout || con._stdout\n stdout.write(text)\n this[lastWasBlankSymbol](false)\n return this\n }\n\n /**\n * Shows a progress indicator that can be cleared with `clearLine()`.\n *\n * Displays a simple status message with a '\u2234' prefix. Does not include\n * animation or spinner. Intended to be cleared once the operation completes.\n * The output stream (stderr or stdout) depends on whether the logger is\n * stream-bound.\n *\n * @param text - The progress message to display\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.progress('Processing files...')\n * // ... do work ...\n * logger.clearLine()\n * logger.success('Files processed')\n *\n * // Stream-specific progress\n * logger.stdout.progress('Loading...')\n * // ... do work ...\n * logger.stdout.clearLine()\n * logger.stdout.log('Done')\n * ```\n */\n progress(text: string): this {\n const con = this.#getConsole()\n const stream = this.#getTargetStream()\n const streamObj = (\n stream === 'stderr' ? con._stderr : con._stdout\n ) as NodeJS.WriteStream & { write: (text: string) => boolean }\n streamObj.write(`\u2234 ${text}`)\n this[lastWasBlankSymbol](false)\n return this\n }\n\n /**\n * Clears the current line in the terminal.\n *\n * Moves the cursor to the beginning of the line and clears all content.\n * Works in both TTY and non-TTY environments. Useful for clearing\n * progress indicators created with `progress()`.\n *\n * The stream to clear (stderr or stdout) depends on whether the logger\n * is stream-bound.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.progress('Loading...')\n * // ... do work ...\n * logger.clearLine()\n * logger.success('Loaded')\n *\n * // Clear multiple progress updates\n * for (const file of files) {\n * logger.progress(`Processing ${file}`)\n * processFile(file)\n * logger.clearLine()\n * }\n * logger.success('All files processed')\n * ```\n */\n clearLine(): this {\n const con = this.#getConsole()\n const stream = this.#getTargetStream()\n const streamObj = (\n stream === 'stderr' ? con._stderr : con._stdout\n ) as NodeJS.WriteStream & {\n isTTY: boolean\n cursorTo: (x: number) => void\n clearLine: (dir: number) => void\n write: (text: string) => boolean\n }\n if (streamObj.isTTY) {\n streamObj.cursorTo(0)\n streamObj.clearLine(0)\n } else {\n streamObj.write('\\r\\x1b[K')\n }\n return this\n }\n}\n\nObject.defineProperties(\n Logger.prototype,\n Object.fromEntries(\n (() => {\n const entries: Array<[string | symbol, PropertyDescriptor]> = [\n [\n kGroupIndentationWidthSymbol,\n {\n ...consolePropAttributes,\n value: 2,\n },\n ],\n [\n Symbol.toStringTag,\n {\n __proto__: null,\n configurable: true,\n value: 'logger',\n } as PropertyDescriptor,\n ],\n ]\n for (const { 0: key, 1: value } of Object.entries(globalConsole)) {\n if (!(Logger.prototype as any)[key] && typeof value === 'function') {\n // Dynamically name the log method without using Object.defineProperty.\n const { [key]: func } = {\n [key](this: Logger, ...args: unknown[]) {\n // Access Console via WeakMap directly since private methods can't be\n // called from dynamically created functions.\n let con = privateConsole.get(this)\n if (con === undefined) {\n // Lazy initialization - this will only happen if someone calls a\n // dynamically added console method before any core logger method.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n // Clean up constructor args - no longer needed after Console creation.\n privateConstructorArgs.delete(this)\n if (ctorArgs.length) {\n con = constructConsole(...ctorArgs)\n } else {\n con = constructConsole({\n stdout: process.stdout,\n stderr: process.stderr,\n }) as typeof console & Record<string, unknown>\n for (const { 0: k, 1: method } of boundConsoleEntries) {\n con[k] = method\n }\n }\n privateConsole.set(this, con)\n }\n const result = (con as any)[key](...args)\n return result === undefined || result === con ? this : result\n },\n }\n entries.push([\n key,\n {\n ...consolePropAttributes,\n value: func,\n },\n ])\n }\n }\n return entries\n })(),\n ),\n)\n\n/**\n * Default logger instance for the application.\n *\n * A pre-configured `Logger` instance that uses the standard `process.stdout`\n * and `process.stderr` streams. This is the recommended logger to import\n * and use throughout your application.\n *\n * @example\n * ```typescript\n * import { logger } from '@socketsecurity/lib'\n *\n * logger.log('Application started')\n * logger.success('Configuration loaded')\n * logger.indent()\n * logger.log('Using port 3000')\n * logger.dedent()\n * ```\n */\nexport const logger = new Logger()\n"],
|
|
5
|
-
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,WAAAC,EAAA,0BAAAC,EAAA,uBAAAC,EAAA,WAAAC,IAAA,eAAAC,EAAAP,GAKA,IAAAQ,EAA+B,8DAC/BC,EAA2B,yCAC3BC,EAA2C,qBAC3CC,EAA+C,qBAuE/C,MAAMC,EAAgB,QAKhBC,EAAe,QAAQ,MACvBC,EAAmB,QAAQ,UAEjC,IAAIC,EAMJ,SAASC,KAAoBC,EAAiB,CAC5C,OAAIF,IAAa,SAIfA,EADkC,QAAQ,cAAc,EACjC,SAElBD,EACLC,EAGAE,CACF,CACF,CAOA,SAASC,GAAiB,CACxB,OAAO,EAAAC,OACT,CAsBO,MAAMjB,GAA6B,IAAM,CAC9C,MAAMkB,EAAiC,CACrC,UAAW,IACb,EAEMC,EAAgD,CACpD,UAAW,IACb,EACMC,EAAO,IAAM,CACjB,MAAMC,KAAY,EAAAC,SAAmB,EAC/BC,EAASP,EAAe,KAC9B,gBAAaE,EAAQ,CACnB,KAAMK,EAAO,IAAIF,EAAY,SAAM,MAAG,EACtC,KAAME,EAAO,KAAKF,EAAY,SAAM,GAAG,EACvC,KAAME,EAAO,KAAKF,EAAY,SAAM,GAAG,EACvC,QAASE,EAAO,MAAMF,EAAY,SAAM,QAAG,EAC3C,KAAME,EAAO,OAAOF,EAAY,SAAM,QAAG,CAC3C,CAAC,KACD,gBAAaH,CAAM,EAGnB,UAAWM,KAAYL,EACrB,OAAOA,EAAQK,CAAsD,CAEzE,EACA,UAAWA,KAAY,QAAQ,QAAQ,OAAO,EAAG,CAC/C,MAAMC,EAAM,QAAyCD,CAAQ,EACzD,OAAOC,GAAO,aACdN,EACAK,CACF,EAAI,IAAIT,KACNK,EAAK,EACEK,EAAG,GAAGV,CAAI,GAGvB,CACA,OAAO,IAAI,MAAMG,EAAQC,CAAO,CAClC,GAAG,EAEGO,EAAsB,CAG1B,sBACA,sBAEA,SACA,QACA,QACA,aACA,aACA,QACA,MACA,SACA,QAOA,OACA,MACA,QACA,OACA,UACA,UACA,QACA,MACF,EACG,OAAOC,GAAK,OAAQjB,EAAsBiB,CAAC,GAAM,UAAU,EAC3D,IAAIA,GAAK,CAACA,EAAIjB,EAAsBiB,CAAC,EAAE,KAAKjB,CAAa,CAAC,CAAC,EAExDkB,EAAwB,CAC5B,UAAW,KACX,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,EACMC,EAAiB,IASjBC,EAAiB,IAAI,QAarBC,EAAyB,IAAI,
|
|
6
|
-
"names": ["logger_exports", "__export", "LOG_SYMBOLS", "Logger", "incLogCallCountSymbol", "lastWasBlankSymbol", "logger", "__toCommonJS", "import_is_unicode_supported", "import_yoctocolors_cjs", "import_objects", "import_strings", "globalConsole", "ReflectApply", "ReflectConstruct", "_Console", "constructConsole", "args", "getYoctocolors", "yoctocolorsCjs", "target", "handler", "init", "supported", "isUnicodeSupported", "colors", "trapName", "fn", "boundConsoleEntries", "n", "consolePropAttributes", "maxIndentation", "privateConsole", "privateConstructorArgs", "
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Console logging utilities with line prefix support.\n * Provides enhanced console methods with formatted output capabilities.\n */\n\nimport isUnicodeSupported from './external/@socketregistry/is-unicode-supported'\nimport yoctocolorsCjs from './external/yoctocolors-cjs'\nimport { objectAssign, objectFreeze } from './objects'\nimport { applyLinePrefix, isBlankString } from './strings'\n\n/**\n * Log symbols for terminal output with colored indicators.\n *\n * Each symbol provides visual feedback for different message types, with\n * Unicode and ASCII fallback support.\n *\n * @example\n * ```typescript\n * import { LOG_SYMBOLS } from '@socketsecurity/lib'\n *\n * console.log(`${LOG_SYMBOLS.success} Operation completed`)\n * console.log(`${LOG_SYMBOLS.fail} Operation failed`)\n * console.log(`${LOG_SYMBOLS.warn} Warning message`)\n * console.log(`${LOG_SYMBOLS.info} Information message`)\n * console.log(`${LOG_SYMBOLS.step} Processing step`)\n * ```\n */\ntype LogSymbols = {\n /** Red colored failure symbol (\u2716 or \u00D7 in ASCII) */\n fail: string\n /** Blue colored information symbol (\u2139 or i in ASCII) */\n info: string\n /** Cyan colored step symbol (\u2192 or > in ASCII) */\n step: string\n /** Green colored success symbol (\u2714 or \u221A in ASCII) */\n success: string\n /** Yellow colored warning symbol (\u26A0 or \u203C in ASCII) */\n warn: string\n}\n\n/**\n * Type definition for logger methods that mirror console methods.\n *\n * All methods return the logger instance for method chaining.\n */\ntype LoggerMethods = {\n [K in keyof typeof console]: (typeof console)[K] extends (\n ...args: infer A\n ) => any\n ? (...args: A) => Logger\n : (typeof console)[K]\n}\n\n/**\n * A task that can be executed with automatic start/complete logging.\n *\n * @example\n * ```typescript\n * const task = logger.createTask('Database migration')\n * task.run(() => {\n * // Migration logic here\n * })\n * // Logs: \"Starting task: Database migration\"\n * // Logs: \"Completed task: Database migration\"\n * ```\n */\ninterface Task {\n /**\n * Executes the task function with automatic logging.\n *\n * @template T - The return type of the task function\n * @param f - The function to execute\n * @returns The result of the task function\n */\n run<T>(f: () => T): T\n}\n\nexport type { LogSymbols, LoggerMethods, Task }\n\nconst globalConsole = console\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\n// tsgo has a bug that incorrectly transpiles destructured exports, resulting in\n// `exports.SomeName = void 0;` which causes runtime errors.\n// See: https://github.com/SocketDev/socket-packageurl-js/issues/3\nconst ReflectApply = Reflect.apply\nconst ReflectConstruct = Reflect.construct\n\nlet _Console: typeof import('console').Console | undefined\n/**\n * Construct a new Console instance.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction constructConsole(...args: unknown[]) {\n if (_Console === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n const nodeConsole = /*@__PURE__*/ require('node:console')\n _Console = nodeConsole.Console\n }\n return ReflectConstruct(\n _Console! as new (\n ...args: unknown[]\n ) => Console, // eslint-disable-line no-undef\n args,\n )\n}\n\n/**\n * Get the yoctocolors module for terminal colors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getYoctocolors() {\n return yoctocolorsCjs\n}\n\n/**\n * Log symbols for terminal output with colored indicators.\n *\n * Provides colored Unicode symbols (\u2714, \u2716, \u26A0, \u2139, \u2192) with ASCII fallbacks (\u221A, \u00D7, \u203C, i, >)\n * for terminals that don't support Unicode. Symbols are color-coded: green for\n * success, red for failure, yellow for warnings, blue for info, cyan for step.\n *\n * The symbols are lazily initialized on first access and then frozen for immutability.\n *\n * @example\n * ```typescript\n * import { LOG_SYMBOLS } from '@socketsecurity/lib'\n *\n * console.log(`${LOG_SYMBOLS.success} Build completed`) // Green \u2714\n * console.log(`${LOG_SYMBOLS.fail} Build failed`) // Red \u2716\n * console.log(`${LOG_SYMBOLS.warn} Deprecated API used`) // Yellow \u26A0\n * console.log(`${LOG_SYMBOLS.info} Starting process`) // Blue \u2139\n * console.log(`${LOG_SYMBOLS.step} Processing files`) // Cyan \u2192\n * ```\n */\nexport const LOG_SYMBOLS = /*@__PURE__*/ (() => {\n const target: Record<string, string> = {\n __proto__: null,\n } as unknown as Record<string, string>\n // Mutable handler to simulate a frozen target.\n const handler: ProxyHandler<Record<string, string>> = {\n __proto__: null,\n } as unknown as ProxyHandler<Record<string, string>>\n const init = () => {\n const supported = isUnicodeSupported()\n const colors = getYoctocolors()\n objectAssign(target, {\n fail: colors.red(supported ? '\u2716' : '\u00D7'),\n info: colors.blue(supported ? '\u2139' : 'i'),\n step: colors.cyan(supported ? '\u2192' : '>'),\n success: colors.green(supported ? '\u2714' : '\u221A'),\n warn: colors.yellow(supported ? '\u26A0' : '\u203C'),\n })\n objectFreeze(target)\n // The handler of a Proxy is mutable after proxy instantiation.\n // We delete the traps to defer to native behavior.\n for (const trapName in handler) {\n delete handler[trapName as keyof ProxyHandler<Record<string, string>>]\n }\n }\n for (const trapName of Reflect.ownKeys(Reflect)) {\n const fn = (Reflect as Record<PropertyKey, unknown>)[trapName]\n if (typeof fn === 'function') {\n ;(handler as Record<string, (...args: unknown[]) => unknown>)[\n trapName as string\n ] = (...args: unknown[]) => {\n init()\n return fn(...args)\n }\n }\n }\n return new Proxy(target, handler)\n})()\n\nconst boundConsoleEntries = [\n // Add bound properties from console[kBindProperties](ignoreErrors, colorMode, groupIndentation).\n // https://github.com/nodejs/node/blob/v24.0.1/lib/internal/console/constructor.js#L230-L265\n '_stderrErrorHandler',\n '_stdoutErrorHandler',\n // Add methods that need to be bound to function properly.\n 'assert',\n 'clear',\n 'count',\n 'countReset',\n 'createTask',\n 'debug',\n 'dir',\n 'dirxml',\n 'error',\n // Skip group methods because in at least Node 20 with the Node --frozen-intrinsics\n // flag it triggers a readonly property for Symbol(kGroupIndent). Instead, we\n // implement these methods ourselves.\n //'group',\n //'groupCollapsed',\n //'groupEnd',\n 'info',\n 'log',\n 'table',\n 'time',\n 'timeEnd',\n 'timeLog',\n 'trace',\n 'warn',\n]\n .filter(n => typeof (globalConsole as any)[n] === 'function')\n .map(n => [n, (globalConsole as any)[n].bind(globalConsole)])\n\nconst consolePropAttributes = {\n __proto__: null,\n writable: true,\n enumerable: false,\n configurable: true,\n}\nconst maxIndentation = 1000\n\n/**\n * WeakMap storing the Console instance for each Logger.\n *\n * Console creation is lazy - deferred until first logging method call.\n * This allows logger to be imported during early Node.js bootstrap before\n * stdout is ready, avoiding ERR_CONSOLE_WRITABLE_STREAM errors.\n */\nconst privateConsole = new WeakMap()\n\n/**\n * WeakMap storing constructor arguments for lazy Console initialization.\n *\n * WeakMap is required instead of a private field (#constructorArgs) because:\n * 1. Private fields can't be accessed from dynamically created functions\n * 2. Logger adds console methods dynamically to its prototype (lines 1560+)\n * 3. These dynamic methods need constructor args for lazy initialization\n * 4. WeakMap allows both regular methods and dynamic functions to access args\n *\n * The args are deleted from the WeakMap after Console is created (memory cleanup).\n */\nconst privateConstructorArgs = new WeakMap()\n\n/**\n * Lazily get console symbols on first access.\n *\n * Deferred to avoid accessing global console during early Node.js bootstrap\n * before stdout is ready.\n * @private\n */\nlet _consoleSymbols: symbol[] | undefined\nfunction getConsoleSymbols(): symbol[] {\n if (_consoleSymbols === undefined) {\n _consoleSymbols = Object.getOwnPropertySymbols(globalConsole)\n }\n return _consoleSymbols\n}\n\n/**\n * Symbol for incrementing the internal log call counter.\n *\n * This is an internal symbol used to track the number of times logging\n * methods have been called on a logger instance.\n */\nexport const incLogCallCountSymbol = Symbol.for('logger.logCallCount++')\n\n/**\n * Lazily get kGroupIndentationWidth symbol on first access.\n * @private\n */\nlet _kGroupIndentationWidthSymbol: symbol | undefined\nfunction getKGroupIndentationWidthSymbol(): symbol {\n if (_kGroupIndentationWidthSymbol === undefined) {\n _kGroupIndentationWidthSymbol =\n getConsoleSymbols().find(s => (s as any).label === 'kGroupIndentWidth') ??\n Symbol('kGroupIndentWidth')\n }\n return _kGroupIndentationWidthSymbol\n}\n\n/**\n * Symbol for tracking whether the last logged line was blank.\n *\n * This is used internally to prevent multiple consecutive blank lines\n * and to determine whether to add spacing before certain messages.\n */\nexport const lastWasBlankSymbol = Symbol.for('logger.lastWasBlank')\n\n/**\n * Enhanced console logger with indentation, colored symbols, and stream management.\n *\n * Provides a fluent API for logging with automatic indentation tracking, colored\n * status symbols, separate stderr/stdout management, and method chaining. All\n * methods return `this` for easy chaining.\n *\n * Features:\n * - Automatic line prefixing with indentation\n * - Colored status symbols (success, fail, warn, info)\n * - Separate indentation tracking for stderr and stdout\n * - Stream-bound logger instances via `.stderr` and `.stdout`\n * - Group/indentation management\n * - Progress indicators with clearable lines\n * - Task execution with automatic logging\n *\n * @example\n * ```typescript\n * import { logger } from '@socketsecurity/lib'\n *\n * // Basic logging with symbols\n * logger.success('Build completed')\n * logger.fail('Build failed')\n * logger.warn('Deprecated API')\n * logger.info('Starting process')\n *\n * // Indentation and grouping\n * logger.log('Processing files:')\n * logger.indent()\n * logger.log('file1.js')\n * logger.log('file2.js')\n * logger.dedent()\n *\n * // Method chaining\n * logger\n * .log('Step 1')\n * .indent()\n * .log('Substep 1.1')\n * .log('Substep 1.2')\n * .dedent()\n * .log('Step 2')\n *\n * // Stream-specific logging\n * logger.stdout.log('Normal output')\n * logger.stderr.error('Error message')\n *\n * // Progress indicators\n * logger.progress('Processing...')\n * // ... do work ...\n * logger.clearLine()\n * logger.success('Done')\n *\n * // Task execution\n * const task = logger.createTask('Migration')\n * task.run(() => {\n * // Migration logic\n * })\n * ```\n */\n/*@__PURE__*/\nexport class Logger {\n /**\n * Static reference to log symbols for convenience.\n *\n * @example\n * ```typescript\n * console.log(`${Logger.LOG_SYMBOLS.success} Done`)\n * ```\n */\n static LOG_SYMBOLS = LOG_SYMBOLS\n\n #parent?: Logger\n #boundStream?: 'stderr' | 'stdout'\n #stderrLogger?: Logger\n #stdoutLogger?: Logger\n #stderrIndention = ''\n #stdoutIndention = ''\n #stderrLastWasBlank = false\n #stdoutLastWasBlank = false\n #logCallCount = 0\n #options: Record<string, unknown>\n #originalStdout?: any\n\n /**\n * Creates a new Logger instance.\n *\n * When called without arguments, creates a logger using the default\n * `process.stdout` and `process.stderr` streams. Can accept custom\n * console constructor arguments for advanced use cases.\n *\n * @param args - Optional console constructor arguments\n *\n * @example\n * ```typescript\n * // Default logger\n * const logger = new Logger()\n *\n * // Custom streams (advanced)\n * const customLogger = new Logger({\n * stdout: customWritableStream,\n * stderr: customErrorStream\n * })\n * ```\n */\n constructor(...args: unknown[]) {\n // Store constructor args for lazy Console initialization.\n privateConstructorArgs.set(this, args)\n\n // Store options if provided (for future extensibility)\n const options = args['0']\n if (typeof options === 'object' && options !== null) {\n this.#options = { __proto__: null, ...options }\n // Store reference to original stdout stream to bypass Console formatting\n this.#originalStdout = (options as any).stdout\n } else {\n this.#options = { __proto__: null }\n }\n\n // Note: Console initialization is now lazy (happens on first use).\n // This allows logger to be imported during early bootstrap before\n // stdout is ready, avoiding ERR_CONSOLE_WRITABLE_STREAM errors.\n }\n\n /**\n * Get the Console instance for this logger, creating it lazily on first access.\n *\n * This lazy initialization allows the logger to be imported during early\n * Node.js bootstrap before stdout is ready, avoiding Console initialization\n * errors (ERR_CONSOLE_WRITABLE_STREAM).\n *\n * @private\n */\n #getConsole(): typeof console & Record<string, unknown> {\n // Ensure prototype is initialized before creating Console.\n ensurePrototypeInitialized()\n\n let con = privateConsole.get(this)\n if (!con) {\n // Lazy initialization - create Console on first use.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n if (ctorArgs.length) {\n con = constructConsole(...ctorArgs)\n } else {\n // Create a new console that acts like the builtin one so that it will\n // work with Node's --frozen-intrinsics flag.\n con = constructConsole({\n stdout: process.stdout,\n stderr: process.stderr,\n }) as typeof console & Record<string, unknown>\n for (const { 0: key, 1: method } of boundConsoleEntries) {\n con[key] = method\n }\n }\n privateConsole.set(this, con)\n // Clean up constructor args - no longer needed after Console creation.\n privateConstructorArgs.delete(this)\n }\n return con\n }\n\n /**\n * Gets a logger instance bound exclusively to stderr.\n *\n * All logging operations on this instance will write to stderr only.\n * Indentation is tracked separately from stdout. The instance is\n * cached and reused on subsequent accesses.\n *\n * @returns A logger instance bound to stderr\n *\n * @example\n * ```typescript\n * // Write errors to stderr\n * logger.stderr.error('Configuration invalid')\n * logger.stderr.warn('Using fallback settings')\n *\n * // Indent only affects stderr\n * logger.stderr.indent()\n * logger.stderr.error('Nested error details')\n * logger.stderr.dedent()\n * ```\n */\n get stderr(): Logger {\n if (!this.#stderrLogger) {\n // Pass parent's constructor args to maintain config.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n const instance = new Logger(...ctorArgs)\n instance.#parent = this\n instance.#boundStream = 'stderr'\n instance.#options = { __proto__: null, ...this.#options }\n this.#stderrLogger = instance\n }\n return this.#stderrLogger\n }\n\n /**\n * Gets a logger instance bound exclusively to stdout.\n *\n * All logging operations on this instance will write to stdout only.\n * Indentation is tracked separately from stderr. The instance is\n * cached and reused on subsequent accesses.\n *\n * @returns A logger instance bound to stdout\n *\n * @example\n * ```typescript\n * // Write normal output to stdout\n * logger.stdout.log('Processing started')\n * logger.stdout.log('Items processed: 42')\n *\n * // Indent only affects stdout\n * logger.stdout.indent()\n * logger.stdout.log('Detailed output')\n * logger.stdout.dedent()\n * ```\n */\n get stdout(): Logger {\n if (!this.#stdoutLogger) {\n // Pass parent's constructor args to maintain config.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n const instance = new Logger(...ctorArgs)\n instance.#parent = this\n instance.#boundStream = 'stdout'\n instance.#options = { __proto__: null, ...this.#options }\n this.#stdoutLogger = instance\n }\n return this.#stdoutLogger\n }\n\n /**\n * Get the root logger (for accessing shared indentation state).\n * @private\n */\n #getRoot(): Logger {\n return this.#parent || this\n }\n\n /**\n * Get indentation for a specific stream.\n * @private\n */\n #getIndent(stream: 'stderr' | 'stdout'): string {\n const root = this.#getRoot()\n return stream === 'stderr' ? root.#stderrIndention : root.#stdoutIndention\n }\n\n /**\n * Set indentation for a specific stream.\n * @private\n */\n #setIndent(stream: 'stderr' | 'stdout', value: string): void {\n const root = this.#getRoot()\n if (stream === 'stderr') {\n root.#stderrIndention = value\n } else {\n root.#stdoutIndention = value\n }\n }\n\n /**\n * Get lastWasBlank state for a specific stream.\n * @private\n */\n #getLastWasBlank(stream: 'stderr' | 'stdout'): boolean {\n const root = this.#getRoot()\n return stream === 'stderr'\n ? root.#stderrLastWasBlank\n : root.#stdoutLastWasBlank\n }\n\n /**\n * Set lastWasBlank state for a specific stream.\n * @private\n */\n #setLastWasBlank(stream: 'stderr' | 'stdout', value: boolean): void {\n const root = this.#getRoot()\n if (stream === 'stderr') {\n root.#stderrLastWasBlank = value\n } else {\n root.#stdoutLastWasBlank = value\n }\n }\n\n /**\n * Get the target stream for this logger instance.\n * @private\n */\n #getTargetStream(): 'stderr' | 'stdout' {\n return this.#boundStream || 'stderr'\n }\n\n /**\n * Apply a console method with indentation.\n * @private\n */\n #apply(\n methodName: string,\n args: unknown[],\n stream?: 'stderr' | 'stdout',\n ): this {\n const con = this.#getConsole()\n const text = args.at(0)\n const hasText = typeof text === 'string'\n // Determine which stream this method writes to\n const targetStream = stream || (methodName === 'log' ? 'stdout' : 'stderr')\n const indent = this.#getIndent(targetStream)\n const logArgs = hasText\n ? [applyLinePrefix(text, { prefix: indent }), ...args.slice(1)]\n : args\n ReflectApply(\n con[methodName] as (...args: unknown[]) => unknown,\n con,\n logArgs,\n )\n this[lastWasBlankSymbol](hasText && isBlankString(logArgs[0]), targetStream)\n ;(this as any)[incLogCallCountSymbol]()\n return this\n }\n\n /**\n * Strip log symbols from the start of text.\n * @private\n */\n #stripSymbols(text: string): string {\n // Strip both unicode and emoji forms of log symbols from the start.\n // Matches: \u2716, \u2717, \u00D7, \u2716\uFE0F, \u26A0, \u203C, \u26A0\uFE0F, \u2714, \u2713, \u221A, \u2714\uFE0F, \u2713\uFE0F, \u2139, \u2139\uFE0F, \u2192, >\n // Also handles variation selectors (U+FE0F) and whitespace after symbol.\n // Note: We don't strip standalone 'i' or '>' to avoid breaking words.\n return text.replace(/^[\u2716\u2717\u00D7\u26A0\u203C\u2714\u2713\u221A\u2139\u2192]\\uFE0F?\\s*/u, '')\n }\n\n /**\n * Apply a method with a symbol prefix.\n * @private\n */\n #symbolApply(symbolType: string, args: unknown[]): this {\n const con = this.#getConsole()\n let text = args.at(0)\n // biome-ignore lint/suspicious/noImplicitAnyLet: Flexible argument handling.\n let extras\n if (typeof text === 'string') {\n text = this.#stripSymbols(text)\n extras = args.slice(1)\n } else {\n extras = args\n text = ''\n }\n // Note: Meta status messages (info/fail/etc) always go to stderr.\n const indent = this.#getIndent('stderr')\n con.error(\n applyLinePrefix(`${LOG_SYMBOLS[symbolType]} ${text}`, {\n prefix: indent,\n }),\n ...extras,\n )\n this[lastWasBlankSymbol](false, 'stderr')\n ;(this as any)[incLogCallCountSymbol]()\n return this\n }\n\n /**\n * Gets the total number of log calls made on this logger instance.\n *\n * Tracks all logging method calls including `log()`, `error()`, `warn()`,\n * `success()`, `fail()`, etc. Useful for testing and monitoring logging activity.\n *\n * @returns The number of times logging methods have been called\n *\n * @example\n * ```typescript\n * logger.log('Message 1')\n * logger.error('Message 2')\n * console.log(logger.logCallCount) // 2\n * ```\n */\n get logCallCount() {\n const root = this.#getRoot()\n return root.#logCallCount\n }\n\n /**\n * Increments the internal log call counter.\n *\n * This is called automatically by logging methods and should not\n * be called directly in normal usage.\n *\n * @returns The logger instance for chaining\n */\n [incLogCallCountSymbol]() {\n const root = this.#getRoot()\n root.#logCallCount += 1\n return this\n }\n\n /**\n * Sets whether the last logged line was blank.\n *\n * Used internally to track blank lines and prevent duplicate spacing.\n * This is called automatically by logging methods.\n *\n * @param value - Whether the last line was blank\n * @param stream - Optional stream to update (defaults to both streams if not bound, or target stream if bound)\n * @returns The logger instance for chaining\n */\n [lastWasBlankSymbol](value: unknown, stream?: 'stderr' | 'stdout'): this {\n if (stream) {\n // Explicit stream specified\n this.#setLastWasBlank(stream, !!value)\n } else if (this.#boundStream) {\n // Stream-bound logger - affect only the bound stream\n this.#setLastWasBlank(this.#boundStream, !!value)\n } else {\n // Root logger with no stream specified - affect both streams\n this.#setLastWasBlank('stderr', !!value)\n this.#setLastWasBlank('stdout', !!value)\n }\n return this\n }\n\n /**\n * Logs an assertion failure message if the value is falsy.\n *\n * Works like `console.assert()` but returns the logger for chaining.\n * If the value is truthy, nothing is logged. If falsy, logs an error\n * message with an assertion failure.\n *\n * @param value - The value to test\n * @param message - Optional message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.assert(true, 'This will not log')\n * logger.assert(false, 'Assertion failed: value is false')\n * logger.assert(items.length > 0, 'No items found')\n * ```\n */\n assert(value: unknown, ...message: unknown[]): this {\n const con = this.#getConsole()\n con.assert(value, message[0] as string, ...message.slice(1))\n this[lastWasBlankSymbol](false)\n return value ? this : this[incLogCallCountSymbol]()\n }\n\n /**\n * Clears the visible terminal screen.\n *\n * Only available on the main logger instance, not on stream-bound instances\n * (`.stderr` or `.stdout`). Resets the log call count and blank line tracking\n * if the output is a TTY.\n *\n * @returns The logger instance for chaining\n * @throws {Error} If called on a stream-bound logger instance\n *\n * @example\n * ```typescript\n * logger.log('Some output')\n * logger.clearVisible() // Screen is now clear\n *\n * // Error: Can't call on stream-bound instance\n * logger.stderr.clearVisible() // throws\n * ```\n */\n clearVisible() {\n if (this.#boundStream) {\n throw new Error(\n 'clearVisible() is only available on the main logger instance, not on stream-bound instances',\n )\n }\n const con = this.#getConsole()\n con.clear()\n if ((con as any)._stdout.isTTY) {\n ;(this as any)[lastWasBlankSymbol](true)\n this.#logCallCount = 0\n }\n return this\n }\n\n /**\n * Increments and logs a counter for the given label.\n *\n * Each unique label maintains its own counter. Works like `console.count()`.\n *\n * @param label - Optional label for the counter\n * @default 'default'\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.count('requests') // requests: 1\n * logger.count('requests') // requests: 2\n * logger.count('errors') // errors: 1\n * logger.count() // default: 1\n * ```\n */\n count(label?: string | undefined): this {\n const con = this.#getConsole()\n con.count(label)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Creates a task that logs start and completion messages automatically.\n *\n * Returns a task object with a `run()` method that executes the provided\n * function and logs \"Starting task: {name}\" before execution and\n * \"Completed task: {name}\" after completion.\n *\n * @param name - The name of the task\n * @returns A task object with a `run()` method\n *\n * @example\n * ```typescript\n * const task = logger.createTask('Database Migration')\n * const result = task.run(() => {\n * // Logs: \"Starting task: Database Migration\"\n * migrateDatabase()\n * return 'success'\n * // Logs: \"Completed task: Database Migration\"\n * })\n * console.log(result) // 'success'\n * ```\n */\n createTask(name: string): Task {\n return {\n run: <T>(f: () => T): T => {\n this.log(`Starting task: ${name}`)\n const result = f()\n this.log(`Completed task: ${name}`)\n return result\n },\n }\n }\n\n /**\n * Decreases the indentation level by removing spaces from the prefix.\n *\n * When called on the main logger, affects both stderr and stdout indentation.\n * When called on a stream-bound logger (`.stderr` or `.stdout`), affects\n * only that stream's indentation.\n *\n * @param spaces - Number of spaces to remove from indentation\n * @default 2\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.indent()\n * logger.log('Indented')\n * logger.dedent()\n * logger.log('Back to normal')\n *\n * // Remove custom amount\n * logger.indent(4)\n * logger.log('Four spaces')\n * logger.dedent(4)\n *\n * // Stream-specific dedent\n * logger.stdout.indent()\n * logger.stdout.log('Indented stdout')\n * logger.stdout.dedent()\n * ```\n */\n dedent(spaces = 2) {\n if (this.#boundStream) {\n // Only affect bound stream\n const current = this.#getIndent(this.#boundStream)\n this.#setIndent(this.#boundStream, current.slice(0, -spaces))\n } else {\n // Affect both streams\n const stderrCurrent = this.#getIndent('stderr')\n const stdoutCurrent = this.#getIndent('stdout')\n this.#setIndent('stderr', stderrCurrent.slice(0, -spaces))\n this.#setIndent('stdout', stdoutCurrent.slice(0, -spaces))\n }\n return this\n }\n\n /**\n * Displays an object's properties in a formatted way.\n *\n * Works like `console.dir()` with customizable options for depth,\n * colors, etc. Useful for inspecting complex objects.\n *\n * @param obj - The object to display\n * @param options - Optional formatting options (Node.js inspect options)\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * const obj = { a: 1, b: { c: 2, d: { e: 3 } } }\n * logger.dir(obj)\n * logger.dir(obj, { depth: 1 }) // Limit nesting depth\n * logger.dir(obj, { colors: true }) // Enable colors\n * ```\n */\n dir(obj: unknown, options?: unknown | undefined): this {\n const con = this.#getConsole()\n con.dir(obj, options)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Displays data as XML/HTML in a formatted way.\n *\n * Works like `console.dirxml()`. In Node.js, behaves the same as `dir()`.\n *\n * @param data - The data to display\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.dirxml(document.body) // In browser environments\n * logger.dirxml(xmlObject) // In Node.js\n * ```\n */\n dirxml(...data: unknown[]): this {\n const con = this.#getConsole()\n con.dirxml(data)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs an error message to stderr.\n *\n * Automatically applies current indentation. All arguments are formatted\n * and logged like `console.error()`.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.error('Build failed')\n * logger.error('Error code:', 500)\n * logger.error('Details:', { message: 'Not found' })\n * ```\n */\n error(...args: unknown[]): this {\n return this.#apply('error', args)\n }\n\n /**\n * Logs a newline to stderr only if the last line wasn't already blank.\n *\n * Prevents multiple consecutive blank lines. Useful for adding spacing\n * between sections without creating excessive whitespace.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.error('Error message')\n * logger.errorNewline() // Adds blank line\n * logger.errorNewline() // Does nothing (already blank)\n * logger.error('Next section')\n * ```\n */\n errorNewline() {\n return this.#getLastWasBlank('stderr') ? this : this.error('')\n }\n\n /**\n * Logs a failure message with a red colored fail symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.fail` (red \u2716).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.fail('Build failed')\n * logger.fail('Test suite failed:', { passed: 5, failed: 3 })\n * ```\n */\n fail(...args: unknown[]): this {\n return this.#symbolApply('fail', args)\n }\n\n /**\n * Starts a new indented log group.\n *\n * If a label is provided, it's logged before increasing indentation.\n * Groups can be nested. Each group increases indentation by the\n * `kGroupIndentWidth` (default 2 spaces). Call `groupEnd()` to close.\n *\n * @param label - Optional label to display before the group\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.group('Processing files:')\n * logger.log('file1.js')\n * logger.log('file2.js')\n * logger.groupEnd()\n *\n * // Nested groups\n * logger.group('Outer')\n * logger.log('Outer content')\n * logger.group('Inner')\n * logger.log('Inner content')\n * logger.groupEnd()\n * logger.groupEnd()\n * ```\n */\n group(...label: unknown[]): this {\n const { length } = label\n if (length) {\n ReflectApply(this.log, this, label)\n }\n this.indent((this as any)[getKGroupIndentationWidthSymbol()])\n if (length) {\n ;(this as any)[lastWasBlankSymbol](false)\n ;(this as any)[incLogCallCountSymbol]()\n }\n return this\n }\n\n /**\n * Starts a new collapsed log group (alias for `group()`).\n *\n * In browser consoles, this creates a collapsed group. In Node.js,\n * it behaves identically to `group()`.\n *\n * @param label - Optional label to display before the group\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.groupCollapsed('Details')\n * logger.log('Hidden by default in browsers')\n * logger.groupEnd()\n * ```\n */\n // groupCollapsed is an alias of group.\n // https://nodejs.org/api/console.html#consolegroupcollapsed\n groupCollapsed(...label: unknown[]): this {\n return ReflectApply(this.group, this, label)\n }\n\n /**\n * Ends the current log group and decreases indentation.\n *\n * Must be called once for each `group()` or `groupCollapsed()` call\n * to properly close the group and restore indentation.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.group('Group 1')\n * logger.log('Content')\n * logger.groupEnd() // Closes 'Group 1'\n * ```\n */\n groupEnd() {\n this.dedent((this as any)[getKGroupIndentationWidthSymbol()])\n return this\n }\n\n /**\n * Increases the indentation level by adding spaces to the prefix.\n *\n * When called on the main logger, affects both stderr and stdout indentation.\n * When called on a stream-bound logger (`.stderr` or `.stdout`), affects\n * only that stream's indentation. Maximum indentation is 1000 spaces.\n *\n * @param spaces - Number of spaces to add to indentation\n * @default 2\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Level 0')\n * logger.indent()\n * logger.log('Level 1')\n * logger.indent()\n * logger.log('Level 2')\n * logger.dedent()\n * logger.dedent()\n *\n * // Custom indent amount\n * logger.indent(4)\n * logger.log('Indented 4 spaces')\n * logger.dedent(4)\n *\n * // Stream-specific indent\n * logger.stdout.indent()\n * logger.stdout.log('Only stdout is indented')\n * ```\n */\n indent(spaces = 2) {\n const spacesToAdd = ' '.repeat(Math.min(spaces, maxIndentation))\n if (this.#boundStream) {\n // Only affect bound stream\n const current = this.#getIndent(this.#boundStream)\n this.#setIndent(this.#boundStream, current + spacesToAdd)\n } else {\n // Affect both streams\n const stderrCurrent = this.#getIndent('stderr')\n const stdoutCurrent = this.#getIndent('stdout')\n this.#setIndent('stderr', stderrCurrent + spacesToAdd)\n this.#setIndent('stdout', stdoutCurrent + spacesToAdd)\n }\n return this\n }\n\n /**\n * Logs an informational message with a blue colored info symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.info` (blue \u2139).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.info('Starting build process')\n * logger.info('Configuration loaded:', config)\n * logger.info('Using cache directory:', cacheDir)\n * ```\n */\n info(...args: unknown[]): this {\n return this.#symbolApply('info', args)\n }\n\n /**\n * Logs a message to stdout.\n *\n * Automatically applies current indentation. All arguments are formatted\n * and logged like `console.log()`. This is the primary method for\n * standard output.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Processing complete')\n * logger.log('Items processed:', 42)\n * logger.log('Results:', { success: true, count: 10 })\n *\n * // Method chaining\n * logger.log('Step 1').log('Step 2').log('Step 3')\n * ```\n */\n log(...args: unknown[]): this {\n return this.#apply('log', args)\n }\n\n /**\n * Logs a newline to stdout only if the last line wasn't already blank.\n *\n * Prevents multiple consecutive blank lines. Useful for adding spacing\n * between sections without creating excessive whitespace.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Section 1')\n * logger.logNewline() // Adds blank line\n * logger.logNewline() // Does nothing (already blank)\n * logger.log('Section 2')\n * ```\n */\n logNewline() {\n return this.#getLastWasBlank('stdout') ? this : this.log('')\n }\n\n /**\n * Resets all indentation to zero.\n *\n * When called on the main logger, resets both stderr and stdout indentation.\n * When called on a stream-bound logger (`.stderr` or `.stdout`), resets\n * only that stream's indentation.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.indent().indent().indent()\n * logger.log('Very indented')\n * logger.resetIndent()\n * logger.log('Back to zero indentation')\n *\n * // Reset only stdout\n * logger.stdout.resetIndent()\n * ```\n */\n resetIndent() {\n if (this.#boundStream) {\n // Only reset bound stream\n this.#setIndent(this.#boundStream, '')\n } else {\n // Reset both streams\n this.#setIndent('stderr', '')\n this.#setIndent('stdout', '')\n }\n return this\n }\n\n /**\n * Logs a main step message with a cyan arrow symbol and blank line before it.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.step` (cyan \u2192) and\n * adds a blank line before the message unless the last line was already blank.\n * Useful for marking major steps in a process with clear visual separation.\n * Always outputs to stdout. If the message starts with an existing symbol,\n * it will be stripped and replaced.\n *\n * @param msg - The step message to log\n * @param extras - Additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.step('Building project')\n * logger.log('Compiling TypeScript...')\n * logger.step('Running tests')\n * logger.log('Running test suite...')\n * // Output:\n * // [blank line]\n * // \u2192 Building project\n * // Compiling TypeScript...\n * // [blank line]\n * // \u2192 Running tests\n * // Running test suite...\n * ```\n */\n step(msg: string, ...extras: unknown[]): this {\n // Add blank line before the step message.\n if (!this.#getLastWasBlank('stdout')) {\n // Use this.log() to properly track the blank line.\n this.log('')\n }\n // Strip existing symbols from the message.\n const text = this.#stripSymbols(msg)\n // Note: Step messages always go to stdout (unlike info/fail/etc which go to stderr).\n const indent = this.#getIndent('stdout')\n const con = this.#getConsole() as typeof console & Record<string, unknown>\n con.log(\n applyLinePrefix(`${LOG_SYMBOLS.step} ${text}`, {\n prefix: indent,\n }),\n ...extras,\n )\n this[lastWasBlankSymbol](false, 'stdout')\n ;(this as any)[incLogCallCountSymbol]()\n return this\n }\n\n /**\n * Logs an indented substep message (stateless).\n *\n * Adds a 2-space indent to the message without affecting the logger's\n * indentation state. Useful for showing sub-items under a main step.\n *\n * @param msg - The substep message to log\n * @param extras - Additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.log('Installing dependencies:')\n * logger.substep('Installing react')\n * logger.substep('Installing typescript')\n * logger.substep('Installing eslint')\n * // Output:\n * // Installing dependencies:\n * // Installing react\n * // Installing typescript\n * // Installing eslint\n * ```\n */\n substep(msg: string, ...extras: unknown[]): this {\n // Add 2-space indent to the message.\n const indentedMsg = ` ${msg}`\n // Let log() handle all tracking.\n return this.log(indentedMsg, ...extras)\n }\n\n /**\n * Logs a success message with a green colored success symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.success` (green \u2714).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.success('Build completed')\n * logger.success('Tests passed:', { total: 42, passed: 42 })\n * logger.success('Deployment successful')\n * ```\n */\n success(...args: unknown[]): this {\n return this.#symbolApply('success', args)\n }\n\n /**\n * Logs a completion message with a success symbol (alias for `success()`).\n *\n * Provides semantic clarity when marking something as \"done\". Does NOT\n * automatically clear the current line - call `clearLine()` first if\n * needed after using `progress()`.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.done('Task completed')\n *\n * // After progress indicator\n * logger.progress('Processing...')\n * // ... do work ...\n * logger.clearLine()\n * logger.done('Processing complete')\n * ```\n */\n done(...args: unknown[]): this {\n return this.#symbolApply('success', args)\n }\n\n /**\n * Displays data in a table format.\n *\n * Works like `console.table()`. Accepts arrays of objects or\n * objects with nested objects. Optionally specify which properties\n * to include in the table.\n *\n * @param tabularData - The data to display as a table\n * @param properties - Optional array of property names to include\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * // Array of objects\n * logger.table([\n * { name: 'Alice', age: 30 },\n * { name: 'Bob', age: 25 }\n * ])\n *\n * // Specify properties to show\n * logger.table(users, ['name', 'email'])\n *\n * // Object with nested objects\n * logger.table({\n * user1: { name: 'Alice', age: 30 },\n * user2: { name: 'Bob', age: 25 }\n * })\n * ```\n */\n table(\n tabularData: unknown,\n properties?: readonly string[] | undefined,\n ): this {\n const con = this.#getConsole()\n con.table(tabularData, properties)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Ends a timer and logs the elapsed time.\n *\n * Logs the duration since `console.time()` was called with the same\n * label. The timer is stopped and removed.\n *\n * @param label - Optional label for the timer\n * @default 'default'\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * console.time('operation')\n * // ... do work ...\n * logger.timeEnd('operation')\n * // Logs: \"operation: 123.456ms\"\n *\n * console.time()\n * // ... do work ...\n * logger.timeEnd()\n * // Logs: \"default: 123.456ms\"\n * ```\n */\n timeEnd(label?: string | undefined): this {\n const con = this.#getConsole()\n con.timeEnd(label)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs the current value of a timer without stopping it.\n *\n * Logs the duration since `console.time()` was called with the same\n * label, but keeps the timer running. Can include additional data\n * to log alongside the time.\n *\n * @param label - Optional label for the timer\n * @param data - Additional data to log with the time\n * @default 'default'\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * console.time('process')\n * // ... partial work ...\n * logger.timeLog('process', 'Checkpoint 1')\n * // Logs: \"process: 123.456ms Checkpoint 1\"\n * // ... more work ...\n * logger.timeLog('process', 'Checkpoint 2')\n * // Logs: \"process: 234.567ms Checkpoint 2\"\n * console.timeEnd('process')\n * ```\n */\n timeLog(label?: string | undefined, ...data: unknown[]): this {\n const con = this.#getConsole()\n con.timeLog(label, ...data)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs a stack trace to the console.\n *\n * Works like `console.trace()`. Shows the call stack leading to\n * where this method was called. Useful for debugging.\n *\n * @param message - Optional message to display with the trace\n * @param args - Additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * function debugFunction() {\n * logger.trace('Debug point reached')\n * }\n *\n * logger.trace('Trace from here')\n * logger.trace('Error context:', { userId: 123 })\n * ```\n */\n trace(message?: unknown | undefined, ...args: unknown[]): this {\n const con = this.#getConsole()\n con.trace(message, ...args)\n this[lastWasBlankSymbol](false)\n return this[incLogCallCountSymbol]()\n }\n\n /**\n * Logs a warning message with a yellow colored warning symbol.\n *\n * Automatically prefixes the message with `LOG_SYMBOLS.warn` (yellow \u26A0).\n * Always outputs to stderr. If the message starts with an existing\n * symbol, it will be stripped and replaced.\n *\n * @param args - Message and additional arguments to log\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.warn('Deprecated API used')\n * logger.warn('Low memory:', { available: '100MB' })\n * logger.warn('Missing optional configuration')\n * ```\n */\n warn(...args: unknown[]): this {\n return this.#symbolApply('warn', args)\n }\n\n /**\n * Writes text directly to stdout without a newline or indentation.\n *\n * Useful for progress indicators or custom formatting where you need\n * low-level control. Does not apply any indentation or formatting.\n *\n * @param text - The text to write\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.write('Processing... ')\n * // ... do work ...\n * logger.write('done\\n')\n *\n * // Build a line incrementally\n * logger.write('Step 1')\n * logger.write('... Step 2')\n * logger.write('... Step 3\\n')\n * ```\n */\n write(text: string): this {\n const con = this.#getConsole()\n // Write directly to the original stdout stream to bypass Console formatting\n // (e.g., group indentation). Try multiple approaches to get the raw stream:\n // 1. Use stored reference from constructor options\n // 2. Try to get from constructor args\n // 3. Fall back to con._stdout (which applies formatting)\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n const stdout =\n this.#originalStdout || (ctorArgs[0] as any)?.stdout || con._stdout\n stdout.write(text)\n this[lastWasBlankSymbol](false)\n return this\n }\n\n /**\n * Shows a progress indicator that can be cleared with `clearLine()`.\n *\n * Displays a simple status message with a '\u2234' prefix. Does not include\n * animation or spinner. Intended to be cleared once the operation completes.\n * The output stream (stderr or stdout) depends on whether the logger is\n * stream-bound.\n *\n * @param text - The progress message to display\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.progress('Processing files...')\n * // ... do work ...\n * logger.clearLine()\n * logger.success('Files processed')\n *\n * // Stream-specific progress\n * logger.stdout.progress('Loading...')\n * // ... do work ...\n * logger.stdout.clearLine()\n * logger.stdout.log('Done')\n * ```\n */\n progress(text: string): this {\n const con = this.#getConsole()\n const stream = this.#getTargetStream()\n const streamObj = (\n stream === 'stderr' ? con._stderr : con._stdout\n ) as NodeJS.WriteStream & { write: (text: string) => boolean }\n streamObj.write(`\u2234 ${text}`)\n this[lastWasBlankSymbol](false)\n return this\n }\n\n /**\n * Clears the current line in the terminal.\n *\n * Moves the cursor to the beginning of the line and clears all content.\n * Works in both TTY and non-TTY environments. Useful for clearing\n * progress indicators created with `progress()`.\n *\n * The stream to clear (stderr or stdout) depends on whether the logger\n * is stream-bound.\n *\n * @returns The logger instance for chaining\n *\n * @example\n * ```typescript\n * logger.progress('Loading...')\n * // ... do work ...\n * logger.clearLine()\n * logger.success('Loaded')\n *\n * // Clear multiple progress updates\n * for (const file of files) {\n * logger.progress(`Processing ${file}`)\n * processFile(file)\n * logger.clearLine()\n * }\n * logger.success('All files processed')\n * ```\n */\n clearLine(): this {\n const con = this.#getConsole()\n const stream = this.#getTargetStream()\n const streamObj = (\n stream === 'stderr' ? con._stderr : con._stdout\n ) as NodeJS.WriteStream & {\n isTTY: boolean\n cursorTo: (x: number) => void\n clearLine: (dir: number) => void\n write: (text: string) => boolean\n }\n if (streamObj.isTTY) {\n streamObj.cursorTo(0)\n streamObj.clearLine(0)\n } else {\n streamObj.write('\\r\\x1b[K')\n }\n return this\n }\n}\n\n/**\n * Lazily add dynamic console methods to Logger prototype.\n *\n * This is deferred until first access to avoid calling Object.entries(globalConsole)\n * during early Node.js bootstrap before stdout is ready.\n * @private\n */\nlet _prototypeInitialized = false\nfunction ensurePrototypeInitialized() {\n if (_prototypeInitialized) {\n return\n }\n _prototypeInitialized = true\n\n const entries: Array<[string | symbol, PropertyDescriptor]> = [\n [\n getKGroupIndentationWidthSymbol(),\n {\n ...consolePropAttributes,\n value: 2,\n },\n ],\n [\n Symbol.toStringTag,\n {\n __proto__: null,\n configurable: true,\n value: 'logger',\n } as PropertyDescriptor,\n ],\n ]\n for (const { 0: key, 1: value } of Object.entries(globalConsole)) {\n if (!(Logger.prototype as any)[key] && typeof value === 'function') {\n // Dynamically name the log method without using Object.defineProperty.\n const { [key]: func } = {\n [key](this: Logger, ...args: unknown[]) {\n // Access Console via WeakMap directly since private methods can't be\n // called from dynamically created functions.\n let con = privateConsole.get(this)\n if (con === undefined) {\n // Lazy initialization - this will only happen if someone calls a\n // dynamically added console method before any core logger method.\n const ctorArgs = privateConstructorArgs.get(this) ?? []\n // Clean up constructor args - no longer needed after Console creation.\n privateConstructorArgs.delete(this)\n if (ctorArgs.length) {\n con = constructConsole(...ctorArgs)\n } else {\n con = constructConsole({\n stdout: process.stdout,\n stderr: process.stderr,\n }) as typeof console & Record<string, unknown>\n for (const { 0: k, 1: method } of boundConsoleEntries) {\n con[k] = method\n }\n }\n privateConsole.set(this, con)\n }\n const result = (con as any)[key](...args)\n return result === undefined || result === con ? this : result\n },\n }\n entries.push([\n key,\n {\n ...consolePropAttributes,\n value: func,\n },\n ])\n }\n }\n Object.defineProperties(Logger.prototype, Object.fromEntries(entries))\n}\n\n/**\n * Default logger instance for the application.\n *\n * A pre-configured `Logger` instance that uses the standard `process.stdout`\n * and `process.stderr` streams. This is the recommended logger to import\n * and use throughout your application.\n *\n * @example\n * ```typescript\n * import { logger } from '@socketsecurity/lib'\n *\n * logger.log('Application started')\n * logger.success('Configuration loaded')\n * logger.indent()\n * logger.log('Using port 3000')\n * logger.dedent()\n * ```\n */\nexport const logger = new Logger()\n"],
|
|
5
|
+
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,WAAAC,EAAA,0BAAAC,EAAA,uBAAAC,EAAA,WAAAC,IAAA,eAAAC,EAAAP,GAKA,IAAAQ,EAA+B,8DAC/BC,EAA2B,yCAC3BC,EAA2C,qBAC3CC,EAA+C,qBAuE/C,MAAMC,EAAgB,QAKhBC,EAAe,QAAQ,MACvBC,EAAmB,QAAQ,UAEjC,IAAIC,EAMJ,SAASC,KAAoBC,EAAiB,CAC5C,OAAIF,IAAa,SAIfA,EADkC,QAAQ,cAAc,EACjC,SAElBD,EACLC,EAGAE,CACF,CACF,CAOA,SAASC,GAAiB,CACxB,OAAO,EAAAC,OACT,CAsBO,MAAMjB,GAA6B,IAAM,CAC9C,MAAMkB,EAAiC,CACrC,UAAW,IACb,EAEMC,EAAgD,CACpD,UAAW,IACb,EACMC,EAAO,IAAM,CACjB,MAAMC,KAAY,EAAAC,SAAmB,EAC/BC,EAASP,EAAe,KAC9B,gBAAaE,EAAQ,CACnB,KAAMK,EAAO,IAAIF,EAAY,SAAM,MAAG,EACtC,KAAME,EAAO,KAAKF,EAAY,SAAM,GAAG,EACvC,KAAME,EAAO,KAAKF,EAAY,SAAM,GAAG,EACvC,QAASE,EAAO,MAAMF,EAAY,SAAM,QAAG,EAC3C,KAAME,EAAO,OAAOF,EAAY,SAAM,QAAG,CAC3C,CAAC,KACD,gBAAaH,CAAM,EAGnB,UAAWM,KAAYL,EACrB,OAAOA,EAAQK,CAAsD,CAEzE,EACA,UAAWA,KAAY,QAAQ,QAAQ,OAAO,EAAG,CAC/C,MAAMC,EAAM,QAAyCD,CAAQ,EACzD,OAAOC,GAAO,aACdN,EACAK,CACF,EAAI,IAAIT,KACNK,EAAK,EACEK,EAAG,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,EACD,SAAW,CAAE,EAAGmF,EAAG,EAAG3C,CAAO,IAAK5B,EAChCyB,EAAI8C,CAAC,EAAI3C,CAEb,CACAxB,EAAe,IAAI,KAAMqB,CAAG,CAC9B,CACA,MAAM6B,EAAU7B,EAAYE,CAAG,EAAE,GAAGtC,CAAI,EACxC,OAAOiE,IAAW,QAAaA,IAAW7B,EAAM,KAAO6B,CACzD,CACF,EACAe,EAAQ,KAAK,CACX1C,EACA,CACE,GAAGzB,EACH,MAAOoE,CACT,CACF,CAAC,CACH,CAEF,OAAO,iBAAiB/F,EAAO,UAAW,OAAO,YAAY8F,CAAO,CAAC,CACvE,CAoBO,MAAM3F,EAAS,IAAIH",
|
|
6
|
+
"names": ["logger_exports", "__export", "LOG_SYMBOLS", "Logger", "incLogCallCountSymbol", "lastWasBlankSymbol", "logger", "__toCommonJS", "import_is_unicode_supported", "import_yoctocolors_cjs", "import_objects", "import_strings", "globalConsole", "ReflectApply", "ReflectConstruct", "_Console", "constructConsole", "args", "getYoctocolors", "yoctocolorsCjs", "target", "handler", "init", "supported", "isUnicodeSupported", "colors", "trapName", "fn", "boundConsoleEntries", "n", "consolePropAttributes", "maxIndentation", "privateConsole", "privateConstructorArgs", "_consoleSymbols", "getConsoleSymbols", "_kGroupIndentationWidthSymbol", "getKGroupIndentationWidthSymbol", "s", "#parent", "#boundStream", "#stderrLogger", "#stdoutLogger", "#stderrIndention", "#stdoutIndention", "#stderrLastWasBlank", "#stdoutLastWasBlank", "#logCallCount", "#options", "#originalStdout", "options", "#getConsole", "ensurePrototypeInitialized", "con", "ctorArgs", "key", "method", "instance", "#getRoot", "#getIndent", "stream", "root", "#setIndent", "value", "#getLastWasBlank", "#setLastWasBlank", "#getTargetStream", "#apply", "methodName", "text", "hasText", "targetStream", "indent", "logArgs", "#stripSymbols", "#symbolApply", "symbolType", "extras", "message", "label", "name", "f", "result", "spaces", "current", "stderrCurrent", "stdoutCurrent", "obj", "data", "length", "spacesToAdd", "msg", "indentedMsg", "tabularData", "properties", "streamObj", "_prototypeInitialized", "entries", "func", "k"]
|
|
7
7
|
}
|