@socketsecurity/lib 2.10.3 → 2.10.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 +33 -0
- package/dist/dlx-binary.js +7 -7
- package/dist/dlx-binary.js.map +3 -3
- package/dist/dlx-package.js +7 -7
- package/dist/dlx-package.js.map +3 -3
- package/dist/dlx.js +4 -4
- package/dist/dlx.js.map +3 -3
- package/dist/download-lock.js.map +2 -2
- package/dist/env/socket-cli.d.ts +7 -0
- package/dist/env/socket-cli.js +1 -1
- package/dist/env/socket-cli.js.map +2 -2
- package/dist/fs.d.ts +81 -26
- package/dist/fs.js +7 -7
- package/dist/fs.js.map +3 -3
- package/dist/ipc.js.map +2 -2
- package/package.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/download-lock.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Download locking utilities to prevent concurrent downloads of the same resource. Uses file-based locking for cross-process synchronization.\n * @deprecated This module is deprecated in favor of `process-lock.ts` which uses\n * directory-based locking (via `mkdir()`) that's more reliable across all filesystems\n * including NFS. See process-lock.ts for detailed explanation of why directory-based\n * locking is superior to file-based locking.\n *\n * Migration: Use `processLock.withLock()` from `./process-lock` instead of\n * `downloadWithLock()` from this module.\n */\n\nimport { existsSync } from 'node:fs'\nimport { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport type { HttpDownloadOptions, HttpDownloadResult } from './http-request'\nimport { httpDownload } from './http-request'\n\nexport interface DownloadLockInfo {\n pid: number\n startTime: number\n url: string\n}\n\nexport interface DownloadWithLockOptions extends HttpDownloadOptions {\n /**\n * Maximum time to wait for lock acquisition in milliseconds.\n * @default 60000 (1 minute)\n */\n lockTimeout?: number | undefined\n /**\n * Directory where lock files are stored.\n * @default '<destPath>.locks'\n */\n locksDir?: string | undefined\n /**\n * Interval for checking stale locks in milliseconds.\n * @default 1000 (1 second)\n */\n pollInterval?: number | undefined\n /**\n * Maximum age of a lock before it's considered stale in milliseconds.\n * Aligned with npm's npx locking strategy (5-10 seconds).\n * @default 10000 (10 seconds)\n */\n staleTimeout?: number | undefined\n}\n\n/**\n * Get the path to the lock file for a destination path.\n * Uses npm npx's concurrency.lock naming convention.\n * For downloads, we use a subdirectory per destination to isolate locks.\n */\nfunction getLockFilePath(destPath: string, locksDir?: string): string {\n // Create a unique subdirectory for each destination using sanitized path.\n const sanitized = destPath.replace(/[^\\w.-]/g, '_')\n const dir = locksDir || join(dirname(destPath), '.locks', sanitized)\n return join(dir, 'concurrency.lock')\n}\n\n/**\n * Check if a lock is stale (process no longer exists or too old).\n */\nfunction isLockStale(\n lockInfo: DownloadLockInfo,\n staleTimeout: number,\n): boolean {\n // Check if lock is too old\n const age = Date.now() - lockInfo.startTime\n if (age > staleTimeout) {\n return true\n }\n\n // Check if process still exists (Node.js specific)\n try {\n // process.kill(pid, 0) doesn't actually kill the process\n // It just checks if the process exists\n process.kill(lockInfo.pid, 0)\n return false\n } catch {\n // Process doesn't exist\n return true\n }\n}\n\n/**\n * Acquire a lock for downloading to a destination path.\n * @throws {Error} When lock cannot be acquired within timeout.\n */\nasync function acquireLock(\n destPath: string,\n url: string,\n options: {\n lockTimeout: number\n locksDir?: string | undefined\n pollInterval: number\n staleTimeout: number\n },\n): Promise<string> {\n const { lockTimeout, locksDir, pollInterval, staleTimeout } = options\n const lockPath = getLockFilePath(destPath, locksDir)\n const lockDir = dirname(lockPath)\n\n // Ensure lock directory exists\n await mkdir(lockDir, { recursive: true })\n\n const startTime = Date.now()\n\n while (true) {\n try {\n // Try to read existing lock\n if (existsSync(lockPath)) {\n // eslint-disable-next-line no-await-in-loop\n const lockContent = await readFile(lockPath, 'utf8')\n const lockInfo: DownloadLockInfo = JSON.parse(lockContent)\n\n // Check if lock is stale\n if (isLockStale(lockInfo, staleTimeout)) {\n // Remove stale lock\n // eslint-disable-next-line no-await-in-loop\n await rm(lockPath, { force: true })\n } else {\n // Lock is valid, check timeout\n if (Date.now() - startTime > lockTimeout) {\n const lockAge = Date.now() - lockInfo.startTime\n throw new Error(\n `Download lock timed out after ${lockTimeout}ms\\n` +\n `Lock held by process ${lockInfo.pid} for ${lockAge}ms\\n` +\n `Resource: ${lockInfo.url}\\n` +\n `Started: ${new Date(lockInfo.startTime).toISOString()}\\n` +\n 'To resolve:\\n' +\n ` 1. Check if process ${lockInfo.pid} is still running: ps -p ${lockInfo.pid}\\n` +\n ` 2. If stale, remove lock file: rm \"${lockPath}\"\\n` +\n ' 3. Or increase lockTimeout option',\n )\n }\n\n // Wait and retry\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n continue\n }\n }\n\n // Try to create lock file\n const lockInfo: DownloadLockInfo = {\n pid: process.pid,\n startTime: Date.now(),\n url,\n }\n\n // eslint-disable-next-line no-await-in-loop\n await writeFile(lockPath, JSON.stringify(lockInfo, null, 2), {\n // Use 'wx' flag to fail if file exists (atomic operation)\n flag: 'wx',\n })\n\n // Successfully acquired lock\n return lockPath\n } catch (e) {\n // If file already exists, another process created it first\n if ((e as NodeJS.ErrnoException).code === 'EEXIST') {\n if (Date.now() - startTime > lockTimeout) {\n throw new Error(`Lock acquisition timed out after ${lockTimeout}ms`)\n }\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n continue\n }\n\n // Other error\n throw e\n }\n }\n}\n\n/**\n * Release a lock by removing the lock file.\n */\nasync function releaseLock(lockPath: string): Promise<void> {\n try {\n await rm(lockPath, { force: true })\n } catch {\n // Ignore errors when releasing lock\n }\n}\n\n/**\n * Download a file with locking to prevent concurrent downloads of the same resource.\n * If another process is already downloading to the same destination, this will wait\n * for the download to complete (up to lockTimeout) before proceeding.\n *\n * @throws {Error} When download fails or lock cannot be acquired.\n *\n * @example\n * ```typescript\n * const result = await downloadWithLock(\n * 'https://example.com/file.tar.gz',\n * '/tmp/downloads/file.tar.gz',\n * {\n * retries: 3,\n * lockTimeout: 60000, // Wait up to 1 minute for other downloads\n * }\n * )\n * ```\n */\nexport async function downloadWithLock(\n url: string,\n destPath: string,\n options?: DownloadWithLockOptions | undefined,\n): Promise<HttpDownloadResult> {\n const {\n lockTimeout = 60_000,\n locksDir,\n pollInterval = 1000,\n // Aligned with npm's npx locking (5-10s range).\n staleTimeout = 10_000,\n ...downloadOptions\n } = { __proto__: null, ...options } as DownloadWithLockOptions\n\n // If file already exists and has content, return immediately\n if (existsSync(destPath)) {\n const statResult = await stat(destPath).catch(() => null)\n if (statResult && statResult.size > 0) {\n return {\n path: destPath,\n size: statResult.size,\n }\n }\n }\n\n // Acquire lock\n const lockPath = await acquireLock(destPath, url, {\n lockTimeout,\n locksDir,\n pollInterval,\n staleTimeout,\n })\n\n try {\n // Check again if file was created while we were waiting for lock\n if (existsSync(destPath)) {\n const statResult = await stat(destPath).catch(() => null)\n if (statResult && statResult.size > 0) {\n return {\n path: destPath,\n size: statResult.size,\n }\n }\n }\n\n // Perform download\n const result = await httpDownload(url, destPath, downloadOptions)\n\n return result\n } finally {\n // Always release lock\n await releaseLock(lockPath)\n }\n}\n"],
|
|
5
|
-
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,IAAA,eAAAC,EAAAH,GAWA,IAAAI,EAA2B,
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Download locking utilities to prevent concurrent downloads of the same resource. Uses file-based locking for cross-process synchronization.\n * @deprecated This module is deprecated in favor of `process-lock.ts` which uses\n * directory-based locking (via `mkdir()`) that's more reliable across all filesystems\n * including NFS. See process-lock.ts for detailed explanation of why directory-based\n * locking is superior to file-based locking.\n *\n * Migration: Use `processLock.withLock()` from `./process-lock` instead of\n * `downloadWithLock()` from this module.\n */\n\nimport { existsSync } from 'node:fs'\n\nimport { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\n\nimport { dirname, join } from 'node:path'\nimport type { HttpDownloadOptions, HttpDownloadResult } from './http-request'\nimport { httpDownload } from './http-request'\n\nexport interface DownloadLockInfo {\n pid: number\n startTime: number\n url: string\n}\n\nexport interface DownloadWithLockOptions extends HttpDownloadOptions {\n /**\n * Maximum time to wait for lock acquisition in milliseconds.\n * @default 60000 (1 minute)\n */\n lockTimeout?: number | undefined\n /**\n * Directory where lock files are stored.\n * @default '<destPath>.locks'\n */\n locksDir?: string | undefined\n /**\n * Interval for checking stale locks in milliseconds.\n * @default 1000 (1 second)\n */\n pollInterval?: number | undefined\n /**\n * Maximum age of a lock before it's considered stale in milliseconds.\n * Aligned with npm's npx locking strategy (5-10 seconds).\n * @default 10000 (10 seconds)\n */\n staleTimeout?: number | undefined\n}\n\n/**\n * Get the path to the lock file for a destination path.\n * Uses npm npx's concurrency.lock naming convention.\n * For downloads, we use a subdirectory per destination to isolate locks.\n */\nfunction getLockFilePath(destPath: string, locksDir?: string): string {\n // Create a unique subdirectory for each destination using sanitized path.\n const sanitized = destPath.replace(/[^\\w.-]/g, '_')\n const dir = locksDir || join(dirname(destPath), '.locks', sanitized)\n return join(dir, 'concurrency.lock')\n}\n\n/**\n * Check if a lock is stale (process no longer exists or too old).\n */\nfunction isLockStale(\n lockInfo: DownloadLockInfo,\n staleTimeout: number,\n): boolean {\n // Check if lock is too old\n const age = Date.now() - lockInfo.startTime\n if (age > staleTimeout) {\n return true\n }\n\n // Check if process still exists (Node.js specific)\n try {\n // process.kill(pid, 0) doesn't actually kill the process\n // It just checks if the process exists\n process.kill(lockInfo.pid, 0)\n return false\n } catch {\n // Process doesn't exist\n return true\n }\n}\n\n/**\n * Acquire a lock for downloading to a destination path.\n * @throws {Error} When lock cannot be acquired within timeout.\n */\nasync function acquireLock(\n destPath: string,\n url: string,\n options: {\n lockTimeout: number\n locksDir?: string | undefined\n pollInterval: number\n staleTimeout: number\n },\n): Promise<string> {\n const { lockTimeout, locksDir, pollInterval, staleTimeout } = options\n const lockPath = getLockFilePath(destPath, locksDir)\n const lockDir = dirname(lockPath)\n\n // Ensure lock directory exists\n await mkdir(lockDir, { recursive: true })\n\n const startTime = Date.now()\n\n while (true) {\n try {\n // Try to read existing lock\n if (existsSync(lockPath)) {\n // eslint-disable-next-line no-await-in-loop\n const lockContent = await readFile(lockPath, 'utf8')\n const lockInfo: DownloadLockInfo = JSON.parse(lockContent)\n\n // Check if lock is stale\n if (isLockStale(lockInfo, staleTimeout)) {\n // Remove stale lock\n // eslint-disable-next-line no-await-in-loop\n await rm(lockPath, { force: true })\n } else {\n // Lock is valid, check timeout\n if (Date.now() - startTime > lockTimeout) {\n const lockAge = Date.now() - lockInfo.startTime\n throw new Error(\n `Download lock timed out after ${lockTimeout}ms\\n` +\n `Lock held by process ${lockInfo.pid} for ${lockAge}ms\\n` +\n `Resource: ${lockInfo.url}\\n` +\n `Started: ${new Date(lockInfo.startTime).toISOString()}\\n` +\n 'To resolve:\\n' +\n ` 1. Check if process ${lockInfo.pid} is still running: ps -p ${lockInfo.pid}\\n` +\n ` 2. If stale, remove lock file: rm \"${lockPath}\"\\n` +\n ' 3. Or increase lockTimeout option',\n )\n }\n\n // Wait and retry\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n continue\n }\n }\n\n // Try to create lock file\n const lockInfo: DownloadLockInfo = {\n pid: process.pid,\n startTime: Date.now(),\n url,\n }\n\n // eslint-disable-next-line no-await-in-loop\n await writeFile(lockPath, JSON.stringify(lockInfo, null, 2), {\n // Use 'wx' flag to fail if file exists (atomic operation)\n flag: 'wx',\n })\n\n // Successfully acquired lock\n return lockPath\n } catch (e) {\n // If file already exists, another process created it first\n if ((e as NodeJS.ErrnoException).code === 'EEXIST') {\n if (Date.now() - startTime > lockTimeout) {\n throw new Error(`Lock acquisition timed out after ${lockTimeout}ms`)\n }\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n continue\n }\n\n // Other error\n throw e\n }\n }\n}\n\n/**\n * Release a lock by removing the lock file.\n */\nasync function releaseLock(lockPath: string): Promise<void> {\n try {\n await rm(lockPath, { force: true })\n } catch {\n // Ignore errors when releasing lock\n }\n}\n\n/**\n * Download a file with locking to prevent concurrent downloads of the same resource.\n * If another process is already downloading to the same destination, this will wait\n * for the download to complete (up to lockTimeout) before proceeding.\n *\n * @throws {Error} When download fails or lock cannot be acquired.\n *\n * @example\n * ```typescript\n * const result = await downloadWithLock(\n * 'https://example.com/file.tar.gz',\n * '/tmp/downloads/file.tar.gz',\n * {\n * retries: 3,\n * lockTimeout: 60000, // Wait up to 1 minute for other downloads\n * }\n * )\n * ```\n */\nexport async function downloadWithLock(\n url: string,\n destPath: string,\n options?: DownloadWithLockOptions | undefined,\n): Promise<HttpDownloadResult> {\n const {\n lockTimeout = 60_000,\n locksDir,\n pollInterval = 1000,\n // Aligned with npm's npx locking (5-10s range).\n staleTimeout = 10_000,\n ...downloadOptions\n } = { __proto__: null, ...options } as DownloadWithLockOptions\n\n // If file already exists and has content, return immediately\n if (existsSync(destPath)) {\n const statResult = await stat(destPath).catch(() => null)\n if (statResult && statResult.size > 0) {\n return {\n path: destPath,\n size: statResult.size,\n }\n }\n }\n\n // Acquire lock\n const lockPath = await acquireLock(destPath, url, {\n lockTimeout,\n locksDir,\n pollInterval,\n staleTimeout,\n })\n\n try {\n // Check again if file was created while we were waiting for lock\n if (existsSync(destPath)) {\n const statResult = await stat(destPath).catch(() => null)\n if (statResult && statResult.size > 0) {\n return {\n path: destPath,\n size: statResult.size,\n }\n }\n }\n\n // Perform download\n const result = await httpDownload(url, destPath, downloadOptions)\n\n return result\n } finally {\n // Always release lock\n await releaseLock(lockPath)\n }\n}\n"],
|
|
5
|
+
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,IAAA,eAAAC,EAAAH,GAWA,IAAAI,EAA2B,mBAE3BC,EAAqD,4BAErDC,EAA8B,qBAE9BC,EAA6B,0BAqC7B,SAASC,E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gBAAab,EAAKR,EAAUoB,CAAe,CAGlE,QAAE,CAEA,MAAMD,EAAYP,CAAQ,CAC5B,CACF",
|
|
6
6
|
"names": ["download_lock_exports", "__export", "downloadWithLock", "__toCommonJS", "import_node_fs", "import_promises", "import_node_path", "import_http_request", "getLockFilePath", "destPath", "locksDir", "sanitized", "dir", "isLockStale", "lockInfo", "staleTimeout", "acquireLock", "url", "options", "lockTimeout", "pollInterval", "lockPath", "lockDir", "startTime", "lockContent", "lockAge", "resolve", "e", "releaseLock", "downloadOptions", "statResult"]
|
|
7
7
|
}
|
package/dist/env/socket-cli.d.ts
CHANGED
|
@@ -6,12 +6,15 @@
|
|
|
6
6
|
export declare function getSocketCliAcceptRisks(): boolean;
|
|
7
7
|
/**
|
|
8
8
|
* Socket CLI API base URL (alternative name).
|
|
9
|
+
* Checks SOCKET_CLI_API_BASE_URL first, then falls back to legacy SOCKET_SECURITY_API_BASE_URL.
|
|
9
10
|
*
|
|
10
11
|
* @returns API base URL or undefined
|
|
11
12
|
*/
|
|
12
13
|
export declare function getSocketCliApiBaseUrl(): string | undefined;
|
|
13
14
|
/**
|
|
14
15
|
* Proxy URL for Socket CLI API requests (alternative name).
|
|
16
|
+
* Checks SOCKET_CLI_API_PROXY, SOCKET_SECURITY_API_PROXY, then standard proxy env vars.
|
|
17
|
+
* Follows the same precedence as v1.x: HTTPS_PROXY → https_proxy → HTTP_PROXY → http_proxy.
|
|
15
18
|
*
|
|
16
19
|
* @returns API proxy URL or undefined
|
|
17
20
|
*/
|
|
@@ -24,6 +27,8 @@ export declare function getSocketCliApiProxy(): string | undefined;
|
|
|
24
27
|
export declare function getSocketCliApiTimeout(): number;
|
|
25
28
|
/**
|
|
26
29
|
* Socket CLI API authentication token (alternative name).
|
|
30
|
+
* Checks SOCKET_CLI_API_TOKEN, SOCKET_CLI_API_KEY, SOCKET_SECURITY_API_TOKEN, SOCKET_SECURITY_API_KEY.
|
|
31
|
+
* Maintains full v1.x backward compatibility.
|
|
27
32
|
*
|
|
28
33
|
* @returns API token or undefined
|
|
29
34
|
*/
|
|
@@ -54,6 +59,7 @@ export declare function getSocketCliNoApiToken(): boolean;
|
|
|
54
59
|
export declare function getSocketCliOptimize(): boolean;
|
|
55
60
|
/**
|
|
56
61
|
* Socket CLI organization slug identifier (alternative name).
|
|
62
|
+
* Checks SOCKET_CLI_ORG_SLUG first, then falls back to SOCKET_ORG_SLUG.
|
|
57
63
|
*
|
|
58
64
|
* @returns Organization slug or undefined
|
|
59
65
|
*/
|
|
@@ -66,6 +72,7 @@ export declare function getSocketCliOrgSlug(): string | undefined;
|
|
|
66
72
|
export declare function getSocketCliViewAllRisks(): boolean;
|
|
67
73
|
/**
|
|
68
74
|
* Socket CLI GitHub authentication token.
|
|
75
|
+
* Checks SOCKET_CLI_GITHUB_TOKEN, SOCKET_SECURITY_GITHUB_PAT, then falls back to GITHUB_TOKEN.
|
|
69
76
|
*
|
|
70
77
|
* @returns GitHub token or undefined
|
|
71
78
|
*/
|
package/dist/env/socket-cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var r=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var E=(n,t)=>{for(var i in t)r(n,i,{get:t[i],enumerable:!0})},u=(n,t,i,C)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of T(t))!I.call(n,o)&&o!==i&&r(n,o,{get:()=>t[o],enumerable:!(C=S(t,o))||C.enumerable});return n};var O=n=>u(r({},"__esModule",{value:!0}),n);var s={};E(s,{getSocketCliAcceptRisks:()=>K,getSocketCliApiBaseUrl:()=>c,getSocketCliApiProxy:()=>p,getSocketCliApiTimeout:()=>A,getSocketCliApiToken:()=>g,getSocketCliConfig:()=>f,getSocketCliFix:()=>l,getSocketCliGithubToken:()=>x,getSocketCliNoApiToken:()=>P,getSocketCliOptimize:()=>L,getSocketCliOrgSlug:()=>k,getSocketCliViewAllRisks:()=>R});module.exports=O(s);var _=require("#env/helpers"),e=require("#env/rewire");function K(){return(0,_.envAsBoolean)((0,e.getEnvValue)("SOCKET_CLI_ACCEPT_RISKS"))}function c(){return(0,e.getEnvValue)("SOCKET_CLI_API_BASE_URL")||(0,e.getEnvValue)("SOCKET_SECURITY_API_BASE_URL")}function p(){return(0,e.getEnvValue)("SOCKET_CLI_API_PROXY")||(0,e.getEnvValue)("SOCKET_SECURITY_API_PROXY")||(0,e.getEnvValue)("HTTPS_PROXY")||(0,e.getEnvValue)("https_proxy")||(0,e.getEnvValue)("HTTP_PROXY")||(0,e.getEnvValue)("http_proxy")}function A(){return(0,_.envAsNumber)((0,e.getEnvValue)("SOCKET_CLI_API_TIMEOUT"))}function g(){return(0,e.getEnvValue)("SOCKET_CLI_API_TOKEN")||(0,e.getEnvValue)("SOCKET_CLI_API_KEY")||(0,e.getEnvValue)("SOCKET_SECURITY_API_TOKEN")||(0,e.getEnvValue)("SOCKET_SECURITY_API_KEY")}function f(){return(0,e.getEnvValue)("SOCKET_CLI_CONFIG")}function l(){return(0,e.getEnvValue)("SOCKET_CLI_FIX")}function P(){return(0,_.envAsBoolean)((0,e.getEnvValue)("SOCKET_CLI_NO_API_TOKEN"))}function L(){return(0,_.envAsBoolean)((0,e.getEnvValue)("SOCKET_CLI_OPTIMIZE"))}function k(){return(0,e.getEnvValue)("SOCKET_CLI_ORG_SLUG")||(0,e.getEnvValue)("SOCKET_ORG_SLUG")}function R(){return(0,_.envAsBoolean)((0,e.getEnvValue)("SOCKET_CLI_VIEW_ALL_RISKS"))}function x(){return(0,e.getEnvValue)("SOCKET_CLI_GITHUB_TOKEN")||(0,e.getEnvValue)("SOCKET_SECURITY_GITHUB_PAT")||(0,e.getEnvValue)("GITHUB_TOKEN")}0&&(module.exports={getSocketCliAcceptRisks,getSocketCliApiBaseUrl,getSocketCliApiProxy,getSocketCliApiTimeout,getSocketCliApiToken,getSocketCliConfig,getSocketCliFix,getSocketCliGithubToken,getSocketCliNoApiToken,getSocketCliOptimize,getSocketCliOrgSlug,getSocketCliViewAllRisks});
|
|
3
3
|
//# sourceMappingURL=socket-cli.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/env/socket-cli.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Socket CLI environment variables.\n * Provides typed getters for SOCKET_CLI_* environment variables (excluding shadow).\n */\n\nimport { envAsBoolean, envAsNumber } from '#env/helpers'\nimport { getEnvValue } from '#env/rewire'\n\n/**\n * Whether to accept all Socket CLI risks (alternative name).\n *\n * @returns Whether to accept all risks\n */\nexport function getSocketCliAcceptRisks(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_ACCEPT_RISKS'))\n}\n\n/**\n * Socket CLI API base URL (alternative name).\n *\n * @returns API base URL or undefined\n */\nexport function getSocketCliApiBaseUrl(): string | undefined {\n return getEnvValue('SOCKET_CLI_API_BASE_URL')\n}\n\n/**\n * Proxy URL for Socket CLI API requests (alternative name).\n *\n * @returns API proxy URL or undefined\n */\nexport function getSocketCliApiProxy(): string | undefined {\n return getEnvValue('SOCKET_CLI_API_PROXY')\n}\n\n/**\n * Timeout in milliseconds for Socket CLI API requests (alternative name).\n *\n * @returns API timeout in milliseconds\n */\nexport function getSocketCliApiTimeout(): number {\n return envAsNumber(getEnvValue('SOCKET_CLI_API_TIMEOUT'))\n}\n\n/**\n * Socket CLI API authentication token (alternative name).\n *\n * @returns API token or undefined\n */\nexport function getSocketCliApiToken(): string | undefined {\n return getEnvValue('SOCKET_CLI_API_TOKEN')\n}\n\n/**\n * Socket CLI configuration file path (alternative name).\n *\n * @returns Config file path or undefined\n */\nexport function getSocketCliConfig(): string | undefined {\n return getEnvValue('SOCKET_CLI_CONFIG')\n}\n\n/**\n * Controls Socket CLI fix mode.\n *\n * @returns Fix mode value or undefined\n */\nexport function getSocketCliFix(): string | undefined {\n return getEnvValue('SOCKET_CLI_FIX')\n}\n\n/**\n * Whether to skip Socket CLI API token requirement (alternative name).\n *\n * @returns Whether to skip API token requirement\n */\nexport function getSocketCliNoApiToken(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_NO_API_TOKEN'))\n}\n\n/**\n * Controls Socket CLI optimization mode.\n *\n * @returns Whether optimization mode is enabled\n */\nexport function getSocketCliOptimize(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_OPTIMIZE'))\n}\n\n/**\n * Socket CLI organization slug identifier (alternative name).\n *\n * @returns Organization slug or undefined\n */\nexport function getSocketCliOrgSlug(): string | undefined {\n return getEnvValue('SOCKET_CLI_ORG_SLUG')\n}\n\n/**\n * Whether to view all Socket CLI risks (alternative name).\n *\n * @returns Whether to view all risks\n */\nexport function getSocketCliViewAllRisks(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_VIEW_ALL_RISKS'))\n}\n\n/**\n * Socket CLI GitHub authentication token.\n *\n * @returns GitHub token or undefined\n */\nexport function getSocketCliGithubToken(): string | undefined {\n return getEnvValue('SOCKET_CLI_GITHUB_TOKEN')\n}\n"],
|
|
5
|
-
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,2BAAAC,EAAA,yBAAAC,EAAA,2BAAAC,EAAA,yBAAAC,EAAA,uBAAAC,EAAA,oBAAAC,EAAA,4BAAAC,EAAA,2BAAAC,EAAA,yBAAAC,EAAA,wBAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAd,GAKA,IAAAe,EAA0C,wBAC1CC,EAA4B,uBAOrB,SAASd,GAAmC,CACjD,SAAO,mBAAa,eAAY,yBAAyB,CAAC,CAC5D,
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Socket CLI environment variables.\n * Provides typed getters for SOCKET_CLI_* environment variables (excluding shadow).\n */\n\nimport { envAsBoolean, envAsNumber } from '#env/helpers'\nimport { getEnvValue } from '#env/rewire'\n\n/**\n * Whether to accept all Socket CLI risks (alternative name).\n *\n * @returns Whether to accept all risks\n */\nexport function getSocketCliAcceptRisks(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_ACCEPT_RISKS'))\n}\n\n/**\n * Socket CLI API base URL (alternative name).\n * Checks SOCKET_CLI_API_BASE_URL first, then falls back to legacy SOCKET_SECURITY_API_BASE_URL.\n *\n * @returns API base URL or undefined\n */\nexport function getSocketCliApiBaseUrl(): string | undefined {\n return (\n getEnvValue('SOCKET_CLI_API_BASE_URL') ||\n getEnvValue('SOCKET_SECURITY_API_BASE_URL')\n )\n}\n\n/**\n * Proxy URL for Socket CLI API requests (alternative name).\n * Checks SOCKET_CLI_API_PROXY, SOCKET_SECURITY_API_PROXY, then standard proxy env vars.\n * Follows the same precedence as v1.x: HTTPS_PROXY \u2192 https_proxy \u2192 HTTP_PROXY \u2192 http_proxy.\n *\n * @returns API proxy URL or undefined\n */\nexport function getSocketCliApiProxy(): string | undefined {\n return (\n getEnvValue('SOCKET_CLI_API_PROXY') ||\n getEnvValue('SOCKET_SECURITY_API_PROXY') ||\n getEnvValue('HTTPS_PROXY') ||\n getEnvValue('https_proxy') ||\n getEnvValue('HTTP_PROXY') ||\n getEnvValue('http_proxy')\n )\n}\n\n/**\n * Timeout in milliseconds for Socket CLI API requests (alternative name).\n *\n * @returns API timeout in milliseconds\n */\nexport function getSocketCliApiTimeout(): number {\n return envAsNumber(getEnvValue('SOCKET_CLI_API_TIMEOUT'))\n}\n\n/**\n * Socket CLI API authentication token (alternative name).\n * Checks SOCKET_CLI_API_TOKEN, SOCKET_CLI_API_KEY, SOCKET_SECURITY_API_TOKEN, SOCKET_SECURITY_API_KEY.\n * Maintains full v1.x backward compatibility.\n *\n * @returns API token or undefined\n */\nexport function getSocketCliApiToken(): string | undefined {\n return (\n getEnvValue('SOCKET_CLI_API_TOKEN') ||\n getEnvValue('SOCKET_CLI_API_KEY') ||\n getEnvValue('SOCKET_SECURITY_API_TOKEN') ||\n getEnvValue('SOCKET_SECURITY_API_KEY')\n )\n}\n\n/**\n * Socket CLI configuration file path (alternative name).\n *\n * @returns Config file path or undefined\n */\nexport function getSocketCliConfig(): string | undefined {\n return getEnvValue('SOCKET_CLI_CONFIG')\n}\n\n/**\n * Controls Socket CLI fix mode.\n *\n * @returns Fix mode value or undefined\n */\nexport function getSocketCliFix(): string | undefined {\n return getEnvValue('SOCKET_CLI_FIX')\n}\n\n/**\n * Whether to skip Socket CLI API token requirement (alternative name).\n *\n * @returns Whether to skip API token requirement\n */\nexport function getSocketCliNoApiToken(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_NO_API_TOKEN'))\n}\n\n/**\n * Controls Socket CLI optimization mode.\n *\n * @returns Whether optimization mode is enabled\n */\nexport function getSocketCliOptimize(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_OPTIMIZE'))\n}\n\n/**\n * Socket CLI organization slug identifier (alternative name).\n * Checks SOCKET_CLI_ORG_SLUG first, then falls back to SOCKET_ORG_SLUG.\n *\n * @returns Organization slug or undefined\n */\nexport function getSocketCliOrgSlug(): string | undefined {\n return getEnvValue('SOCKET_CLI_ORG_SLUG') || getEnvValue('SOCKET_ORG_SLUG')\n}\n\n/**\n * Whether to view all Socket CLI risks (alternative name).\n *\n * @returns Whether to view all risks\n */\nexport function getSocketCliViewAllRisks(): boolean {\n return envAsBoolean(getEnvValue('SOCKET_CLI_VIEW_ALL_RISKS'))\n}\n\n/**\n * Socket CLI GitHub authentication token.\n * Checks SOCKET_CLI_GITHUB_TOKEN, SOCKET_SECURITY_GITHUB_PAT, then falls back to GITHUB_TOKEN.\n *\n * @returns GitHub token or undefined\n */\nexport function getSocketCliGithubToken(): string | undefined {\n return (\n getEnvValue('SOCKET_CLI_GITHUB_TOKEN') ||\n getEnvValue('SOCKET_SECURITY_GITHUB_PAT') ||\n getEnvValue('GITHUB_TOKEN')\n )\n}\n"],
|
|
5
|
+
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EA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BaseUrl", "getSocketCliApiProxy", "getSocketCliApiTimeout", "getSocketCliApiToken", "getSocketCliConfig", "getSocketCliFix", "getSocketCliGithubToken", "getSocketCliNoApiToken", "getSocketCliOptimize", "getSocketCliOrgSlug", "getSocketCliViewAllRisks", "__toCommonJS", "import_helpers", "import_rewire"]
|
|
7
7
|
}
|
package/dist/fs.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Provides enhanced fs operations, glob matching, and directory traversal functions.
|
|
4
4
|
*/
|
|
5
5
|
import type { Abortable } from 'node:events';
|
|
6
|
-
import type { ObjectEncodingOptions, OpenMode, PathLike } from 'node:fs';
|
|
6
|
+
import type { MakeDirectoryOptions, ObjectEncodingOptions, OpenMode, PathLike } from 'node:fs';
|
|
7
7
|
import type { JsonReviver } from './json';
|
|
8
8
|
import { type Remap } from './objects';
|
|
9
9
|
/**
|
|
@@ -463,7 +463,7 @@ export declare function readDirNamesSync(dirname: PathLike, options?: ReadDirOpt
|
|
|
463
463
|
* ```
|
|
464
464
|
*/
|
|
465
465
|
/*@__NO_SIDE_EFFECTS__*/
|
|
466
|
-
export declare function readFileBinary(filepath: PathLike, options?: ReadFileOptions | undefined): Promise<
|
|
466
|
+
export declare function readFileBinary(filepath: PathLike, options?: ReadFileOptions | undefined): Promise<NonSharedBuffer>;
|
|
467
467
|
/**
|
|
468
468
|
* Read a file as UTF-8 text asynchronously.
|
|
469
469
|
* Returns a string with the file contents decoded as UTF-8.
|
|
@@ -644,6 +644,61 @@ export declare function safeDelete(filepath: PathLike | PathLike[], options?: Re
|
|
|
644
644
|
*/
|
|
645
645
|
/*@__NO_SIDE_EFFECTS__*/
|
|
646
646
|
export declare function safeDeleteSync(filepath: PathLike | PathLike[], options?: RemoveOptions | undefined): void;
|
|
647
|
+
/**
|
|
648
|
+
* Safely create a directory asynchronously, ignoring EEXIST errors.
|
|
649
|
+
* This function wraps fs.promises.mkdir and handles the race condition where
|
|
650
|
+
* the directory might already exist, which is common in concurrent code.
|
|
651
|
+
*
|
|
652
|
+
* Unlike fs.promises.mkdir with recursive:true, this function:
|
|
653
|
+
* - Silently ignores EEXIST errors (directory already exists)
|
|
654
|
+
* - Re-throws all other errors (permissions, invalid path, etc.)
|
|
655
|
+
* - Works reliably in multi-process/concurrent scenarios
|
|
656
|
+
*
|
|
657
|
+
* @param path - Directory path to create
|
|
658
|
+
* @param options - Options including recursive and mode settings
|
|
659
|
+
* @returns Promise that resolves when directory is created or already exists
|
|
660
|
+
*
|
|
661
|
+
* @example
|
|
662
|
+
* ```ts
|
|
663
|
+
* // Create a directory, no error if it exists
|
|
664
|
+
* await safeMkdir('./config')
|
|
665
|
+
*
|
|
666
|
+
* // Create nested directories
|
|
667
|
+
* await safeMkdir('./data/cache/temp', { recursive: true })
|
|
668
|
+
*
|
|
669
|
+
* // Create with specific permissions
|
|
670
|
+
* await safeMkdir('./secure', { mode: 0o700 })
|
|
671
|
+
* ```
|
|
672
|
+
*/
|
|
673
|
+
/*@__NO_SIDE_EFFECTS__*/
|
|
674
|
+
export declare function safeMkdir(path: PathLike, options?: MakeDirectoryOptions | undefined): Promise<void>;
|
|
675
|
+
/**
|
|
676
|
+
* Safely create a directory synchronously, ignoring EEXIST errors.
|
|
677
|
+
* This function wraps fs.mkdirSync and handles the race condition where
|
|
678
|
+
* the directory might already exist, which is common in concurrent code.
|
|
679
|
+
*
|
|
680
|
+
* Unlike fs.mkdirSync with recursive:true, this function:
|
|
681
|
+
* - Silently ignores EEXIST errors (directory already exists)
|
|
682
|
+
* - Re-throws all other errors (permissions, invalid path, etc.)
|
|
683
|
+
* - Works reliably in multi-process/concurrent scenarios
|
|
684
|
+
*
|
|
685
|
+
* @param path - Directory path to create
|
|
686
|
+
* @param options - Options including recursive and mode settings
|
|
687
|
+
*
|
|
688
|
+
* @example
|
|
689
|
+
* ```ts
|
|
690
|
+
* // Create a directory, no error if it exists
|
|
691
|
+
* safeMkdirSync('./config')
|
|
692
|
+
*
|
|
693
|
+
* // Create nested directories
|
|
694
|
+
* safeMkdirSync('./data/cache/temp', { recursive: true })
|
|
695
|
+
*
|
|
696
|
+
* // Create with specific permissions
|
|
697
|
+
* safeMkdirSync('./secure', { mode: 0o700 })
|
|
698
|
+
* ```
|
|
699
|
+
*/
|
|
700
|
+
/*@__NO_SIDE_EFFECTS__*/
|
|
701
|
+
export declare function safeMkdirSync(path: PathLike, options?: MakeDirectoryOptions | undefined): void;
|
|
647
702
|
/**
|
|
648
703
|
* Safely read a file asynchronously, returning undefined on error.
|
|
649
704
|
* Useful when you want to attempt reading a file without handling errors explicitly.
|
|
@@ -666,7 +721,30 @@ export declare function safeDeleteSync(filepath: PathLike | PathLike[], options?
|
|
|
666
721
|
* ```
|
|
667
722
|
*/
|
|
668
723
|
/*@__NO_SIDE_EFFECTS__*/
|
|
669
|
-
export declare function safeReadFile(filepath: PathLike, options?: SafeReadOptions | undefined): Promise<
|
|
724
|
+
export declare function safeReadFile(filepath: PathLike, options?: SafeReadOptions | undefined): Promise<NonSharedBuffer>;
|
|
725
|
+
/**
|
|
726
|
+
* Safely read a file synchronously, returning undefined on error.
|
|
727
|
+
* Useful when you want to attempt reading a file without handling errors explicitly.
|
|
728
|
+
* Returns undefined for any error (file not found, permission denied, etc.).
|
|
729
|
+
*
|
|
730
|
+
* @param filepath - Path to file
|
|
731
|
+
* @param options - Read options including encoding and default value
|
|
732
|
+
* @returns File contents, or undefined on error
|
|
733
|
+
*
|
|
734
|
+
* @example
|
|
735
|
+
* ```ts
|
|
736
|
+
* // Try to read a config file
|
|
737
|
+
* const config = safeReadFileSync('./config.txt')
|
|
738
|
+
* if (config) {
|
|
739
|
+
* console.log('Config loaded successfully')
|
|
740
|
+
* }
|
|
741
|
+
*
|
|
742
|
+
* // Read binary file safely
|
|
743
|
+
* const buffer = safeReadFileSync('./image.png', { encoding: null })
|
|
744
|
+
* ```
|
|
745
|
+
*/
|
|
746
|
+
/*@__NO_SIDE_EFFECTS__*/
|
|
747
|
+
export declare function safeReadFileSync(filepath: PathLike, options?: SafeReadOptions | undefined): string | NonSharedBuffer;
|
|
670
748
|
/**
|
|
671
749
|
* Safely get file stats asynchronously, returning undefined on error.
|
|
672
750
|
* Useful for checking file existence and properties without error handling.
|
|
@@ -708,29 +786,6 @@ export declare function safeStats(filepath: PathLike): Promise<import("fs").Stat
|
|
|
708
786
|
*/
|
|
709
787
|
/*@__NO_SIDE_EFFECTS__*/
|
|
710
788
|
export declare function safeStatsSync(filepath: PathLike, options?: ReadFileOptions | undefined): import("fs").BigIntStats | import("fs").Stats;
|
|
711
|
-
/**
|
|
712
|
-
* Safely read a file synchronously, returning undefined on error.
|
|
713
|
-
* Useful when you want to attempt reading a file without handling errors explicitly.
|
|
714
|
-
* Returns undefined for any error (file not found, permission denied, etc.).
|
|
715
|
-
*
|
|
716
|
-
* @param filepath - Path to file
|
|
717
|
-
* @param options - Read options including encoding and default value
|
|
718
|
-
* @returns File contents, or undefined on error
|
|
719
|
-
*
|
|
720
|
-
* @example
|
|
721
|
-
* ```ts
|
|
722
|
-
* // Try to read a config file
|
|
723
|
-
* const config = safeReadFileSync('./config.txt')
|
|
724
|
-
* if (config) {
|
|
725
|
-
* console.log('Config loaded successfully')
|
|
726
|
-
* }
|
|
727
|
-
*
|
|
728
|
-
* // Read binary file safely
|
|
729
|
-
* const buffer = safeReadFileSync('./image.png', { encoding: null })
|
|
730
|
-
* ```
|
|
731
|
-
*/
|
|
732
|
-
/*@__NO_SIDE_EFFECTS__*/
|
|
733
|
-
export declare function safeReadFileSync(filepath: PathLike, options?: SafeReadOptions | undefined): string | NonSharedBuffer;
|
|
734
789
|
/**
|
|
735
790
|
* Generate a unique filepath by adding number suffix if the path exists.
|
|
736
791
|
* Appends `-1`, `-2`, etc. before the file extension until a non-existent path is found.
|
package/dist/fs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var F=Object.defineProperty;var
|
|
3
|
-
Ensure the file exists or create it with the expected structure.`,{cause:d}):
|
|
4
|
-
Check file permissions or run with appropriate access.`,{cause:d}):d}return}return(0,b.jsonParse)(r,{filepath:String(n),reviver:i,throws:c})}function re(n,e){const t=typeof e=="string"?{encoding:e}:e,{reviver:i,throws:o,...s}={__proto__:null,...t},c=o===void 0||!!o,a=
|
|
5
|
-
Ensure the file exists or create it with the expected structure.`,{cause:d}):
|
|
6
|
-
Check file permissions or run with appropriate access.`,{cause:d}):d}return}return(0,b.jsonParse)(r,{filepath:String(n),reviver:i,throws:c})}let O;function N(){if(O===void 0){const n=
|
|
7
|
-
`,s!==void 0?s:!0,c,a);await d.promises.writeFile(n,
|
|
8
|
-
`,s!==void 0?s:!0,c,a);d.writeFileSync(n,
|
|
2
|
+
var F=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var $=(n,e)=>{for(var t in e)F(n,t,{get:e[t],enumerable:!0})},B=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of W(e))!M.call(n,o)&&o!==t&&F(n,o,{get:()=>e[o],enumerable:!(i=T(e,o))||i.enumerable});return n};var q=n=>B(F({},"__esModule",{value:!0}),n);var ye={};$(ye,{findUp:()=>V,findUpSync:()=>G,invalidatePathCache:()=>I,isDir:()=>z,isDirEmptySync:()=>j,isDirSync:()=>X,isSymLinkSync:()=>K,readDirNames:()=>Q,readDirNamesSync:()=>Y,readFileBinary:()=>Z,readFileBinarySync:()=>ne,readFileUtf8:()=>ee,readFileUtf8Sync:()=>te,readJson:()=>ie,readJsonSync:()=>re,safeDelete:()=>oe,safeDeleteSync:()=>se,safeMkdir:()=>ae,safeMkdirSync:()=>ce,safeReadFile:()=>de,safeReadFileSync:()=>fe,safeStats:()=>U,safeStatsSync:()=>C,uniqueSync:()=>le,validateFiles:()=>H,writeJson:()=>ue,writeJsonSync:()=>pe});module.exports=q(ye);var v=require("#constants/process"),_=require("./arrays"),S=require("./globs"),b=require("./json"),D=require("./objects"),p=require("./path"),E=require("./paths/rewire"),R=require("./sorts");const w=(0,v.getAbortSignal)(),L=(0,D.objectFreeze)({__proto__:null,force:!0,maxRetries:3,recursive:!0,retryDelay:200});let P;function f(){return P===void 0&&(P=require("node:fs")),P}let k;function m(){return k===void 0&&(k=require("node:path")),k}function J(n,e,t){const{ignore:i,includeEmpty:o=!0,sort:s=!0}={__proto__:null,...t},c=m(),a=n.filter(r=>r.isDirectory()&&(o||!j(c.join(e||r.parentPath,r.name),{ignore:i}))).map(r=>r.name);return s?a.sort(R.naturalCompare):a}function A(n,e,t,i,o=2){const s=t?e:"";return`${JSON.stringify(n,i,o).replace(/\n/g,e)}${s}`}async function V(n,e){const{cwd:t=process.cwd(),signal:i=w}={__proto__:null,...e};let{onlyDirectories:o=!1,onlyFiles:s=!0}={__proto__:null,...e};o&&(s=!1),s&&(o=!1);const c=f(),a=m();let r=a.resolve(t);const{root:d}=a.parse(r),l=(0,_.isArray)(n)?n:[n];for(;r&&r!==d;){for(const g of l){if(i?.aborted)return;const u=a.join(r,g);try{const y=await c.promises.stat(u);if(!o&&y.isFile())return(0,p.normalizePath)(u);if(!s&&y.isDirectory())return(0,p.normalizePath)(u)}catch{}}r=a.dirname(r)}}function G(n,e){const{cwd:t=process.cwd(),stopAt:i}={__proto__:null,...e};let{onlyDirectories:o=!1,onlyFiles:s=!0}={__proto__:null,...e};o&&(s=!1),s&&(o=!1);const c=f(),a=m();let r=a.resolve(t);const{root:d}=a.parse(r),l=i?a.resolve(i):void 0,g=(0,_.isArray)(n)?n:[n];for(;r&&r!==d;){if(l&&r===l){for(const u of g){const y=a.join(r,u);try{const h=c.statSync(y);if(!o&&h.isFile())return(0,p.normalizePath)(y);if(!s&&h.isDirectory())return(0,p.normalizePath)(y)}catch{}}return}for(const u of g){const y=a.join(r,u);try{const h=c.statSync(y);if(!o&&h.isFile())return(0,p.normalizePath)(y);if(!s&&h.isDirectory())return(0,p.normalizePath)(y)}catch{}}r=a.dirname(r)}}async function z(n){return!!(await U(n))?.isDirectory()}function X(n){return!!C(n)?.isDirectory()}function j(n,e){const{ignore:t=S.defaultIgnore}={__proto__:null,...e},i=f();try{const o=i.readdirSync(n),{length:s}=o;if(s===0)return!0;const c=(0,S.getGlobMatcher)(t,{cwd:(0,p.pathLikeToString)(n)});let a=0;for(let r=0;r<s;r+=1){const d=o[r];d&&c(d)&&(a+=1)}return a===s}catch{return!1}}function K(n){const e=f();try{return e.lstatSync(n).isSymbolicLink()}catch{}return!1}function H(n){const e=f(),t=[],i=[],{R_OK:o}=e.constants;for(const s of n)try{e.accessSync(s,o),t.push(s)}catch{i.push(s)}return{__proto__:null,validPaths:t,invalidPaths:i}}async function Q(n,e){const t=f();try{return J(await t.promises.readdir(n,{__proto__:null,encoding:"utf8",withFileTypes:!0}),String(n),e)}catch{}return[]}function Y(n,e){const t=f();try{return J(t.readdirSync(n,{__proto__:null,encoding:"utf8",withFileTypes:!0}),String(n),e)}catch{}return[]}async function Z(n,e){const t=typeof e=="string"?{encoding:e}:e;return await f().promises.readFile(n,{signal:w,...t,encoding:null})}async function ee(n,e){const t=typeof e=="string"?{encoding:e}:e;return await f().promises.readFile(n,{signal:w,...t,encoding:"utf8"})}function ne(n,e){const t=typeof e=="string"?{encoding:e}:e;return f().readFileSync(n,{...t,encoding:null})}function te(n,e){const t=typeof e=="string"?{encoding:e}:e;return f().readFileSync(n,{...t,encoding:"utf8"})}async function ie(n,e){const t=typeof e=="string"?{encoding:e}:e,{reviver:i,throws:o,...s}={__proto__:null,...t},c=o===void 0||!!o,a=f();let r="";try{r=await a.promises.readFile(n,{__proto__:null,encoding:"utf8",...s})}catch(d){if(c){const l=d.code;throw l==="ENOENT"?new Error(`JSON file not found: ${n}
|
|
3
|
+
Ensure the file exists or create it with the expected structure.`,{cause:d}):l==="EACCES"||l==="EPERM"?new Error(`Permission denied reading JSON file: ${n}
|
|
4
|
+
Check file permissions or run with appropriate access.`,{cause:d}):d}return}return(0,b.jsonParse)(r,{filepath:String(n),reviver:i,throws:c})}function re(n,e){const t=typeof e=="string"?{encoding:e}:e,{reviver:i,throws:o,...s}={__proto__:null,...t},c=o===void 0||!!o,a=f();let r="";try{r=a.readFileSync(n,{__proto__:null,encoding:"utf8",...s})}catch(d){if(c){const l=d.code;throw l==="ENOENT"?new Error(`JSON file not found: ${n}
|
|
5
|
+
Ensure the file exists or create it with the expected structure.`,{cause:d}):l==="EACCES"||l==="EPERM"?new Error(`Permission denied reading JSON file: ${n}
|
|
6
|
+
Check file permissions or run with appropriate access.`,{cause:d}):d}return}return(0,b.jsonParse)(r,{filepath:String(n),reviver:i,throws:c})}let O;function N(){if(O===void 0){const n=m(),{getOsTmpDir:e,getSocketCacacheDir:t,getSocketUserDir:i}=require("#lib/paths");O=[n.resolve(e()),n.resolve(t()),n.resolve(i())]}return O}function I(){O=void 0}(0,E.registerCacheInvalidation)(I);async function oe(n,e){const t=require("./external/del"),{deleteAsync:i}=t,o={__proto__:null,...e},s=(0,_.isArray)(n)?n.map(p.pathLikeToString):[(0,p.pathLikeToString)(n)];let c=o.force!==!1;if(!c&&s.length>0){const a=m(),r=N();s.every(l=>{const g=a.resolve(l);for(const u of r){const y=g.startsWith(u+a.sep)||g===u,x=a.relative(u,g).startsWith("..");if(y&&!x)return!0}return!1})&&(c=!0)}await i(s,{concurrency:o.maxRetries||L.maxRetries,dryRun:!1,force:c,onlyFiles:!1})}function se(n,e){const t=require("./external/del"),{deleteSync:i}=t,o={__proto__:null,...e},s=(0,_.isArray)(n)?n.map(p.pathLikeToString):[(0,p.pathLikeToString)(n)];let c=o.force!==!1;if(!c&&s.length>0){const a=m(),r=N();s.every(l=>{const g=a.resolve(l);for(const u of r){const y=g.startsWith(u+a.sep)||g===u,x=a.relative(u,g).startsWith("..");if(y&&!x)return!0}return!1})&&(c=!0)}i(s,{concurrency:o.maxRetries||L.maxRetries,dryRun:!1,force:c,onlyFiles:!1})}async function ae(n,e){const t=f();try{await t.promises.mkdir(n,e)}catch(i){if(typeof i=="object"&&i!==null&&"code"in i&&i.code!=="EEXIST")throw i}}function ce(n,e){const t=f();try{t.mkdirSync(n,e)}catch(i){if(typeof i=="object"&&i!==null&&"code"in i&&i.code!=="EEXIST")throw i}}async function de(n,e){const t=typeof e=="string"?{encoding:e}:e,i=f();try{return await i.promises.readFile(n,{signal:w,...t})}catch{}}function fe(n,e){const t=typeof e=="string"?{encoding:e}:e,i=f();try{return i.readFileSync(n,{__proto__:null,...t})}catch{}}async function U(n){const e=f();try{return await e.promises.stat(n)}catch{}}function C(n,e){const t=typeof e=="string"?{encoding:e}:e,i=f();try{return i.statSync(n,{__proto__:null,throwIfNoEntry:!1,...t})}catch{}}function le(n){const e=f(),t=m(),i=String(n);if(!e.existsSync(i))return(0,p.normalizePath)(i);const o=t.dirname(i),s=t.extname(i),c=t.basename(i,s);let a=1,r;do r=t.join(o,`${c}-${a}${s}`),a++;while(e.existsSync(r));return(0,p.normalizePath)(r)}async function ue(n,e,t){const i=typeof t=="string"?{encoding:t}:t,{EOL:o,finalEOL:s,replacer:c,spaces:a,...r}={__proto__:null,...i},d=f(),l=A(e,o||`
|
|
7
|
+
`,s!==void 0?s:!0,c,a);await d.promises.writeFile(n,l,{encoding:"utf8",...r,__proto__:null})}function pe(n,e,t){const i=typeof t=="string"?{encoding:t}:t,{EOL:o,finalEOL:s,replacer:c,spaces:a,...r}={__proto__:null,...i},d=f(),l=A(e,o||`
|
|
8
|
+
`,s!==void 0?s:!0,c,a);d.writeFileSync(n,l,{encoding:"utf8",...r,__proto__:null})}0&&(module.exports={findUp,findUpSync,invalidatePathCache,isDir,isDirEmptySync,isDirSync,isSymLinkSync,readDirNames,readDirNamesSync,readFileBinary,readFileBinarySync,readFileUtf8,readFileUtf8Sync,readJson,readJsonSync,safeDelete,safeDeleteSync,safeMkdir,safeMkdirSync,safeReadFile,safeReadFileSync,safeStats,safeStatsSync,uniqueSync,validateFiles,writeJson,writeJsonSync});
|
|
9
9
|
//# sourceMappingURL=fs.js.map
|