-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemporary-executor.ts
More file actions
64 lines (56 loc) · 1.92 KB
/
temporary-executor.ts
File metadata and controls
64 lines (56 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @fileoverview Temporary package executor detection utilities for Socket ecosystem.
* Identifies and handles temporary execution contexts such as npx, pnpm dlx, and yarn dlx.
*/
import process from 'node:process'
import { WIN32 } from './constants/platform'
import { normalizePath } from './paths/normalize'
/**
* Detects if the current process is running in a temporary package execution context
* such as npm exec, npx, pnpm dlx, or yarn dlx.
*
* When package managers run commands via exec/npx/dlx, they execute in temporary directories
* that are cleaned up after execution. Creating persistent shadows or modifying PATH
* in these contexts can break subsequent package manager commands.
*
* @example
* ```typescript
* if (isRunningInTemporaryExecutor()) {
* console.log('Running in a temporary executor context')
* }
* ```
*/
export function isRunningInTemporaryExecutor(cwd = process.cwd()): boolean {
// Check environment variable for exec/npx/dlx indicators.
const userAgent = process.env['npm_config_user_agent']
if (
userAgent?.includes('exec') ||
userAgent?.includes('npx') ||
userAgent?.includes('dlx')
) {
return true
}
// Normalize the cwd path for consistent checking across platforms.
const normalizedCwd = normalizePath(cwd)
// Check if running from npm's npx cache.
const npmCache = process.env['npm_config_cache']
if (npmCache && normalizedCwd.includes(normalizePath(npmCache))) {
return true
}
// Check common temporary execution path patterns.
const tempPatterns = [
// npm's npx cache directory
'_npx',
// pnpm dlx temporary store
'.pnpm-store',
// Common dlx directory prefix
'dlx-',
// Yarn Berry PnP virtual packages.
'.yarn/$$',
]
// Yarn on Windows uses AppData/Local/Temp/xfs- pattern.
if (WIN32) {
tempPatterns.push('AppData/Local/Temp/xfs-')
}
return tempPatterns.some(pattern => normalizedCwd.includes(pattern))
}