@socketsecurity/lib 5.7.0 → 5.8.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 CHANGED
@@ -5,6 +5,49 @@ 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
+ ## [5.8.1](https://github.com/SocketDev/socket-lib/releases/tag/v5.8.1) - 2026-03-11
9
+
10
+ ### Performance
11
+
12
+ - **windows**: Add comprehensive caching for expensive PATH resolution operations
13
+ - `getBinPath()`, `getBinPathSync()`: Cache binary path lookups
14
+ - `findRealBin()`: Cache `all:true` lookups and use single `whichSync({ all: true })` call
15
+ - `getVoltaBinPath()`: Cache Volta binary resolution
16
+ - `spawn()`: Cache binary path resolution before spawning
17
+ - `getGitPath()`: Cache git binary path
18
+ - `getCachedRealpath()`: New helper caching `realpathSync()` calls for git operations
19
+ - `findGitRoot()`: Cache git root directory lookups
20
+ - `findPackageJson()`: Cache package.json path lookups
21
+ - `readPackageJson()`: Cache parsed package.json content
22
+ - `resolveBinaryPath()`: Cache binary path resolution with Windows extension handling
23
+ - `NPM_BIN_PATH`, `NPM_REAL_EXEC_PATH`: Share npm path resolution to avoid duplicate `which.sync()` calls
24
+ - `ProcessLockManager.isStale()`: Use single `statSync({ throwIfNoEntry: false })` instead of `existsSync()` + `statSync()`
25
+ - All caches validate entries with `existsSync()` and remove stale entries automatically
26
+
27
+ ## [5.8.0](https://github.com/SocketDev/socket-lib/releases/tag/v5.8.0) - 2026-03-10
28
+
29
+ ### Added
30
+
31
+ - **archives**: Added secure archive extraction utilities with support for ZIP, TAR, TAR.GZ, and TGZ formats
32
+ - Configurable limits: `maxFileSize` (default 100MB), `maxTotalSize` (default 1GB)
33
+ - Cross-platform path normalization
34
+ - External dependencies: adm-zip@0.5.16, tar-fs@3.1.2 (bundled, +212KB)
35
+ - Security features: path traversal protection, file size limits, total size limits, symlink blocking
36
+ - Strip option to remove leading path components (like tar `--strip-components`)
37
+ - `detectArchiveFormat()` - Detect archive type from file extension
38
+ - `extractArchive()` - Generic extraction with auto-format detection
39
+ - `extractTar()`, `extractTarGz()`, `extractZip()` - Format-specific extractors
40
+
41
+ - **releases/github**: Added archive extraction support for GitHub releases
42
+ - Auto-detects format from asset filename
43
+ - Enhanced `downloadAndExtractZip()` to use generic archive helpers
44
+ - Supports ZIP, TAR, TAR.GZ, and TGZ assets
45
+ - `downloadAndExtractArchive()` - Generic archive download and extraction
46
+
47
+ ### Changed
48
+
49
+ - **dependencies**: Deduplicated 14 external bundle packages to single versions using pnpm overrides and patches
50
+
8
51
  ## [5.7.0](https://github.com/SocketDev/socket-lib/releases/tag/v5.7.0) - 2026-02-12
9
52
 
10
53
  ### Added
@@ -67,7 +110,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
67
110
  - **provenance**: Fixed incorrect package name in provenance workflow
68
111
  - Changed from `@socketregistry/lib` to `@socketsecurity/lib`
69
112
 
70
-
71
113
  ## [5.6.0](https://github.com/SocketDev/socket-lib/releases/tag/v5.6.0) - 2026-02-08
72
114
 
73
115
  ### Added
@@ -1073,6 +1115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1073
1115
  This release completely refactors the environment variable system, consolidating 60+ individual env constant files into grouped getter modules with AsyncLocalStorage-based test rewiring.
1074
1116
 
1075
1117
  **Consolidated env files** - Individual files replaced with grouped modules:
1118
+
1076
1119
  - `env/github.ts` - All GitHub-related env vars (GITHUB_TOKEN, GH_TOKEN, GITHUB_API_URL, etc.)
1077
1120
  - `env/socket.ts` - Socket-specific env vars (SOCKET_API_TOKEN, SOCKET_CACACHE_DIR, etc.)
1078
1121
  - `env/socket-cli.ts` - Socket CLI env vars (SOCKET_CLI_API_TOKEN, SOCKET_CLI_CONFIG, etc.)
@@ -1084,6 +1127,7 @@ This release completely refactors the environment variable system, consolidating
1084
1127
  - `env/test.ts` - Test framework env vars (VITEST, JEST_WORKER_ID)
1085
1128
 
1086
1129
  **Constants → Getter functions** - All env constants converted to functions:
1130
+
1087
1131
  ```typescript
1088
1132
  // Before (v1.x):
1089
1133
  import { GITHUB_TOKEN } from '#env/github-token'
@@ -1093,6 +1137,7 @@ import { getGithubToken } from '#env/github'
1093
1137
  ```
1094
1138
 
1095
1139
  **Deleted files** - Removed 60+ individual env constant files:
1140
+
1096
1141
  - `env/github-token.ts`, `env/socket-api-token.ts`, etc. → Consolidated into grouped files
1097
1142
  - `env/getters.ts` → Functions moved to their respective grouped files
1098
1143
 
@@ -1122,6 +1167,7 @@ afterEach(() => {
1122
1167
  ```
1123
1168
 
1124
1169
  **Features:**
1170
+
1125
1171
  - Allows toggling between snapshot and live behavior
1126
1172
  - Compatible with `vi.stubEnv()` as fallback
1127
1173
 
@@ -1224,7 +1270,7 @@ afterEach(() => {
1224
1270
  ### Added
1225
1271
 
1226
1272
  - Added `dlx-package` module for installing and executing npm packages directly
1227
- - Content-addressed caching using SHA256 hash (like npm's _npx)
1273
+ - Content-addressed caching using SHA256 hash (like npm's \_npx)
1228
1274
  - Auto-force for version ranges (^, ~, >, <) to get latest within range
1229
1275
  - Cross-platform support with comprehensive tests (30 tests)
1230
1276
  - Parses scoped and unscoped package specs correctly
package/README.md CHANGED
@@ -7,47 +7,219 @@
7
7
  [![Follow @SocketSecurity](https://img.shields.io/twitter/follow/SocketSecurity?style=social)](https://twitter.com/SocketSecurity)
8
8
  [![Follow @socket.dev on Bluesky](https://img.shields.io/badge/Follow-@socket.dev-1DA1F2?style=social&logo=bluesky)](https://bsky.app/profile/socket.dev)
9
9
 
10
- Core library for [Socket.dev](https://socket.dev/) tools.
10
+ Core infrastructure library for [Socket.dev](https://socket.dev/) security tools. Provides utilities for file system operations, process spawning, HTTP requests, environment detection, logging, spinners, and more.
11
+
12
+ ## Prerequisites
13
+
14
+ **Node.js 22 or higher** is required.
11
15
 
12
16
  ## Install
13
17
 
14
18
  ```bash
19
+ # Using pnpm (recommended)
15
20
  pnpm add @socketsecurity/lib
21
+
22
+ # Using npm
23
+ npm install @socketsecurity/lib
24
+
25
+ # Using yarn
26
+ yarn add @socketsecurity/lib
16
27
  ```
17
28
 
18
- ## Usage
29
+ ## Quick Start
19
30
 
20
31
  ```typescript
21
- // Tree-shakeable exports
22
32
  import { Spinner } from '@socketsecurity/lib/spinner'
23
- import { readJsonFile } from '@socketsecurity/lib/fs'
24
- import { NODE_MODULES } from '@socketsecurity/lib/constants/packages'
33
+ import { getDefaultLogger } from '@socketsecurity/lib/logger'
34
+ import { readJson } from '@socketsecurity/lib/fs'
35
+
36
+ const logger = getDefaultLogger()
37
+ const spinner = Spinner({ text: 'Loading package.json...' })
25
38
 
26
- const spinner = Spinner({ text: 'Loading...' })
27
39
  spinner.start()
28
- const pkg = await readJsonFile('./package.json')
29
- spinner.stop()
40
+ const pkg = await readJson('./package.json')
41
+ spinner.successAndStop('Loaded successfully')
42
+
43
+ logger.success(`Package: ${pkg.name}@${pkg.version}`)
30
44
  ```
31
45
 
46
+ ## Documentation
47
+
48
+ - [Getting Started](./docs/getting-started.md) - Prerequisites, installation, and first examples
49
+ - [Visual Effects](./docs/visual-effects.md) - Spinners, loggers, themes, and progress indicators
50
+ - [File System](./docs/file-system.md) - File operations, globs, paths, and safe deletion
51
+ - [HTTP Utilities](./docs/http-utilities.md) - Making requests, downloading files, and retry logic
52
+ - [Process Utilities](./docs/process-utilities.md) - Spawning processes, IPC, and locks
53
+ - [Package Management](./docs/package-management.md) - npm/pnpm/yarn detection and operations
54
+ - [Environment](./docs/environment.md) - CI detection, env getters, and platform checks
55
+ - [Constants](./docs/constants.md) - Node versions, npm URLs, and platform values
56
+ - [Examples](./docs/examples.md) - Real-world usage patterns
57
+ - [Troubleshooting](./docs/troubleshooting.md) - Common issues and solutions
58
+
32
59
  ## What's Inside
33
60
 
34
- - **Visual Effects** → logger, spinner, themes
35
- - **File System** → fs, globs, paths
36
- - **Package Management** → dlx, npm, pnpm, yarn
37
- - **Process & Spawn** → process spawning
38
- - **Environment** env getters
39
- - **Constants** node, npm, platform
40
- - **Utilities** arrays, objects, promises, strings
61
+ ### Visual Effects
62
+
63
+ Spinners, colored loggers, themes, progress bars, and terminal output formatting.
64
+
65
+ - `Spinner` - Animated CLI spinners with progress tracking
66
+ - `getDefaultLogger()` - Colored console logger with symbols
67
+ - `LOG_SYMBOLS` - Colored terminal symbols (✓, ✗, ⚠, ℹ, →)
68
+ - `setTheme()` - Customize colors across the library
69
+
70
+ ### File System
71
+
72
+ Cross-platform file operations with safe deletion and convenient wrappers.
73
+
74
+ - `readFileUtf8()`, `readFileBinary()` - Read files as text or binary
75
+ - `readJson()`, `writeJson()` - Parse and format JSON files
76
+ - `safeDelete()` - Protected deletion with safety checks
77
+ - `findUp()`, `findUpSync()` - Traverse up to find files
78
+ - `safeMkdir()` - Create directories without EEXIST errors
79
+ - `validateFiles()` - Check file readability (useful for Yarn PnP, pnpm)
80
+
81
+ ### HTTP Utilities
82
+
83
+ Native Node.js HTTP/HTTPS requests with retry logic and redirects.
84
+
85
+ - `httpJson()` - Fetch and parse JSON from APIs
86
+ - `httpText()` - Fetch text/HTML content
87
+ - `httpDownload()` - Download files with progress callbacks
88
+ - `httpRequest()` - Full control over requests and responses
89
+ - Automatic redirects, exponential backoff retries, timeout support
90
+
91
+ ### Process Management
92
+
93
+ Spawn child processes safely with cross-platform support.
94
+
95
+ - `spawn()` - Promise-based process spawning with output capture
96
+ - `spawnSync()` - Synchronous version for blocking operations
97
+ - Array-based arguments prevent command injection
98
+ - Automatic Windows `.cmd`/`.bat` handling
99
+ - `ProcessLock` - Ensure only one instance runs at a time
100
+ - `setupIPC()` - Inter-process communication
101
+
102
+ ### Environment Detection
103
+
104
+ Type-safe environment variable access and platform detection.
105
+
106
+ - `getCI()` - Detect CI environment
107
+ - `getNodeEnv()` - Get NODE_ENV value
108
+ - `isTest()` - Check if running tests
109
+ - `getHome()` - Home directory (Unix/Linux/macOS)
110
+ - Test rewiring with `setEnv()`, `resetEnv()`
111
+
112
+ ### Package Management
113
+
114
+ Detect and work with npm, pnpm, and yarn.
115
+
116
+ - `detectPackageManager()` - Identify package manager from lock files
117
+ - Package manifest operations
118
+ - Lock file management
119
+
120
+ ### Constants
121
+
122
+ Pre-defined values for Node.js, npm, and platform detection.
123
+
124
+ - `getNodeMajorVersion()` - Get current Node.js major version
125
+ - `WIN32`, `DARWIN` - Platform booleans (use `!WIN32 && !DARWIN` for Linux)
126
+ - `getAbortSignal()` - Global abort signal
127
+
128
+ ### Utilities
129
+
130
+ Helpers for arrays, objects, strings, promises, sorting, and more.
131
+
132
+ - Arrays, objects, strings manipulation
133
+ - Promise utilities and queues
134
+ - Natural sorting
135
+ - Version comparison
136
+ - Error handling with causes
137
+
138
+ ## Features
139
+
140
+ - **Tree-shakeable exports** - Import only what you need
141
+ - **Cross-platform** - Works on Windows, macOS, and Linux
142
+ - **TypeScript-first** - Full type safety with .d.ts files
143
+ - **Zero dependencies** (for core HTTP - uses Node.js native modules)
144
+ - **Well-tested** - 84% coverage with comprehensive test suite
145
+ - **Security-focused** - Safe defaults, command injection protection
146
+ - **CommonJS output** - Compatible with Node.js tooling
147
+
148
+ ## Common Use Cases
149
+
150
+ ### Running Shell Commands
151
+
152
+ ```typescript
153
+ import { spawn } from '@socketsecurity/lib/spawn'
154
+
155
+ const result = await spawn('git', ['status'])
156
+ console.log(result.stdout)
157
+ ```
158
+
159
+ ### Making API Requests
160
+
161
+ ```typescript
162
+ import { httpJson } from '@socketsecurity/lib/http-request'
163
+
164
+ const data = await httpJson('https://api.example.com/data')
165
+ ```
166
+
167
+ ### Visual Feedback
168
+
169
+ ```typescript
170
+ import { Spinner } from '@socketsecurity/lib/spinner'
171
+
172
+ const spinner = Spinner({ text: 'Processing...' })
173
+ spinner.start()
174
+ // ... do work ...
175
+ spinner.successAndStop('Complete!')
176
+ ```
177
+
178
+ ### Safe File Deletion
179
+
180
+ ```typescript
181
+ import { safeDelete } from '@socketsecurity/lib/fs'
182
+
183
+ // Protected against deleting parent directories
184
+ await safeDelete('./build')
185
+ ```
186
+
187
+ ## Troubleshooting
188
+
189
+ **Module not found**: Verify you're importing from the correct path:
190
+
191
+ ```typescript
192
+ // Correct
193
+ import { Spinner } from '@socketsecurity/lib/spinner'
194
+
195
+ // Wrong
196
+ import { Spinner } from '@socketsecurity/lib'
197
+ ```
198
+
199
+ **Node version error**: This library requires Node.js 22+. Check your version:
200
+
201
+ ```bash
202
+ node --version
203
+ ```
204
+
205
+ For more issues, see the [Troubleshooting Guide](./docs/troubleshooting.md).
41
206
 
42
207
  ## Development
43
208
 
44
209
  ```bash
45
- pnpm install # Install
46
- pnpm build # Build
47
- pnpm test # Test
210
+ pnpm install # Install dependencies
211
+ pnpm build # Build the library
212
+ pnpm test # Run tests
213
+ pnpm run cover # Run tests with coverage
48
214
  pnpm dev # Watch mode
215
+ pnpm run lint # Check code style
216
+ pnpm run fix # Fix formatting issues
49
217
  ```
50
218
 
219
+ ## Contributing
220
+
221
+ Contributions are welcome! Please read the [CLAUDE.md](./CLAUDE.md) file for development guidelines and coding standards.
222
+
51
223
  ## License
52
224
 
53
225
  MIT
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Archive format type.
3
+ */
4
+ export type ArchiveFormat = 'tar' | 'tar.gz' | 'tgz' | 'zip';
5
+ /**
6
+ * Options for archive extraction.
7
+ */
8
+ export interface ExtractOptions {
9
+ /** Suppress log messages */
10
+ quiet?: boolean;
11
+ /** Strip leading path components (like tar --strip-components) */
12
+ strip?: number;
13
+ /** Maximum size of a single extracted file in bytes (default: 100MB) */
14
+ maxFileSize?: number;
15
+ /** Maximum total extracted size in bytes (default: 1GB) */
16
+ maxTotalSize?: number;
17
+ }
18
+ /**
19
+ * Detect archive format from file path.
20
+ *
21
+ * @param filePath - Path to archive file
22
+ * @returns Archive format or null if unknown
23
+ */
24
+ export declare function detectArchiveFormat(filePath: string): ArchiveFormat | null;
25
+ /**
26
+ * Extract a tar archive to a directory.
27
+ *
28
+ * @param archivePath - Path to tar file
29
+ * @param outputDir - Directory to extract to
30
+ * @param options - Extraction options
31
+ */
32
+ export declare function extractTar(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;
33
+ /**
34
+ * Extract a gzipped tar archive to a directory.
35
+ *
36
+ * @param archivePath - Path to tar.gz or tgz file
37
+ * @param outputDir - Directory to extract to
38
+ * @param options - Extraction options
39
+ */
40
+ export declare function extractTarGz(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;
41
+ /**
42
+ * Extract a zip archive to a directory.
43
+ *
44
+ * @param archivePath - Path to zip file
45
+ * @param outputDir - Directory to extract to
46
+ * @param options - Extraction options
47
+ */
48
+ export declare function extractZip(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;
49
+ /**
50
+ * Extract an archive to a directory.
51
+ * Automatically detects format from file extension.
52
+ *
53
+ * @param archivePath - Path to archive file
54
+ * @param outputDir - Directory to extract to
55
+ * @param options - Extraction options
56
+ * @throws Error if archive format is not supported
57
+ */
58
+ export declare function extractArchive(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;