@socketsecurity/lib 1.0.4 → 1.1.0
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 +25 -0
- package/dist/abort.js.map +2 -2
- package/dist/argv/parse.js.map +2 -2
- package/dist/arrays.d.ts +143 -0
- package/dist/arrays.js.map +2 -2
- package/dist/bin.js +1 -4
- package/dist/bin.js.map +2 -2
- package/dist/cacache.d.ts +0 -2
- package/dist/cacache.js +0 -1
- package/dist/cacache.js.map +2 -2
- package/dist/cache-with-ttl.js.map +2 -2
- package/dist/dlx.js.map +2 -2
- package/dist/external/@yarnpkg/extensions.d.ts +0 -1
- package/dist/external/cacache.d.ts +0 -7
- package/dist/external/debug.d.ts +0 -3
- package/dist/external/fast-sort.d.ts +0 -1
- package/dist/external/libnpmpack.d.ts +0 -1
- package/dist/external/make-fetch-happen.d.ts +0 -1
- package/dist/external/pacote.d.ts +0 -5
- package/dist/external/semver.d.ts +0 -1
- package/dist/external/validate-npm-package-name.js +1 -1
- package/dist/external/yargs-parser.d.ts +0 -1
- package/dist/external/yoctocolors-cjs.js +1 -1
- package/dist/external/zod.js +9 -9
- package/dist/fs.d.ts +595 -23
- package/dist/fs.js.map +2 -2
- package/dist/git.d.ts +488 -41
- package/dist/git.js.map +2 -2
- package/dist/github.d.ts +361 -12
- package/dist/github.js.map +2 -2
- package/dist/http-request.d.ts +463 -4
- package/dist/http-request.js.map +2 -2
- package/dist/json.d.ts +177 -4
- package/dist/json.js.map +2 -2
- package/dist/logger.d.ts +823 -70
- package/dist/logger.js +654 -51
- package/dist/logger.js.map +2 -2
- package/dist/objects.d.ts +386 -10
- package/dist/objects.js.map +2 -2
- package/dist/path.d.ts +270 -6
- package/dist/path.js.map +2 -2
- package/dist/promises.d.ts +432 -27
- package/dist/promises.js +3 -0
- package/dist/promises.js.map +2 -2
- package/dist/signal-exit.js.map +2 -2
- package/dist/sorts.js.map +2 -2
- package/dist/spawn.d.ts +242 -33
- package/dist/spawn.js.map +2 -2
- package/dist/spinner.d.ts +260 -20
- package/dist/spinner.js +201 -63
- package/dist/spinner.js.map +2 -2
- package/dist/stdio/clear.d.ts +130 -9
- package/dist/stdio/clear.js.map +2 -2
- package/dist/stdio/divider.d.ts +106 -10
- package/dist/stdio/divider.js +10 -0
- package/dist/stdio/divider.js.map +2 -2
- package/dist/stdio/footer.d.ts +70 -3
- package/dist/stdio/footer.js.map +2 -2
- package/dist/stdio/header.d.ts +93 -12
- package/dist/stdio/header.js.map +2 -2
- package/dist/stdio/mask.d.ts +82 -14
- package/dist/stdio/mask.js +25 -4
- package/dist/stdio/mask.js.map +2 -2
- package/dist/stdio/progress.d.ts +112 -15
- package/dist/stdio/progress.js +43 -3
- package/dist/stdio/progress.js.map +2 -2
- package/dist/stdio/prompts.d.ts +95 -5
- package/dist/stdio/prompts.js.map +2 -2
- package/dist/stdio/stderr.d.ts +114 -11
- package/dist/stdio/stderr.js.map +2 -2
- package/dist/stdio/stdout.d.ts +107 -11
- package/dist/stdio/stdout.js.map +2 -2
- package/dist/strings.d.ts +357 -28
- package/dist/strings.js.map +2 -2
- package/dist/suppress-warnings.js.map +2 -2
- package/dist/validation/json-parser.d.ts +226 -7
- package/dist/validation/json-parser.js.map +2 -2
- package/dist/validation/types.d.ts +114 -12
- package/dist/validation/types.js.map +1 -1
- package/package.json +5 -3
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,31 @@ 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
|
+
## [1.1.0] - 2025-10-23
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Added `filterOutput` option to `stdio/mask` for filtering output chunks before display/buffering
|
|
13
|
+
- Added `overrideExitCode` option to `stdio/mask` for customizing exit codes based on captured output
|
|
14
|
+
- Added comprehensive JSDoc documentation across entire library for enhanced VSCode IntelliSense
|
|
15
|
+
- Detailed @param, @returns, @template, @throws tags
|
|
16
|
+
- Practical @example blocks with real-world usage patterns
|
|
17
|
+
- @default tags showing default values
|
|
18
|
+
- Enhanced interface property documentation
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- Improved TypeScript type hints and tooltips throughout library
|
|
23
|
+
- Enhanced documentation for all core utilities (arrays, fs, git, github, http-request, json, logger, objects, path, promises, spawn, spinner, strings)
|
|
24
|
+
- Enhanced documentation for stdio utilities (clear, divider, footer, header, mask, progress, prompts, stderr, stdout)
|
|
25
|
+
- Enhanced documentation for validation utilities (json-parser, types)
|
|
26
|
+
|
|
27
|
+
## [1.0.5] - 2025-10-22
|
|
28
|
+
|
|
29
|
+
### Added
|
|
30
|
+
|
|
31
|
+
- Added support for custom retry delays from onRetry callback
|
|
32
|
+
|
|
8
33
|
## [1.0.4] - 2025-10-21
|
|
9
34
|
|
|
10
35
|
### Fixed
|
package/dist/abort.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/abort.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Abort signal utilities.\n */\n\n/**\n * Create a composite AbortSignal from multiple signals.\n */\nexport function createCompositeAbortSignal(\n ...signals: Array<AbortSignal | null | undefined>\n): AbortSignal {\n const validSignals = signals.filter(s => s != null) as AbortSignal[]\n\n if (validSignals.length === 0) {\n return new AbortController().signal\n }\n\n if (validSignals.length === 1) {\n
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,SAAS,8BACX,SACU;AACb,QAAM,eAAe,QAAQ,OAAO,OAAK,KAAK,IAAI;AAElD,MAAI,aAAa,WAAW,GAAG;AAC7B,WAAO,IAAI,gBAAgB,EAAE;AAAA,EAC/B;AAEA,MAAI,aAAa,WAAW,GAAG;
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Abort signal utilities.\n */\n\n/**\n * Create a composite AbortSignal from multiple signals.\n */\nexport function createCompositeAbortSignal(\n ...signals: Array<AbortSignal | null | undefined>\n): AbortSignal {\n const validSignals = signals.filter(s => s != null) as AbortSignal[]\n\n if (validSignals.length === 0) {\n return new AbortController().signal\n }\n\n if (validSignals.length === 1) {\n return validSignals[0]!\n }\n\n const controller = new AbortController()\n\n for (const signal of validSignals) {\n if (signal.aborted) {\n controller.abort()\n return controller.signal\n }\n signal.addEventListener('abort', () => controller.abort(), { once: true })\n }\n\n return controller.signal\n}\n\n/**\n * Create an AbortSignal that triggers after a timeout.\n */\nexport function createTimeoutSignal(ms: number): AbortSignal {\n if (typeof ms !== 'number' || Number.isNaN(ms)) {\n throw new TypeError('timeout must be a number')\n }\n if (!Number.isFinite(ms)) {\n throw new TypeError('timeout must be a finite number')\n }\n if (ms <= 0) {\n throw new TypeError('timeout must be a positive number')\n }\n const controller = new AbortController()\n setTimeout(() => controller.abort(), ms)\n return controller.signal\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,SAAS,8BACX,SACU;AACb,QAAM,eAAe,QAAQ,OAAO,OAAK,KAAK,IAAI;AAElD,MAAI,aAAa,WAAW,GAAG;AAC7B,WAAO,IAAI,gBAAgB,EAAE;AAAA,EAC/B;AAEA,MAAI,aAAa,WAAW,GAAG;AAC7B,WAAO,aAAa,CAAC;AAAA,EACvB;AAEA,QAAM,aAAa,IAAI,gBAAgB;AAEvC,aAAW,UAAU,cAAc;AACjC,QAAI,OAAO,SAAS;AAClB,iBAAW,MAAM;AACjB,aAAO,WAAW;AAAA,IACpB;AACA,WAAO,iBAAiB,SAAS,MAAM,WAAW,MAAM,GAAG,EAAE,MAAM,KAAK,CAAC;AAAA,EAC3E;AAEA,SAAO,WAAW;AACpB;AAKO,SAAS,oBAAoB,IAAyB;AAC3D,MAAI,OAAO,OAAO,YAAY,OAAO,MAAM,EAAE,GAAG;AAC9C,UAAM,IAAI,UAAU,0BAA0B;AAAA,EAChD;AACA,MAAI,CAAC,OAAO,SAAS,EAAE,GAAG;AACxB,UAAM,IAAI,UAAU,iCAAiC;AAAA,EACvD;AACA,MAAI,MAAM,GAAG;AACX,UAAM,IAAI,UAAU,mCAAmC;AAAA,EACzD;AACA,QAAM,aAAa,IAAI,gBAAgB;AACvC,aAAW,MAAM,WAAW,MAAM,GAAG,EAAE;AACvC,SAAO,WAAW;AACpB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/argv/parse.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/argv/parse.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Argument parsing utilities for CLI applications.\n * Uses yargs-parser internally for robust argument parsing with Node.js parseArgs-compatible API.\n */\n\nimport yargsParser from '../external/yargs-parser'\n\n/**\n * Yargs parser options interface.\n */\ninterface YargsOptions {\n // Array of option names that should be treated as booleans.\n boolean?: string[] | undefined\n // Array of option names that should be treated as strings.\n string?: string[] | undefined\n // Array of option names that should accept multiple values.\n array?: string[] | undefined\n // Map of short aliases to full option names.\n alias?: Record<string, string | string[]> | undefined\n // Default values for options.\n default?: Record<string, unknown> | undefined\n // Transform functions to coerce parsed values.\n coerce?: Record<string, (value: unknown) => unknown> | undefined\n // Whether to treat unknown options as positional arguments.\n 'unknown-options-as-args'?: boolean | undefined\n // Whether to parse numeric strings as numbers.\n 'parse-numbers'?: boolean | undefined\n // Whether to parse positional arguments as numbers.\n 'parse-positional-numbers'?: boolean | undefined\n // Whether to support --no-<option> negation for booleans.\n 'boolean-negation'?: boolean | undefined\n // Whether to stop parsing options after the first positional.\n 'halt-at-non-option'?: boolean | undefined\n // Advanced yargs-parser configuration options.\n configuration?: Record<string, boolean | string> | undefined\n // Whether to throw on unknown options.\n strict?: boolean | undefined\n}\n\n/**\n * Yargs parser result interface.\n */\ninterface YargsArguments extends Record<string, unknown> {\n _: string[]\n $0?: string\n}\n\n/**\n * Options for configuring argument parsing, similar to Node.js util.parseArgs.\n */\nexport interface ParseArgsOptionsConfig {\n // Whether the option accepts multiple values (array).\n multiple?: boolean | undefined\n // Short alias for the option (single character).\n short?: string | undefined\n // Type of the option value.\n type?: 'boolean' | 'string' | undefined\n // Default value for the option.\n default?: unknown | undefined\n // Transform function to coerce parsed values.\n coerce?: (value: unknown) => unknown | undefined\n}\n\n/**\n * Configuration object for parseArgs function, similar to Node.js util.parseArgs.\n */\nexport interface ParseArgsConfig {\n // Command-line arguments to parse (defaults to process.argv.slice(2)).\n args?: readonly string[] | undefined\n // Options configuration object.\n options?: Record<string, ParseArgsOptionsConfig> | undefined\n // Whether to throw on unknown options (default: true).\n strict?: boolean | undefined\n // Whether to populate tokens array (not implemented, for API compatibility).\n tokens?: boolean | undefined\n // Whether to allow positional arguments after options.\n allowPositionals?: boolean | undefined\n // Whether to allow negative numbers as option values.\n allowNegative?: boolean | undefined\n // Advanced yargs-parser configuration passthrough.\n configuration?: Record<string, boolean | string> | undefined\n}\n\n/**\n * Result of parsing command-line arguments.\n */\nexport interface ParsedArgs<T = Record<string, unknown>> {\n // Parsed option values.\n values: T\n // Positional arguments (non-option arguments).\n positionals: string[]\n // Raw parsed arguments object from yargs-parser.\n raw: YargsArguments\n}\n\n/**\n * Parse command-line arguments with a Node.js parseArgs-compatible API.\n * Uses yargs-parser internally for robust argument parsing.\n */\nexport function parseArgs<T = Record<string, unknown>>(\n config: ParseArgsConfig = {},\n): ParsedArgs<T> {\n const {\n allowNegative = false,\n allowPositionals = true,\n args = process.argv.slice(2),\n configuration,\n options = {},\n strict = true,\n } = config\n\n // Convert parseArgs options to yargs-parser options.\n const yargsOptions: YargsOptions = {\n // Arrays of option names to treat as specific types.\n boolean: [],\n string: [],\n array: [],\n // Maps for aliases, defaults, and transformations.\n alias: {},\n default: {},\n coerce: {},\n 'unknown-options-as-args': !strict,\n 'parse-numbers': false,\n 'parse-positional-numbers': false,\n 'boolean-negation': !allowNegative,\n 'halt-at-non-option': !allowPositionals,\n configuration: {\n // Enable kebab-case to camelCase conversion (e.g., --temp-dir \u2192 tempDir).\n 'camel-case-expansion': true,\n // Disable dot notation to avoid confusing nested property parsing.\n 'dot-notation': false,\n // Convert duplicate arguments into arrays automatically.\n 'duplicate-arguments-array': true,\n // Flatten nested arrays from duplicate arguments for cleaner output.\n 'flatten-duplicate-arrays': true,\n // Populate the '--' key with arguments after the -- separator.\n 'populate--': true,\n // Allow short option grouping like -abc for -a -b -c.\n 'short-option-groups': true,\n // Keep aliased keys in the result for flexibility.\n 'strip-aliased': false,\n // Keep both kebab-case and camelCase keys for flexibility.\n 'strip-dashed': false,\n ...configuration,\n },\n }\n\n // Process each option configuration.\n for (const { 0: key, 1: optionConfig } of Object.entries(options)) {\n const {\n coerce,\n default: defaultValue,\n multiple,\n short,\n type,\n } = optionConfig\n\n // Set the option type.\n if (type === 'boolean') {\n yargsOptions.boolean?.push(key)\n } else if (type === 'string') {\n yargsOptions.string?.push(key)\n }\n\n // Handle multiple values (arrays).\n if (multiple) {\n yargsOptions.array?.push(key)\n }\n\n // Set short alias.\n if (short) {\n ;(yargsOptions.alias as Record<string, string>)[short] = key\n }\n\n // Set default value.\n if (defaultValue !== undefined) {\n ;(yargsOptions.default as Record<string, unknown>)[key] = defaultValue\n }\n\n // Set coerce function.\n if (coerce) {\n ;(yargsOptions.coerce as Record<string, unknown>)[key] = coerce\n }\n }\n\n // Parse the arguments.\n const parsed = yargsParser(args as string[], yargsOptions)\n\n // Extract positional arguments.\n const positionals = parsed._ || []\n\n // Remove the positionals array from values to match Node.js parseArgs behavior.\n const { _, ...values } = parsed\n\n // Ensure positionals are strings.\n const stringPositionals = positionals.map(String)\n\n return {\n values: values as T,\n positionals: stringPositionals,\n raw: parsed as YargsArguments,\n }\n}\n\n/**\n * Parse command-line arguments with Socket defaults.\n * Provides sensible defaults for Socket CLI applications.\n */\nexport function parseArgsWithDefaults<T = Record<string, unknown>>(\n config: ParseArgsConfig = {},\n): ParsedArgs<T> {\n return parseArgs<T>({\n strict: false,\n allowPositionals: true,\n ...config,\n })\n}\n\n/**\n * Common parseArgs configuration for Socket registry scripts.\n */\nexport const commonParseArgsConfig: ParseArgsConfig = {\n options: {\n force: {\n type: 'boolean',\n short: 'f',\n default: false,\n },\n quiet: {\n type: 'boolean',\n short: 'q',\n default: false,\n },\n },\n strict: false,\n}\n\n/**\n * Extract positional arguments from process.argv.\n * Useful for commands that accept file paths or other positional parameters.\n */\nexport function getPositionalArgs(startIndex = 2): string[] {\n const args = process.argv.slice(startIndex)\n const positionals: string[] = []\n let i = 0\n\n while (i < args.length) {\n
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,0BAAwB;AA8FjB,SAAS,UACd,SAA0B,CAAC,GACZ;AACf,QAAM;AAAA,IACJ,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,OAAO,QAAQ,KAAK,MAAM,CAAC;AAAA,IAC3B;AAAA,IACA,UAAU,CAAC;AAAA,IACX,SAAS;AAAA,EACX,IAAI;AAGJ,QAAM,eAA6B;AAAA;AAAA,IAEjC,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,IACT,OAAO,CAAC;AAAA;AAAA,IAER,OAAO,CAAC;AAAA,IACR,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,IACT,2BAA2B,CAAC;AAAA,IAC5B,iBAAiB;AAAA,IACjB,4BAA4B;AAAA,IAC5B,oBAAoB,CAAC;AAAA,IACrB,sBAAsB,CAAC;AAAA,IACvB,eAAe;AAAA;AAAA,MAEb,wBAAwB;AAAA;AAAA,MAExB,gBAAgB;AAAA;AAAA,MAEhB,6BAA6B;AAAA;AAAA,MAE7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SAAS;AAAA,IACX;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA,QAAQ;AACV;AAMO,SAAS,kBAAkB,aAAa,GAAa;AAC1D,QAAM,OAAO,QAAQ,KAAK,MAAM,UAAU;AAC1C,QAAM,cAAwB,CAAC;AAC/B,MAAI,IAAI;AAER,SAAO,IAAI,KAAK,QAAQ;
|
|
4
|
+
"sourcesContent": ["/**\n * Argument parsing utilities for CLI applications.\n * Uses yargs-parser internally for robust argument parsing with Node.js parseArgs-compatible API.\n */\n\nimport yargsParser from '../external/yargs-parser'\n\n/**\n * Yargs parser options interface.\n */\ninterface YargsOptions {\n // Array of option names that should be treated as booleans.\n boolean?: string[] | undefined\n // Array of option names that should be treated as strings.\n string?: string[] | undefined\n // Array of option names that should accept multiple values.\n array?: string[] | undefined\n // Map of short aliases to full option names.\n alias?: Record<string, string | string[]> | undefined\n // Default values for options.\n default?: Record<string, unknown> | undefined\n // Transform functions to coerce parsed values.\n coerce?: Record<string, (value: unknown) => unknown> | undefined\n // Whether to treat unknown options as positional arguments.\n 'unknown-options-as-args'?: boolean | undefined\n // Whether to parse numeric strings as numbers.\n 'parse-numbers'?: boolean | undefined\n // Whether to parse positional arguments as numbers.\n 'parse-positional-numbers'?: boolean | undefined\n // Whether to support --no-<option> negation for booleans.\n 'boolean-negation'?: boolean | undefined\n // Whether to stop parsing options after the first positional.\n 'halt-at-non-option'?: boolean | undefined\n // Advanced yargs-parser configuration options.\n configuration?: Record<string, boolean | string> | undefined\n // Whether to throw on unknown options.\n strict?: boolean | undefined\n}\n\n/**\n * Yargs parser result interface.\n */\ninterface YargsArguments extends Record<string, unknown> {\n _: string[]\n $0?: string\n}\n\n/**\n * Options for configuring argument parsing, similar to Node.js util.parseArgs.\n */\nexport interface ParseArgsOptionsConfig {\n // Whether the option accepts multiple values (array).\n multiple?: boolean | undefined\n // Short alias for the option (single character).\n short?: string | undefined\n // Type of the option value.\n type?: 'boolean' | 'string' | undefined\n // Default value for the option.\n default?: unknown | undefined\n // Transform function to coerce parsed values.\n coerce?: (value: unknown) => unknown | undefined\n}\n\n/**\n * Configuration object for parseArgs function, similar to Node.js util.parseArgs.\n */\nexport interface ParseArgsConfig {\n // Command-line arguments to parse (defaults to process.argv.slice(2)).\n args?: readonly string[] | undefined\n // Options configuration object.\n options?: Record<string, ParseArgsOptionsConfig> | undefined\n // Whether to throw on unknown options (default: true).\n strict?: boolean | undefined\n // Whether to populate tokens array (not implemented, for API compatibility).\n tokens?: boolean | undefined\n // Whether to allow positional arguments after options.\n allowPositionals?: boolean | undefined\n // Whether to allow negative numbers as option values.\n allowNegative?: boolean | undefined\n // Advanced yargs-parser configuration passthrough.\n configuration?: Record<string, boolean | string> | undefined\n}\n\n/**\n * Result of parsing command-line arguments.\n */\nexport interface ParsedArgs<T = Record<string, unknown>> {\n // Parsed option values.\n values: T\n // Positional arguments (non-option arguments).\n positionals: string[]\n // Raw parsed arguments object from yargs-parser.\n raw: YargsArguments\n}\n\n/**\n * Parse command-line arguments with a Node.js parseArgs-compatible API.\n * Uses yargs-parser internally for robust argument parsing.\n */\nexport function parseArgs<T = Record<string, unknown>>(\n config: ParseArgsConfig = {},\n): ParsedArgs<T> {\n const {\n allowNegative = false,\n allowPositionals = true,\n args = process.argv.slice(2),\n configuration,\n options = {},\n strict = true,\n } = config\n\n // Convert parseArgs options to yargs-parser options.\n const yargsOptions: YargsOptions = {\n // Arrays of option names to treat as specific types.\n boolean: [],\n string: [],\n array: [],\n // Maps for aliases, defaults, and transformations.\n alias: {},\n default: {},\n coerce: {},\n 'unknown-options-as-args': !strict,\n 'parse-numbers': false,\n 'parse-positional-numbers': false,\n 'boolean-negation': !allowNegative,\n 'halt-at-non-option': !allowPositionals,\n configuration: {\n // Enable kebab-case to camelCase conversion (e.g., --temp-dir \u2192 tempDir).\n 'camel-case-expansion': true,\n // Disable dot notation to avoid confusing nested property parsing.\n 'dot-notation': false,\n // Convert duplicate arguments into arrays automatically.\n 'duplicate-arguments-array': true,\n // Flatten nested arrays from duplicate arguments for cleaner output.\n 'flatten-duplicate-arrays': true,\n // Populate the '--' key with arguments after the -- separator.\n 'populate--': true,\n // Allow short option grouping like -abc for -a -b -c.\n 'short-option-groups': true,\n // Keep aliased keys in the result for flexibility.\n 'strip-aliased': false,\n // Keep both kebab-case and camelCase keys for flexibility.\n 'strip-dashed': false,\n ...configuration,\n },\n }\n\n // Process each option configuration.\n for (const { 0: key, 1: optionConfig } of Object.entries(options)) {\n const {\n coerce,\n default: defaultValue,\n multiple,\n short,\n type,\n } = optionConfig\n\n // Set the option type.\n if (type === 'boolean') {\n yargsOptions.boolean?.push(key)\n } else if (type === 'string') {\n yargsOptions.string?.push(key)\n }\n\n // Handle multiple values (arrays).\n if (multiple) {\n yargsOptions.array?.push(key)\n }\n\n // Set short alias.\n if (short) {\n ;(yargsOptions.alias as Record<string, string>)[short] = key\n }\n\n // Set default value.\n if (defaultValue !== undefined) {\n ;(yargsOptions.default as Record<string, unknown>)[key] = defaultValue\n }\n\n // Set coerce function.\n if (coerce) {\n ;(yargsOptions.coerce as Record<string, unknown>)[key] = coerce\n }\n }\n\n // Parse the arguments.\n const parsed = yargsParser(args as string[], yargsOptions)\n\n // Extract positional arguments.\n const positionals = parsed._ || []\n\n // Remove the positionals array from values to match Node.js parseArgs behavior.\n const { _, ...values } = parsed\n\n // Ensure positionals are strings.\n const stringPositionals = positionals.map(String)\n\n return {\n values: values as T,\n positionals: stringPositionals,\n raw: parsed as YargsArguments,\n }\n}\n\n/**\n * Parse command-line arguments with Socket defaults.\n * Provides sensible defaults for Socket CLI applications.\n */\nexport function parseArgsWithDefaults<T = Record<string, unknown>>(\n config: ParseArgsConfig = {},\n): ParsedArgs<T> {\n return parseArgs<T>({\n strict: false,\n allowPositionals: true,\n ...config,\n })\n}\n\n/**\n * Common parseArgs configuration for Socket registry scripts.\n */\nexport const commonParseArgsConfig: ParseArgsConfig = {\n options: {\n force: {\n type: 'boolean',\n short: 'f',\n default: false,\n },\n quiet: {\n type: 'boolean',\n short: 'q',\n default: false,\n },\n },\n strict: false,\n}\n\n/**\n * Extract positional arguments from process.argv.\n * Useful for commands that accept file paths or other positional parameters.\n */\nexport function getPositionalArgs(startIndex = 2): string[] {\n const args = process.argv.slice(startIndex)\n const positionals: string[] = []\n let i = 0\n\n while (i < args.length) {\n const arg = args[i]!\n // Stop at first flag\n if (arg.startsWith('-')) {\n break\n }\n positionals.push(arg)\n i++\n }\n\n return positionals\n}\n\n/**\n * Check if a specific flag is present in argv.\n */\nexport function hasFlag(flag: string, argv = process.argv): boolean {\n const flagVariants = [\n `--${flag}`,\n // Short flag.\n `-${flag.charAt(0)}`,\n ]\n return flagVariants.some(variant => argv.includes(variant))\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,0BAAwB;AA8FjB,SAAS,UACd,SAA0B,CAAC,GACZ;AACf,QAAM;AAAA,IACJ,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,OAAO,QAAQ,KAAK,MAAM,CAAC;AAAA,IAC3B;AAAA,IACA,UAAU,CAAC;AAAA,IACX,SAAS;AAAA,EACX,IAAI;AAGJ,QAAM,eAA6B;AAAA;AAAA,IAEjC,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,IACT,OAAO,CAAC;AAAA;AAAA,IAER,OAAO,CAAC;AAAA,IACR,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,IACT,2BAA2B,CAAC;AAAA,IAC5B,iBAAiB;AAAA,IACjB,4BAA4B;AAAA,IAC5B,oBAAoB,CAAC;AAAA,IACrB,sBAAsB,CAAC;AAAA,IACvB,eAAe;AAAA;AAAA,MAEb,wBAAwB;AAAA;AAAA,MAExB,gBAAgB;AAAA;AAAA,MAEhB,6BAA6B;AAAA;AAAA,M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ACP,SAAS;AAAA,IACX;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA,QAAQ;AACV;AAMO,SAAS,kBAAkB,aAAa,GAAa;AAC1D,QAAM,OAAO,QAAQ,KAAK,MAAM,UAAU;AAC1C,QAAM,cAAwB,CAAC;AAC/B,MAAI,IAAI;AAER,SAAO,IAAI,KAAK,QAAQ;AACtB,UAAM,MAAM,KAAK,CAAC;AAElB,QAAI,IAAI,WAAW,GAAG,GAAG;AACvB;AAAA,IACF;AACA,gBAAY,KAAK,GAAG;AACpB;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,QAAQ,MAAc,OAAO,QAAQ,MAAe;AAClE,QAAM,eAAe;AAAA,IACnB,KAAK,IAAI;AAAA;AAAA,IAET,IAAI,KAAK,OAAO,CAAC,CAAC;AAAA,EACpB;AACA,SAAO,aAAa,KAAK,aAAW,KAAK,SAAS,OAAO,CAAC;AAC5D;",
|
|
6
6
|
"names": ["yargsParser"]
|
|
7
7
|
}
|
package/dist/arrays.d.ts
CHANGED
|
@@ -1,10 +1,63 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Split an array into chunks of a specified size.
|
|
3
|
+
*
|
|
4
|
+
* Divides an array into smaller arrays of the specified chunk size.
|
|
5
|
+
* The last chunk may contain fewer elements if the array length is not
|
|
6
|
+
* evenly divisible by the chunk size.
|
|
7
|
+
*
|
|
8
|
+
* @param arr - The array to split into chunks (can be readonly)
|
|
9
|
+
* @param size - Size of each chunk. Must be greater than 0.
|
|
10
|
+
* @default 2
|
|
11
|
+
* @returns Array of chunks, where each chunk is an array of elements
|
|
12
|
+
* @throws {Error} If chunk size is less than or equal to 0
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* // Split into pairs (default)
|
|
17
|
+
* arrayChunk([1, 2, 3, 4, 5])
|
|
18
|
+
* // Returns: [[1, 2], [3, 4], [5]]
|
|
19
|
+
*
|
|
20
|
+
* // Split into groups of 3
|
|
21
|
+
* arrayChunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3)
|
|
22
|
+
* // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
|
|
23
|
+
*
|
|
24
|
+
* // Works with readonly arrays
|
|
25
|
+
* const readonlyArr = [1, 2, 3] as const
|
|
26
|
+
* arrayChunk(readonlyArr)
|
|
27
|
+
* // Returns: [[1, 2], [3]]
|
|
28
|
+
* ```
|
|
3
29
|
*/
|
|
4
30
|
/*@__NO_SIDE_EFFECTS__*/
|
|
5
31
|
export declare function arrayChunk<T>(arr: T[] | readonly T[], size?: number | undefined): T[][];
|
|
6
32
|
/**
|
|
7
33
|
* Get unique values from an array.
|
|
34
|
+
*
|
|
35
|
+
* Returns a new array containing only the unique values from the input array.
|
|
36
|
+
* Uses `Set` internally for efficient deduplication. Order of first occurrence
|
|
37
|
+
* is preserved.
|
|
38
|
+
*
|
|
39
|
+
* @param arr - The array to deduplicate (can be readonly)
|
|
40
|
+
* @returns New array with duplicate values removed
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* // Remove duplicate numbers
|
|
45
|
+
* arrayUnique([1, 2, 2, 3, 1, 4])
|
|
46
|
+
* // Returns: [1, 2, 3, 4]
|
|
47
|
+
*
|
|
48
|
+
* // Remove duplicate strings
|
|
49
|
+
* arrayUnique(['apple', 'banana', 'apple', 'cherry'])
|
|
50
|
+
* // Returns: ['apple', 'banana', 'cherry']
|
|
51
|
+
*
|
|
52
|
+
* // Works with readonly arrays
|
|
53
|
+
* const readonlyArr = [1, 1, 2] as const
|
|
54
|
+
* arrayUnique(readonlyArr)
|
|
55
|
+
* // Returns: [1, 2]
|
|
56
|
+
*
|
|
57
|
+
* // Empty arrays return empty
|
|
58
|
+
* arrayUnique([])
|
|
59
|
+
* // Returns: []
|
|
60
|
+
* ```
|
|
8
61
|
*/
|
|
9
62
|
/*@__NO_SIDE_EFFECTS__*/
|
|
10
63
|
export declare function arrayUnique<T>(arr: T[] | readonly T[]): T[];
|
|
@@ -15,15 +68,105 @@ export declare function arrayUnique<T>(arr: T[] | readonly T[]): T[];
|
|
|
15
68
|
/**
|
|
16
69
|
* Alias for native Array.isArray.
|
|
17
70
|
* Determines whether the passed value is an array.
|
|
71
|
+
*
|
|
72
|
+
* This is a direct reference to the native `Array.isArray` method,
|
|
73
|
+
* providing a type guard that narrows the type to an array type.
|
|
74
|
+
* Exported for consistency with other array utilities in this module.
|
|
75
|
+
*
|
|
76
|
+
* @param value - The value to check
|
|
77
|
+
* @returns `true` if the value is an array, `false` otherwise
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* // Check if value is an array
|
|
82
|
+
* isArray([1, 2, 3])
|
|
83
|
+
* // Returns: true
|
|
84
|
+
*
|
|
85
|
+
* isArray('not an array')
|
|
86
|
+
* // Returns: false
|
|
87
|
+
*
|
|
88
|
+
* isArray(null)
|
|
89
|
+
* // Returns: false
|
|
90
|
+
*
|
|
91
|
+
* // Type guard usage
|
|
92
|
+
* function processValue(value: unknown) {
|
|
93
|
+
* if (isArray(value)) {
|
|
94
|
+
* // TypeScript knows value is an array here
|
|
95
|
+
* console.log(value.length)
|
|
96
|
+
* }
|
|
97
|
+
* }
|
|
98
|
+
* ```
|
|
18
99
|
*/
|
|
19
100
|
export declare const isArray: (arg: any) => arg is any[];
|
|
20
101
|
/**
|
|
21
102
|
* Join array elements with proper "and" conjunction formatting.
|
|
103
|
+
*
|
|
104
|
+
* Formats an array of strings into a grammatically correct list using
|
|
105
|
+
* "and" as the conjunction. Uses `Intl.ListFormat` for proper English
|
|
106
|
+
* formatting with Oxford comma support.
|
|
107
|
+
*
|
|
108
|
+
* @param arr - Array of strings to join (can be readonly)
|
|
109
|
+
* @returns Formatted string with proper "and" conjunction
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* ```ts
|
|
113
|
+
* // Two items
|
|
114
|
+
* joinAnd(['apples', 'oranges'])
|
|
115
|
+
* // Returns: "apples and oranges"
|
|
116
|
+
*
|
|
117
|
+
* // Three or more items (Oxford comma)
|
|
118
|
+
* joinAnd(['apples', 'oranges', 'bananas'])
|
|
119
|
+
* // Returns: "apples, oranges, and bananas"
|
|
120
|
+
*
|
|
121
|
+
* // Single item
|
|
122
|
+
* joinAnd(['apples'])
|
|
123
|
+
* // Returns: "apples"
|
|
124
|
+
*
|
|
125
|
+
* // Empty array
|
|
126
|
+
* joinAnd([])
|
|
127
|
+
* // Returns: ""
|
|
128
|
+
*
|
|
129
|
+
* // Usage in messages
|
|
130
|
+
* const items = ['React', 'Vue', 'Angular']
|
|
131
|
+
* console.log(`You can choose ${joinAnd(items)}`)
|
|
132
|
+
* // Outputs: "You can choose React, Vue, and Angular"
|
|
133
|
+
* ```
|
|
22
134
|
*/
|
|
23
135
|
/*@__NO_SIDE_EFFECTS__*/
|
|
24
136
|
export declare function joinAnd(arr: string[] | readonly string[]): string;
|
|
25
137
|
/**
|
|
26
138
|
* Join array elements with proper "or" disjunction formatting.
|
|
139
|
+
*
|
|
140
|
+
* Formats an array of strings into a grammatically correct list using
|
|
141
|
+
* "or" as the disjunction. Uses `Intl.ListFormat` for proper English
|
|
142
|
+
* formatting with Oxford comma support.
|
|
143
|
+
*
|
|
144
|
+
* @param arr - Array of strings to join (can be readonly)
|
|
145
|
+
* @returns Formatted string with proper "or" disjunction
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* // Two items
|
|
150
|
+
* joinOr(['yes', 'no'])
|
|
151
|
+
* // Returns: "yes or no"
|
|
152
|
+
*
|
|
153
|
+
* // Three or more items (Oxford comma)
|
|
154
|
+
* joinOr(['red', 'green', 'blue'])
|
|
155
|
+
* // Returns: "red, green, or blue"
|
|
156
|
+
*
|
|
157
|
+
* // Single item
|
|
158
|
+
* joinOr(['maybe'])
|
|
159
|
+
* // Returns: "maybe"
|
|
160
|
+
*
|
|
161
|
+
* // Empty array
|
|
162
|
+
* joinOr([])
|
|
163
|
+
* // Returns: ""
|
|
164
|
+
*
|
|
165
|
+
* // Usage in prompts
|
|
166
|
+
* const options = ['npm', 'yarn', 'pnpm']
|
|
167
|
+
* console.log(`Choose a package manager: ${joinOr(options)}`)
|
|
168
|
+
* // Outputs: "Choose a package manager: npm, yarn, or pnpm"
|
|
169
|
+
* ```
|
|
27
170
|
*/
|
|
28
171
|
/*@__NO_SIDE_EFFECTS__*/
|
|
29
172
|
export declare function joinOr(arr: string[] | readonly string[]): string;
|
package/dist/arrays.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/arrays.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Array utility functions for formatting lists and collections.\n * Provides conjunction and disjunction formatters using Intl.ListFormat.\n */\n\nlet _conjunctionFormatter: Intl.ListFormat | undefined\n/**\n * Get a cached Intl.ListFormat instance for conjunction (and) formatting.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getConjunctionFormatter() {\n if (_conjunctionFormatter === undefined) {\n _conjunctionFormatter = new Intl.ListFormat('en', {\n style: 'long',\n // \"and\" lists.\n type: 'conjunction',\n })\n }\n return _conjunctionFormatter\n}\n\nlet _disjunctionFormatter: Intl.ListFormat | undefined\n/**\n * Get a cached Intl.ListFormat instance for disjunction (or) formatting.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getDisjunctionFormatter() {\n if (_disjunctionFormatter === undefined) {\n _disjunctionFormatter = new Intl.ListFormat('en', {\n style: 'long',\n // \"or\" lists.\n type: 'disjunction',\n })\n }\n return _disjunctionFormatter\n}\n\n/**\n * Split an array into chunks of a specified size.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function arrayChunk<T>(\n arr: T[] | readonly T[],\n size?: number | undefined,\n): T[][] {\n const chunkSize = size ?? 2\n if (chunkSize <= 0) {\n throw new Error('Chunk size must be greater than 0')\n }\n const { length } = arr\n const actualChunkSize = Math.min(length, chunkSize)\n const chunks = []\n for (let i = 0; i < length; i += actualChunkSize) {\n chunks.push(arr.slice(i, i + actualChunkSize) as T[])\n }\n return chunks\n}\n\n/**\n * Get unique values from an array.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function arrayUnique<T>(arr: T[] | readonly T[]): T[] {\n return [...new Set(arr)]\n}\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\n// tsgo has a bug that incorrectly transpiles destructured exports, resulting in\n// `exports.SomeName = void 0;` which causes runtime errors.\n// See: https://github.com/SocketDev/socket-packageurl-js/issues/3\n\n/**\n * Alias for native Array.isArray.\n * Determines whether the passed value is an array.\n */\nexport const isArray = Array.isArray\n\n/**\n * Join array elements with proper \"and\" conjunction formatting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function joinAnd(arr: string[] | readonly string[]): string {\n return getConjunctionFormatter().format(arr)\n}\n\n/**\n * Join array elements with proper \"or\" disjunction formatting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function joinOr(arr: string[] | readonly string[]): string {\n return getDisjunctionFormatter().format(arr)\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,IAAI;AAAA;
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Array utility functions for formatting lists and collections.\n * Provides conjunction and disjunction formatters using Intl.ListFormat.\n */\n\nlet _conjunctionFormatter: Intl.ListFormat | undefined\n/**\n * Get a cached Intl.ListFormat instance for conjunction (and) formatting.\n *\n * Creates a singleton formatter for English \"and\" lists using the long style.\n * The formatter is lazily initialized on first use and reused for performance.\n *\n * @returns Cached Intl.ListFormat instance configured for conjunction formatting\n *\n * @example\n * ```ts\n * const formatter = getConjunctionFormatter()\n * formatter.format(['apple', 'banana', 'cherry'])\n * // Returns: \"apple, banana, and cherry\"\n * ```\n *\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getConjunctionFormatter() {\n if (_conjunctionFormatter === undefined) {\n _conjunctionFormatter = new Intl.ListFormat('en', {\n style: 'long',\n // \"and\" lists.\n type: 'conjunction',\n })\n }\n return _conjunctionFormatter\n}\n\nlet _disjunctionFormatter: Intl.ListFormat | undefined\n/**\n * Get a cached Intl.ListFormat instance for disjunction (or) formatting.\n *\n * Creates a singleton formatter for English \"or\" lists using the long style.\n * The formatter is lazily initialized on first use and reused for performance.\n *\n * @returns Cached Intl.ListFormat instance configured for disjunction formatting\n *\n * @example\n * ```ts\n * const formatter = getDisjunctionFormatter()\n * formatter.format(['red', 'blue', 'green'])\n * // Returns: \"red, blue, or green\"\n * ```\n *\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getDisjunctionFormatter() {\n if (_disjunctionFormatter === undefined) {\n _disjunctionFormatter = new Intl.ListFormat('en', {\n style: 'long',\n // \"or\" lists.\n type: 'disjunction',\n })\n }\n return _disjunctionFormatter\n}\n\n/**\n * Split an array into chunks of a specified size.\n *\n * Divides an array into smaller arrays of the specified chunk size.\n * The last chunk may contain fewer elements if the array length is not\n * evenly divisible by the chunk size.\n *\n * @param arr - The array to split into chunks (can be readonly)\n * @param size - Size of each chunk. Must be greater than 0.\n * @default 2\n * @returns Array of chunks, where each chunk is an array of elements\n * @throws {Error} If chunk size is less than or equal to 0\n *\n * @example\n * ```ts\n * // Split into pairs (default)\n * arrayChunk([1, 2, 3, 4, 5])\n * // Returns: [[1, 2], [3, 4], [5]]\n *\n * // Split into groups of 3\n * arrayChunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3)\n * // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]\n *\n * // Works with readonly arrays\n * const readonlyArr = [1, 2, 3] as const\n * arrayChunk(readonlyArr)\n * // Returns: [[1, 2], [3]]\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function arrayChunk<T>(\n arr: T[] | readonly T[],\n size?: number | undefined,\n): T[][] {\n const chunkSize = size ?? 2\n if (chunkSize <= 0) {\n throw new Error('Chunk size must be greater than 0')\n }\n const { length } = arr\n const actualChunkSize = Math.min(length, chunkSize)\n const chunks = []\n for (let i = 0; i < length; i += actualChunkSize) {\n chunks.push(arr.slice(i, i + actualChunkSize) as T[])\n }\n return chunks\n}\n\n/**\n * Get unique values from an array.\n *\n * Returns a new array containing only the unique values from the input array.\n * Uses `Set` internally for efficient deduplication. Order of first occurrence\n * is preserved.\n *\n * @param arr - The array to deduplicate (can be readonly)\n * @returns New array with duplicate values removed\n *\n * @example\n * ```ts\n * // Remove duplicate numbers\n * arrayUnique([1, 2, 2, 3, 1, 4])\n * // Returns: [1, 2, 3, 4]\n *\n * // Remove duplicate strings\n * arrayUnique(['apple', 'banana', 'apple', 'cherry'])\n * // Returns: ['apple', 'banana', 'cherry']\n *\n * // Works with readonly arrays\n * const readonlyArr = [1, 1, 2] as const\n * arrayUnique(readonlyArr)\n * // Returns: [1, 2]\n *\n * // Empty arrays return empty\n * arrayUnique([])\n * // Returns: []\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function arrayUnique<T>(arr: T[] | readonly T[]): T[] {\n return [...new Set(arr)]\n}\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\n// tsgo has a bug that incorrectly transpiles destructured exports, resulting in\n// `exports.SomeName = void 0;` which causes runtime errors.\n// See: https://github.com/SocketDev/socket-packageurl-js/issues/3\n\n/**\n * Alias for native Array.isArray.\n * Determines whether the passed value is an array.\n *\n * This is a direct reference to the native `Array.isArray` method,\n * providing a type guard that narrows the type to an array type.\n * Exported for consistency with other array utilities in this module.\n *\n * @param value - The value to check\n * @returns `true` if the value is an array, `false` otherwise\n *\n * @example\n * ```ts\n * // Check if value is an array\n * isArray([1, 2, 3])\n * // Returns: true\n *\n * isArray('not an array')\n * // Returns: false\n *\n * isArray(null)\n * // Returns: false\n *\n * // Type guard usage\n * function processValue(value: unknown) {\n * if (isArray(value)) {\n * // TypeScript knows value is an array here\n * console.log(value.length)\n * }\n * }\n * ```\n */\nexport const isArray = Array.isArray\n\n/**\n * Join array elements with proper \"and\" conjunction formatting.\n *\n * Formats an array of strings into a grammatically correct list using\n * \"and\" as the conjunction. Uses `Intl.ListFormat` for proper English\n * formatting with Oxford comma support.\n *\n * @param arr - Array of strings to join (can be readonly)\n * @returns Formatted string with proper \"and\" conjunction\n *\n * @example\n * ```ts\n * // Two items\n * joinAnd(['apples', 'oranges'])\n * // Returns: \"apples and oranges\"\n *\n * // Three or more items (Oxford comma)\n * joinAnd(['apples', 'oranges', 'bananas'])\n * // Returns: \"apples, oranges, and bananas\"\n *\n * // Single item\n * joinAnd(['apples'])\n * // Returns: \"apples\"\n *\n * // Empty array\n * joinAnd([])\n * // Returns: \"\"\n *\n * // Usage in messages\n * const items = ['React', 'Vue', 'Angular']\n * console.log(`You can choose ${joinAnd(items)}`)\n * // Outputs: \"You can choose React, Vue, and Angular\"\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function joinAnd(arr: string[] | readonly string[]): string {\n return getConjunctionFormatter().format(arr)\n}\n\n/**\n * Join array elements with proper \"or\" disjunction formatting.\n *\n * Formats an array of strings into a grammatically correct list using\n * \"or\" as the disjunction. Uses `Intl.ListFormat` for proper English\n * formatting with Oxford comma support.\n *\n * @param arr - Array of strings to join (can be readonly)\n * @returns Formatted string with proper \"or\" disjunction\n *\n * @example\n * ```ts\n * // Two items\n * joinOr(['yes', 'no'])\n * // Returns: \"yes or no\"\n *\n * // Three or more items (Oxford comma)\n * joinOr(['red', 'green', 'blue'])\n * // Returns: \"red, green, or blue\"\n *\n * // Single item\n * joinOr(['maybe'])\n * // Returns: \"maybe\"\n *\n * // Empty array\n * joinOr([])\n * // Returns: \"\"\n *\n * // Usage in prompts\n * const options = ['npm', 'yarn', 'pnpm']\n * console.log(`Choose a package manager: ${joinOr(options)}`)\n * // Outputs: \"Choose a package manager: npm, yarn, or pnpm\"\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function joinOr(arr: string[] | readonly string[]): string {\n return getDisjunctionFormatter().format(arr)\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,IAAI;AAAA;AAmBJ,SAAS,0BAA0B;AACjC,MAAI,0BAA0B,QAAW;AACvC,4BAAwB,IAAI,KAAK,WAAW,MAAM;AAAA,MAChD,OAAO;AAAA;AAAA,MAEP,MAAM;AAAA,IACR,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAmBJ,SAAS,0BAA0B;AACjC,MAAI,0BAA0B,QAAW;AACvC,4BAAwB,IAAI,KAAK,WAAW,MAAM;AAAA,MAChD,OAAO;AAAA;AAAA,MAEP,MAAM;AAAA,IACR,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAAA;AAgCO,SAAS,WACd,KACA,MACO;AACP,QAAM,YAAY,QAAQ;AAC1B,MAAI,aAAa,GAAG;AAClB,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AACA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,kBAAkB,KAAK,IAAI,QAAQ,SAAS;AAClD,QAAM,SAAS,CAAC;AAChB,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK,iBAAiB;AAChD,WAAO,KAAK,IAAI,MAAM,GAAG,IAAI,eAAe,CAAQ;AAAA,EACtD;AACA,SAAO;AACT;AAAA;AAiCO,SAAS,YAAe,KAA8B;AAC3D,SAAO,CAAC,GAAG,IAAI,IAAI,GAAG,CAAC;AACzB;AAuCO,MAAM,UAAU,MAAM;AAAA;AAqCtB,SAAS,QAAQ,KAA2C;AACjE,UAAO,wCAAwB,GAAE,OAAO,GAAG;AAC7C;AAAA;AAqCO,SAAS,OAAO,KAA2C;AAChE,UAAO,wCAAwB,GAAE,OAAO,GAAG;AAC7C;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/bin.js
CHANGED
|
@@ -69,10 +69,7 @@ async function execBin(binPath, args, options) {
|
|
|
69
69
|
error.code = "ENOENT";
|
|
70
70
|
throw error;
|
|
71
71
|
}
|
|
72
|
-
const binCommand = Array.isArray(resolvedPath) ?
|
|
73
|
-
// biome-ignore lint/style/noNonNullAssertion: which always returns non-empty array.
|
|
74
|
-
resolvedPath[0]
|
|
75
|
-
) : resolvedPath;
|
|
72
|
+
const binCommand = Array.isArray(resolvedPath) ? resolvedPath[0] : resolvedPath;
|
|
76
73
|
return await (0, import_spawn.spawn)(binCommand, args ?? [], options);
|
|
77
74
|
}
|
|
78
75
|
async function whichBin(binName, options) {
|
package/dist/bin.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/bin.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Binary path resolution and execution utilities for package managers.\n * Provides cross-platform bin path lookup, command execution, and path normalization.\n */\n\nimport { APPDATA } from '#env/appdata'\nimport { HOME } from '#env/home'\nimport { LOCALAPPDATA } from '#env/localappdata'\nimport { XDG_DATA_HOME } from '#env/xdg-data-home'\n\nimport { readJsonSync } from './fs'\nimport { getOwn } from './objects'\nimport { isPath, normalizePath } from './path'\nimport { spawn } from './spawn'\n\nlet _fs: typeof import('node:fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _fs!\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _path!\n}\n\nlet _which: typeof import('which') | undefined\n/**\n * Lazily load the which module for finding executables.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getWhich() {\n if (_which === undefined) {\n _which = /*@__PURE__*/ require('./external/which')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _which!\n}\n\n/**\n * Execute a binary with the given arguments.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function execBin(\n binPath: string,\n args?: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n // Resolve the binary path.\n const resolvedPath = isPath(binPath)\n ? resolveBinPathSync(binPath)\n : await whichBin(binPath)\n\n if (!resolvedPath) {\n const error = new Error(`Binary not found: ${binPath}`) as Error & {\n code: string\n }\n error.code = 'ENOENT'\n throw error\n }\n\n // Execute the binary directly.\n const binCommand = Array.isArray(resolvedPath)\n ? // biome-ignore lint/style/noNonNullAssertion: which always returns non-empty array.\n resolvedPath[0]!\n : resolvedPath\n return await spawn(binCommand, args ?? [], options)\n}\n\n/**\n * Find and resolve a binary in the system PATH asynchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport async function whichBin(\n binName: string,\n options?: import('which').Options,\n): Promise<string | string[] | undefined> {\n const which = getWhich()\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = await which?.(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (options?.all) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Find and resolve a binary in the system PATH synchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport function whichBinSync(\n binName: string,\n options?: import('which').Options,\n): string | string[] | undefined {\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = getWhich()?.sync(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (getOwn(options, 'all')) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Check if a directory path contains any shadow bin patterns.\n */\nexport function isShadowBinPath(dirPath: string | undefined): boolean {\n if (!dirPath) {\n return false\n }\n // Check for node_modules/.bin pattern (Unix and Windows)\n const normalized = dirPath.replace(/\\\\/g, '/')\n return normalized.includes('node_modules/.bin')\n}\n\n/**\n * Find the real executable for a binary, bypassing shadow bins.\n */\nexport function findRealBin(\n binName: string,\n commonPaths: string[] = [],\n): string | undefined {\n const fs = getFs()\n const path = getPath()\n const which = getWhich()\n\n // Try common locations first.\n for (const binPath of commonPaths) {\n if (fs?.existsSync(binPath)) {\n return binPath\n }\n }\n\n // Fall back to which.sync if no direct path found.\n const binPath = which?.sync(binName, { nothrow: true })\n if (binPath) {\n const binDir = path?.dirname(binPath)\n\n if (isShadowBinPath(binDir)) {\n // This is likely a shadowed binary, try to find the real one.\n const allPaths = which?.sync(binName, { all: true, nothrow: true }) || []\n // Ensure allPaths is an array.\n const pathsArray = Array.isArray(allPaths)\n ? allPaths\n : typeof allPaths === 'string'\n ? [allPaths]\n : []\n\n for (const altPath of pathsArray) {\n const altDir = path?.dirname(altPath)\n if (!isShadowBinPath(altDir)) {\n return altPath\n }\n }\n }\n return binPath\n }\n // If all else fails, return undefined to indicate binary not found.\n return undefined\n}\n\n/**\n * Find the real npm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealNpm(): string {\n const fs = getFs()\n const path = getPath()\n\n // Try to find npm in the same directory as the node executable.\n const nodeDir = path?.dirname(process.execPath)\n const npmInNodeDir = path?.join(nodeDir, 'npm')\n\n if (fs?.existsSync(npmInNodeDir)) {\n return npmInNodeDir\n }\n\n // Try common npm locations.\n const commonPaths = ['/usr/local/bin/npm', '/usr/bin/npm']\n const result = findRealBin('npm', commonPaths)\n\n // If we found a valid path, return it.\n if (result && fs?.existsSync(result)) {\n return result\n }\n\n // As a last resort, try to use whichBinSync to find npm.\n // This handles cases where npm is installed in non-standard locations.\n const npmPath = whichBinSync('npm', { nothrow: true })\n if (npmPath && typeof npmPath === 'string' && fs?.existsSync(npmPath)) {\n return npmPath\n }\n\n // Return the basic 'npm' and let the system resolve it.\n return 'npm'\n}\n\n/**\n * Find the real pnpm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealPnpm(): string {\n const WIN32 = require('../constants/platform').WIN32\n const path = getPath()\n\n // Try common pnpm locations.\n const commonPaths = WIN32\n ? [\n // Windows common paths.\n path?.join(APPDATA as string, 'npm', 'pnpm.cmd'),\n path?.join(APPDATA as string, 'npm', 'pnpm'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm.cmd'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm'),\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm.cmd',\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm',\n ].filter(Boolean)\n : [\n // Unix common paths.\n '/usr/local/bin/pnpm',\n '/usr/bin/pnpm',\n path?.join(\n (XDG_DATA_HOME as string) || `${HOME as string}/.local/share`,\n 'pnpm/pnpm',\n ),\n path?.join(HOME as string, '.pnpm/pnpm'),\n ].filter(Boolean)\n\n return findRealBin('pnpm', commonPaths) ?? ''\n}\n\n/**\n * Find the real yarn executable, bypassing any aliases and shadow bins.\n */\nexport function findRealYarn(): string {\n const path = getPath()\n\n // Try common yarn locations.\n const commonPaths = [\n '/usr/local/bin/yarn',\n '/usr/bin/yarn',\n path?.join(HOME as string, '.yarn/bin/yarn'),\n path?.join(HOME as string, '.config/yarn/global/node_modules/.bin/yarn'),\n ].filter(Boolean)\n\n return findRealBin('yarn', commonPaths) ?? ''\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Resolve a binary path to its actual executable file.\n * Handles Windows .cmd wrappers and Unix shell scripts.\n */\nexport function resolveBinPathSync(binPath: string): string {\n const fs = getFs()\n const path = getPath()\n\n // If it's not an absolute path, try to find it in PATH first\n if (!path?.isAbsolute(binPath)) {\n try {\n const resolved = whichBinSync(binPath)\n if (resolved) {\n // biome-ignore lint/style/noParameterAssign: Reassigning for normalization.\n binPath = resolved as string\n }\n } catch {}\n }\n\n // Normalize the path once for consistent pattern matching.\n // biome-ignore lint/style/noParameterAssign: Normalizing path for consistent handling.\n binPath = normalizePath(binPath)\n\n // Handle empty string that normalized to '.' (current directory)\n if (binPath === '.') {\n return binPath\n }\n\n const ext = path?.extname(binPath)\n const extLowered = ext.toLowerCase()\n const basename = path?.basename(binPath, ext)\n const voltaIndex =\n basename === 'node' ? -1 : (/(?<=\\/)\\.volta\\//i.exec(binPath)?.index ?? -1)\n if (voltaIndex !== -1) {\n const voltaPath = binPath.slice(0, voltaIndex)\n const voltaToolsPath = path?.join(voltaPath, 'tools')\n const voltaImagePath = path?.join(voltaToolsPath, 'image')\n const voltaUserPath = path?.join(voltaToolsPath, 'user')\n const voltaPlatform = readJsonSync(\n path?.join(voltaUserPath, 'platform.json'),\n { throws: false },\n ) as\n // biome-ignore lint/suspicious/noExplicitAny: Volta platform config structure is dynamic.\n any\n const voltaNodeVersion = voltaPlatform?.node?.runtime\n const voltaNpmVersion = voltaPlatform?.node?.npm\n let voltaBinPath = ''\n if (basename === 'npm' || basename === 'npx') {\n if (voltaNpmVersion) {\n const relCliPath = `bin/${basename}-cli.js`\n voltaBinPath = path?.join(\n voltaImagePath,\n `npm/${voltaNpmVersion}/${relCliPath}`,\n )\n if (voltaNodeVersion && !fs?.existsSync(voltaBinPath)) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n } else {\n const voltaUserBinPath = path?.join(voltaUserPath, 'bin')\n const binInfo = readJsonSync(\n path?.join(voltaUserBinPath, `${basename}.json`),\n { throws: false },\n ) as\n // biome-ignore lint/suspicious/noExplicitAny: Volta bin info structure is dynamic.\n any\n const binPackage = binInfo?.package\n if (binPackage) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `packages/${binPackage}/bin/${basename}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = `${voltaBinPath}.cmd`\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n }\n if (voltaBinPath) {\n try {\n return normalizePath(fs?.realpathSync.native(voltaBinPath))\n } catch {}\n return voltaBinPath\n }\n }\n const WIN32 = require('../constants/platform').WIN32\n if (WIN32) {\n const hasKnownExt =\n extLowered === '' ||\n extLowered === '.cmd' ||\n extLowered === '.exe' ||\n extLowered === '.ps1'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n if (hasKnownExt && isNpmOrNpx) {\n // The quick route assumes a bin path like: C:\\Program Files\\nodejs\\npm.cmd\n const quickPath = path?.join(\n path?.dirname(binPath),\n `node_modules/npm/bin/${basename}-cli.js`,\n )\n if (fs?.existsSync(quickPath)) {\n try {\n return fs?.realpathSync.native(quickPath)\n } catch {}\n return quickPath\n }\n }\n let relPath = ''\n if (\n hasKnownExt &&\n // Only parse shell scripts and batch files, not actual executables.\n // .exe files are already executables and don't need path resolution from wrapper scripts.\n extLowered !== '.exe' &&\n // Check if file exists before attempting to read it to avoid ENOENT errors.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n if (isNpmOrNpx) {\n if (extLowered === '.cmd') {\n // \"npm.cmd\" and \"npx.cmd\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.cmd\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.cmd\n relPath =\n basename === 'npm'\n ? /(?<=\"NPM_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=\"NPX_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"npm\" and \"npx\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n } else if (extLowered === '.ps1') {\n // \"npm.ps1\" and \"npx.ps1\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.ps1\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.ps1\n relPath =\n basename === 'npm'\n ? /(?<=\\$NPM_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n : /(?<=\\$NPX_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n }\n } else if (isPnpmOrYarn) {\n if (extLowered === '.cmd') {\n // pnpm.cmd and yarn.cmd can have different formats depending on installation method\n // Common formats include:\n // 1. Setup-pnpm action format: node \"%~dp0\\..\\pnpm\\bin\\pnpm.cjs\" %*\n // 2. npm install -g pnpm format: similar to cmd-shim\n // 3. Standalone installer format: various patterns\n\n // Try setup-pnpm/setup-yarn action format first\n relPath =\n /(?<=node\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(source)?.[1] || ''\n\n // Try alternative format: \"%~dp0\\node.exe\" \"%~dp0\\..\\package\\bin\\binary.js\" %*\n if (!relPath) {\n relPath =\n /(?<=\"%~dp0\\\\[^\"]*node[^\"]*\"\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(\n source,\n )?.[1] || ''\n }\n\n // Try cmd-shim format as fallback\n if (!relPath) {\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '') {\n // Extensionless pnpm/yarn - try common shebang formats\n // Handle pnpm installed via standalone installer or global install\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // Note: may have multiple spaces between arguments\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n if (!relPath) {\n // Also try: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=exec\\s+node\\s+\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n }\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n relPath = /(?<=\"\\$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.ps1') {\n // PowerShell format\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.cmd') {\n // \"bin.CMD\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L98:\n //\n // @ECHO off\n // GOTO start\n // :find_dp0\n // SET dp0=%~dp0\n // EXIT /b\n // :start\n // SETLOCAL\n // CALL :find_dp0\n //\n // IF EXIST \"%dp0%\\node.exe\" (\n // SET \"_prog=%dp0%\\node.exe\"\n // ) ELSE (\n // SET \"_prog=node\"\n // SET PATHEXT=%PATHEXT:;.JS;=;%\n // )\n //\n // endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\..\\<PACKAGE_NAME>\\path\\to\\bin.js\" %*\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"bin\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L138:\n //\n // #!/bin/sh\n // basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n //\n // case `uname` in\n // *CYGWIN*|*MINGW*|*MSYS*)\n // if command -v cygpath > /dev/null 2>&1; then\n // basedir=`cygpath -w \"$basedir\"`\n // fi\n // ;;\n // esac\n //\n // if [ -x \"$basedir/node\" ]; then\n // exec \"$basedir/node\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // else\n // exec node \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // fi\n relPath = /(?<=\"$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '.ps1') {\n // \"bin.PS1\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L192:\n //\n // #!/usr/bin/env pwsh\n // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n //\n // $exe=\"\"\n // if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n // # Fix case when both the Windows and Linux builds of Node\n // # are installed in the same directory\n // $exe=\".exe\"\n // }\n // $ret=0\n // if (Test-Path \"$basedir/node$exe\") {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // } else {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // }\n // exit $ret\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n if (relPath) {\n // biome-ignore lint/style/noParameterAssign: Resolving wrapper script target.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n } else {\n // Handle Unix shell scripts (non-Windows platforms)\n let hasNoExt = extLowered === ''\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n\n // Handle special case where pnpm path in CI has extra segments.\n // In setup-pnpm GitHub Action, the path might be malformed like:\n // /home/runner/setup-pnpm/node_modules/.bin/pnpm/bin/pnpm.cjs\n // This happens when the shell script contains a relative path that\n // when resolved, creates an invalid nested structure.\n if (isPnpmOrYarn && binPath.includes('/.bin/pnpm/bin/')) {\n // Extract the correct pnpm bin path.\n const binIndex = binPath.indexOf('/.bin/pnpm')\n if (binIndex !== -1) {\n // Get the base path up to /.bin/pnpm.\n const baseBinPath = binPath.slice(0, binIndex + '/.bin/pnpm'.length)\n // Check if the original shell script exists.\n try {\n const stats = fs?.statSync(baseBinPath)\n // Only use this path if it's a file (the shell script).\n if (stats.isFile()) {\n // biome-ignore lint/style/noParameterAssign: Fixing pnpm nested bin structure.\n binPath = normalizePath(baseBinPath)\n // Recompute hasNoExt since we changed the path.\n hasNoExt = !path?.extname(binPath)\n }\n } catch {\n // If stat fails, continue with the original path.\n }\n }\n }\n\n if (\n hasNoExt &&\n (isPnpmOrYarn || isNpmOrNpx) &&\n // For extensionless files (Unix shell scripts), verify existence before reading.\n // This prevents ENOENT errors when the bin path doesn't exist.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n let relPath = ''\n\n if (isPnpmOrYarn) {\n // Handle pnpm/yarn Unix shell scripts.\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // or: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n // Example: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n // ^^^^^^^^^^^^^^^^^^^^^ captures this part\n // This regex needs to be more careful to not match \"$@\" at the end.\n relPath =\n /(?<=\"\\$basedir\\/)[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n }\n // Special case for setup-pnpm GitHub Action which may use a different format.\n // The setup-pnpm action creates a shell script that references ../pnpm/bin/pnpm.cjs\n if (!relPath) {\n // Try to match: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n const match = /exec\\s+node\\s+\"?\\$basedir\\/([^\"]+)\"?\\s+\"\\$@\"/.exec(\n source,\n )\n if (match) {\n relPath = match[1] || ''\n }\n }\n // Check if the extracted path looks wrong (e.g., pnpm/bin/pnpm.cjs without ../).\n // This happens with setup-pnpm action when it creates a malformed shell script.\n if (relPath && basename === 'pnpm' && relPath.startsWith('pnpm/')) {\n // The path should be ../pnpm/... not pnpm/...\n // Prepend ../ to fix the relative path.\n relPath = `../${relPath}`\n }\n } else if (isNpmOrNpx) {\n // Handle npm/npx Unix shell scripts\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n }\n\n if (relPath) {\n // Resolve the relative path to handle .. segments properly.\n // biome-ignore lint/style/noParameterAssign: Resolving shell script target.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n }\n try {\n const realPath = fs?.realpathSync.native(binPath)\n return normalizePath(realPath)\n } catch {}\n // Return normalized path even if realpath fails.\n return normalizePath(binPath)\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAwB;AACxB,kBAAqB;AACrB,0BAA6B;AAC7B,2BAA8B;AAE9B,gBAA6B;AAC7B,qBAAuB;AACvB,kBAAsC;AACtC,mBAAsB;AAEtB,IAAI;AAAA;AAKJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAGrB,UAAoB,QAAQ,SAAS;AAAA,EACvC;
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Binary path resolution and execution utilities for package managers.\n * Provides cross-platform bin path lookup, command execution, and path normalization.\n */\n\nimport { APPDATA } from '#env/appdata'\nimport { HOME } from '#env/home'\nimport { LOCALAPPDATA } from '#env/localappdata'\nimport { XDG_DATA_HOME } from '#env/xdg-data-home'\n\nimport { readJsonSync } from './fs'\nimport { getOwn } from './objects'\nimport { isPath, normalizePath } from './path'\nimport { spawn } from './spawn'\n\nlet _fs: typeof import('node:fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs!\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path!\n}\n\nlet _which: typeof import('which') | undefined\n/**\n * Lazily load the which module for finding executables.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getWhich() {\n if (_which === undefined) {\n _which = /*@__PURE__*/ require('./external/which')\n }\n return _which!\n}\n\n/**\n * Execute a binary with the given arguments.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function execBin(\n binPath: string,\n args?: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n // Resolve the binary path.\n const resolvedPath = isPath(binPath)\n ? resolveBinPathSync(binPath)\n : await whichBin(binPath)\n\n if (!resolvedPath) {\n const error = new Error(`Binary not found: ${binPath}`) as Error & {\n code: string\n }\n error.code = 'ENOENT'\n throw error\n }\n\n // Execute the binary directly.\n const binCommand = Array.isArray(resolvedPath)\n ? resolvedPath[0]!\n : resolvedPath\n return await spawn(binCommand, args ?? [], options)\n}\n\n/**\n * Find and resolve a binary in the system PATH asynchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport async function whichBin(\n binName: string,\n options?: import('which').Options,\n): Promise<string | string[] | undefined> {\n const which = getWhich()\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = await which?.(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (options?.all) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Find and resolve a binary in the system PATH synchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport function whichBinSync(\n binName: string,\n options?: import('which').Options,\n): string | string[] | undefined {\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = getWhich()?.sync(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (getOwn(options, 'all')) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Check if a directory path contains any shadow bin patterns.\n */\nexport function isShadowBinPath(dirPath: string | undefined): boolean {\n if (!dirPath) {\n return false\n }\n // Check for node_modules/.bin pattern (Unix and Windows)\n const normalized = dirPath.replace(/\\\\/g, '/')\n return normalized.includes('node_modules/.bin')\n}\n\n/**\n * Find the real executable for a binary, bypassing shadow bins.\n */\nexport function findRealBin(\n binName: string,\n commonPaths: string[] = [],\n): string | undefined {\n const fs = getFs()\n const path = getPath()\n const which = getWhich()\n\n // Try common locations first.\n for (const binPath of commonPaths) {\n if (fs?.existsSync(binPath)) {\n return binPath\n }\n }\n\n // Fall back to which.sync if no direct path found.\n const binPath = which?.sync(binName, { nothrow: true })\n if (binPath) {\n const binDir = path?.dirname(binPath)\n\n if (isShadowBinPath(binDir)) {\n // This is likely a shadowed binary, try to find the real one.\n const allPaths = which?.sync(binName, { all: true, nothrow: true }) || []\n // Ensure allPaths is an array.\n const pathsArray = Array.isArray(allPaths)\n ? allPaths\n : typeof allPaths === 'string'\n ? [allPaths]\n : []\n\n for (const altPath of pathsArray) {\n const altDir = path?.dirname(altPath)\n if (!isShadowBinPath(altDir)) {\n return altPath\n }\n }\n }\n return binPath\n }\n // If all else fails, return undefined to indicate binary not found.\n return undefined\n}\n\n/**\n * Find the real npm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealNpm(): string {\n const fs = getFs()\n const path = getPath()\n\n // Try to find npm in the same directory as the node executable.\n const nodeDir = path?.dirname(process.execPath)\n const npmInNodeDir = path?.join(nodeDir, 'npm')\n\n if (fs?.existsSync(npmInNodeDir)) {\n return npmInNodeDir\n }\n\n // Try common npm locations.\n const commonPaths = ['/usr/local/bin/npm', '/usr/bin/npm']\n const result = findRealBin('npm', commonPaths)\n\n // If we found a valid path, return it.\n if (result && fs?.existsSync(result)) {\n return result\n }\n\n // As a last resort, try to use whichBinSync to find npm.\n // This handles cases where npm is installed in non-standard locations.\n const npmPath = whichBinSync('npm', { nothrow: true })\n if (npmPath && typeof npmPath === 'string' && fs?.existsSync(npmPath)) {\n return npmPath\n }\n\n // Return the basic 'npm' and let the system resolve it.\n return 'npm'\n}\n\n/**\n * Find the real pnpm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealPnpm(): string {\n const WIN32 = require('../constants/platform').WIN32\n const path = getPath()\n\n // Try common pnpm locations.\n const commonPaths = WIN32\n ? [\n // Windows common paths.\n path?.join(APPDATA as string, 'npm', 'pnpm.cmd'),\n path?.join(APPDATA as string, 'npm', 'pnpm'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm.cmd'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm'),\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm.cmd',\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm',\n ].filter(Boolean)\n : [\n // Unix common paths.\n '/usr/local/bin/pnpm',\n '/usr/bin/pnpm',\n path?.join(\n (XDG_DATA_HOME as string) || `${HOME as string}/.local/share`,\n 'pnpm/pnpm',\n ),\n path?.join(HOME as string, '.pnpm/pnpm'),\n ].filter(Boolean)\n\n return findRealBin('pnpm', commonPaths) ?? ''\n}\n\n/**\n * Find the real yarn executable, bypassing any aliases and shadow bins.\n */\nexport function findRealYarn(): string {\n const path = getPath()\n\n // Try common yarn locations.\n const commonPaths = [\n '/usr/local/bin/yarn',\n '/usr/bin/yarn',\n path?.join(HOME as string, '.yarn/bin/yarn'),\n path?.join(HOME as string, '.config/yarn/global/node_modules/.bin/yarn'),\n ].filter(Boolean)\n\n return findRealBin('yarn', commonPaths) ?? ''\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Resolve a binary path to its actual executable file.\n * Handles Windows .cmd wrappers and Unix shell scripts.\n */\nexport function resolveBinPathSync(binPath: string): string {\n const fs = getFs()\n const path = getPath()\n\n // If it's not an absolute path, try to find it in PATH first\n if (!path?.isAbsolute(binPath)) {\n try {\n const resolved = whichBinSync(binPath)\n if (resolved) {\n binPath = resolved as string\n }\n } catch {}\n }\n\n // Normalize the path once for consistent pattern matching.\n binPath = normalizePath(binPath)\n\n // Handle empty string that normalized to '.' (current directory)\n if (binPath === '.') {\n return binPath\n }\n\n const ext = path?.extname(binPath)\n const extLowered = ext.toLowerCase()\n const basename = path?.basename(binPath, ext)\n const voltaIndex =\n basename === 'node' ? -1 : (/(?<=\\/)\\.volta\\//i.exec(binPath)?.index ?? -1)\n if (voltaIndex !== -1) {\n const voltaPath = binPath.slice(0, voltaIndex)\n const voltaToolsPath = path?.join(voltaPath, 'tools')\n const voltaImagePath = path?.join(voltaToolsPath, 'image')\n const voltaUserPath = path?.join(voltaToolsPath, 'user')\n const voltaPlatform = readJsonSync(\n path?.join(voltaUserPath, 'platform.json'),\n { throws: false },\n ) as any\n const voltaNodeVersion = voltaPlatform?.node?.runtime\n const voltaNpmVersion = voltaPlatform?.node?.npm\n let voltaBinPath = ''\n if (basename === 'npm' || basename === 'npx') {\n if (voltaNpmVersion) {\n const relCliPath = `bin/${basename}-cli.js`\n voltaBinPath = path?.join(\n voltaImagePath,\n `npm/${voltaNpmVersion}/${relCliPath}`,\n )\n if (voltaNodeVersion && !fs?.existsSync(voltaBinPath)) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n } else {\n const voltaUserBinPath = path?.join(voltaUserPath, 'bin')\n const binInfo = readJsonSync(\n path?.join(voltaUserBinPath, `${basename}.json`),\n { throws: false },\n ) as any\n const binPackage = binInfo?.package\n if (binPackage) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `packages/${binPackage}/bin/${basename}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = `${voltaBinPath}.cmd`\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n }\n if (voltaBinPath) {\n try {\n return normalizePath(fs?.realpathSync.native(voltaBinPath))\n } catch {}\n return voltaBinPath\n }\n }\n const WIN32 = require('../constants/platform').WIN32\n if (WIN32) {\n const hasKnownExt =\n extLowered === '' ||\n extLowered === '.cmd' ||\n extLowered === '.exe' ||\n extLowered === '.ps1'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n if (hasKnownExt && isNpmOrNpx) {\n // The quick route assumes a bin path like: C:\\Program Files\\nodejs\\npm.cmd\n const quickPath = path?.join(\n path?.dirname(binPath),\n `node_modules/npm/bin/${basename}-cli.js`,\n )\n if (fs?.existsSync(quickPath)) {\n try {\n return fs?.realpathSync.native(quickPath)\n } catch {}\n return quickPath\n }\n }\n let relPath = ''\n if (\n hasKnownExt &&\n // Only parse shell scripts and batch files, not actual executables.\n // .exe files are already executables and don't need path resolution from wrapper scripts.\n extLowered !== '.exe' &&\n // Check if file exists before attempting to read it to avoid ENOENT errors.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n if (isNpmOrNpx) {\n if (extLowered === '.cmd') {\n // \"npm.cmd\" and \"npx.cmd\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.cmd\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.cmd\n relPath =\n basename === 'npm'\n ? /(?<=\"NPM_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=\"NPX_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"npm\" and \"npx\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n } else if (extLowered === '.ps1') {\n // \"npm.ps1\" and \"npx.ps1\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.ps1\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.ps1\n relPath =\n basename === 'npm'\n ? /(?<=\\$NPM_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n : /(?<=\\$NPX_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n }\n } else if (isPnpmOrYarn) {\n if (extLowered === '.cmd') {\n // pnpm.cmd and yarn.cmd can have different formats depending on installation method\n // Common formats include:\n // 1. Setup-pnpm action format: node \"%~dp0\\..\\pnpm\\bin\\pnpm.cjs\" %*\n // 2. npm install -g pnpm format: similar to cmd-shim\n // 3. Standalone installer format: various patterns\n\n // Try setup-pnpm/setup-yarn action format first\n relPath =\n /(?<=node\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(source)?.[1] || ''\n\n // Try alternative format: \"%~dp0\\node.exe\" \"%~dp0\\..\\package\\bin\\binary.js\" %*\n if (!relPath) {\n relPath =\n /(?<=\"%~dp0\\\\[^\"]*node[^\"]*\"\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(\n source,\n )?.[1] || ''\n }\n\n // Try cmd-shim format as fallback\n if (!relPath) {\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '') {\n // Extensionless pnpm/yarn - try common shebang formats\n // Handle pnpm installed via standalone installer or global install\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // Note: may have multiple spaces between arguments\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n if (!relPath) {\n // Also try: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=exec\\s+node\\s+\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n }\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n relPath = /(?<=\"\\$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.ps1') {\n // PowerShell format\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.cmd') {\n // \"bin.CMD\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L98:\n //\n // @ECHO off\n // GOTO start\n // :find_dp0\n // SET dp0=%~dp0\n // EXIT /b\n // :start\n // SETLOCAL\n // CALL :find_dp0\n //\n // IF EXIST \"%dp0%\\node.exe\" (\n // SET \"_prog=%dp0%\\node.exe\"\n // ) ELSE (\n // SET \"_prog=node\"\n // SET PATHEXT=%PATHEXT:;.JS;=;%\n // )\n //\n // endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\..\\<PACKAGE_NAME>\\path\\to\\bin.js\" %*\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"bin\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L138:\n //\n // #!/bin/sh\n // basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n //\n // case `uname` in\n // *CYGWIN*|*MINGW*|*MSYS*)\n // if command -v cygpath > /dev/null 2>&1; then\n // basedir=`cygpath -w \"$basedir\"`\n // fi\n // ;;\n // esac\n //\n // if [ -x \"$basedir/node\" ]; then\n // exec \"$basedir/node\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // else\n // exec node \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // fi\n relPath = /(?<=\"$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '.ps1') {\n // \"bin.PS1\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L192:\n //\n // #!/usr/bin/env pwsh\n // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n //\n // $exe=\"\"\n // if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n // # Fix case when both the Windows and Linux builds of Node\n // # are installed in the same directory\n // $exe=\".exe\"\n // }\n // $ret=0\n // if (Test-Path \"$basedir/node$exe\") {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // } else {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // }\n // exit $ret\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n if (relPath) {\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n } else {\n // Handle Unix shell scripts (non-Windows platforms)\n let hasNoExt = extLowered === ''\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n\n // Handle special case where pnpm path in CI has extra segments.\n // In setup-pnpm GitHub Action, the path might be malformed like:\n // /home/runner/setup-pnpm/node_modules/.bin/pnpm/bin/pnpm.cjs\n // This happens when the shell script contains a relative path that\n // when resolved, creates an invalid nested structure.\n if (isPnpmOrYarn && binPath.includes('/.bin/pnpm/bin/')) {\n // Extract the correct pnpm bin path.\n const binIndex = binPath.indexOf('/.bin/pnpm')\n if (binIndex !== -1) {\n // Get the base path up to /.bin/pnpm.\n const baseBinPath = binPath.slice(0, binIndex + '/.bin/pnpm'.length)\n // Check if the original shell script exists.\n try {\n const stats = fs?.statSync(baseBinPath)\n // Only use this path if it's a file (the shell script).\n if (stats.isFile()) {\n binPath = normalizePath(baseBinPath)\n // Recompute hasNoExt since we changed the path.\n hasNoExt = !path?.extname(binPath)\n }\n } catch {\n // If stat fails, continue with the original path.\n }\n }\n }\n\n if (\n hasNoExt &&\n (isPnpmOrYarn || isNpmOrNpx) &&\n // For extensionless files (Unix shell scripts), verify existence before reading.\n // This prevents ENOENT errors when the bin path doesn't exist.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n let relPath = ''\n\n if (isPnpmOrYarn) {\n // Handle pnpm/yarn Unix shell scripts.\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // or: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n // Example: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n // ^^^^^^^^^^^^^^^^^^^^^ captures this part\n // This regex needs to be more careful to not match \"$@\" at the end.\n relPath =\n /(?<=\"\\$basedir\\/)[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n }\n // Special case for setup-pnpm GitHub Action which may use a different format.\n // The setup-pnpm action creates a shell script that references ../pnpm/bin/pnpm.cjs\n if (!relPath) {\n // Try to match: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n const match = /exec\\s+node\\s+\"?\\$basedir\\/([^\"]+)\"?\\s+\"\\$@\"/.exec(\n source,\n )\n if (match) {\n relPath = match[1] || ''\n }\n }\n // Check if the extracted path looks wrong (e.g., pnpm/bin/pnpm.cjs without ../).\n // This happens with setup-pnpm action when it creates a malformed shell script.\n if (relPath && basename === 'pnpm' && relPath.startsWith('pnpm/')) {\n // The path should be ../pnpm/... not pnpm/...\n // Prepend ../ to fix the relative path.\n relPath = `../${relPath}`\n }\n } else if (isNpmOrNpx) {\n // Handle npm/npx Unix shell scripts\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n }\n\n if (relPath) {\n // Resolve the relative path to handle .. segments properly.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n }\n try {\n const realPath = fs?.realpathSync.native(binPath)\n return normalizePath(realPath)\n } catch {}\n // Return normalized path even if realpath fails.\n return normalizePath(binPath)\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAwB;AACxB,kBAAqB;AACrB,0BAA6B;AAC7B,2BAA8B;AAE9B,gBAA6B;AAC7B,qBAAuB;AACvB,kBAAsC;AACtC,mBAAsB;AAEtB,IAA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BAAU,MAAM,CAAC,KAAK;AAAA,UACxB;AAAA,QACF;AAGA,YAAI,WAAW,aAAa,UAAU,QAAQ,WAAW,OAAO,GAAG;AAGjE,oBAAU,MAAM,OAAO;AAAA,QACzB;AAAA,MACF,WAAW,YAAY;AAErB,kBACE,aAAa,QACT,0CAA0C,KAAK,MAAM,IAAI,CAAC,KAAK,KAC/D,0CAA0C,KAAK,MAAM,IAAI,CAAC,KAAK;AAAA,MACvE;AAEA,UAAI,SAAS;AAEX,sBAAU,2BAAc,MAAM,QAAQ,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AACA,MAAI;AACF,UAAM,WAAW,IAAI,aAAa,OAAO,OAAO;AAChD,eAAO,2BAAc,QAAQ;AAAA,EAC/B,QAAQ;AAAA,EAAC;AAET,aAAO,2BAAc,OAAO;AAC9B;",
|
|
6
6
|
"names": ["binPath"]
|
|
7
7
|
}
|
package/dist/cacache.d.ts
CHANGED
|
@@ -6,7 +6,6 @@ export interface GetOptions {
|
|
|
6
6
|
export interface PutOptions {
|
|
7
7
|
integrity?: string | undefined;
|
|
8
8
|
size?: number | undefined;
|
|
9
|
-
// biome-ignore lint/suspicious/noExplicitAny: User-provided arbitrary metadata.
|
|
10
9
|
metadata?: any | undefined;
|
|
11
10
|
memoize?: boolean | undefined;
|
|
12
11
|
}
|
|
@@ -14,7 +13,6 @@ export interface CacheEntry {
|
|
|
14
13
|
data: Buffer;
|
|
15
14
|
integrity: string;
|
|
16
15
|
key: string;
|
|
17
|
-
// biome-ignore lint/suspicious/noExplicitAny: User-provided arbitrary metadata.
|
|
18
16
|
metadata?: any | undefined;
|
|
19
17
|
path: string;
|
|
20
18
|
size: number;
|
package/dist/cacache.js
CHANGED
package/dist/cacache.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/cacache.ts"],
|
|
4
|
-
"sourcesContent": ["/** @fileoverview Cacache utilities for Socket ecosystem shared content-addressable cache. */\n\nimport { getSocketCacacheDir } from './paths'\n\nexport interface GetOptions {\n integrity?: string | undefined\n size?: number | undefined\n memoize?: boolean | undefined\n}\n\nexport interface PutOptions {\n integrity?: string | undefined\n size?: number | undefined\n
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAoC;
|
|
4
|
+
"sourcesContent": ["/** @fileoverview Cacache utilities for Socket ecosystem shared content-addressable cache. */\n\nimport { getSocketCacacheDir } from './paths'\n\nexport interface GetOptions {\n integrity?: string | undefined\n size?: number | undefined\n memoize?: boolean | undefined\n}\n\nexport interface PutOptions {\n integrity?: string | undefined\n size?: number | undefined\n metadata?: any | undefined\n memoize?: boolean | undefined\n}\n\nexport interface CacheEntry {\n data: Buffer\n integrity: string\n key: string\n metadata?: any | undefined\n path: string\n size: number\n time: number\n}\n\nexport interface RemoveOptions {\n /**\n * Optional key prefix to filter removals.\n * If provided, only keys starting with this prefix will be removed.\n * Can include wildcards (*) for pattern matching.\n *\n * @example\n * { prefix: 'socket-sdk' } // Simple prefix\n * { prefix: 'socket-sdk:scans:abc*' } // With wildcard\n */\n prefix?: string | undefined\n}\n\n/**\n * Get the cacache module for cache operations.\n */\nfunction getCacache() {\n return /*@__PURE__*/ require('./external/cacache')\n}\n\n/**\n * Convert wildcard pattern to regex for matching.\n * Supports * as wildcard (matches any characters).\n */\nfunction patternToRegex(pattern: string): RegExp {\n // Escape regex special characters except *\n const escaped = pattern.replaceAll(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n // Convert * to .* (match any characters)\n const regexPattern = escaped.replaceAll('*', '.*')\n return new RegExp(`^${regexPattern}`)\n}\n\n/**\n * Check if a key matches a pattern (with wildcard support).\n */\nfunction matchesPattern(key: string, pattern: string): boolean {\n // If no wildcards, use simple prefix matching (faster)\n if (!pattern.includes('*')) {\n return key.startsWith(pattern)\n }\n // Use regex for wildcard patterns\n const regex = patternToRegex(pattern)\n return regex.test(key)\n}\n\n/**\n * Clear entries from the Socket shared cache.\n *\n * Supports wildcard patterns (*) in prefix for flexible matching.\n * For simple prefixes without wildcards, uses efficient streaming.\n * For wildcard patterns, iterates and matches each entry.\n *\n * @param options - Optional configuration for selective clearing\n * @param options.prefix - Prefix or pattern to match (supports * wildcards)\n * @returns Number of entries removed (only when prefix is specified)\n *\n * @example\n * // Clear all entries\n * await clear()\n *\n * @example\n * // Clear entries with simple prefix\n * const removed = await clear({ prefix: 'socket-sdk:scans' })\n * console.log(`Removed ${removed} scan cache entries`)\n *\n * @example\n * // Clear entries with wildcard pattern\n * await clear({ prefix: 'socket-sdk:scans:abc*' })\n * await clear({ prefix: 'socket-sdk:npm/lodash/*' })\n */\nexport async function clear(\n options?: RemoveOptions | undefined,\n): Promise<number | undefined> {\n const opts = { __proto__: null, ...options } as RemoveOptions\n const cacache = getCacache()\n const cacheDir = getSocketCacacheDir()\n\n // If no prefix specified, clear everything.\n if (!opts.prefix) {\n try {\n await cacache.rm.all(cacheDir)\n return\n } catch (e) {\n // Ignore ENOTEMPTY errors - can occur when multiple processes\n // are cleaning up concurrently (e.g., in CI test environments).\n if ((e as NodeJS.ErrnoException)?.code !== 'ENOTEMPTY') {\n throw e\n }\n return\n }\n }\n\n const hasWildcard = opts.prefix.includes('*')\n\n // For simple prefix (no wildcards), use faster iteration.\n if (!hasWildcard) {\n let removed = 0\n const stream = cacache.ls.stream(cacheDir)\n\n for await (const entry of stream) {\n if (entry.key.startsWith(opts.prefix)) {\n try {\n await cacache.rm.entry(cacheDir, entry.key)\n removed++\n } catch {\n // Ignore individual removal errors (e.g., already removed by another process).\n }\n }\n }\n\n return removed\n }\n\n // For wildcard patterns, need to match each entry.\n let removed = 0\n const stream = cacache.ls.stream(cacheDir)\n\n for await (const entry of stream) {\n if (matchesPattern(entry.key, opts.prefix)) {\n try {\n await cacache.rm.entry(cacheDir, entry.key)\n removed++\n } catch {\n // Ignore individual removal errors.\n }\n }\n }\n\n return removed\n}\n\n/**\n * Get data from the Socket shared cache by key.\n * @throws {Error} When cache entry is not found.\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function get(\n key: string,\n options?: GetOptions | undefined,\n): Promise<CacheEntry> {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: \"pattern*\" }).',\n )\n }\n const cacache = getCacache() as any\n return await cacache.get(getSocketCacacheDir(), key, options)\n}\n\n/**\n * Put data into the Socket shared cache with a key.\n *\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function put(\n key: string,\n data: string | Buffer,\n options?: PutOptions | undefined,\n) {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: \"pattern*\" }).',\n )\n }\n const cacache = getCacache()\n return await cacache.put(getSocketCacacheDir(), key, data, options)\n}\n\n/**\n * Remove an entry from the Socket shared cache by key.\n *\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function remove(key: string): Promise<unknown> {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Use clear({ prefix: \"pattern*\" }) to remove multiple entries.',\n )\n }\n const cacache = getCacache() as any\n return await cacache.rm.entry(getSocketCacacheDir(), key)\n}\n\n/**\n * Get data from the Socket shared cache by key without throwing.\n */\nexport async function safeGet(\n key: string,\n options?: GetOptions | undefined,\n): Promise<CacheEntry | undefined> {\n try {\n return await get(key, options)\n } catch {\n return undefined\n }\n}\n\n/**\n * Execute a callback with a temporary directory for cache operations.\n */\nexport async function withTmp<T>(\n callback: (tmpDirPath: string) => Promise<T>,\n): Promise<T> {\n const cacache = getCacache()\n // The DefinitelyTyped types for cacache.tmp.withTmp are incorrect.\n // It actually returns the callback's return value, not void.\n return (await cacache.tmp.withTmp(\n getSocketCacacheDir(),\n {},\n callback as any,\n )) as T\n}\n"],
|
|
5
|
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