@socketsecurity/lib 2.10.4 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +50 -24
- package/README.md +231 -40
- package/dist/constants/platform.js +1 -1
- package/dist/constants/platform.js.map +3 -3
- package/dist/cover/code.js +1 -1
- package/dist/cover/code.js.map +3 -3
- package/dist/debug.js +2 -2
- package/dist/debug.js.map +3 -3
- package/dist/dlx-binary.d.ts +29 -6
- package/dist/dlx-binary.js +6 -6
- package/dist/dlx-binary.js.map +3 -3
- package/dist/dlx-package.d.ts +16 -1
- package/dist/dlx-package.js +6 -6
- package/dist/dlx-package.js.map +3 -3
- package/dist/dlx.js +1 -1
- package/dist/dlx.js.map +3 -3
- package/dist/env/rewire.js +1 -1
- package/dist/env/rewire.js.map +3 -3
- package/dist/external/yoctocolors-cjs.d.ts +14 -0
- package/dist/fs.d.ts +2 -2
- package/dist/fs.js.map +1 -1
- package/dist/git.js +1 -1
- package/dist/git.js.map +3 -3
- package/dist/http-request.js +1 -1
- package/dist/http-request.js.map +3 -3
- package/dist/index.d.ts +6 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/ipc.js +1 -1
- package/dist/ipc.js.map +3 -3
- package/dist/links/index.d.ts +65 -0
- package/dist/links/index.js +3 -0
- package/dist/links/index.js.map +7 -0
- package/dist/logger.d.ts +21 -18
- package/dist/logger.js +1 -1
- package/dist/logger.js.map +3 -3
- package/dist/packages/isolation.js +1 -1
- package/dist/packages/isolation.js.map +3 -3
- package/dist/paths.js +1 -1
- package/dist/paths.js.map +2 -2
- package/dist/process-lock.js +2 -2
- package/dist/process-lock.js.map +3 -3
- package/dist/promises.d.ts +6 -21
- package/dist/promises.js +1 -1
- package/dist/promises.js.map +2 -2
- package/dist/prompts/index.d.ts +115 -0
- package/dist/prompts/index.js +3 -0
- package/dist/prompts/index.js.map +7 -0
- package/dist/spinner.d.ts +33 -23
- package/dist/spinner.js +1 -1
- package/dist/spinner.js.map +3 -3
- package/dist/stdio/mask.d.ts +2 -2
- package/dist/stdio/mask.js +4 -4
- package/dist/stdio/mask.js.map +3 -3
- package/dist/stdio/stdout.js +1 -1
- package/dist/stdio/stdout.js.map +3 -3
- package/dist/themes/context.d.ts +80 -0
- package/dist/themes/context.js +3 -0
- package/dist/themes/context.js.map +7 -0
- package/dist/themes/index.d.ts +53 -0
- package/dist/themes/index.js +3 -0
- package/dist/themes/index.js.map +7 -0
- package/dist/themes/themes.d.ts +49 -0
- package/dist/themes/themes.js +3 -0
- package/dist/themes/themes.js.map +7 -0
- package/dist/themes/types.d.ts +92 -0
- package/dist/themes/types.js +3 -0
- package/dist/themes/types.js.map +7 -0
- package/dist/themes/utils.d.ts +78 -0
- package/dist/themes/utils.js +3 -0
- package/dist/themes/utils.js.map +7 -0
- package/package.json +39 -11
- package/dist/download-lock.d.ts +0 -49
- package/dist/download-lock.js +0 -10
- package/dist/download-lock.js.map +0 -7
- package/dist/packages/registry.d.ts +0 -8
- package/dist/packages/registry.js +0 -3
- package/dist/packages/registry.js.map +0 -7
package/dist/ipc.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/ipc.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * IPC (Inter-Process Communication) Module\n * ==========================================\n *\n * This module provides secure inter-process communication utilities for Socket CLI\n * and related tools. It replaces environment variable passing with more secure and\n * scalable alternatives.\n *\n * ## Key Features:\n * - File-based stub communication for initial data handoff\n * - Node.js IPC channel support for real-time bidirectional messaging\n * - Automatic cleanup of temporary files\n * - Type-safe message validation with Zod schemas\n * - Timeout handling for reliability\n *\n * ## Use Cases:\n * 1. Passing API tokens between processes without exposing them in env vars\n * 2. Transferring large configuration objects that exceed env var size limits\n * 3. Bidirectional communication between parent and child processes\n * 4. Secure handshake protocols between Socket CLI components\n *\n * ## Security Considerations:\n * - Stub files are created with restricted permissions in OS temp directory\n * - Messages include timestamps for freshness validation\n * - Automatic cleanup prevents sensitive data persistence\n * - Unique IDs prevent message replay attacks\n *\n * @module ipc\n */\n\nimport crypto from 'node:crypto'\n\nimport { promises as fs } from 'node:fs'\n\nimport path from 'node:path'\n\nimport { safeDeleteSync } from './fs'\nimport { getOsTmpDir } from './paths'\nimport { z } from './zod'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\n/**\n * Zod Schemas for Runtime Validation\n * ====================================\n * These schemas provide runtime type safety for IPC messages,\n * ensuring data integrity across process boundaries.\n */\n\n/**\n * Base IPC message schema - validates the core message structure.\n * All IPC messages must conform to this schema.\n */\nconst IpcMessageSchema = z.object({\n /** Unique identifier for message tracking and response correlation. */\n id: z.string().min(1),\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: z.number().positive(),\n /** Message type identifier for routing and handling. */\n type: z.string().min(1),\n /** Payload data - can be any JSON-serializable value. */\n data: z.unknown(),\n})\n\n/**\n * IPC handshake schema - used for initial connection establishment.\n * The handshake includes version info and authentication tokens.\n * @internal Exported for testing purposes.\n */\nexport const IpcHandshakeSchema = IpcMessageSchema.extend({\n type: z.literal('handshake'),\n data: z.object({\n /** Protocol version for compatibility checking. */\n version: z.string(),\n /** Process ID for identification. */\n pid: z.number().int().positive(),\n /** Optional API token for authentication. */\n apiToken: z.string().optional(),\n /** Application name for multi-app support. */\n appName: z.string(),\n }),\n})\n\n/**\n * IPC stub file schema - validates the structure of stub files.\n * Stub files are used for passing data between processes via filesystem.\n */\nconst IpcStubSchema = z.object({\n /** Process ID that created the stub. */\n pid: z.number().int().positive(),\n /** Creation timestamp for age validation. */\n timestamp: z.number().positive(),\n /** The actual data payload. */\n data: z.unknown(),\n})\n\n/**\n * TypeScript interfaces for IPC communication.\n * These types ensure type consistency across the IPC module.\n */\n\n/**\n * Base IPC message interface.\n * All IPC messages must conform to this structure.\n */\nexport interface IpcMessage<T = unknown> {\n /** Unique identifier for message tracking and response correlation. */\n id: string\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: number\n /** Message type identifier for routing and handling. */\n type: string\n /** Payload data - can be any JSON-serializable value. */\n data: T\n}\n\n/**\n * IPC handshake message interface.\n * Used for initial connection establishment.\n */\nexport interface IpcHandshake\n extends IpcMessage<{\n /** Protocol version for compatibility checking. */\n version: string\n /** Process ID for identification. */\n pid: number\n /** Optional API token for authentication. */\n apiToken?: string\n /** Application name for multi-app support. */\n appName: string\n }> {\n type: 'handshake'\n}\n\n/**\n * IPC stub file interface.\n * Represents the structure of stub files used for filesystem-based IPC.\n */\nexport interface IpcStub {\n /** Process ID that created the stub. */\n pid: number\n /** Creation timestamp for age validation. */\n timestamp: number\n /** The actual data payload. */\n data: unknown\n}\n\n/**\n * Options for IPC communication\n */\nexport interface IpcOptions {\n /** Timeout in milliseconds for async operations. */\n timeout?: number\n /** Text encoding for message serialization. */\n encoding?: BufferEncoding\n}\n\n/**\n * Create a unique IPC channel identifier for message correlation.\n *\n * Generates a unique identifier that combines:\n * - A prefix for namespacing (defaults to 'socket')\n * - The current process ID for process identification\n * - A random hex string for uniqueness\n *\n * @param prefix - Optional prefix to namespace the channel ID\n * @returns A unique channel identifier string\n *\n * @example\n * ```typescript\n * const channelId = createIpcChannelId('socket-cli')\n * // Returns: 'socket-cli-12345-a1b2c3d4e5f6g7h8'\n * ```\n */\nexport function createIpcChannelId(prefix = 'socket'): string {\n return `${prefix}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`\n}\n\n/**\n * Get the IPC stub path for a given application.\n *\n * This function generates a unique file path for IPC stub files that are used\n * to pass data between processes. The stub files are stored in a hidden directory\n * within the system's temporary folder.\n *\n * ## Path Structure:\n * - Base: System temp directory (e.g., /tmp on Unix, %TEMP% on Windows)\n * - Directory: `.socket-ipc/{appName}/`\n * - Filename: `stub-{pid}.json`\n *\n * ## Security Features:\n * - Files are isolated per application via appName parameter\n * - Process ID in filename prevents collisions between concurrent processes\n * - Temporary directory location ensures automatic cleanup on system restart\n *\n * @param appName - The application identifier (e.g., 'socket-cli', 'socket-dlx')\n * @returns Full path to the IPC stub file\n *\n * @example\n * ```typescript\n * const stubPath = getIpcStubPath('socket-cli')\n * // Returns: '/tmp/.socket-ipc/socket-cli/stub-12345.json' (Unix)\n * // Returns: 'C:\\\\Users\\\\Name\\\\AppData\\\\Local\\\\Temp\\\\.socket-ipc\\\\socket-cli\\\\stub-12345.json' (Windows)\n * ```\n *\n * @used Currently used by socket-cli for self-update and inter-process communication\n */\nexport function getIpcStubPath(appName: string): string {\n // Get the system's temporary directory - this is platform-specific.\n const tempDir = getOsTmpDir()\n\n // Create a hidden directory structure for Socket IPC files.\n // The dot prefix makes it hidden on Unix-like systems.\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n\n // Generate filename with process ID to ensure uniqueness.\n // The PID prevents conflicts when multiple processes run simultaneously.\n return path.join(stubDir, `stub-${process.pid}.json`)\n}\n\n/**\n * Ensure IPC directory exists for stub file creation.\n *\n * This helper function creates the directory structure needed for IPC stub files.\n * It's called before writing stub files to ensure the parent directories exist.\n *\n * @param filePath - Full path to the file that needs its directory created\n * @returns Promise that resolves when directory is created\n *\n * @internal Helper function used by writeIpcStub\n */\nasync function ensureIpcDirectory(filePath: string): Promise<void> {\n const dir = path.dirname(filePath)\n // Create directory recursively if it doesn't exist.\n await fs.mkdir(dir, { recursive: true })\n}\n\n/**\n * Write IPC data to a stub file for inter-process data transfer.\n *\n * This function creates a stub file containing data that needs to be passed\n * between processes. The stub file includes metadata like process ID and\n * timestamp for validation.\n *\n * ## File Structure:\n * ```json\n * {\n * \"pid\": 12345,\n * \"timestamp\": 1699564234567,\n * \"data\": { ... }\n * }\n * ```\n *\n * ## Use Cases:\n * - Passing API tokens to child processes\n * - Transferring configuration between Socket CLI components\n * - Sharing large data that exceeds environment variable limits\n *\n * @param appName - The application identifier\n * @param data - The data to write to the stub file\n * @returns Promise resolving to the stub file path\n *\n * @example\n * ```typescript\n * const stubPath = await writeIpcStub('socket-cli', {\n * apiToken: 'secret-token',\n * config: { ... }\n * })\n * // Pass stubPath to child process for reading\n * ```\n */\nexport async function writeIpcStub(\n appName: string,\n data: unknown,\n): Promise<string> {\n const stubPath = getIpcStubPath(appName)\n await ensureIpcDirectory(stubPath)\n\n // Create stub data with validation metadata.\n const ipcData: IpcStub = {\n data,\n pid: process.pid,\n timestamp: Date.now(),\n }\n\n // Validate data structure with Zod schema.\n const validated = IpcStubSchema.parse(ipcData)\n\n // Write with pretty printing for debugging.\n await fs.writeFile(stubPath, JSON.stringify(validated, null, 2), 'utf8')\n return stubPath\n}\n\n/**\n * Read IPC data from a stub file with automatic cleanup.\n *\n * This function reads data from an IPC stub file and validates its freshness.\n * Stale files (older than 5 minutes) are automatically cleaned up to prevent\n * accumulation of temporary files.\n *\n * ## Validation Steps:\n * 1. Read and parse JSON file\n * 2. Validate structure with Zod schema\n * 3. Check timestamp freshness\n * 4. Clean up if stale\n * 5. Return data if valid\n *\n * @param stubPath - Path to the stub file to read\n * @returns Promise resolving to the data or null if invalid/stale\n *\n * @example\n * ```typescript\n * const data = await readIpcStub('/tmp/.socket-ipc/socket-cli/stub-12345.json')\n * if (data) {\n * console.log('Received:', data)\n * }\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function readIpcStub(stubPath: string): Promise<unknown> {\n try {\n const content = await fs.readFile(stubPath, 'utf8')\n const parsed = JSON.parse(content)\n // Validate structure with Zod schema.\n const validated = IpcStubSchema.parse(parsed)\n // Check age for freshness validation.\n const ageMs = Date.now() - validated.timestamp\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n if (ageMs > maxAgeMs) {\n // Clean up stale file. IPC stubs are always in tmpdir, so use force: true.\n try {\n safeDeleteSync(stubPath, { force: true })\n } catch {\n // Ignore deletion errors\n }\n return null\n }\n return validated.data\n } catch {\n // Return null for any errors (file not found, invalid JSON, validation failure).\n return null\n }\n}\n\n/**\n * Clean up IPC stub files for an application.\n *\n * This maintenance function removes stale IPC stub files to prevent\n * accumulation in the temporary directory. It's designed to be called\n * periodically or on application startup.\n *\n * ## Cleanup Rules:\n * - Files older than 5 minutes are removed (checked via both filesystem mtime and JSON timestamp)\n * - Only stub files (stub-*.json) are processed\n * - Errors are silently ignored (best-effort cleanup)\n *\n * @param appName - The application identifier\n * @returns Promise that resolves when cleanup is complete\n *\n * @example\n * ```typescript\n * // Clean up on application startup\n * await cleanupIpcStubs('socket-cli')\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function cleanupIpcStubs(appName: string): Promise<void> {\n const tempDir = getOsTmpDir()\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n try {\n const files = await fs.readdir(stubDir)\n const now = Date.now()\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n // Process each file in parallel for efficiency.\n await Promise.all(\n files.map(async file => {\n if (file.startsWith('stub-') && file.endsWith('.json')) {\n const filePath = path.join(stubDir, file)\n try {\n // Check both filesystem mtime and JSON timestamp for more reliable detection\n const stats = await fs.stat(filePath)\n const mtimeAge = now - stats.mtimeMs\n let isStale = mtimeAge > maxAgeMs\n\n // Always check the timestamp inside the JSON file for accuracy\n // This is more reliable than filesystem mtime in some environments\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(content)\n const validated = IpcStubSchema.parse(parsed)\n const contentAge = now - validated.timestamp\n // File is stale if EITHER check indicates staleness\n isStale = isStale || contentAge > maxAgeMs\n } catch {\n // If we can't read/parse the file, rely on mtime check\n }\n\n if (isStale) {\n // IPC stubs are always in tmpdir, so we can use force: true to skip path checks\n safeDeleteSync(filePath, { force: true })\n }\n } catch {\n // Ignore errors for individual files.\n }\n }\n }),\n )\n } catch {\n // Directory might not exist, that's ok.\n }\n}\n\n/**\n * Send data through Node.js IPC channel.\n *\n * This function sends structured messages through the Node.js IPC channel\n * when available. The IPC channel must be established with stdio: ['pipe', 'pipe', 'pipe', 'ipc'].\n *\n * ## Requirements:\n * - Process must have been spawned with IPC channel enabled\n * - Message must be serializable to JSON\n * - Process.send() must be available\n *\n * @param process - The process object with IPC channel\n * @param message - The IPC message to send\n * @returns true if message was sent, false otherwise\n *\n * @example\n * ```typescript\n * const message = createIpcMessage('handshake', { version: '1.0.0' })\n * const sent = sendIpc(childProcess, message)\n * ```\n *\n * @unused Reserved for bidirectional communication implementation\n */\nexport function sendIpc(\n process: NodeJS.Process | unknown,\n message: IpcMessage,\n): boolean {\n if (\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function'\n ) {\n try {\n // Validate message structure before sending.\n const validated = IpcMessageSchema.parse(message)\n return process.send(validated)\n } catch {\n return false\n }\n }\n return false\n}\n\n/**\n * Receive data through Node.js IPC channel.\n *\n * Sets up a listener for IPC messages with automatic validation and parsing.\n * Returns a cleanup function to remove the listener when no longer needed.\n *\n * ## Message Flow:\n * 1. Receive raw message from IPC channel\n * 2. Validate with parseIpcMessage\n * 3. Call handler if valid\n * 4. Ignore invalid messages\n *\n * @param handler - Function to call with valid IPC messages\n * @returns Cleanup function to remove the listener\n *\n * @example\n * ```typescript\n * const cleanup = onIpc((message) => {\n * console.log('Received:', message.type, message.data)\n * })\n * // Later...\n * cleanup() // Remove listener\n * ```\n *\n * @unused Reserved for bidirectional communication\n */\nexport function onIpc(handler: (message: IpcMessage) => void): () => void {\n const listener = (message: unknown) => {\n const parsed = parseIpcMessage(message)\n if (parsed) {\n handler(parsed)\n }\n }\n process.on('message', listener)\n // Return cleanup function for proper resource management.\n return () => {\n process.off('message', listener)\n }\n}\n\n/**\n * Create a promise that resolves when a specific IPC message is received.\n *\n * This utility function provides async/await support for IPC communication,\n * allowing you to wait for specific message types with timeout support.\n *\n * ## Features:\n * - Automatic timeout handling\n * - Type-safe message data\n * - Resource cleanup on completion\n * - Promise-based API\n *\n * @param messageType - The message type to wait for\n * @param options - Options including timeout configuration\n * @returns Promise resolving to the message data\n *\n * @example\n * ```typescript\n * try {\n * const response = await waitForIpc<ConfigData>('config-response', {\n * timeout: 5000 // 5 seconds\n * })\n * console.log('Config received:', response)\n * } catch (error) {\n * console.error('Timeout waiting for config')\n * }\n * ```\n *\n * @unused Reserved for request-response pattern implementation\n */\nexport function waitForIpc<T = unknown>(\n messageType: string,\n options: IpcOptions = {},\n): Promise<T> {\n const { timeout = 30_000 } = options\n return new Promise((resolve, reject) => {\n let cleanup: (() => void) | null = null\n let timeoutId: NodeJS.Timeout | null = null\n const handleTimeout = () => {\n if (cleanup) {\n cleanup()\n }\n reject(new Error(`IPC timeout waiting for message type: ${messageType}`))\n }\n const handleMessage = (message: IpcMessage) => {\n if (message.type === messageType) {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n if (cleanup) {\n cleanup()\n }\n resolve(message.data as T)\n }\n }\n cleanup = onIpc(handleMessage)\n if (timeout > 0) {\n timeoutId = setTimeout(handleTimeout, timeout)\n }\n })\n}\n\n/**\n * Create an IPC message with proper structure and metadata.\n *\n * This factory function creates properly structured IPC messages with:\n * - Unique ID for tracking\n * - Timestamp for freshness\n * - Type for routing\n * - Data payload\n *\n * @param type - The message type identifier\n * @param data - The message payload\n * @returns A properly structured IPC message\n *\n * @example\n * ```typescript\n * const handshake = createIpcMessage('handshake', {\n * version: '1.0.0',\n * pid: process.pid,\n * appName: 'socket-cli'\n * })\n * ```\n *\n * @unused Reserved for future message creation needs\n */\nexport function createIpcMessage<T = unknown>(\n type: string,\n data: T,\n): IpcMessage<T> {\n return {\n id: crypto.randomBytes(16).toString('hex'),\n timestamp: Date.now(),\n type,\n data,\n }\n}\n\n/**\n * Check if process has IPC channel available.\n *\n * This utility checks whether a process object has the necessary\n * properties for IPC communication. Used to determine if IPC\n * messaging is possible before attempting to send.\n *\n * @param process - The process object to check\n * @returns true if IPC is available, false otherwise\n *\n * @example\n * ```typescript\n * if (hasIpcChannel(childProcess)) {\n * sendIpc(childProcess, message)\n * } else {\n * // Fall back to alternative communication method\n * }\n * ```\n *\n * @unused Reserved for IPC availability detection\n */\nexport function hasIpcChannel(process: unknown): boolean {\n return Boolean(\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function' &&\n 'channel' in process &&\n process.channel !== undefined,\n )\n}\n\n/**\n * Safely parse and validate IPC messages.\n *\n * This function performs runtime validation of incoming messages\n * to ensure they conform to the IPC message structure. It uses\n * Zod schemas for robust validation.\n *\n * ## Validation Steps:\n * 1. Check if message is an object\n * 2. Validate required fields exist\n * 3. Validate field types\n * 4. Return typed message or null\n *\n * @param message - The raw message to parse\n * @returns Parsed IPC message or null if invalid\n *\n * @example\n * ```typescript\n * const parsed = parseIpcMessage(rawMessage)\n * if (parsed) {\n * handleMessage(parsed)\n * }\n * ```\n *\n * @unused Reserved for message validation needs\n */\nexport function parseIpcMessage(message: unknown): IpcMessage | null {\n try {\n // Use Zod schema for comprehensive validation.\n const validated = IpcMessageSchema.parse(message)\n return validated as IpcMessage\n } catch {\n // Return null for any validation failure.\n return null\n }\n}\n"],
|
|
5
|
-
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,oBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,kBAAAC,EAAA,UAAAC,EAAA,oBAAAC,EAAA,gBAAAC,EAAA,YAAAC,EAAA,eAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAd,GA8BA,IAAAe,EAAmB,
|
|
6
|
-
"names": ["ipc_exports", "__export", "IpcHandshakeSchema", "cleanupIpcStubs", "createIpcChannelId", "createIpcMessage", "getIpcStubPath", "hasIpcChannel", "onIpc", "parseIpcMessage", "readIpcStub", "sendIpc", "waitForIpc", "writeIpcStub", "__toCommonJS", "
|
|
4
|
+
"sourcesContent": ["/**\n * IPC (Inter-Process Communication) Module\n * ==========================================\n *\n * This module provides secure inter-process communication utilities for Socket CLI\n * and related tools. It replaces environment variable passing with more secure and\n * scalable alternatives.\n *\n * ## Key Features:\n * - File-based stub communication for initial data handoff\n * - Node.js IPC channel support for real-time bidirectional messaging\n * - Automatic cleanup of temporary files\n * - Type-safe message validation with Zod schemas\n * - Timeout handling for reliability\n *\n * ## Use Cases:\n * 1. Passing API tokens between processes without exposing them in env vars\n * 2. Transferring large configuration objects that exceed env var size limits\n * 3. Bidirectional communication between parent and child processes\n * 4. Secure handshake protocols between Socket CLI components\n *\n * ## Security Considerations:\n * - Stub files are created with restricted permissions in OS temp directory\n * - Messages include timestamps for freshness validation\n * - Automatic cleanup prevents sensitive data persistence\n * - Unique IDs prevent message replay attacks\n *\n * @module ipc\n */\n\nimport crypto from 'crypto'\n\nimport { promises as fs } from 'fs'\n\nimport path from 'path'\n\nimport { safeDeleteSync } from './fs'\nimport { getOsTmpDir } from './paths'\nimport { z } from './zod'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\n/**\n * Zod Schemas for Runtime Validation\n * ====================================\n * These schemas provide runtime type safety for IPC messages,\n * ensuring data integrity across process boundaries.\n */\n\n/**\n * Base IPC message schema - validates the core message structure.\n * All IPC messages must conform to this schema.\n */\nconst IpcMessageSchema = z.object({\n /** Unique identifier for message tracking and response correlation. */\n id: z.string().min(1),\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: z.number().positive(),\n /** Message type identifier for routing and handling. */\n type: z.string().min(1),\n /** Payload data - can be any JSON-serializable value. */\n data: z.unknown(),\n})\n\n/**\n * IPC handshake schema - used for initial connection establishment.\n * The handshake includes version info and authentication tokens.\n * @internal Exported for testing purposes.\n */\nexport const IpcHandshakeSchema = IpcMessageSchema.extend({\n type: z.literal('handshake'),\n data: z.object({\n /** Protocol version for compatibility checking. */\n version: z.string(),\n /** Process ID for identification. */\n pid: z.number().int().positive(),\n /** Optional API token for authentication. */\n apiToken: z.string().optional(),\n /** Application name for multi-app support. */\n appName: z.string(),\n }),\n})\n\n/**\n * IPC stub file schema - validates the structure of stub files.\n * Stub files are used for passing data between processes via filesystem.\n */\nconst IpcStubSchema = z.object({\n /** Process ID that created the stub. */\n pid: z.number().int().positive(),\n /** Creation timestamp for age validation. */\n timestamp: z.number().positive(),\n /** The actual data payload. */\n data: z.unknown(),\n})\n\n/**\n * TypeScript interfaces for IPC communication.\n * These types ensure type consistency across the IPC module.\n */\n\n/**\n * Base IPC message interface.\n * All IPC messages must conform to this structure.\n */\nexport interface IpcMessage<T = unknown> {\n /** Unique identifier for message tracking and response correlation. */\n id: string\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: number\n /** Message type identifier for routing and handling. */\n type: string\n /** Payload data - can be any JSON-serializable value. */\n data: T\n}\n\n/**\n * IPC handshake message interface.\n * Used for initial connection establishment.\n */\nexport interface IpcHandshake\n extends IpcMessage<{\n /** Protocol version for compatibility checking. */\n version: string\n /** Process ID for identification. */\n pid: number\n /** Optional API token for authentication. */\n apiToken?: string\n /** Application name for multi-app support. */\n appName: string\n }> {\n type: 'handshake'\n}\n\n/**\n * IPC stub file interface.\n * Represents the structure of stub files used for filesystem-based IPC.\n */\nexport interface IpcStub {\n /** Process ID that created the stub. */\n pid: number\n /** Creation timestamp for age validation. */\n timestamp: number\n /** The actual data payload. */\n data: unknown\n}\n\n/**\n * Options for IPC communication\n */\nexport interface IpcOptions {\n /** Timeout in milliseconds for async operations. */\n timeout?: number\n /** Text encoding for message serialization. */\n encoding?: BufferEncoding\n}\n\n/**\n * Create a unique IPC channel identifier for message correlation.\n *\n * Generates a unique identifier that combines:\n * - A prefix for namespacing (defaults to 'socket')\n * - The current process ID for process identification\n * - A random hex string for uniqueness\n *\n * @param prefix - Optional prefix to namespace the channel ID\n * @returns A unique channel identifier string\n *\n * @example\n * ```typescript\n * const channelId = createIpcChannelId('socket-cli')\n * // Returns: 'socket-cli-12345-a1b2c3d4e5f6g7h8'\n * ```\n */\nexport function createIpcChannelId(prefix = 'socket'): string {\n return `${prefix}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`\n}\n\n/**\n * Get the IPC stub path for a given application.\n *\n * This function generates a unique file path for IPC stub files that are used\n * to pass data between processes. The stub files are stored in a hidden directory\n * within the system's temporary folder.\n *\n * ## Path Structure:\n * - Base: System temp directory (e.g., /tmp on Unix, %TEMP% on Windows)\n * - Directory: `.socket-ipc/{appName}/`\n * - Filename: `stub-{pid}.json`\n *\n * ## Security Features:\n * - Files are isolated per application via appName parameter\n * - Process ID in filename prevents collisions between concurrent processes\n * - Temporary directory location ensures automatic cleanup on system restart\n *\n * @param appName - The application identifier (e.g., 'socket-cli', 'socket-dlx')\n * @returns Full path to the IPC stub file\n *\n * @example\n * ```typescript\n * const stubPath = getIpcStubPath('socket-cli')\n * // Returns: '/tmp/.socket-ipc/socket-cli/stub-12345.json' (Unix)\n * // Returns: 'C:\\\\Users\\\\Name\\\\AppData\\\\Local\\\\Temp\\\\.socket-ipc\\\\socket-cli\\\\stub-12345.json' (Windows)\n * ```\n *\n * @used Currently used by socket-cli for self-update and inter-process communication\n */\nexport function getIpcStubPath(appName: string): string {\n // Get the system's temporary directory - this is platform-specific.\n const tempDir = getOsTmpDir()\n\n // Create a hidden directory structure for Socket IPC files.\n // The dot prefix makes it hidden on Unix-like systems.\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n\n // Generate filename with process ID to ensure uniqueness.\n // The PID prevents conflicts when multiple processes run simultaneously.\n return path.join(stubDir, `stub-${process.pid}.json`)\n}\n\n/**\n * Ensure IPC directory exists for stub file creation.\n *\n * This helper function creates the directory structure needed for IPC stub files.\n * It's called before writing stub files to ensure the parent directories exist.\n *\n * @param filePath - Full path to the file that needs its directory created\n * @returns Promise that resolves when directory is created\n *\n * @internal Helper function used by writeIpcStub\n */\nasync function ensureIpcDirectory(filePath: string): Promise<void> {\n const dir = path.dirname(filePath)\n // Create directory recursively if it doesn't exist.\n await fs.mkdir(dir, { recursive: true })\n}\n\n/**\n * Write IPC data to a stub file for inter-process data transfer.\n *\n * This function creates a stub file containing data that needs to be passed\n * between processes. The stub file includes metadata like process ID and\n * timestamp for validation.\n *\n * ## File Structure:\n * ```json\n * {\n * \"pid\": 12345,\n * \"timestamp\": 1699564234567,\n * \"data\": { ... }\n * }\n * ```\n *\n * ## Use Cases:\n * - Passing API tokens to child processes\n * - Transferring configuration between Socket CLI components\n * - Sharing large data that exceeds environment variable limits\n *\n * @param appName - The application identifier\n * @param data - The data to write to the stub file\n * @returns Promise resolving to the stub file path\n *\n * @example\n * ```typescript\n * const stubPath = await writeIpcStub('socket-cli', {\n * apiToken: 'secret-token',\n * config: { ... }\n * })\n * // Pass stubPath to child process for reading\n * ```\n */\nexport async function writeIpcStub(\n appName: string,\n data: unknown,\n): Promise<string> {\n const stubPath = getIpcStubPath(appName)\n await ensureIpcDirectory(stubPath)\n\n // Create stub data with validation metadata.\n const ipcData: IpcStub = {\n data,\n pid: process.pid,\n timestamp: Date.now(),\n }\n\n // Validate data structure with Zod schema.\n const validated = IpcStubSchema.parse(ipcData)\n\n // Write with pretty printing for debugging.\n await fs.writeFile(stubPath, JSON.stringify(validated, null, 2), 'utf8')\n return stubPath\n}\n\n/**\n * Read IPC data from a stub file with automatic cleanup.\n *\n * This function reads data from an IPC stub file and validates its freshness.\n * Stale files (older than 5 minutes) are automatically cleaned up to prevent\n * accumulation of temporary files.\n *\n * ## Validation Steps:\n * 1. Read and parse JSON file\n * 2. Validate structure with Zod schema\n * 3. Check timestamp freshness\n * 4. Clean up if stale\n * 5. Return data if valid\n *\n * @param stubPath - Path to the stub file to read\n * @returns Promise resolving to the data or null if invalid/stale\n *\n * @example\n * ```typescript\n * const data = await readIpcStub('/tmp/.socket-ipc/socket-cli/stub-12345.json')\n * if (data) {\n * console.log('Received:', data)\n * }\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function readIpcStub(stubPath: string): Promise<unknown> {\n try {\n const content = await fs.readFile(stubPath, 'utf8')\n const parsed = JSON.parse(content)\n // Validate structure with Zod schema.\n const validated = IpcStubSchema.parse(parsed)\n // Check age for freshness validation.\n const ageMs = Date.now() - validated.timestamp\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n if (ageMs > maxAgeMs) {\n // Clean up stale file. IPC stubs are always in tmpdir, so use force: true.\n try {\n safeDeleteSync(stubPath, { force: true })\n } catch {\n // Ignore deletion errors\n }\n return null\n }\n return validated.data\n } catch {\n // Return null for any errors (file not found, invalid JSON, validation failure).\n return null\n }\n}\n\n/**\n * Clean up IPC stub files for an application.\n *\n * This maintenance function removes stale IPC stub files to prevent\n * accumulation in the temporary directory. It's designed to be called\n * periodically or on application startup.\n *\n * ## Cleanup Rules:\n * - Files older than 5 minutes are removed (checked via both filesystem mtime and JSON timestamp)\n * - Only stub files (stub-*.json) are processed\n * - Errors are silently ignored (best-effort cleanup)\n *\n * @param appName - The application identifier\n * @returns Promise that resolves when cleanup is complete\n *\n * @example\n * ```typescript\n * // Clean up on application startup\n * await cleanupIpcStubs('socket-cli')\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function cleanupIpcStubs(appName: string): Promise<void> {\n const tempDir = getOsTmpDir()\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n try {\n const files = await fs.readdir(stubDir)\n const now = Date.now()\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n // Process each file in parallel for efficiency.\n await Promise.all(\n files.map(async file => {\n if (file.startsWith('stub-') && file.endsWith('.json')) {\n const filePath = path.join(stubDir, file)\n try {\n // Check both filesystem mtime and JSON timestamp for more reliable detection\n const stats = await fs.stat(filePath)\n const mtimeAge = now - stats.mtimeMs\n let isStale = mtimeAge > maxAgeMs\n\n // Always check the timestamp inside the JSON file for accuracy\n // This is more reliable than filesystem mtime in some environments\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(content)\n const validated = IpcStubSchema.parse(parsed)\n const contentAge = now - validated.timestamp\n // File is stale if EITHER check indicates staleness\n isStale = isStale || contentAge > maxAgeMs\n } catch {\n // If we can't read/parse the file, rely on mtime check\n }\n\n if (isStale) {\n // IPC stubs are always in tmpdir, so we can use force: true to skip path checks\n safeDeleteSync(filePath, { force: true })\n }\n } catch {\n // Ignore errors for individual files.\n }\n }\n }),\n )\n } catch {\n // Directory might not exist, that's ok.\n }\n}\n\n/**\n * Send data through Node.js IPC channel.\n *\n * This function sends structured messages through the Node.js IPC channel\n * when available. The IPC channel must be established with stdio: ['pipe', 'pipe', 'pipe', 'ipc'].\n *\n * ## Requirements:\n * - Process must have been spawned with IPC channel enabled\n * - Message must be serializable to JSON\n * - Process.send() must be available\n *\n * @param process - The process object with IPC channel\n * @param message - The IPC message to send\n * @returns true if message was sent, false otherwise\n *\n * @example\n * ```typescript\n * const message = createIpcMessage('handshake', { version: '1.0.0' })\n * const sent = sendIpc(childProcess, message)\n * ```\n *\n * @unused Reserved for bidirectional communication implementation\n */\nexport function sendIpc(\n process: NodeJS.Process | unknown,\n message: IpcMessage,\n): boolean {\n if (\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function'\n ) {\n try {\n // Validate message structure before sending.\n const validated = IpcMessageSchema.parse(message)\n return process.send(validated)\n } catch {\n return false\n }\n }\n return false\n}\n\n/**\n * Receive data through Node.js IPC channel.\n *\n * Sets up a listener for IPC messages with automatic validation and parsing.\n * Returns a cleanup function to remove the listener when no longer needed.\n *\n * ## Message Flow:\n * 1. Receive raw message from IPC channel\n * 2. Validate with parseIpcMessage\n * 3. Call handler if valid\n * 4. Ignore invalid messages\n *\n * @param handler - Function to call with valid IPC messages\n * @returns Cleanup function to remove the listener\n *\n * @example\n * ```typescript\n * const cleanup = onIpc((message) => {\n * console.log('Received:', message.type, message.data)\n * })\n * // Later...\n * cleanup() // Remove listener\n * ```\n *\n * @unused Reserved for bidirectional communication\n */\nexport function onIpc(handler: (message: IpcMessage) => void): () => void {\n const listener = (message: unknown) => {\n const parsed = parseIpcMessage(message)\n if (parsed) {\n handler(parsed)\n }\n }\n process.on('message', listener)\n // Return cleanup function for proper resource management.\n return () => {\n process.off('message', listener)\n }\n}\n\n/**\n * Create a promise that resolves when a specific IPC message is received.\n *\n * This utility function provides async/await support for IPC communication,\n * allowing you to wait for specific message types with timeout support.\n *\n * ## Features:\n * - Automatic timeout handling\n * - Type-safe message data\n * - Resource cleanup on completion\n * - Promise-based API\n *\n * @param messageType - The message type to wait for\n * @param options - Options including timeout configuration\n * @returns Promise resolving to the message data\n *\n * @example\n * ```typescript\n * try {\n * const response = await waitForIpc<ConfigData>('config-response', {\n * timeout: 5000 // 5 seconds\n * })\n * console.log('Config received:', response)\n * } catch (error) {\n * console.error('Timeout waiting for config')\n * }\n * ```\n *\n * @unused Reserved for request-response pattern implementation\n */\nexport function waitForIpc<T = unknown>(\n messageType: string,\n options: IpcOptions = {},\n): Promise<T> {\n const { timeout = 30_000 } = options\n return new Promise((resolve, reject) => {\n let cleanup: (() => void) | null = null\n let timeoutId: NodeJS.Timeout | null = null\n const handleTimeout = () => {\n if (cleanup) {\n cleanup()\n }\n reject(new Error(`IPC timeout waiting for message type: ${messageType}`))\n }\n const handleMessage = (message: IpcMessage) => {\n if (message.type === messageType) {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n if (cleanup) {\n cleanup()\n }\n resolve(message.data as T)\n }\n }\n cleanup = onIpc(handleMessage)\n if (timeout > 0) {\n timeoutId = setTimeout(handleTimeout, timeout)\n }\n })\n}\n\n/**\n * Create an IPC message with proper structure and metadata.\n *\n * This factory function creates properly structured IPC messages with:\n * - Unique ID for tracking\n * - Timestamp for freshness\n * - Type for routing\n * - Data payload\n *\n * @param type - The message type identifier\n * @param data - The message payload\n * @returns A properly structured IPC message\n *\n * @example\n * ```typescript\n * const handshake = createIpcMessage('handshake', {\n * version: '1.0.0',\n * pid: process.pid,\n * appName: 'socket-cli'\n * })\n * ```\n *\n * @unused Reserved for future message creation needs\n */\nexport function createIpcMessage<T = unknown>(\n type: string,\n data: T,\n): IpcMessage<T> {\n return {\n id: crypto.randomBytes(16).toString('hex'),\n timestamp: Date.now(),\n type,\n data,\n }\n}\n\n/**\n * Check if process has IPC channel available.\n *\n * This utility checks whether a process object has the necessary\n * properties for IPC communication. Used to determine if IPC\n * messaging is possible before attempting to send.\n *\n * @param process - The process object to check\n * @returns true if IPC is available, false otherwise\n *\n * @example\n * ```typescript\n * if (hasIpcChannel(childProcess)) {\n * sendIpc(childProcess, message)\n * } else {\n * // Fall back to alternative communication method\n * }\n * ```\n *\n * @unused Reserved for IPC availability detection\n */\nexport function hasIpcChannel(process: unknown): boolean {\n return Boolean(\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function' &&\n 'channel' in process &&\n process.channel !== undefined,\n )\n}\n\n/**\n * Safely parse and validate IPC messages.\n *\n * This function performs runtime validation of incoming messages\n * to ensure they conform to the IPC message structure. It uses\n * Zod schemas for robust validation.\n *\n * ## Validation Steps:\n * 1. Check if message is an object\n * 2. Validate required fields exist\n * 3. Validate field types\n * 4. Return typed message or null\n *\n * @param message - The raw message to parse\n * @returns Parsed IPC message or null if invalid\n *\n * @example\n * ```typescript\n * const parsed = parseIpcMessage(rawMessage)\n * if (parsed) {\n * handleMessage(parsed)\n * }\n * ```\n *\n * @unused Reserved for message validation needs\n */\nexport function parseIpcMessage(message: unknown): IpcMessage | null {\n try {\n // Use Zod schema for comprehensive validation.\n const validated = IpcMessageSchema.parse(message)\n return validated as IpcMessage\n } catch {\n // Return null for any validation failure.\n return null\n }\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["ipc_exports", "__export", "IpcHandshakeSchema", "cleanupIpcStubs", "createIpcChannelId", "createIpcMessage", "getIpcStubPath", "hasIpcChannel", "onIpc", "parseIpcMessage", "readIpcStub", "sendIpc", "waitForIpc", "writeIpcStub", "__toCommonJS", "import_crypto", "import_fs", "import_path", "import_paths", "import_zod", "IpcMessageSchema", "IpcStubSchema", "prefix", "crypto", "appName", "tempDir", "stubDir", "path", "ensureIpcDirectory", "filePath", "dir", "fs", "data", "stubPath", "ipcData", "validated", "content", "parsed", "ageMs", "maxAgeMs", "files", "now", "file", "stats", "isStale", "contentAge", "process", "message", "handler", "listener", "messageType", "options", "timeout", "resolve", "reject", "cleanup", "timeoutId", "handleTimeout", "type"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Theme } from '../themes/types';
|
|
2
|
+
import type { ThemeName } from '../themes/themes';
|
|
3
|
+
/**
|
|
4
|
+
* Options for creating themed links.
|
|
5
|
+
*/
|
|
6
|
+
export type LinkOptions = {
|
|
7
|
+
/** Theme to use (overrides global) */
|
|
8
|
+
theme?: Theme | ThemeName | undefined;
|
|
9
|
+
/** Show URL as fallback if terminal doesn't support links */
|
|
10
|
+
fallback?: boolean | undefined;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Create a themed hyperlink for terminal output.
|
|
14
|
+
* The link text is colored using the theme's link color.
|
|
15
|
+
*
|
|
16
|
+
* Note: Most terminals support ANSI color codes but not clickable links.
|
|
17
|
+
* This function colors the text but does not create clickable hyperlinks.
|
|
18
|
+
* For clickable links, use a library like 'terminal-link' separately.
|
|
19
|
+
*
|
|
20
|
+
* @param text - Link text to display
|
|
21
|
+
* @param url - URL (included in fallback mode)
|
|
22
|
+
* @param options - Link configuration options
|
|
23
|
+
* @returns Colored link text
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { link } from '@socketsecurity/lib/links'
|
|
28
|
+
*
|
|
29
|
+
* // Use current theme
|
|
30
|
+
* console.log(link('Documentation', 'https://socket.dev'))
|
|
31
|
+
*
|
|
32
|
+
* // Override theme
|
|
33
|
+
* console.log(link('API Docs', 'https://api.socket.dev', {
|
|
34
|
+
* theme: 'coana'
|
|
35
|
+
* }))
|
|
36
|
+
*
|
|
37
|
+
* // Show URL as fallback
|
|
38
|
+
* console.log(link('GitHub', 'https://github.com', {
|
|
39
|
+
* fallback: true
|
|
40
|
+
* }))
|
|
41
|
+
* // Output: "GitHub (https://github.com)"
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function link(text: string, url: string, options?: LinkOptions): string;
|
|
45
|
+
/**
|
|
46
|
+
* Create multiple themed links from an array of link specifications.
|
|
47
|
+
*
|
|
48
|
+
* @param links - Array of [text, url] pairs
|
|
49
|
+
* @param options - Link configuration options
|
|
50
|
+
* @returns Array of colored link texts
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* import { links } from '@socketsecurity/lib/links'
|
|
55
|
+
*
|
|
56
|
+
* const formatted = links([
|
|
57
|
+
* ['Documentation', 'https://socket.dev'],
|
|
58
|
+
* ['API Reference', 'https://api.socket.dev'],
|
|
59
|
+
* ['GitHub', 'https://github.com/SocketDev']
|
|
60
|
+
* ])
|
|
61
|
+
*
|
|
62
|
+
* formatted.forEach(link => console.log(link))
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
export declare function links(linkSpecs: Array<[text: string, url: string]>, options?: LinkOptions): string[];
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/* Socket Lib - Built with esbuild */
|
|
2
|
+
var k=Object.create;var l=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var d=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty;var C=(e,o)=>{for(var r in o)l(e,r,{get:o[r],enumerable:!0})},a=(e,o,r,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of u(o))!T.call(e,n)&&n!==r&&l(e,n,{get:()=>o[n],enumerable:!(t=g(o,n))||t.enumerable});return e};var b=(e,o,r)=>(r=e!=null?k(d(e)):{},a(o||!e||!e.__esModule?l(r,"default",{value:e,enumerable:!0}):r,e)),L=e=>a(l({},"__esModule",{value:!0}),e);var O={};C(O,{link:()=>y,links:()=>N});module.exports=L(O);var c=b(require("../external/yoctocolors-cjs")),f=require("../themes/context"),h=require("../themes/utils");function y(e,o,r){const t={__proto__:null,fallback:!1,...r},n=typeof t.theme=="string"?require("../themes/themes").THEMES[t.theme]:t.theme??(0,f.getTheme)(),s=(0,h.resolveColor)(n.colors.link,n.colors),m=c.default;let i;if(typeof s=="string"&&s!=="inherit"){const p=m[s];i=p?p(e):m.cyan(e)}else Array.isArray(s),i=m.cyan(e);return t.fallback?`${i} (${o})`:i}function N(e,o){return e.map(([r,t])=>y(r,t,o))}0&&(module.exports={link,links});
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/links/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Themed hyperlink utilities for terminal output.\n * Provides colored hyperlinks using theme configuration.\n */\n\nimport yoctocolorsCjs from '../external/yoctocolors-cjs'\nimport type { ColorName } from '../spinner'\nimport { getTheme } from '../themes/context'\nimport { resolveColor } from '../themes/utils'\nimport type { Theme } from '../themes/types'\nimport type { ThemeName } from '../themes/themes'\n\n/**\n * Options for creating themed links.\n */\nexport type LinkOptions = {\n /** Theme to use (overrides global) */\n theme?: Theme | ThemeName | undefined\n /** Show URL as fallback if terminal doesn't support links */\n fallback?: boolean | undefined\n}\n\n/**\n * Create a themed hyperlink for terminal output.\n * The link text is colored using the theme's link color.\n *\n * Note: Most terminals support ANSI color codes but not clickable links.\n * This function colors the text but does not create clickable hyperlinks.\n * For clickable links, use a library like 'terminal-link' separately.\n *\n * @param text - Link text to display\n * @param url - URL (included in fallback mode)\n * @param options - Link configuration options\n * @returns Colored link text\n *\n * @example\n * ```ts\n * import { link } from '@socketsecurity/lib/links'\n *\n * // Use current theme\n * console.log(link('Documentation', 'https://socket.dev'))\n *\n * // Override theme\n * console.log(link('API Docs', 'https://api.socket.dev', {\n * theme: 'coana'\n * }))\n *\n * // Show URL as fallback\n * console.log(link('GitHub', 'https://github.com', {\n * fallback: true\n * }))\n * // Output: \"GitHub (https://github.com)\"\n * ```\n */\nexport function link(text: string, url: string, options?: LinkOptions): string {\n const opts = { __proto__: null, fallback: false, ...options } as LinkOptions\n\n // Resolve theme\n const theme =\n typeof opts.theme === 'string'\n ? require('../themes/themes').THEMES[opts.theme]\n : (opts.theme ?? getTheme())\n\n // Resolve link color\n const linkColor = resolveColor(theme.colors.link, theme.colors)\n\n // Apply color - for now just use cyan as a simple fallback\n // Note: RGB color support to be added in yoctocolors wrapper\n const colors = yoctocolorsCjs\n let colored: string\n if (typeof linkColor === 'string' && linkColor !== 'inherit') {\n // Use named color method if available\n const colorMethod = colors[linkColor as ColorName]\n colored = colorMethod ? colorMethod(text) : colors.cyan(text)\n } else if (Array.isArray(linkColor)) {\n // RGB color - for now fallback to cyan\n // Note: RGB color support to be implemented\n colored = colors.cyan(text)\n } else {\n colored = colors.cyan(text)\n }\n\n // Return with or without URL fallback\n return opts.fallback ? `${colored} (${url})` : colored\n}\n\n/**\n * Create multiple themed links from an array of link specifications.\n *\n * @param links - Array of [text, url] pairs\n * @param options - Link configuration options\n * @returns Array of colored link texts\n *\n * @example\n * ```ts\n * import { links } from '@socketsecurity/lib/links'\n *\n * const formatted = links([\n * ['Documentation', 'https://socket.dev'],\n * ['API Reference', 'https://api.socket.dev'],\n * ['GitHub', 'https://github.com/SocketDev']\n * ])\n *\n * formatted.forEach(link => console.log(link))\n * ```\n */\nexport function links(\n linkSpecs: Array<[text: string, url: string]>,\n options?: LinkOptions,\n): string[] {\n return linkSpecs.map(([text, url]) => link(text, url, options))\n}\n"],
|
|
5
|
+
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,UAAAC,IAAA,eAAAC,EAAAJ,GAKA,IAAAK,EAA2B,0CAE3BC,EAAyB,6BACzBC,EAA6B,2BA8CtB,SAASL,EAAKM,EAAcC,EAAaC,EAA+B,CAC7E,MAAMC,EAAO,CAAE,UAAW,KAAM,SAAU,GAAO,GAAGD,CAAQ,EAGtDE,EACJ,OAAOD,EAAK,OAAU,SAClB,QAAQ,kBAAkB,EAAE,OAAOA,EAAK,KAAK,EAC5CA,EAAK,UAAS,YAAS,EAGxBE,KAAY,gBAAaD,EAAM,OAAO,KAAMA,EAAM,MAAM,EAIxDE,EAAS,EAAAC,QACf,IAAIC,EACJ,GAAI,OAAOH,GAAc,UAAYA,IAAc,UAAW,CAE5D,MAAMI,EAAcH,EAAOD,CAAsB,EACjDG,EAAUC,EAAcA,EAAYT,CAAI,EAAIM,EAAO,KAAKN,CAAI,CAC9D,MAAW,MAAM,QAAQK,CAAS,EAGhCG,EAAUF,EAAO,KAAKN,CAAI,EAM5B,OAAOG,EAAK,SAAW,GAAGK,CAAO,KAAKP,CAAG,IAAMO,CACjD,CAsBO,SAASb,EACde,EACAR,EACU,CACV,OAAOQ,EAAU,IAAI,CAAC,CAACV,EAAMC,CAAG,IAAMP,EAAKM,EAAMC,EAAKC,CAAO,CAAC,CAChE",
|
|
6
|
+
"names": ["links_exports", "__export", "link", "links", "__toCommonJS", "import_yoctocolors_cjs", "import_context", "import_utils", "text", "url", "options", "opts", "theme", "linkColor", "colors", "yoctocolorsCjs", "colored", "colorMethod", "linkSpecs"]
|
|
7
|
+
}
|
package/dist/logger.d.ts
CHANGED
|
@@ -63,20 +63,22 @@ export type { LogSymbols, LoggerMethods, Task };
|
|
|
63
63
|
* Log symbols for terminal output with colored indicators.
|
|
64
64
|
*
|
|
65
65
|
* Provides colored Unicode symbols (✔, ✖, ⚠, ℹ, →) with ASCII fallbacks (√, ×, ‼, i, >)
|
|
66
|
-
* for terminals that don't support Unicode. Symbols are
|
|
67
|
-
*
|
|
66
|
+
* for terminals that don't support Unicode. Symbols are colored according to the active
|
|
67
|
+
* theme's color palette (success, error, warning, info, step).
|
|
68
68
|
*
|
|
69
|
-
* The symbols are lazily initialized on first access and
|
|
69
|
+
* The symbols are lazily initialized on first access and automatically update when the
|
|
70
|
+
* fallback theme changes (via setTheme()). Note that LOG_SYMBOLS reflect the global
|
|
71
|
+
* fallback theme, not async-local theme contexts from withTheme().
|
|
70
72
|
*
|
|
71
73
|
* @example
|
|
72
74
|
* ```typescript
|
|
73
75
|
* import { LOG_SYMBOLS } from '@socketsecurity/lib'
|
|
74
76
|
*
|
|
75
|
-
* console.log(`${LOG_SYMBOLS.success} Build completed`) //
|
|
76
|
-
* console.log(`${LOG_SYMBOLS.fail} Build failed`) //
|
|
77
|
-
* console.log(`${LOG_SYMBOLS.warn} Deprecated API used`) //
|
|
78
|
-
* console.log(`${LOG_SYMBOLS.info} Starting process`) //
|
|
79
|
-
* console.log(`${LOG_SYMBOLS.step} Processing files`) //
|
|
77
|
+
* console.log(`${LOG_SYMBOLS.success} Build completed`) // Theme success color ✔
|
|
78
|
+
* console.log(`${LOG_SYMBOLS.fail} Build failed`) // Theme error color ✖
|
|
79
|
+
* console.log(`${LOG_SYMBOLS.warn} Deprecated API used`) // Theme warning color ⚠
|
|
80
|
+
* console.log(`${LOG_SYMBOLS.info} Starting process`) // Theme info color ℹ
|
|
81
|
+
* console.log(`${LOG_SYMBOLS.step} Processing files`) // Theme step color →
|
|
80
82
|
* ```
|
|
81
83
|
*/
|
|
82
84
|
export declare const LOG_SYMBOLS: Record<string, string>;
|
|
@@ -923,21 +925,22 @@ export declare class Logger {
|
|
|
923
925
|
clearLine(): this;
|
|
924
926
|
}
|
|
925
927
|
/**
|
|
926
|
-
*
|
|
928
|
+
* Get the default logger instance.
|
|
929
|
+
* Lazily creates the logger to avoid circular dependencies during module initialization.
|
|
930
|
+
* Reuses the same instance across calls.
|
|
927
931
|
*
|
|
928
|
-
*
|
|
929
|
-
* and `process.stderr` streams. This is the recommended logger to import
|
|
930
|
-
* and use throughout your application.
|
|
932
|
+
* @returns Shared default logger instance
|
|
931
933
|
*
|
|
932
934
|
* @example
|
|
933
|
-
* ```
|
|
934
|
-
* import {
|
|
935
|
+
* ```ts
|
|
936
|
+
* import { getDefaultLogger } from '@socketsecurity/lib/logger'
|
|
935
937
|
*
|
|
938
|
+
* const logger = getDefaultLogger()
|
|
936
939
|
* logger.log('Application started')
|
|
937
940
|
* logger.success('Configuration loaded')
|
|
938
|
-
* logger.indent()
|
|
939
|
-
* logger.log('Using port 3000')
|
|
940
|
-
* logger.dedent()
|
|
941
941
|
* ```
|
|
942
942
|
*/
|
|
943
|
-
export declare
|
|
943
|
+
export declare function getDefaultLogger(): Logger;
|
|
944
|
+
// REMOVED: Deprecated `logger` export
|
|
945
|
+
// Migration: Use getDefaultLogger() instead
|
|
946
|
+
// See: getDefaultLogger() function above
|
package/dist/logger.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var G=Object.create;var w=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var s in t)w(e,s,{get:t[s],enumerable:!0})},A=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of v(t))!N.call(e,o)&&o!==s&&w(e,o,{get:()=>t[o],enumerable:!(n=Y(t,o))||n.enumerable});return e};var W=(e,t,s)=>(s=e!=null?G(H(e)):{},A(t||!e||!e.__esModule?w(s,"default",{value:e,enumerable:!0}):s,e)),z=e=>A(w({},"__esModule",{value:!0}),e);var X={};V(X,{LOG_SYMBOLS:()=>m,Logger:()=>d,getDefaultLogger:()=>Q,incLogCallCountSymbol:()=>l,lastWasBlankSymbol:()=>u});module.exports=z(X);var P=W(require("./external/@socketregistry/is-unicode-supported")),j=W(require("./external/yoctocolors-cjs")),f=require("./strings"),_=require("./themes/context");const y=console,C=Reflect.apply,D=Reflect.construct;let L;function k(...e){return L===void 0&&(L=require("node:console").Console),D(L,e)}function F(){return j.default}function p(e,t,s){return typeof t=="string"?s[t](e):s.rgb(t[0],t[1],t[2])(e)}const m=(()=>{const e={__proto__:null};let t=!1;const s={__proto__:null},n=()=>{const r=(0,P.default)(),c=F(),a=(0,_.getTheme)(),g=a.colors.success,B=a.colors.error,M=a.colors.warning,$=a.colors.info,K=a.colors.step;e.fail=p(r?"\u2716":"\xD7",B,c),e.info=p(r?"\u2139":"i",$,c),e.step=p(r?"\u2192":">",K,c),e.success=p(r?"\u2714":"\u221A",g,c),e.warn=p(r?"\u26A0":"\u203C",M,c)},o=()=>{if(!t){n(),t=!0;for(const r in s)delete s[r]}},i=()=>{t&&n()};for(const r of Reflect.ownKeys(Reflect)){const c=Reflect[r];typeof c=="function"&&(s[r]=(...a)=>(o(),c(...a)))}return(0,_.onThemeChange)(()=>{i()}),new Proxy(e,s)})(),E=["_stderrErrorHandler","_stdoutErrorHandler","assert","clear","count","countReset","createTask","debug","dir","dirxml","error","info","log","table","time","timeEnd","timeLog","trace","warn"].filter(e=>typeof y[e]=="function").map(e=>[e,y[e].bind(y)]),I={__proto__:null,writable:!0,enumerable:!1,configurable:!0},J=1e3,b=new WeakMap,h=new WeakMap;let S;function q(){return S===void 0&&(S=Object.getOwnPropertySymbols(y)),S}const l=Symbol.for("logger.logCallCount++");let x;function R(){return x===void 0&&(x=q().find(e=>e.label==="kGroupIndentWidth")??Symbol("kGroupIndentWidth")),x}const u=Symbol.for("logger.lastWasBlank");class d{static LOG_SYMBOLS=m;#c;#s;#l;#a;#g="";#f="";#p=!1;#y=!1;#h=0;#o;#w;constructor(...t){h.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(){U();let t=b.get(this);if(!t){const s=h.get(this)??[];if(s.length)t=k(...s);else{t=k({stdout:process.stdout,stderr:process.stderr});for(const{0:n,1:o}of E)t[n]=o}b.set(this,t),h.delete(this)}return t}get stderr(){if(!this.#l){const t=h.get(this)??[],s=new d(...t);s.#c=this,s.#s="stderr",s.#o={__proto__:null,...this.#o},this.#l=s}return this.#l}get stdout(){if(!this.#a){const t=h.get(this)??[],s=new d(...t);s.#c=this,s.#s="stdout",s.#o={__proto__:null,...this.#o},this.#a=s}return this.#a}#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}#m(){return this.#s||"stderr"}#k(t,s,n){const o=this.#t(),i=s.at(0),r=typeof i=="string",c=n||(t==="log"?"stdout":"stderr"),a=this.#n(c),g=r?[(0,f.applyLinePrefix)(i,{prefix:a}),...s.slice(1)]:s;return C(o[t],o,g),this[u](r&&(0,f.isBlankString)(g[0]),c),this[l](),this}#b(t){return t.replace(/^[✖✗×⚠‼✔✓√ℹ→]\uFE0F?\s*/u,"")}#i(t,s){const n=this.#t();let o=s.at(0),i;typeof o=="string"?(o=this.#b(o),i=s.slice(1)):(i=s,o="");const r=this.#n("stderr");return n.error((0,f.applyLinePrefix)(`${m[t]} ${o}`,{prefix:r}),...i),this[u](!1,"stderr"),this[l](),this}get logCallCount(){return this.#r().#h}[l](){const t=this.#r();return t.#h+=1,this}[u](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[u](!1),t?this:this[l]()}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[u](!0),this.#h=0),this}count(t){return this.#t().count(t),this[u](!1),this[l]()}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[u](!1),this[l]()}dirxml(...t){return this.#t().dirxml(t),this[u](!1),this[l]()}error(...t){return this.#k("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&&C(this.log,this,t),this.indent(this[R()]),s&&(this[u](!1),this[l]()),this}groupCollapsed(...t){return C(this.group,this,t)}groupEnd(){return this.dedent(this[R()]),this}indent(t=2){const s=" ".repeat(Math.min(t,J));if(this.#s){const n=this.#n(this.#s);this.#e(this.#s,n+s)}else{const n=this.#n("stderr"),o=this.#n("stdout");this.#e("stderr",n+s),this.#e("stdout",o+s)}return this}info(...t){return this.#i("info",t)}log(...t){return this.#k("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),o=this.#n("stdout");return this.#t().log((0,f.applyLinePrefix)(`${m.step} ${n}`,{prefix:o}),...s),this[u](!1,"stdout"),this[l](),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[u](!1),this[l]()}timeEnd(t){return this.#t().timeEnd(t),this[u](!1),this[l]()}timeLog(t,...s){return this.#t().timeLog(t,...s),this[u](!1),this[l]()}trace(t,...s){return this.#t().trace(t,...s),this[u](!1),this[l]()}warn(...t){return this.#i("warn",t)}write(t){const s=this.#t(),n=h.get(this)??[];return(this.#w||n[0]?.stdout||s._stdout).write(t),this[u](!1),this}progress(t){const s=this.#t();return(this.#m()==="stderr"?s._stderr:s._stdout).write(`\u2234 ${t}`),this[u](!1),this}clearLine(){const t=this.#t(),n=this.#m()==="stderr"?t._stderr:t._stdout;return n.isTTY?(n.cursorTo(0),n.clearLine(0)):n.write("\r\x1B[K"),this}}let O=!1;function U(){if(O)return;O=!0;const e=[[R(),{...I,value:2}],[Symbol.toStringTag,{__proto__:null,configurable:!0,value:"logger"}]];for(const{0:t,1:s}of Object.entries(y))if(!d.prototype[t]&&typeof s=="function"){const{[t]:n}={[t](...o){let i=b.get(this);if(i===void 0){const c=h.get(this)??[];if(h.delete(this),c.length)i=k(...c);else{i=k({stdout:process.stdout,stderr:process.stderr});for(const{0:a,1:g}of E)i[a]=g}b.set(this,i)}const r=i[t](...o);return r===void 0||r===i?this:r}};e.push([t,{...I,value:n}])}Object.defineProperties(d.prototype,Object.fromEntries(e))}let T;function Q(){return T===void 0&&(T=new d),T}0&&(module.exports={LOG_SYMBOLS,Logger,getDefaultLogger,incLogCallCountSymbol,lastWasBlankSymbol});
|
|
3
3
|
//# sourceMappingURL=logger.js.map
|